answer
stringlengths
17
10.2M
package org.xcolab.service.proposal.service.proposalattribute; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.xcolab.client.comment.exceptions.ThreadNotFoundException; import org.xcolab.client.comment.pojo.CommentThread; import org.xcolab.client.comment.util.ThreadClientUtil; import org.xcolab.model.tables.pojos.Proposal; import org.xcolab.model.tables.pojos.ProposalAttribute; import org.xcolab.model.tables.pojos.ProposalVersion; import org.xcolab.service.proposal.domain.proposal.ProposalDao; import org.xcolab.service.proposal.domain.proposalattribute.ProposalAttributeDao; import org.xcolab.service.proposal.domain.proposalversion.ProposalVersionDao; import org.xcolab.service.contest.exceptions.NotFoundException; import java.sql.Timestamp; import java.util.Date; import java.util.List; @Service public class ProposalAttributeService { private final ProposalAttributeDao proposalAttributeDao; private final ProposalDao proposalDao; private final ProposalVersionDao proposalVersionDao; @Autowired public ProposalAttributeService(ProposalDao proposalDao, ProposalAttributeDao proposalAttributeDao, ProposalVersionDao proposalVersionDao) { this.proposalAttributeDao = proposalAttributeDao; this.proposalDao = proposalDao; this.proposalVersionDao = proposalVersionDao; } public ProposalAttribute setAttribute(ProposalAttribute proposalAttribute, Long authorId) { try { Proposal proposal = proposalDao.get(proposalAttribute.getProposalId()); int currentVersion = proposalVersionDao.findMaxVersion(proposalAttribute.getProposalId()); Integer version = proposalAttribute.getVersion(); boolean isNewVersion = false; if (version == null || version < currentVersion) { version = currentVersion + 1; isNewVersion = true; } List<ProposalAttribute> currentProposalAttributes = proposalAttributeDao.findByGiven(proposal.getProposalId(), null, null, currentVersion); // for each attribute, if it isn't the one that we are changing, simply // update it to the most recent version // if it is the one that we are changing then leave old one as it is and // create new one for new proposal version for (ProposalAttribute attribute : currentProposalAttributes) { ProposalAttributeDetectUpdateAlgorithm updateAlgorithm = new ProposalAttributeDetectUpdateAlgorithm(attribute); if (!updateAlgorithm.hasBeenUpdated(proposalAttribute.getName(), zeroIfNull(proposalAttribute.getAdditionalId()), zeroIfNull(proposalAttribute.getNumericValue()), zeroIfNull(proposalAttribute.getRealValue()))) { // clone the attribute and set its version to the new value attribute.setVersion(version); proposalAttributeDao.update(attribute); } else { } } // set new value for provided attribute proposalAttribute.setVersion(version); ProposalAttribute attribute = proposalAttributeDao .create(proposalAttribute);//setAttributeValue(proposalId, newVersion, // attributeName, additionalId, stringValue, numericValue, realValue); Timestamp updatedDate = new Timestamp((new Date()).getTime()); proposal.setUpdatedDate(updatedDate); // create newly created version descriptor if (isNewVersion) { createProposalVersionDescription(authorId, proposalAttribute.getProposalId(), version, proposalAttribute.getName(), proposalAttribute.getAdditionalId(), updatedDate); } proposalDao.update(proposal); // Update the proposal name in the discussion category if (proposalAttribute.getName().equals(ProposalAttributeKeys.NAME)) { try { CommentThread thread = ThreadClientUtil.getThread(proposal.getDiscussionId()); thread.setTitle( String.format("%s %s", getProposalNameFromOldTitle(thread.getTitle()), proposalAttribute.getStringValue())); ThreadClientUtil.updateThread(thread); } catch (ThreadNotFoundException ignored) { } } return attribute; } catch (NotFoundException ignored) { return null; } } private static String getProposalNameFromOldTitle(String oldTitle) { if (oldTitle != null) { String[] threadTokens = oldTitle.split(" "); if (threadTokens.length > 1) { return threadTokens[0]; } } return " "; } private static Double zeroIfNull(Double val) { if (val == null) { return 0.0; } else { return val; } } private static Long zeroIfNull(Long val) { if (val == null) { return 0L; } else { return val; } } private void createProposalVersionDescription(long authorId, long proposalId, int version, String updateType, long additionalId, Timestamp updatedDate) { ProposalVersion proposalVersion = new ProposalVersion(); proposalVersion.setProposalId(proposalId); proposalVersion.setVersion(version); proposalVersion.setAuthorId(authorId); proposalVersion.setUpdateType(updateType); proposalVersion.setUpdateAdditionalId(additionalId); proposalVersion.setCreateDate(updatedDate); proposalVersionDao.create(proposalVersion); } }
package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.Range; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.time.Day; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimePeriodAnchor; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.Year; /** * A collection of test cases for the {@link TimeSeriesCollection} class. */ public class TimeSeriesCollectionTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimeSeriesCollectionTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimeSeriesCollectionTests(String name) { super(name); } /** * Some tests for the equals() method. */ public void testEquals() { TimeSeriesCollection c1 = new TimeSeriesCollection(); TimeSeriesCollection c2 = new TimeSeriesCollection(); TimeSeries s1 = new TimeSeries("Series 1"); TimeSeries s2 = new TimeSeries("Series 2"); // newly created collections should be equal boolean b1 = c1.equals(c2); assertTrue("b1", b1); // add series to collection 1, should be not equal c1.addSeries(s1); c1.addSeries(s2); boolean b2 = c1.equals(c2); assertFalse("b2", b2); // now add the same series to collection 2 to make them equal again... c2.addSeries(s1); c2.addSeries(s2); boolean b3 = c1.equals(c2); assertTrue("b3", b3); // now remove series 2 from collection 2 c2.removeSeries(s2); boolean b4 = c1.equals(c2); assertFalse("b4", b4); // now remove series 2 from collection 1 to make them equal again c1.removeSeries(s2); boolean b5 = c1.equals(c2); assertTrue("b5", b5); } /** * Tests the remove series method. */ public void testRemoveSeries() { TimeSeriesCollection c1 = new TimeSeriesCollection(); TimeSeries s1 = new TimeSeries("Series 1"); TimeSeries s2 = new TimeSeries("Series 2"); TimeSeries s3 = new TimeSeries("Series 3"); TimeSeries s4 = new TimeSeries("Series 4"); c1.addSeries(s1); c1.addSeries(s2); c1.addSeries(s3); c1.addSeries(s4); c1.removeSeries(s3); TimeSeries s = c1.getSeries(2); boolean b1 = s.equals(s4); assertTrue(b1); } /** * Some checks for the {@link TimeSeriesCollection#removeSeries(int)} * method. */ public void testRemoveSeries_int() { TimeSeriesCollection c1 = new TimeSeriesCollection(); TimeSeries s1 = new TimeSeries("Series 1"); TimeSeries s2 = new TimeSeries("Series 2"); TimeSeries s3 = new TimeSeries("Series 3"); TimeSeries s4 = new TimeSeries("Series 4"); c1.addSeries(s1); c1.addSeries(s2); c1.addSeries(s3); c1.addSeries(s4); c1.removeSeries(2); assertTrue(c1.getSeries(2).equals(s4)); c1.removeSeries(0); assertTrue(c1.getSeries(0).equals(s2)); assertEquals(2, c1.getSeriesCount()); } /** * Test the getSurroundingItems() method to ensure it is returning the * values we expect. */ public void testGetSurroundingItems() { TimeSeries series = new TimeSeries("Series 1"); TimeSeriesCollection collection = new TimeSeriesCollection(series); collection.setXPosition(TimePeriodAnchor.MIDDLE); // for a series with no data, we expect {-1, -1}... int[] result = collection.getSurroundingItems(0, 1000L); assertTrue(result[0] == -1); assertTrue(result[1] == -1); // now test with a single value in the series... Day today = new Day(); long start1 = today.getFirstMillisecond(); long middle1 = today.getMiddleMillisecond(); long end1 = today.getLastMillisecond(); series.add(today, 99.9); result = collection.getSurroundingItems(0, start1); assertTrue(result[0] == -1); assertTrue(result[1] == 0); result = collection.getSurroundingItems(0, middle1); assertTrue(result[0] == 0); assertTrue(result[1] == 0); result = collection.getSurroundingItems(0, end1); assertTrue(result[0] == 0); assertTrue(result[1] == -1); // now add a second value to the series... Day tomorrow = (Day) today.next(); long start2 = tomorrow.getFirstMillisecond(); long middle2 = tomorrow.getMiddleMillisecond(); long end2 = tomorrow.getLastMillisecond(); series.add(tomorrow, 199.9); result = collection.getSurroundingItems(0, start2); assertTrue(result[0] == 0); assertTrue(result[1] == 1); result = collection.getSurroundingItems(0, middle2); assertTrue(result[0] == 1); assertTrue(result[1] == 1); result = collection.getSurroundingItems(0, end2); assertTrue(result[0] == 1); assertTrue(result[1] == -1); // now add a third value to the series... Day yesterday = (Day) today.previous(); long start3 = yesterday.getFirstMillisecond(); long middle3 = yesterday.getMiddleMillisecond(); long end3 = yesterday.getLastMillisecond(); series.add(yesterday, 1.23); result = collection.getSurroundingItems(0, start3); assertTrue(result[0] == -1); assertTrue(result[1] == 0); result = collection.getSurroundingItems(0, middle3); assertTrue(result[0] == 0); assertTrue(result[1] == 0); result = collection.getSurroundingItems(0, end3); assertTrue(result[0] == 0); assertTrue(result[1] == 1); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimeSeriesCollection c1 = new TimeSeriesCollection(createSeries()); TimeSeriesCollection c2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(c1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); c2 = (TimeSeriesCollection) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(c1, c2); } /** * Creates a time series for testing. * * @return A time series. */ private TimeSeries createSeries() { RegularTimePeriod t = new Day(); TimeSeries series = new TimeSeries("Test"); series.add(t, 1.0); t = t.next(); series.add(t, 2.0); t = t.next(); series.add(t, null); t = t.next(); series.add(t, 4.0); return series; } /** * A test for bug report 1170825. */ public void test1170825() { TimeSeries s1 = new TimeSeries("Series1"); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); try { /* TimeSeries s = */ dataset.getSeries(1); } catch (IllegalArgumentException e) { // correct outcome } catch (IndexOutOfBoundsException e) { assertTrue(false); // wrong outcome } } /** * Some tests for the indexOf() method. */ public void testIndexOf() { TimeSeries s1 = new TimeSeries("S1"); TimeSeries s2 = new TimeSeries("S2"); TimeSeriesCollection dataset = new TimeSeriesCollection(); assertEquals(-1, dataset.indexOf(s1)); assertEquals(-1, dataset.indexOf(s2)); dataset.addSeries(s1); assertEquals(0, dataset.indexOf(s1)); assertEquals(-1, dataset.indexOf(s2)); dataset.addSeries(s2); assertEquals(0, dataset.indexOf(s1)); assertEquals(1, dataset.indexOf(s2)); dataset.removeSeries(s1); assertEquals(-1, dataset.indexOf(s1)); assertEquals(0, dataset.indexOf(s2)); TimeSeries s2b = new TimeSeries("S2"); assertEquals(0, dataset.indexOf(s2b)); } private static final double EPSILON = 0.0000000001; /** * This method provides a check for the bounds calculated using the * {@link DatasetUtilities#findDomainBounds(org.jfree.data.xy.XYDataset, * java.util.List, boolean)} method. */ public void testFindDomainBounds() { TimeSeriesCollection dataset = new TimeSeriesCollection(); List visibleSeriesKeys = new java.util.ArrayList(); Range r = DatasetUtilities.findDomainBounds(dataset, visibleSeriesKeys, true); assertNull(r); TimeSeries s1 = new TimeSeries("S1"); dataset.addSeries(s1); visibleSeriesKeys.add("S1"); r = DatasetUtilities.findDomainBounds(dataset, visibleSeriesKeys, true); assertNull(r); // store the current time zone TimeZone saved = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris")); s1.add(new Year(2008), 8.0); r = DatasetUtilities.findDomainBounds(dataset, visibleSeriesKeys, true); assertEquals(1199142000000.0, r.getLowerBound(), EPSILON); assertEquals(1230764399999.0, r.getUpperBound(), EPSILON); TimeSeries s2 = new TimeSeries("S2"); dataset.addSeries(s2); s2.add(new Year(2009), 9.0); s2.add(new Year(2010), 10.0); r = DatasetUtilities.findDomainBounds(dataset, visibleSeriesKeys, true); assertEquals(1199142000000.0, r.getLowerBound(), EPSILON); assertEquals(1230764399999.0, r.getUpperBound(), EPSILON); visibleSeriesKeys.add("S2"); r = DatasetUtilities.findDomainBounds(dataset, visibleSeriesKeys, true); assertEquals(1199142000000.0, r.getLowerBound(), EPSILON); assertEquals(1293836399999.0, r.getUpperBound(), EPSILON); // restore the default time zone TimeZone.setDefault(saved); } /** * Basic checks for cloning. */ public void testCloning() { TimeSeries s1 = new TimeSeries("Series"); s1.add(new Year(2009), 1.1); TimeSeriesCollection c1 = new TimeSeriesCollection(); c1.addSeries(s1); TimeSeriesCollection c2 = null; try { c2 = (TimeSeriesCollection) c1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(c1 != c2); assertTrue(c1.getClass() == c2.getClass()); assertTrue(c1.equals(c2)); // check independence s1.setDescription("XYZ"); assertFalse(c1.equals(c2)); c2.getSeries(0).setDescription("XYZ"); assertTrue(c1.equals(c2)); } /** * A test to cover bug 3445507. */ public void testBug3445507() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2011), null); s1.add(new Year(2012), null); TimeSeries s2 = new TimeSeries("S2"); s2.add(new Year(2011), 5.0); s2.add(new Year(2012), 6.0); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); List keys = new ArrayList(); keys.add("S1"); keys.add("S2"); Range r = dataset.getRangeBounds(keys, new Range( Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), false); assertEquals(5.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } }
package alluxio.master; import alluxio.AlluxioURI; import alluxio.Configuration; import alluxio.Constants; import alluxio.LocalAlluxioClusterResource; import alluxio.client.ClientContext; import alluxio.client.WriteType; import alluxio.client.file.FileOutStream; import alluxio.client.file.FileSystem; import alluxio.client.file.URIStatus; import alluxio.client.file.options.CreateDirectoryOptions; import alluxio.client.file.options.CreateFileOptions; import alluxio.client.file.options.DeleteOptions; import alluxio.client.file.options.SetAttributeOptions; import alluxio.exception.AccessControlException; import alluxio.exception.FileDoesNotExistException; import alluxio.exception.InvalidPathException; import alluxio.master.file.FileSystemMaster; import alluxio.master.journal.Journal; import alluxio.master.journal.JournalWriter; import alluxio.master.journal.ReadWriteJournal; import alluxio.security.authentication.AuthenticatedClientUser; import alluxio.security.group.GroupMappingService; import alluxio.underfs.UnderFileSystem; import alluxio.util.IdUtils; import alluxio.util.io.PathUtils; import alluxio.wire.FileInfo; import com.google.common.collect.Lists; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Test master journal, including checkpoint and entry log. Most tests will test entry log first, * followed by the checkpoint. */ public class JournalIntegrationTest { @Rule public LocalAlluxioClusterResource mLocalAlluxioClusterResource = new LocalAlluxioClusterResource(Constants.GB, Constants.GB, Constants.MASTER_JOURNAL_LOG_SIZE_BYTES_MAX, Integer.toString(Constants.KB)); private LocalAlluxioCluster mLocalAlluxioCluster = null; private FileSystem mFileSystem = null; private AlluxioURI mRootUri = new AlluxioURI(AlluxioURI.SEPARATOR); private Configuration mMasterConfiguration = null; /** * Tests adding a block. */ @Test public void addBlockTest() throws Exception { AlluxioURI uri = new AlluxioURI("/xyz"); CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(64); FileOutStream os = mFileSystem.createFile(uri, options); for (int k = 0; k < 1000; k++) { os.write(k); } os.close(); URIStatus status = mFileSystem.getStatus(uri); mLocalAlluxioCluster.stopFS(); addBlockTestUtil(status); } private FileSystemMaster createFsMasterFromJournal() throws IOException { return MasterTestUtils.createFileSystemMasterFromJournal(mMasterConfiguration); } private void deleteFsMasterJournalLogs() throws IOException { String journalFolder = mLocalAlluxioCluster.getMaster().getJournalFolder(); Journal journal = new ReadWriteJournal( PathUtils.concatPath(journalFolder, Constants.FILE_SYSTEM_MASTER_NAME)); UnderFileSystem.get(journalFolder, mMasterConfiguration).delete(journal.getCurrentLogFilePath(), true); } private void addBlockTestUtil(URIStatus status) throws AccessControlException, IOException, InvalidPathException, FileDoesNotExistException { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(1, fsMaster.getFileInfoList(mRootUri, false).size()); long xyzId = fsMaster.getFileId(new AlluxioURI("/xyz")); Assert.assertTrue(xyzId != IdUtils.INVALID_FILE_ID); FileInfo fsMasterInfo = fsMaster.getFileInfo(xyzId); Assert.assertEquals(0, fsMaster.getFileInfo(xyzId).getInMemoryPercentage()); Assert.assertEquals(status.getBlockIds(), fsMasterInfo.getBlockIds()); Assert.assertEquals(status.getBlockSizeBytes(), fsMasterInfo.getBlockSizeBytes()); Assert.assertEquals(status.getLength(), fsMasterInfo.getLength()); fsMaster.stop(); } /** * Tests flushing the journal multiple times, without writing any data. */ @Test public void multipleFlushTest() throws Exception { // Set the max log size to 0 to force a flush to write a new file. String existingMax = mMasterConfiguration.get(Constants.MASTER_JOURNAL_LOG_SIZE_BYTES_MAX); mMasterConfiguration.set(Constants.MASTER_JOURNAL_LOG_SIZE_BYTES_MAX, "0"); try { String journalFolder = mLocalAlluxioCluster.getMaster().getJournalFolder(); ReadWriteJournal journal = new ReadWriteJournal( PathUtils.concatPath(journalFolder, Constants.FILE_SYSTEM_MASTER_NAME)); JournalWriter writer = journal.getNewWriter(); writer.getCheckpointOutputStream(0).close(); // Flush multiple times, without writing to the log. writer.getEntryOutputStream().flush(); writer.getEntryOutputStream().flush(); writer.getEntryOutputStream().flush(); String[] paths = UnderFileSystem.get(journalFolder, mMasterConfiguration) .list(journal.getCompletedDirectory()); // Make sure no new empty files were created. Assert.assertTrue(paths == null || paths.length == 0); } finally { // Reset the max log size. mMasterConfiguration.set(Constants.MASTER_JOURNAL_LOG_SIZE_BYTES_MAX, existingMax); } } /** * Tests loading metadata. */ @Test public void loadMetadataTest() throws Exception { String ufsRoot = PathUtils .concatPath(mLocalAlluxioCluster.getMasterConf().get(Constants.UNDERFS_ADDRESS)); UnderFileSystem ufs = UnderFileSystem.get(ufsRoot, mLocalAlluxioCluster.getMasterConf()); ufs.create(ufsRoot + "/xyz"); mFileSystem.loadMetadata(new AlluxioURI("/xyz")); URIStatus status = mFileSystem.getStatus(new AlluxioURI("/xyz")); mLocalAlluxioCluster.stopFS(); loadMetadataTestUtil(status); deleteFsMasterJournalLogs(); loadMetadataTestUtil(status); } private void loadMetadataTestUtil(URIStatus status) throws AccessControlException, IOException, InvalidPathException, FileDoesNotExistException { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(1, fsMaster.getFileInfoList(mRootUri, false).size()); Assert.assertTrue(fsMaster.getFileId(new AlluxioURI("/xyz")) != IdUtils.INVALID_FILE_ID); FileInfo fsMasterInfo = fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI("/xyz"))); Assert.assertEquals(status, new URIStatus(fsMasterInfo)); fsMaster.stop(); } @Before public final void before() throws Exception { mLocalAlluxioCluster = mLocalAlluxioClusterResource.get(); mFileSystem = mLocalAlluxioCluster.getClient(); mMasterConfiguration = mLocalAlluxioCluster.getMasterConf(); } /** * Tests completed edit log deletion. */ @Test public void completedEditLogDeletionTest() throws Exception { for (int i = 0; i < 124; i++) { mFileSystem.createFile(new AlluxioURI("/a" + i), CreateFileOptions.defaults().setBlockSizeBytes((i + 10) / 10 * 64)).close(); } mLocalAlluxioCluster.stopFS(); String journalFolder = FileSystemMaster.getJournalDirectory(mLocalAlluxioCluster.getMaster().getJournalFolder()); Journal journal = new ReadWriteJournal(journalFolder); String completedPath = journal.getCompletedDirectory(); Assert.assertTrue( UnderFileSystem.get(completedPath, mMasterConfiguration).list(completedPath).length > 1); multiEditLogTestUtil(); Assert.assertTrue( UnderFileSystem.get(completedPath, mMasterConfiguration).list(completedPath).length <= 1); multiEditLogTestUtil(); } /** * Tests file and directory creation and deletion. */ @Test public void deleteTest() throws Exception { CreateDirectoryOptions recMkdir = CreateDirectoryOptions.defaults().setRecursive(true); DeleteOptions recDelete = DeleteOptions.defaults().setRecursive(true); for (int i = 0; i < 10; i++) { String dirPath = "/i" + i; mFileSystem.createDirectory(new AlluxioURI(dirPath), recMkdir); for (int j = 0; j < 10; j++) { CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes((i + j + 1) * 64); String filePath = dirPath + "/j" + j; mFileSystem.createFile(new AlluxioURI(filePath), option).close(); if (j >= 5) { mFileSystem.delete(new AlluxioURI(filePath), recDelete); } } if (i >= 5) { mFileSystem.delete(new AlluxioURI(dirPath), recDelete); } } mLocalAlluxioCluster.stopFS(); deleteTestUtil(); deleteFsMasterJournalLogs(); deleteTestUtil(); } private void deleteTestUtil() throws Exception { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(5, fsMaster.getFileInfoList(mRootUri, false).size()); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { Assert.assertTrue( fsMaster.getFileId(new AlluxioURI("/i" + i + "/j" + j)) != IdUtils.INVALID_FILE_ID); } } fsMaster.stop(); } @Test public void emptyImageTest() throws Exception { mLocalAlluxioCluster.stopFS(); FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(0, fsMaster.getFileInfoList(mRootUri, false).size()); fsMaster.stop(); } /** * Tests file and directory creation. */ @Test public void fileDirectoryTest() throws Exception { for (int i = 0; i < 10; i++) { mFileSystem.createDirectory(new AlluxioURI("/i" + i)); for (int j = 0; j < 10; j++) { CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes((i + j + 1) * 64); mFileSystem.createFile(new AlluxioURI("/i" + i + "/j" + j), option).close(); } } mLocalAlluxioCluster.stopFS(); fileDirectoryTestUtil(); deleteFsMasterJournalLogs(); fileDirectoryTestUtil(); } private void fileDirectoryTestUtil() throws Exception { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(10, fsMaster.getFileInfoList(mRootUri, false).size()); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { Assert.assertTrue( fsMaster.getFileId(new AlluxioURI("/i" + i + "/j" + j)) != IdUtils.INVALID_FILE_ID); } } fsMaster.stop(); } /** * Tests file creation. */ @Test public void fileTest() throws Exception { CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes(64); AlluxioURI filePath = new AlluxioURI("/xyz"); mFileSystem.createFile(filePath, option).close(); URIStatus status = mFileSystem.getStatus(filePath); mLocalAlluxioCluster.stopFS(); fileTestUtil(status); deleteFsMasterJournalLogs(); fileTestUtil(status); } private void fileTestUtil(URIStatus status) throws AccessControlException, IOException, InvalidPathException, FileDoesNotExistException { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(1, fsMaster.getFileInfoList(mRootUri, false).size()); long fileId = fsMaster.getFileId(new AlluxioURI("/xyz")); Assert.assertTrue(fileId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(status, new URIStatus(fsMaster.getFileInfo(fileId))); fsMaster.stop(); } /** * Tests journalling of inodes being pinned. */ @Test public void pinTest() throws Exception { SetAttributeOptions setPinned = SetAttributeOptions.defaults().setPinned(true); SetAttributeOptions setUnpinned = SetAttributeOptions.defaults().setPinned(false); AlluxioURI dirUri = new AlluxioURI("/myFolder"); mFileSystem.createDirectory(dirUri); mFileSystem.setAttribute(dirUri, setPinned); AlluxioURI file0Path = new AlluxioURI("/myFolder/file0"); CreateFileOptions op = CreateFileOptions.defaults().setBlockSizeBytes(64); mFileSystem.createFile(file0Path, op).close(); mFileSystem.setAttribute(file0Path, setUnpinned); AlluxioURI file1Path = new AlluxioURI("/myFolder/file1"); mFileSystem.createFile(file1Path, op).close(); URIStatus directoryStatus = mFileSystem.getStatus(dirUri); URIStatus file0Status = mFileSystem.getStatus(file0Path); URIStatus file1Status = mFileSystem.getStatus(file1Path); mLocalAlluxioCluster.stopFS(); pinTestUtil(directoryStatus, file0Status, file1Status); deleteFsMasterJournalLogs(); pinTestUtil(directoryStatus, file0Status, file1Status); } private void pinTestUtil(URIStatus directory, URIStatus file0, URIStatus file1) throws AccessControlException, IOException, InvalidPathException, FileDoesNotExistException { FileSystemMaster fsMaster = createFsMasterFromJournal(); FileInfo info = fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI("/myFolder"))); Assert.assertEquals(directory, new URIStatus(info)); Assert.assertTrue(info.isPinned()); info = fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI("/myFolder/file0"))); Assert.assertEquals(file0, new URIStatus(info)); Assert.assertFalse(info.isPinned()); info = fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI("/myFolder/file1"))); Assert.assertEquals(file1, new URIStatus(info)); Assert.assertTrue(info.isPinned()); fsMaster.stop(); } /** * Tests directory creation. */ @Test public void directoryTest() throws Exception { AlluxioURI directoryPath = new AlluxioURI("/xyz"); mFileSystem.createDirectory(directoryPath); URIStatus status = mFileSystem.getStatus(directoryPath); mLocalAlluxioCluster.stopFS(); directoryTestUtil(status); deleteFsMasterJournalLogs(); directoryTestUtil(status); } private void directoryTestUtil(URIStatus status) throws AccessControlException, IOException, InvalidPathException, FileDoesNotExistException { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(1, fsMaster.getFileInfoList(mRootUri, false).size()); long fileId = fsMaster.getFileId(new AlluxioURI("/xyz")); Assert.assertTrue(fileId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(status, new URIStatus(fsMaster.getFileInfo(fileId))); fsMaster.stop(); } @Test public void persistDirectoryLaterTest() throws Exception { String[] directories = new String[] { "/d11", "/d11/d21", "/d11/d22", "/d12", "/d12/d21", "/d12/d22", }; CreateDirectoryOptions options = CreateDirectoryOptions.defaults().setRecursive(true).setWriteType(WriteType.MUST_CACHE); for (String directory : directories) { mFileSystem.createDirectory(new AlluxioURI(directory), options); } options.setWriteType(WriteType.CACHE_THROUGH); for (String directory : directories) { mFileSystem.createDirectory(new AlluxioURI(directory), options); } Map<String, URIStatus> directoryStatuses = new HashMap<>(); for (String directory : directories) { directoryStatuses.put(directory, mFileSystem.getStatus(new AlluxioURI(directory))); } mLocalAlluxioCluster.stopFS(); persistDirectoryLaterTestUtil(directoryStatuses); deleteFsMasterJournalLogs(); persistDirectoryLaterTestUtil(directoryStatuses); } private void persistDirectoryLaterTestUtil(Map<String, URIStatus> directoryStatuses) throws Exception { FileSystemMaster fsMaster = createFsMasterFromJournal(); for (Map.Entry<String, URIStatus> directoryStatus : directoryStatuses.entrySet()) { Assert.assertEquals( directoryStatus.getValue(), new URIStatus(fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI(directoryStatus .getKey()))))); } } /** * Tests files creation. */ @Test public void manyFileTest() throws Exception { for (int i = 0; i < 10; i++) { CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes((i + 1) * 64); mFileSystem.createFile(new AlluxioURI("/a" + i), option).close(); } mLocalAlluxioCluster.stopFS(); manyFileTestUtil(); deleteFsMasterJournalLogs(); manyFileTestUtil(); } private void manyFileTestUtil() throws Exception { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(10, fsMaster.getFileInfoList(mRootUri, false).size()); for (int k = 0; k < 10; k++) { Assert.assertTrue(fsMaster.getFileId(new AlluxioURI("/a" + k)) != IdUtils.INVALID_FILE_ID); } fsMaster.stop(); } /** * Tests reading multiple edit logs. */ @Test public void multiEditLogTest() throws Exception { for (int i = 0; i < 124; i++) { CreateFileOptions op = CreateFileOptions.defaults().setBlockSizeBytes((i + 10) / 10 * 64); mFileSystem.createFile(new AlluxioURI("/a" + i), op); } mLocalAlluxioCluster.stopFS(); multiEditLogTestUtil(); deleteFsMasterJournalLogs(); multiEditLogTestUtil(); } private void multiEditLogTestUtil() throws Exception { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(124, fsMaster.getFileInfoList(mRootUri, false).size()); for (int k = 0; k < 124; k++) { Assert.assertTrue(fsMaster.getFileId(new AlluxioURI("/a" + k)) != IdUtils.INVALID_FILE_ID); } fsMaster.stop(); } /** * Tests file and directory creation, and rename. */ @Test public void renameTest() throws Exception { for (int i = 0; i < 10; i++) { mFileSystem.createDirectory(new AlluxioURI("/i" + i)); for (int j = 0; j < 10; j++) { CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes((i + j + 1) * 64); AlluxioURI path = new AlluxioURI("/i" + i + "/j" + j); mFileSystem.createFile(path, option).close(); mFileSystem.rename(path, new AlluxioURI("/i" + i + "/jj" + j)); } mFileSystem.rename(new AlluxioURI("/i" + i), new AlluxioURI("/ii" + i)); } mLocalAlluxioCluster.stopFS(); renameTestUtil(); deleteFsMasterJournalLogs(); renameTestUtil(); } private void renameTestUtil() throws Exception { FileSystemMaster fsMaster = createFsMasterFromJournal(); long rootId = fsMaster.getFileId(mRootUri); Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID); Assert.assertEquals(10, fsMaster.getFileInfoList(mRootUri, false).size()); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { Assert.assertTrue( fsMaster.getFileId(new AlluxioURI("/ii" + i + "/jj" + j)) != IdUtils.INVALID_FILE_ID); } } fsMaster.stop(); } private List<FileInfo> lsr(FileSystemMaster fsMaster, AlluxioURI uri) throws FileDoesNotExistException, InvalidPathException, AccessControlException { List<FileInfo> files = fsMaster.getFileInfoList(uri, false); List<FileInfo> ret = new ArrayList<>(files); for (FileInfo file : files) { ret.addAll(lsr(fsMaster, new AlluxioURI(file.getPath()))); } return ret; } private void rawTableTestUtil(FileInfo fileInfo) throws Exception { FileSystemMaster fsMaster = createFsMasterFromJournal(); long fileId = fsMaster.getFileId(mRootUri); Assert.assertTrue(fileId != -1); // "ls -r /" should return 11 FileInfos, one is table root "/xyz", the others are 10 columns. Assert.assertEquals(11, lsr(fsMaster, mRootUri).size()); fileId = fsMaster.getFileId(new AlluxioURI("/xyz")); Assert.assertTrue(fileId != -1); Assert.assertEquals(fileInfo, fsMaster.getFileInfo(fileId)); fsMaster.stop(); } @Test @LocalAlluxioClusterResource.Config(confParams = { Constants.SECURITY_AUTHENTICATION_TYPE, "SIMPLE", Constants.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "true", Constants.SECURITY_GROUP_MAPPING, FakeUserGroupsMapping.FULL_CLASS_NAME}) public void setAclTest() throws Exception { AlluxioURI filePath = new AlluxioURI("/file"); ClientContext.getConf().set(Constants.SECURITY_LOGIN_USERNAME, "alluxio"); CreateFileOptions op = CreateFileOptions.defaults().setBlockSizeBytes(64); mFileSystem.createFile(filePath, op).close(); mFileSystem.setAttribute(filePath, SetAttributeOptions.defaults().setOwner("user1").setRecursive(false)); mFileSystem.setAttribute(filePath, SetAttributeOptions.defaults().setGroup("group1").setRecursive(false)); mFileSystem.setAttribute(filePath, SetAttributeOptions.defaults().setPermission((short) 0400).setRecursive(false)); URIStatus status = mFileSystem.getStatus(filePath); mLocalAlluxioCluster.stopFS(); aclTestUtil(status); deleteFsMasterJournalLogs(); aclTestUtil(status); } private void aclTestUtil(URIStatus status) throws Exception { FileSystemMaster fsMaster = createFsMasterFromJournal(); AuthenticatedClientUser.set("user1"); FileInfo info = fsMaster.getFileInfo(new AlluxioURI("/file")); Assert.assertEquals(status, new URIStatus(info)); fsMaster.stop(); } public static class FakeUserGroupsMapping implements GroupMappingService { // The fullly qualified class name of this group mapping service. This is needed to configure // the alluxio cluster public static final String FULL_CLASS_NAME = "alluxio.master.JournalIntegrationTest$FakeUserGroupsMapping"; private HashMap<String, String> mUserGroups = new HashMap<>(); public FakeUserGroupsMapping() { mUserGroups.put("alluxio", "supergroup"); mUserGroups.put("user1", "group1"); mUserGroups.put("others", "anygroup"); } @Override public List<String> getGroups(String user) throws IOException { if (mUserGroups.containsKey(user)) { return Lists.newArrayList(mUserGroups.get(user).split(",")); } return Lists.newArrayList(mUserGroups.get("others").split(",")); } @Override public void setConf(Configuration conf) throws IOException { // no-op } } }
package nl.mvdr.tinustris.engine; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import nl.mvdr.tinustris.gui.GameRenderer; import nl.mvdr.tinustris.input.InputController; import nl.mvdr.tinustris.input.InputState; import nl.mvdr.tinustris.model.FrameAndInputStatesContainer; import nl.mvdr.tinustris.model.GameState; import nl.mvdr.tinustris.netcode.InputPublisher; /** * Offers functionality for starting and stopping the game loop. * * @param <S> game state type * * @author Martijn van de Rijdt */ @Slf4j @RequiredArgsConstructor @ToString public class GameLoop<S extends GameState> { /** Update rate for the game state. */ private static final double GAME_HERTZ = 60.0; /** How much time each frame should take for our target update rate, in nanoseconds. */ public static final double TIME_BETWEEN_UPDATES = 1_000_000_000 / GAME_HERTZ; /** At the very most we will update the game this many times before a new render. **/ private static final int MAX_UPDATES_BEFORE_RENDER = 5; /** Target frame rate for rendering the game. May be lower than the update rate. */ private static final double TARGET_FPS = GAME_HERTZ; /** Target time between renders, in nanoseconds. */ private static final double TARGET_TIME_BETWEEN_RENDERS = 1_000_000_000 / TARGET_FPS; /** Input controllers. */ @NonNull private final List<InputController> inputControllers; /** Game engine. */ @NonNull private final GameEngine<S> gameEngine; /** Game renderer. */ @NonNull private final GameRenderer<S> gameRenderer; /** Input publisher. */ @NonNull private final InputPublisher publisher; /** Indicates whether the game should be running. */ private boolean running; /** Indicates whether the game is paused. */ private boolean paused; /** Starts the game loop. */ public void start() { running = true; paused = false; Thread loop = new Thread(this::gameLoop, "Game loop"); loop.start(); } /** Game loop. Should be run on a dedicated thread. */ private void gameLoop() { // The moment the game state was last updated. double lastUpdateTime = System.nanoTime(); // The moment the game was last rendered. double lastRenderTime = System.nanoTime(); // Number of frames processed in the current second. int framesThisSecond = 0; // Start of the current second. int lastSecondTime = (int) (lastUpdateTime / 1_000_000_000); // Total frame counter. int totalUpdateCount = 0; S gameState = gameEngine.initGameState(); gameRenderer.render(gameState); log.info("Starting main game loop."); try { while (running && !gameState.isGameOver()) { double now = System.nanoTime(); int updateCount = 0; if (!paused) { // Do as many game updates as we need to, potentially playing catchup. while (TIME_BETWEEN_UPDATES < now - lastUpdateTime && updateCount < MAX_UPDATES_BEFORE_RENDER) { List<InputState> inputStates = retrieveAndPublishInputStates(totalUpdateCount); gameState = gameEngine.computeNextState(gameState, inputStates); lastUpdateTime += TIME_BETWEEN_UPDATES; updateCount++; totalUpdateCount++; } // If for some reason an update takes forever, we don't want to do an insane number of catchups. // If you were doing some sort of game that needed to keep EXACT time, you would get rid of this. if (now - lastUpdateTime > TIME_BETWEEN_UPDATES) { lastUpdateTime = now - TIME_BETWEEN_UPDATES; } // Render. gameRenderer.render(gameState); framesThisSecond++; lastRenderTime = now; // Log the number of frames. int thisSecond = (int) (lastUpdateTime / 1_000_000_000); if (lastSecondTime < thisSecond) { log.info("New second: {}, frames in previous second: {}, total update count: {}.", thisSecond, framesThisSecond, totalUpdateCount); framesThisSecond = 0; lastSecondTime = thisSecond; } // Yield until it has been at least the target time between renders. This saves the CPU from // hogging. while (now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES) { Thread.yield(); // This stops the app from consuming all your CPU. It makes this slightly less accurate, but is // worth it. You can remove this line and it will still work (better), your CPU just climbs on // certain OSes. Thread.sleep(1); now = System.nanoTime(); } } } } catch (RuntimeException | InterruptedException e) { // In case of InterruptedException: no need to re-interrupt the thread, it will terminate immediately. log.error("Fatal exception encountered in game loop.", e); } running = false; log.info("Finished main game loop. Final game state: " + gameState); } /** * Retrieves the current inputs for all players. * * @param updateIndex index of the current frame / update * @return inputs */ private List<InputState> retrieveAndPublishInputStates(int updateIndex) { // Get the input states. List<InputState> inputStates = inputControllers.stream() .map(InputController::getInputState) .collect(Collectors.toList()); // Publish the local input states via the publisher to any remote game instances. Map<Integer, InputState> inputStateMap = IntStream.range(0, inputStates.size()) .filter(i -> inputControllers.get(i).isLocal()) .mapToObj(Integer::valueOf) .collect(Collectors.toMap(Function.identity(), inputStates::get)); publisher.publish(new FrameAndInputStatesContainer(updateIndex, inputStateMap)); return inputStates; } /** Stops the game loop. */ public void stop() { log.info("Stopping the game."); running = false; } /** Pauses the game. */ public void pause() { log.info("Pausing the game."); paused = true; } /** Unpauses the game. */ public void unpause() { log.info("Unpausing the game."); paused = false; } /** Pauses or unpauses the game. */ public void togglePaused() { log.info("Toggling the pause."); paused = !paused; log.info("Game paused: " + paused); } }
package org.eclipse.birt.report.designer.internal.ui.dialogs; import java.util.HashMap; import java.util.List; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.ReportPlugin; import org.eclipse.birt.report.designer.util.ColorManager; import org.eclipse.birt.report.viewer.utilities.WebViewer; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.CloseWindowListener; import org.eclipse.swt.browser.StatusTextEvent; import org.eclipse.swt.browser.StatusTextListener; import org.eclipse.swt.browser.TitleEvent; import org.eclipse.swt.browser.TitleListener; import org.eclipse.swt.browser.WindowEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; /** * When tries to delete the data source and data set, if other element * references them, this dialog will show up. Click the node and position the * node in editor to choose the node to be deleted. * * */ public class InputParameterHtmlDialog extends Dialog { /** * The title of the dialog */ private String title; /** * Default dialog title */ public static final String TITLE = Messages.getString( "InputParameterDailog.dialog.title" ); //$NON-NLS-1$ /** * File URI String */ private String uri; /** * Browser object */ private Browser browser; /** * Display options */ private HashMap options; /** * Taget Browser object */ //private Browser target; // parameter viewer model. public static final String VIEWER_PARAMETER = "parameter"; //$NON-NLS-1$ // frameset viewer model. public static final String VIEWER_FRAMESET = "frameset"; //$NON-NLS-1$ // running viewer model. public static final String VIEWER_RUN = "run"; //$NON-NLS-1$ // return from Browser Closed public static final int RETURN_CODE_BROWSER_CLOSED = 1001; // status text for Close event public static final String STATUS_CLOSE = "close"; //$NON-NLS-1$ // status text for Cancel event public static final String STATUS_CANCEL = "cancel"; //$NON-NLS-1$ /** * Constructor. * * @param parent * The parent shell * @param title * The title of the dialog */ public InputParameterHtmlDialog( Shell parent, String title, String uri, Browser target ) { super( parent ); this.title = title; this.uri = uri; //this.target = target; } /** * Self-defined string escaper */ protected String stringEscape( String string ) { return string.replaceAll( "&", "&&" ); //$NON-NLS-1$ //$NON-NLS-2$ } /** * override the super method. * * @param parent * The parent */ protected Control createButtonBar( Composite parent ) { return parent; } /** * Creates the dialog area. * * @param parent * The parent */ protected Control createDialogArea( Composite parent ) { parent.setBackground( ColorManager.getColor( 219, 228, 238 ) ); Composite composite = (Composite) super.createDialogArea( parent ); GridData gd = new GridData( ); gd.widthHint = 520; gd.heightHint = 395; composite.setLayoutData( gd ); GridLayout layout = new GridLayout( ); layout.numColumns = 1; layout.verticalSpacing = 0; layout.horizontalSpacing = 0; layout.marginHeight = 0; layout.marginWidth = 0; composite.setLayout( layout ); browser = new Browser( composite, SWT.NONE ); gd = new GridData( GridData.FILL_BOTH ); gd.horizontalSpan = 1; browser.setLayoutData( gd ); // Listen window close event browser.addCloseWindowListener( new CloseWindowListener( ) { public void close( final WindowEvent event ) { ( (Browser) event.widget ).getShell( ).close( ); List parameters = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .getParameters( ) .getContents( ); if ( parameters != null && parameters.size( ) > 0 ) { setReturnCode( RETURN_CODE_BROWSER_CLOSED ); } } } ); // Listen window status changed event browser.addStatusTextListener( new StatusTextListener( ) { public void changed( StatusTextEvent event ) { if ( STATUS_CLOSE.equalsIgnoreCase( event.text ) ) { ( (Browser) event.widget ).getShell( ).close( ); List parameters = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .getParameters( ) .getContents( ); if ( parameters != null && parameters.size( ) > 0 ) { // refresh the report setReturnCode( RETURN_CODE_BROWSER_CLOSED ); } } else if ( STATUS_CANCEL.equalsIgnoreCase( event.text ) ) { // If fire cancel event, close parameter dialog directly if ( !( (Browser) event.widget ).getShell( ).isDisposed( ) ) ( (Browser) event.widget ).getShell( ).close( ); } } } ); browser.addTitleListener( new TitleListener( ) { public void changed( TitleEvent event ) { if ( STATUS_CANCEL.equalsIgnoreCase( event.title ) ) { // If fire cancel event, close parameter dialog directly if ( !( (Browser) event.widget ).getShell( ).isDisposed( ) ) ( (Browser) event.widget ).getShell( ).close( ); } } } ); display( ); return composite; } /** * Refresh swt browser */ public void display( ) { if ( browser != null && uri != null && uri.length( ) > 0 ) { if ( this.options == null ) { this.options = new HashMap( ); this.options.put( WebViewer.SERVLET_NAME_KEY, VIEWER_PARAMETER ); this.options.put( WebViewer.FORMAT_KEY, WebViewer.HTML ); } this.options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ).getResourceFolder( ) ); WebViewer.display( uri, browser, this.options ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.dialogs.BaseDialog#initDialog() */ protected boolean initDialog( ) { return true; } /** * Configures the given shell in preparation for opening this window in it. * <p> * The <code>BaseDialog</code> overrides this framework method sets in * order to set the title of the dialog. * </p> * * @param shell * the shell */ protected void configureShell( Shell shell ) { super.configureShell( shell ); if ( title != null ) { shell.setText( title ); } } /** * Sets the title of the dialog */ public void setTitle( String newTitle ) { title = newTitle; if ( getShell( ) != null ) { getShell( ).setText( newTitle ); } } /** * Gets the title of the dialog * * @return Returns the title. */ public String getTitle( ) { return title; } public String getUri( ) { return uri; } public void setUri( String uri ) { this.uri = uri; } }
package org.eclipse.smarthome.io.rest.core.internal.extensions; import java.net.URI; import java.net.URISyntaxException; import java.text.Collator; import java.util.Comparator; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Stream; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; import org.eclipse.smarthome.core.auth.Role; import org.eclipse.smarthome.core.common.ThreadPoolManager; import org.eclipse.smarthome.core.events.Event; import org.eclipse.smarthome.core.events.EventPublisher; import org.eclipse.smarthome.core.extension.Extension; import org.eclipse.smarthome.core.extension.ExtensionEventFactory; import org.eclipse.smarthome.core.extension.ExtensionService; import org.eclipse.smarthome.core.extension.ExtensionType; import org.eclipse.smarthome.io.rest.JSONResponse; import org.eclipse.smarthome.io.rest.LocaleUtil; import org.eclipse.smarthome.io.rest.RESTResource; import org.eclipse.smarthome.io.rest.Stream2JSONInputStream; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** * This class acts as a REST resource for extensions and provides methods to install and uninstall them. * * @author Kai Kreuzer - Initial contribution and API * @author Franck Dechavanne - Added DTOs to ApiResponses */ @Path(ExtensionResource.PATH_EXTENSIONS) @RolesAllowed({ Role.ADMIN }) @Api(value = ExtensionResource.PATH_EXTENSIONS) @Component(service = { RESTResource.class, ExtensionResource.class }) public class ExtensionResource implements RESTResource { private static final String THREAD_POOL_NAME = "extensionService"; public static final String PATH_EXTENSIONS = "extensions"; private final Logger logger = LoggerFactory.getLogger(ExtensionResource.class); private final Set<ExtensionService> extensionServices = new CopyOnWriteArraySet<>(); private EventPublisher eventPublisher; @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) protected void addExtensionService(ExtensionService featureService) { this.extensionServices.add(featureService); } protected void removeExtensionService(ExtensionService featureService) { this.extensionServices.remove(featureService); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) protected void setEventPublisher(EventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } protected void unsetEventPublisher(EventPublisher eventPublisher) { this.eventPublisher = null; } @Context UriInfo uriInfo; @GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get all extensions.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class) }) public Response getExtensions(@HeaderParam("Accept-Language") @ApiParam(value = "language") String language) { logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath()); Locale locale = LocaleUtil.getLocale(language); return Response.ok(new Stream2JSONInputStream(getAllExtensions(locale))).build(); } @GET @Path("/types") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get all extension types.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class) }) public Response getTypes(@HeaderParam("Accept-Language") @ApiParam(value = "language") String language) { logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath()); Locale locale = LocaleUtil.getLocale(language); Stream<ExtensionType> extensionTypeStream = getAllExtensionTypes(locale).stream().distinct(); return Response.ok(new Stream2JSONInputStream(extensionTypeStream)).build(); } @GET @Path("/{extensionId: [a-zA-Z_0-9-]*}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get extension with given ID.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class), @ApiResponse(code = 404, message = "Not found") }) public Response getById(@HeaderParam("Accept-Language") @ApiParam(value = "language") String language, @PathParam("extensionId") @ApiParam(value = "extension ID", required = true) String extensionId) { logger.debug("Received HTTP GET request at '{}'.", uriInfo.getPath()); Locale locale = LocaleUtil.getLocale(language); ExtensionService extensionService = getExtensionService(extensionId); Extension responseObject = extensionService.getExtension(extensionId, locale); if (responseObject != null) { return Response.ok(responseObject).build(); } return Response.status(404).build(); } @POST @Path("/{extensionId: [a-zA-Z_0-9-:]*}/install") @ApiOperation(value = "Installs the extension with the given ID.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response installExtension( final @PathParam("extensionId") @ApiParam(value = "extension ID", required = true) String extensionId) { ThreadPoolManager.getPool(THREAD_POOL_NAME).submit(() -> { try { ExtensionService extensionService = getExtensionService(extensionId); extensionService.install(extensionId); } catch (Exception e) { logger.error("Exception while installing extension: {}", e.getMessage()); postFailureEvent(extensionId, e.getMessage()); } }); return Response.ok().build(); } @POST @Path("/url/{url}/install") @ApiOperation(value = "Installs the extension from the given URL.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "The given URL is malformed or not valid.") }) public Response installExtensionByURL( final @PathParam("url") @ApiParam(value = "extension install URL", required = true) String url) { try { URI extensionURI = new URI(url); String extensionId = getExtensionId(extensionURI); installExtension(extensionId); } catch (URISyntaxException | IllegalArgumentException e) { logger.error("Exception while parsing the extension URL '{}': {}", url, e.getMessage()); return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "The given URL is malformed or not valid."); } return Response.ok().build(); } @POST @Path("/{extensionId: [a-zA-Z_0-9-:]*}/uninstall") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response uninstallExtension( final @PathParam("extensionId") @ApiParam(value = "extension ID", required = true) String extensionId) { ThreadPoolManager.getPool(THREAD_POOL_NAME).submit(() -> { try { ExtensionService extensionService = getExtensionService(extensionId); extensionService.uninstall(extensionId); } catch (Exception e) { logger.error("Exception while uninstalling extension: {}", e.getMessage()); postFailureEvent(extensionId, e.getMessage()); } }); return Response.ok().build(); } private void postFailureEvent(String extensionId, String msg) { if (eventPublisher != null) { Event event = ExtensionEventFactory.createExtensionFailureEvent(extensionId, msg); eventPublisher.post(event); } } @Override public boolean isSatisfied() { return !extensionServices.isEmpty(); } private Stream<Extension> getAllExtensions(Locale locale) { return extensionServices.stream().map(s -> s.getExtensions(locale)).flatMap(l -> l.stream()); } private Set<ExtensionType> getAllExtensionTypes(Locale locale) { final Collator coll = Collator.getInstance(locale); coll.setStrength(Collator.PRIMARY); Set<ExtensionType> ret = new TreeSet<>(new Comparator<ExtensionType>() { @Override public int compare(ExtensionType o1, ExtensionType o2) { return coll.compare(o1.getLabel(), o2.getLabel()); } }); for (ExtensionService extensionService : extensionServices) { ret.addAll(extensionService.getTypes(locale)); } return ret; } private ExtensionService getExtensionService(final String extensionId) { for (ExtensionService extensionService : extensionServices) { for (Extension extension : extensionService.getExtensions(Locale.getDefault())) { if (extensionId.equals(extension.getId())) { return extensionService; } } } throw new IllegalArgumentException("No extension service registered for " + extensionId); } private String getExtensionId(URI extensionURI) { for (ExtensionService extensionService : extensionServices) { String extensionId = extensionService.getExtensionId(extensionURI); if (StringUtils.isNotBlank(extensionId)) { return extensionId; } } throw new IllegalArgumentException("No extension service registered for URI " + extensionURI); } }
// My Answer for CodeIQ Q431 //CodeIQ Q431 // Quiz-Title: Restricted Words // Hello World // PerlqqqwRuby%Q%q%w // AppleScript(osascript)/C/C++/C#/Clojure/D/Erlang/Fortran/Go/Groovy/Haskell/ // Hello Algorithm/HSP/Java/JavaScript(Node.js)/Kuin/Lisp/Lua/OCaml/Pascal/ // Perl/PHP/Pike/Python/R/Ruby/Scala/Scheme/Smalltalk/VB.Net // Java package codeiq; class JavaHelloWorld { public static void main(String[] args) { int one = (int)Math.signum(Math.PI); int two = one + one; int four = two + two; StringBuilder sb = new StringBuilder(new JavaHelloWorld().getClass().getName()); sb.delete(one - one, sb.length() - four - four - two); sb.insert(one + four, new java.util.Date().toString().charAt(one + two)); System.out.println(sb.toString()); } }
package com.worth.ifs.competitionsetup.service; import com.worth.ifs.application.resource.QuestionResource; import com.worth.ifs.application.service.QuestionService; import com.worth.ifs.competitionsetup.model.Question; import com.worth.ifs.form.resource.FormInputResource; import com.worth.ifs.form.resource.FormInputScope; import com.worth.ifs.form.service.FormInputService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CompetitionSetupQuestionServiceImpl implements CompetitionSetupQuestionService { private static final Log LOG = LogFactory.getLog(CompetitionSetupQuestionServiceImpl.class); @Autowired private QuestionService questionService; @Autowired private FormInputService formInputService; private final Long fileUploadId = 4L; private final Long assessorScoreId = 23L; @Override public void updateQuestion(Question question) { QuestionResource questionResource = questionService.getById(question.getId()); List<FormInputResource> formInputResources = formInputService.findApplicationInputsByQuestion(question.getId()); List<FormInputResource> formInputAssessmentResources = formInputService.findAssessmentInputsByQuestion(question.getId()); questionResource.setName(question.getTitle()); questionResource.setDescription(question.getSubTitle()); questionService.save(questionResource); FormInputResource formInputResource = new FormInputResource(); Optional<FormInputResource> result = formInputResources.stream().filter(formInput -> !formInput.getFormInputType().equals(4L)).findFirst(); if(result.isPresent()) { formInputResource = result.get(); } else { //set default values if needed formInputResource.setQuestion(question.getId()); formInputResource.setScope(FormInputScope.APPLICATION); formInputResource.setFormInputType(2L); } formInputResource.setGuidanceQuestion(question.getGuidanceTitle()); formInputResource.setGuidanceAnswer(question.getGuidance()); formInputResource.setWordCount(question.getMaxWords()); formInputService.save(formInputResource); handleAppendix(question, formInputResources, questionResource, formInputResource); handleAssessorScore(question, formInputAssessmentResources, questionResource, formInputResource); } private void handleAppendix(Question question, List<FormInputResource> formInputResources, QuestionResource questionResource, FormInputResource formInputResource) { if(question.getAppendix()) { //check if it's there otherwise add if(!hasAppendix(formInputResources)) { FormInputResource appendix = new FormInputResource(); appendix.setFormInputType(fileUploadId); appendix.setGuidanceQuestion("What should I include in the appendix?"); appendix.setGuidanceAnswer("<p>You may include an appendix of additional information to support the question.</p>" + "<p>You may include, for example, a Gantt chart or project management structure.</p>" + "<p>The appendix should:</p>" + "<ul class=\\\"list-bullet\\\"><li>be in a portable document format (.pdf)</li>" + "<li>be readable with 100% magnification</li>" + "<li>contain your application number and project title at the top</li>" + "<li>not be any longer than 6 sides of A4. Longer appendices will only have the first 6 pages assessed</li><" + "li>be less than 1mb in size</li>" + "</ul>"); appendix.setDescription("Appendix"); appendix.setIncludedInApplicationSummary(true); appendix.setQuestion(questionResource.getId()); appendix.setCompetition(formInputResource.getCompetition()); appendix.setScope(FormInputScope.APPLICATION); appendix.setPriority(formInputResource.getPriority() + 1); appendix.setWordCount(null); formInputService.save(appendix); } } else { //check if it's there then delete if(hasAppendix(formInputResources)) { Long appendixId = formInputResources .stream() .filter(formInput -> formInput.getFormInputType().equals(fileUploadId)).findFirst() .get() .getId(); formInputService.delete(appendixId); } } } private Boolean hasAppendix(List<FormInputResource> formInputResources) { return checkFormInputsForType(formInputResources, fileUploadId); } private void handleAssessorScore(Question question, List<FormInputResource> formInputResources, QuestionResource questionResource, FormInputResource formInputResource) { if(question.getScored()) { //check if it's there otherwise add if(!hasAssessorScore(formInputResources)) { FormInputResource assessorScore = new FormInputResource(); assessorScore.setFormInputType(assessorScoreId); assessorScore.setGuidanceQuestion(null); assessorScore.setGuidanceAnswer(null); assessorScore.setDescription("Question score"); assessorScore.setIncludedInApplicationSummary(false); assessorScore.setQuestion(questionResource.getId()); assessorScore.setCompetition(formInputResource.getCompetition()); assessorScore.setScope(FormInputScope.ASSESSMENT); assessorScore.setPriority(0); assessorScore.setWordCount(null); formInputService.save(assessorScore); } } else { //check if it's there then delete if(hasAssessorScore(formInputResources)) { Long scoreId = formInputResources .stream() .filter(formInput -> formInput.getScope() == FormInputScope.ASSESSMENT && formInput.getFormInputType().equals(assessorScoreId)) .findFirst() .get() .getId(); formInputService.delete(scoreId); } } } private Boolean hasAssessorScore(List<FormInputResource> formInputResources) { return checkFormInputsForType(formInputResources, assessorScoreId); } private Boolean checkFormInputsForType(List<FormInputResource> formInputResources, Long typeId) { return formInputResources.stream().anyMatch(formInput -> formInput.getFormInputType().equals(typeId)); } }
package org.geomajas.plugin.geocoder.gwt.example.client; import com.google.gwt.core.client.GWT; import com.smartgwt.client.data.DataSource; import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.Record; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; import com.smartgwt.client.widgets.layout.VLayout; import org.geomajas.gwt.client.util.WidgetLayout; import org.geomajas.gwt.client.widget.MapWidget; import org.geomajas.gwt.client.widget.Toolbar; import org.geomajas.gwt.example.base.SamplePanel; import org.geomajas.gwt.example.base.SamplePanelFactory; import org.geomajas.plugin.geocoder.client.GeocoderWidget; import org.geomajas.plugin.geocoder.gwt.example.client.i18n.GeocoderMessages; /** * Sample to demonstrate use of the geocoder plug-in. * * @author Joachim Van der Auwera */ public class GeocoderPanel extends SamplePanel { public static final String TITLE = "Geocoder"; public static final GeocoderMessages MESSAGES = GWT.create(GeocoderMessages.class); private static final String FIELD_LABEL = "label"; private static final String FIELD_REGEX = "regex"; public static final SamplePanelFactory FACTORY = new SamplePanelFactory() { public SamplePanel createPanel() { return new GeocoderPanel(); } }; /** * @return The viewPanel Canvas */ public Canvas getViewPanel() { VLayout layout = new VLayout(); layout.setWidth100(); layout.setHeight100(); // @extract-start createGwtWidget, Create GWT widget in toolbar final MapWidget map = new MapWidget("mapGeocoderOsm", "appGeocoder"); final Toolbar toolbar = new Toolbar(map); // @extract-skip-start toolbar.setButtonSize(WidgetLayout.toolbarLargeButtonSize); // @extract-skip-end final GeocoderWidget geocoderWidget = new GeocoderWidget(map, "description", "Geocoder"); toolbar.addMember(geocoderWidget); // @extract-end SelectItem geocoderSource = new SelectItem("geocoderSource", ""); geocoderSource.setDefaultToFirstOption(true); geocoderSource.setOptionDataSource(getGeocoderSelectDataSource()); geocoderSource.setDisplayField(FIELD_LABEL); geocoderSource.setValueField(FIELD_REGEX); geocoderSource.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent event) { geocoderWidget.setServicePattern((String) event.getValue()); } }); DynamicForm geocoderSourceForm = new DynamicForm(); geocoderSourceForm.setFields(geocoderSource); toolbar.addMember(geocoderSourceForm); layout.addMember(toolbar); layout.addMember(map); return layout; } private DataSource getGeocoderSelectDataSource() { DataSource dataSource = new DataSource(); dataSource.setClientOnly(true); DataSourceField label = new DataSourceTextField(FIELD_LABEL); DataSourceField regex = new DataSourceTextField(FIELD_REGEX); dataSource.setFields(label, regex); Record record; record = new Record(); record.setAttribute(FIELD_LABEL, "all"); record.setAttribute(FIELD_REGEX, ".*"); dataSource.addData(record); record = new Record(); record.setAttribute(FIELD_LABEL, "Yahoo! PlaceFinder"); record.setAttribute(FIELD_REGEX, "yahoo"); dataSource.addData(record); record = new Record(); record.setAttribute(FIELD_LABEL, "GeoNames"); record.setAttribute(FIELD_REGEX, "geonames"); dataSource.addData(record); record = new Record(); record.setAttribute(FIELD_LABEL, "offline"); record.setAttribute(FIELD_REGEX, "offline"); dataSource.addData(record); return dataSource; } public String getDescription() { return MESSAGES.geocoderDescription(); } public String[] getConfigurationFiles() { return new String[]{"classpath:org/geomajas/plugin/geocoder/gwt/example/geocoder.xml", "classpath:org/geomajas/plugin/geocoder/gwt/example/appGeocoder.xml", "classpath:org/geomajas/plugin/geocoder/gwt/example/mapGeocoderOsm.xml", "classpath:org/geomajas/gwt/example/base/layerOsm.xml"}; } public String ensureUserLoggedIn() { return "luc"; } }
package org.xwiki.filter.xml.internal.parser; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Stack; import java.util.regex.Matcher; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang3.ArrayUtils; import org.apache.xerces.parsers.XMLParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xwiki.component.util.ReflectionUtils; import org.xwiki.filter.FilterDescriptor; import org.xwiki.filter.FilterElementDescriptor; import org.xwiki.filter.FilterElementParameterDescriptor; import org.xwiki.filter.FilterEventParameters; import org.xwiki.filter.UnknownFilter; import org.xwiki.filter.xml.XMLConfiguration; import org.xwiki.filter.xml.internal.XMLUtils; import org.xwiki.filter.xml.internal.parameter.ParameterManager; import org.xwiki.properties.ConverterManager; import org.xwiki.properties.converter.ConversionException; import org.xwiki.xml.Sax2Dom; /** * Default implementation of {@link XMLParser}. * * @version $Id$ * @since 5.2M1 */ // TODO: move from ContentHandler to XMLEventConsumer or XMLEventWriter public class DefaultXMLParser extends DefaultHandler implements ContentHandler { /** * Logging helper object. */ protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultXMLParser.class); private ParameterManager parameterManager; private ConverterManager stringConverter; private FilterDescriptor filterDescriptor; private Object filter; private Stack<Block> blockStack = new Stack<Block>(); private int elementDepth = 0; private StringBuilder content; private XMLConfiguration configuration; public static class Block { public String name; public FilterElementDescriptor filterElement; public boolean beginSent = false; public List<Object> parameters = new ArrayList<Object>(); public FilterEventParameters namedParameters = new FilterEventParameters(); public Sax2Dom parametersDOMBuilder; public int elementDepth; private Object[] parametersTable; public Block(String name, FilterElementDescriptor listenerElement, int elementDepth) { this.name = name; this.filterElement = listenerElement; this.elementDepth = elementDepth; } public boolean isContainer() { return this.filterElement == null || this.filterElement.getBeginMethod() != null; } public void setParameter(String name, Object value) { this.namedParameters.put(name, value); } public void setParameter(int index, Object value) { for (int i = this.parameters.size(); i <= index; ++i) { this.parameters.add(this.filterElement.getParameters()[i].getDefaultValue()); } this.parameters.set(index, value); this.parametersTable = null; } public List<Object> getParametersList() { return this.parameters; } public Object[] getParametersTable() { if (this.parametersTable == null) { if (this.parameters.isEmpty()) { this.parametersTable = ArrayUtils.EMPTY_OBJECT_ARRAY; } this.parametersTable = this.parameters.toArray(); } return this.parametersTable; } public void fireBeginEvent(Object listener) throws SAXException { if (this.filterElement != null) { fireEvent(this.filterElement.getBeginMethod(), listener); } else if (listener instanceof UnknownFilter) { try { ((UnknownFilter) listener).beginUnknwon(this.name, this.namedParameters); } catch (Exception e) { throw new SAXException("Failed to invoke unknown event with name [" + this.name + "] and parameters [" + this.namedParameters + "]", e); } } this.beginSent = true; } public void fireEndEvent(Object listener) throws SAXException { if (this.filterElement != null) { fireEvent(this.filterElement.getEndMethod(), listener); } else if (listener instanceof UnknownFilter) { try { ((UnknownFilter) listener).endUnknwon(this.name, this.namedParameters); } catch (Exception e) { throw new SAXException("Failed to invoke unknown event with name [" + this.name + "] and parameters [" + this.namedParameters + "]", e); } } } public void fireOnEvent(Object listener) throws SAXException { if (this.filterElement != null) { fireEvent(this.filterElement.getOnMethod(), listener); } else if (listener instanceof UnknownFilter) { try { ((UnknownFilter) listener).onUnknwon(this.name, this.namedParameters); } catch (Exception e) { throw new SAXException("Failed to invoke unknown event with name [" + this.name + "] and parameters [" + this.namedParameters + "]", e); } } } private void fireEvent(Method eventMethod, Object listener) throws SAXException { Object[] parameters = getParametersTable(); Class<?>[] methodParameters = eventMethod.getParameterTypes(); Object[] properParameters; // Missing parameters if (methodParameters.length > parameters.length) { properParameters = new Object[methodParameters.length]; for (int i = 0; i < methodParameters.length; ++i) { if (i < parameters.length) { properParameters[i] = parameters[i]; } else { properParameters[i] = this.filterElement.getParameters()[i].getDefaultValue(); } } } else { properParameters = parameters; } // Invalid primitive for (int i = 0; i < properParameters.length; ++i) { Object parameter = properParameters[i]; if (parameter == null) { Class<?> methodParameter = methodParameters[i]; if (methodParameter.isPrimitive()) { properParameters[i] = XMLUtils.emptyValue(methodParameter); } } } // Send event try { eventMethod.invoke(listener, properParameters); } catch (InvocationTargetException e) { throw new SAXException("Event [" + eventMethod + "] thrown exception", e.getCause() instanceof Exception ? (Exception) e.getCause() : e); } catch (Exception e) { throw new SAXException("Failed to invoke event [" + eventMethod + "]", e); } } } public DefaultXMLParser(Object listener, FilterDescriptor listenerDescriptor, ConverterManager stringConverter, ParameterManager parameterManager, XMLConfiguration configuration) { this.filter = listener; this.filterDescriptor = listenerDescriptor; this.stringConverter = stringConverter; this.parameterManager = parameterManager; this.configuration = configuration != null ? configuration : new XMLConfiguration(); } private boolean onBlockChild() { boolean result; if (!this.blockStack.isEmpty()) { Block currentBlock = this.blockStack.peek(); return currentBlock.elementDepth == (this.elementDepth - 1); } else { result = false; } return result; } private boolean onBlockElement(String elementName) { boolean result; if (!this.blockStack.isEmpty()) { Block currentBlock = this.blockStack.peek(); result = (this.elementDepth - currentBlock.elementDepth <= 1) && !this.configuration.getElementParameters().equals(elementName); } else { result = true; } return result; } private boolean onParametersElement(String elementName) { return onBlockChild() && this.configuration.getElementParameters().equals(elementName); } private int extractParameterIndex(String elementName) { Matcher matcher = XMLUtils.INDEX_PATTERN.matcher(elementName); matcher.find(); return Integer.valueOf(matcher.group(1)); } private boolean isReservedBlockAttribute(String attributeName) { return this.configuration.getAttributeBlockName().equals(attributeName) || this.configuration.getAttributeParameterName().equals(attributeName); } private void setParameter(Block block, String name, Object value, boolean attribute) throws SAXException { if (XMLUtils.INDEX_PATTERN.matcher(name).matches()) { int parameterIndex = extractParameterIndex(name); if (block.filterElement != null && block.filterElement.getParameters().length > parameterIndex) { FilterElementParameterDescriptor<?> filterParameter = block.filterElement.getParameters()[parameterIndex]; setParameter(block, filterParameter, value); } else { LOGGER.warn("Unknown element parameter [{}] (=[{}]) in block [{}]", name, value, block.name); block.setParameter(name, value); } } else if (!attribute || !isReservedBlockAttribute(name)) { FilterElementParameterDescriptor<?> filterParameter = block.filterElement != null ? block.filterElement.getParameter(name) : null; if (filterParameter != null) { setParameter(block, filterParameter, value); } else { LOGGER.warn("Unknown element parameter [{}] (=[{}]) in block [{}]", name, value, block.name); block.setParameter(name, value); } } } private void setParameter(Block block, FilterElementParameterDescriptor<?> filterParameter, Object value) throws SAXException { Type type = filterParameter.getType(); if (value instanceof Element) { try { block.setParameter(filterParameter.getIndex(), unserializeParameter(type, (Element) value)); } catch (ClassNotFoundException e) { throw new SAXException("Failed to parse property", e); } } else if (value instanceof String) { String stringValue = (String) value; Class<?> typeClass = ReflectionUtils.getTypeClass(type); if (typeClass == String.class || typeClass == Object.class) { block.setParameter(filterParameter.getIndex(), stringValue); } else { try { block.setParameter(filterParameter.getIndex(), this.stringConverter.convert(type, value)); } catch (ConversionException e) { if (stringValue.isEmpty()) { block.setParameter(filterParameter.getIndex(), XMLUtils.emptyValue(typeClass)); } LOGGER.warn("Unsuported conversion to type [{}] for value [{}]", type, value); } } } else { LOGGER.warn("Unsuported type [{}] for value [{}]", value.getClass(), value); } } private Object unserializeParameter(Type type, Element element) throws ClassNotFoundException { if (element.hasAttribute(this.configuration.getAttributeParameterType())) { String typeString = element.getAttribute(this.configuration.getAttributeParameterType()); return this.parameterManager.unSerialize( Class.forName(typeString, true, Thread.currentThread().getContextClassLoader()), element); } return this.parameterManager.unSerialize(type, element); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { Block currentBlock = this.blockStack.isEmpty() ? null : this.blockStack.peek(); if (onBlockElement(qName)) { if (currentBlock != null) { // send previous event if (!currentBlock.beginSent) { currentBlock.fireBeginEvent(this.filter); } } // push new event Block block = getBlock(qName, attributes); this.blockStack.push(block); if (!block.isContainer() && block.filterElement != null && block.filterElement.getParameters().length > 0) { this.content = new StringBuilder(); } // Extract simple parameters from attributes for (int i = 0; i < attributes.getLength(); ++i) { String attributeName = attributes.getQName(i); setParameter(block, attributeName, attributes.getValue(i), true); } } else { if (onParametersElement(qName)) { // starting a new block parameter if (currentBlock.filterElement != null) { try { currentBlock.parametersDOMBuilder = new Sax2Dom(); } catch (ParserConfigurationException e) { throw new SAXException("Failed to create new Sax2Dom handler", e); } currentBlock.parametersDOMBuilder.startDocument(); } } if (currentBlock.parametersDOMBuilder != null) { currentBlock.parametersDOMBuilder.startElement(uri, localName, qName, attributes); } } ++this.elementDepth; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { Block currentBlock = this.blockStack.isEmpty() ? null : this.blockStack.peek(); --this.elementDepth; if (onBlockElement(qName)) { Block block = this.blockStack.pop(); // Flush pending begin event and send end event or send on event if (block.isContainer()) { if (!block.beginSent) { block.fireBeginEvent(this.filter); } block.fireEndEvent(this.filter); } else { if (block.getParametersList().size() == 0 && this.filterDescriptor.getElement(qName).getParameters().length > 0) { if (this.content != null && this.content.length() > 0) { block.setParameter( 0, this.stringConverter.convert( this.filterDescriptor.getElement(qName).getParameters()[0].getType(), this.content.toString())); this.content = null; } } block.fireOnEvent(this.filter); } } else if (currentBlock.parametersDOMBuilder != null) { currentBlock.parametersDOMBuilder.endElement(uri, localName, qName); if (onParametersElement(qName)) { currentBlock.parametersDOMBuilder.endDocument(); Element rootElement = currentBlock.parametersDOMBuilder.getRootElement(); NodeList parameterNodes = rootElement.getChildNodes(); for (int i = 0; i < parameterNodes.getLength(); ++i) { Node parameterNode = parameterNodes.item(i); if (parameterNode.getNodeType() == Node.ELEMENT_NODE) { String nodeName = parameterNode.getLocalName(); setParameter(currentBlock, nodeName, parameterNode, true); } } currentBlock.parametersDOMBuilder = null; } } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (!this.blockStack.isEmpty() && this.blockStack.peek().parametersDOMBuilder != null) { this.blockStack.peek().parametersDOMBuilder.characters(ch, start, length); } else if (this.content != null) { this.content.append(ch, start, length); } } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (!this.blockStack.isEmpty() && this.blockStack.peek().parametersDOMBuilder != null) { this.blockStack.peek().parametersDOMBuilder.ignorableWhitespace(ch, start, length); } } @Override public void skippedEntity(String name) throws SAXException { if (!this.blockStack.isEmpty() && this.blockStack.peek().parametersDOMBuilder != null) { this.blockStack.peek().parametersDOMBuilder.skippedEntity(name); } } private Block getBlock(String qName, Attributes attributes) { String blockName; if (this.configuration.getElementBlock().equals(qName)) { blockName = attributes.getValue(this.configuration.getAttributeBlockName()); } else { blockName = qName; } FilterElementDescriptor element = this.filterDescriptor.getElement(blockName); if (element == null) { LOGGER.warn("Uknown filter element [{}]", blockName); } return new Block(qName, element, this.elementDepth); } }
package org.jasig.portal; import java.io.*; import java.util.*; import java.lang.SecurityManager; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.*; import javax.servlet.http.*; import java.security.AccessController; import org.jasig.portal.services.LogService; import org.jasig.portal.jndi.JNDIManager; import com.oreilly.servlet.multipart.MultipartParser; import com.oreilly.servlet.multipart.FilePart; import com.oreilly.servlet.multipart.ParamPart; public class PortalSessionManager extends HttpServlet { public static String renderBase = "render.uP"; public static String detachBaseStart = "detach_"; private static int sizeLimit = 3000000; // Should be channel specific private static boolean initialized = false; /** * Initialize the PortalSessionManager servlet * @exception ServletException */ public void init () throws ServletException { if(!initialized) { // Retrieve the servlet configuration object from the servlet container ServletConfig sc = getServletConfig(); // Make sure the ServletConfig object is available if (sc == null) { throw new ServletException("PortalSessionManager.init(): ServletConfig object was returned as null"); } // Get the portal base directory String sPortalBaseDir = sc.getInitParameter("portalBaseDir"); // Make sure the directory is a properly formatted string sPortalBaseDir.replace('/', File.separatorChar); sPortalBaseDir.replace('\\', File.separatorChar); // Add a seperator on the end of the path if it's missing if (!sPortalBaseDir.endsWith(File.separator)) { sPortalBaseDir += File.separator; } // Make sure the portal base directory is properly set if (sPortalBaseDir == null) { throw new ServletException("PortalSessionManager.init(): portalBaseDir not found, check web.xml file"); } // Try to create a file pointing to the portal base directory File portalBaseDir = new java.io.File(sPortalBaseDir); // Make sure the directory exists if (!portalBaseDir.exists()) { throw new ServletException("PortalSessionManager.init(): Portal base directory " + sPortalBaseDir + " does not exist"); } // Set the portal base directory GenericPortalBean.setPortalBaseDir(sPortalBaseDir); JNDIManager.initializePortalContext(); // Flag that the portal has been initialized initialized = true; // Get the SAX implementation if (System.getProperty("org.xml.sax.driver") == null) System.setProperty("org.xml.sax.driver", PropertiesManager.getProperty("org.xml.sax.driver")); // Set the UserLayoutStoreImpl try { // Should obtain implementation in a better way! GenericPortalBean.setUserLayoutStore(RdbmServices.getUserLayoutStoreImpl()); } catch (Exception e) { throw new ServletException(e); } } } /** * put your documentation comment here * @param req * @param res * @exception ServletException, IOException */ public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * put your documentation comment here * @param req * @param res * @exception ServletException, IOException */ public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // forwarding ServletContext sc = this.getServletContext(); HttpSession session = req.getSession(); if (session != null) { // LogService.instance().log(LogService.DEBUG, "PortalSessionManager::doGet() : request path \""+req.getServletPath()+"\"."); String redirectBase = null; RequestParamWrapper myReq = new RequestParamWrapper(req); myReq.setBaseRequest(req); if ((redirectBase = this.doRedirect(myReq)) != null) { // cache request sc.setAttribute("oreqp_" + session.getId(), myReq); // initial request, requeres forwarding session.setAttribute("forwarded", new Boolean(true)); // forward // LogService.instance().log(LogService.DEBUG,"PortalSessionManager::doGet() : caching request, sending redirect"); //this.getServletContext().getRequestDispatcher("/render.uP").forward(req,res); res.sendRedirect(req.getContextPath() + redirectBase); } else { // delete old request Boolean forwarded = (Boolean)session.getAttribute("forwarded"); if (forwarded != null) session.removeAttribute("forwarded"); // proceed with rendering // LogService.instance().log(LogService.DEBUG,"PortalSessionManager::doGet() : processing redirected (clean) request"); // look if the UserInstance object is already in the session, otherwise // make a new one UserInstance layout = (UserInstance)session.getAttribute("UserInstance"); if (layout == null) { layout = UserInstanceFactory.getUserInstance(myReq); session.setAttribute("UserInstance", layout); // LogService.instance().log(LogService.DEBUG,"PortalSessionManager;:doGet() : instantiating new UserInstance"); } RequestParamWrapper oreqp = null; if (forwarded != null && forwarded.booleanValue()) oreqp = (RequestParamWrapper)sc.getAttribute("oreqp_" + session.getId()); if (oreqp != null) { oreqp.setBaseRequest(req); layout.writeContent(oreqp, res, res.getWriter()); } else { layout.writeContent(myReq, res, res.getWriter()); } } } else { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h1>" + getServletConfig().getServletName() + "</h1>"); out.println("Session object is null !??"); out.println("</body></html>"); } } /** * This function determines if a given request needs to be redirected * @param req * @return */ private String doRedirect (HttpServletRequest req) { HttpSession session = req.getSession(); String redirectBase = "/" + renderBase; // default value if (session != null) { Boolean forwarded = (Boolean)session.getAttribute("forwarded"); if (forwarded != null && forwarded.booleanValue()) return null; String servletPath = req.getServletPath(); String uPFile = servletPath.substring(servletPath.lastIndexOf('/'), servletPath.length()); // redirect everything except for render.uP and detach.uP with no parameters boolean detach_mode = uPFile.startsWith("/" + detachBaseStart); if (!req.getParameterNames().hasMoreElements()) { if (servletPath.equals("/" + renderBase) || servletPath.startsWith("/" + detachBaseStart)) return null; } // the only exception to redirect is the detach if (detach_mode) redirectBase = uPFile; } // redirect by default return "/" + renderBase; } /** * RequestParamWrapper persists various information * from the source request. * Once given a "base request", it substitutes corresponding * base information with that acquired from the source. * * The following information is extracted from the source: * request parameters * path info * path translated * context path * query string * servlet path * request uri */ public class RequestParamWrapper implements HttpServletRequest, Serializable { // the request being wrapped private HttpServletRequest req; private Hashtable parameters; private String pathInfo; private String pathTranslated; private String contextPath; private String queryString; private String servletPath; private String requestURI; /** * put your documentation comment here * @param HttpServletRequest source */ public RequestParamWrapper (HttpServletRequest source) { // leech all of the information from the source request parameters = new Hashtable(); String contentType = source.getContentType(); if (contentType != null && contentType.startsWith("multipart/form-data")) { com.oreilly.servlet.multipart.Part attachmentPart; try { MultipartParser multi = new MultipartParser(source, sizeLimit, true, true); while ((attachmentPart = multi.readNextPart()) != null) { String partName = attachmentPart.getName(); if (attachmentPart.isParam()) { ParamPart parameterPart = (ParamPart)attachmentPart; String paramValue = parameterPart.getStringValue(); if (parameters.containsKey(partName)) { /* Assume they meant a multivalued tag, like a checkbox */ String[] oldValueArray = (String[])parameters.get(partName); String[] valueArray = new String[oldValueArray.length + 1]; for (int i = 0; i < oldValueArray.length; i++) { valueArray[i] = oldValueArray[i]; } valueArray[oldValueArray.length] = paramValue; parameters.put(partName, valueArray); } else { String[] valueArray = new String[1]; valueArray[0] = paramValue; parameters.put(partName, valueArray); } } else if (attachmentPart.isFile()) { FilePart filePart = (FilePart)attachmentPart; String filename = filePart.getFileName(); if (filename != null) { MultipartDataSource fileUpload = new MultipartDataSource(filePart); if (parameters.containsKey(partName)) { MultipartDataSource[] oldValueArray = (MultipartDataSource[])parameters.get(partName); MultipartDataSource[] valueArray = new MultipartDataSource[oldValueArray.length + 1]; for (int i = 0; i < oldValueArray.length; i++) { valueArray[i] = oldValueArray[i]; } valueArray[oldValueArray.length] = fileUpload; parameters.put(partName, valueArray); } else { MultipartDataSource[] valueArray = new MultipartDataSource[1]; valueArray[0] = fileUpload; parameters.put(partName, valueArray); } } } } } catch (Exception e) { LogService.instance().log(LogService.ERROR, e); } } Enumeration en = source.getParameterNames(); if (en != null) { while (en.hasMoreElements()) { String pName = (String)en.nextElement(); parameters.put(pName, source.getParameterValues(pName)); } } pathInfo = source.getPathInfo(); pathTranslated = source.getPathTranslated(); contextPath = source.getContextPath(); queryString = source.getQueryString(); servletPath = source.getServletPath(); requestURI = source.getRequestURI(); } /** * put your documentation comment here * @param base */ public void setBaseRequest (HttpServletRequest base) { this.req = base; } /** * Overloaded method * @param name * @return */ public String getParameter (String name) { String[] value_array = this.getParameterValues(name); if ((value_array != null) && (value_array.length > 0)) return value_array[0]; else return null; } /** * Overloaded method * @return */ public Enumeration getParameterNames () { return this.parameters.keys(); } /** * Return a String[] for this parameter * @param parameter name * @result String[] if parameter is not an Object[] */ public String[] getParameterValues (String name) { Object[] pars = (Object[])this.parameters.get(name); if (pars instanceof String[]) { return (String[])this.parameters.get(name); } else { return null; } } /** * Return the Object represented by this parameter name * @param parameter name * @result Object */ public Object[] getObjectParameterValues (String name) { return (Object[])this.parameters.get(name); } public String getPathInfo () { return pathInfo; } public String getPathTranslated () { return pathTranslated; } public String getContextPath () { return contextPath; } public String getQueryString () { return queryString; } public String getServletPath () { return servletPath; } public String getRequestURI () { return requestURI; } // pass through methods public String getAuthType () { return req.getAuthType(); } public Cookie[] getCookies () { return req.getCookies(); } public long getDateHeader (String name) { return req.getDateHeader(name); } public String getHeader (String name) { return req.getHeader(name); } public Enumeration getHeaders (String name) { return req.getHeaders(name); } public Enumeration getHeaderNames () { return req.getHeaderNames(); } public int getIntHeader (String name) { return req.getIntHeader(name); } public String getMethod () { return req.getMethod(); } public String getRemoteUser () { return req.getRemoteUser(); } public boolean isUserInRole (String role) { return req.isUserInRole(role); } public java.security.Principal getUserPrincipal () { return req.getUserPrincipal(); } public String getRequestedSessionId () { return req.getRequestedSessionId(); } public HttpSession getSession (boolean create) { return req.getSession(create); } public HttpSession getSession () { return req.getSession(); } public boolean isRequestedSessionIdValid () { return req.isRequestedSessionIdValid(); } public boolean isRequestedSessionIdFromCookie () { return req.isRequestedSessionIdFromCookie(); } public boolean isRequestedSessionIdFromURL () { return req.isRequestedSessionIdFromURL(); } public boolean isRequestedSessionIdFromUrl () { return req.isRequestedSessionIdFromURL(); } public Object getAttribute (String name) { return req.getAttribute(name); } public Enumeration getAttributeNames () { return req.getAttributeNames(); } public String getCharacterEncoding () { return req.getCharacterEncoding(); } public int getContentLength () { return req.getContentLength(); } public String getContentType () { return req.getContentType(); } public ServletInputStream getInputStream () throws IOException { return req.getInputStream(); } public String getProtocol () { return req.getProtocol(); } public String getScheme () { return req.getScheme(); } public String getServerName () { return req.getServerName(); } public int getServerPort () { return req.getServerPort(); } public BufferedReader getReader () throws IOException { return req.getReader(); } public String getRemoteAddr () { return req.getRemoteAddr(); } public String getRemoteHost () { return req.getRemoteHost(); } public void setAttribute (String name, Object o) { req.setAttribute(name, o); } public void removeAttribute (String name) { req.removeAttribute(name); } public Locale getLocale () { return req.getLocale(); } public Enumeration getLocales () { return req.getLocales(); } public boolean isSecure () { return req.isSecure(); } public RequestDispatcher getRequestDispatcher (String path) { return req.getRequestDispatcher(path); } public String getRealPath (String path) { throw new RuntimeException("HttpServletRequest.getRealPath(String path) is deprectated! Use ServletContext.getRealPath(String path) instead."); } } }
package io.quarkus.resteasy.server.common.deployment; import static io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT; import static io.quarkus.runtime.annotations.ConfigPhase.BUILD_TIME; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationTarget.Kind; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.MethodParameterInfo; import org.jboss.jandex.Type; import org.jboss.logging.Logger; import org.jboss.resteasy.api.validation.ResteasyConstraintViolation; import org.jboss.resteasy.api.validation.ViolationReport; import org.jboss.resteasy.microprofile.config.FilterConfigSource; import org.jboss.resteasy.microprofile.config.ServletConfigSource; import org.jboss.resteasy.microprofile.config.ServletContextConfigSource; import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.arc.deployment.AnnotationsTransformerBuildItem; import io.quarkus.arc.deployment.BeanArchiveIndexBuildItem; import io.quarkus.arc.deployment.BeanContainerBuildItem; import io.quarkus.arc.deployment.BeanDefiningAnnotationBuildItem; import io.quarkus.arc.deployment.UnremovableBeanBuildItem; import io.quarkus.arc.deployment.UnremovableBeanBuildItem.BeanClassNameExclusion; import io.quarkus.arc.processor.AnnotationsTransformer; import io.quarkus.arc.processor.BuiltinScope; import io.quarkus.arc.processor.DotNames; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.Record; import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.ProxyUnwrapperBuildItem; import io.quarkus.deployment.builditem.substrate.ReflectiveClassBuildItem; import io.quarkus.deployment.builditem.substrate.ReflectiveHierarchyBuildItem; import io.quarkus.deployment.builditem.substrate.RuntimeInitializedClassBuildItem; import io.quarkus.deployment.builditem.substrate.SubstrateConfigBuildItem; import io.quarkus.deployment.builditem.substrate.SubstrateProxyDefinitionBuildItem; import io.quarkus.deployment.builditem.substrate.SubstrateResourceBuildItem; import io.quarkus.jaxb.deployment.JaxbEnabledBuildItem; import io.quarkus.resteasy.common.deployment.JaxrsProvidersToRegisterBuildItem; import io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.ResteasyCommonConfig; import io.quarkus.resteasy.common.deployment.ResteasyDotNames; import io.quarkus.resteasy.server.common.runtime.QuarkusInjectorFactory; import io.quarkus.resteasy.server.common.runtime.ResteasyServerCommonTemplate; import io.quarkus.runtime.annotations.ConfigItem; import io.quarkus.runtime.annotations.ConfigRoot; /** * Processor that builds the RESTEasy server configuration. */ public class ResteasyServerCommonProcessor { private static final Logger log = Logger.getLogger("io.quarkus.resteasy"); private static final String JAX_RS_APPLICATION_PARAMETER_NAME = "javax.ws.rs.Application"; private static final DotName JSONB_ANNOTATION = DotName.createSimple("javax.json.bind.annotation.JsonbAnnotation"); private static final DotName[] METHOD_ANNOTATIONS = { ResteasyDotNames.GET, ResteasyDotNames.HEAD, ResteasyDotNames.DELETE, ResteasyDotNames.OPTIONS, ResteasyDotNames.PATCH, ResteasyDotNames.POST, ResteasyDotNames.PUT, }; private static final DotName[] RESTEASY_PARAM_ANNOTATIONS = { ResteasyDotNames.RESTEASY_QUERY_PARAM, ResteasyDotNames.RESTEASY_FORM_PARAM, ResteasyDotNames.RESTEASY_COOKIE_PARAM, ResteasyDotNames.RESTEASY_PATH_PARAM, ResteasyDotNames.RESTEASY_HEADER_PARAM, ResteasyDotNames.RESTEASY_MATRIX_PARAM, }; /** * JAX-RS configuration. */ ResteasyConfig resteasyConfig; ResteasyCommonConfig commonConfig; @ConfigRoot(phase = BUILD_TIME) static final class ResteasyConfig { @ConfigItem(defaultValue = "true") boolean singletonResources; /** * Set this to override the default path for JAX-RS resources if there are no * annotated application classes. */ @ConfigItem(defaultValue = "/") String path; } @BuildStep SubstrateConfigBuildItem config() { return SubstrateConfigBuildItem.builder() .addResourceBundle("messages") .build(); } @BuildStep public void build( BuildProducer<ReflectiveClassBuildItem> reflectiveClass, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy, BuildProducer<SubstrateProxyDefinitionBuildItem> proxyDefinition, BuildProducer<SubstrateResourceBuildItem> resource, BuildProducer<RuntimeInitializedClassBuildItem> runtimeClasses, BuildProducer<BytecodeTransformerBuildItem> transformers, BuildProducer<ResteasyServerConfigBuildItem> resteasyServerConfig, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, JaxrsProvidersToRegisterBuildItem jaxrsProvidersToRegisterBuildItem, CombinedIndexBuildItem combinedIndexBuildItem, BeanArchiveIndexBuildItem beanArchiveIndexBuildItem) throws Exception { IndexView index = combinedIndexBuildItem.getIndex(); resource.produce(new SubstrateResourceBuildItem("META-INF/services/javax.ws.rs.client.ClientBuilder")); Collection<AnnotationInstance> applicationPaths = index.getAnnotations(ResteasyDotNames.APPLICATION_PATH); // currently we only examine the first class that is annotated with @ApplicationPath so best // fail if the user code has multiple such annotations instead of surprising the user // at runtime if (applicationPaths.size() > 1) { throw createMultipleApplicationsException(applicationPaths); } Collection<AnnotationInstance> paths = beanArchiveIndexBuildItem.getIndex().getAnnotations(ResteasyDotNames.PATH); if (paths.isEmpty()) { // no detected @Path, bail out return; } final String path; final String appClass; if (!applicationPaths.isEmpty()) { AnnotationInstance applicationPath = applicationPaths.iterator().next(); path = applicationPath.value().asString(); appClass = applicationPath.target().asClass().name().toString(); } else { path = resteasyConfig.path; appClass = null; } Set<String> resources = new HashSet<>(); Set<DotName> pathInterfaces = new HashSet<>(); Set<ClassInfo> withoutDefaultCtor = new HashSet<>(); for (AnnotationInstance annotation : paths) { if (annotation.target().kind() == AnnotationTarget.Kind.CLASS) { ClassInfo clazz = annotation.target().asClass(); if (!Modifier.isInterface(clazz.flags())) { String className = clazz.name().toString(); resources.add(className); reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, className)); if (!clazz.hasNoArgsConstructor()) { withoutDefaultCtor.add(clazz); } } else { pathInterfaces.add(clazz.name()); } } } // look for all implementations of interfaces annotated @Path for (final DotName iface : pathInterfaces) { final Collection<ClassInfo> implementors = index.getAllKnownImplementors(iface); for (final ClassInfo implementor : implementors) { String className = implementor.name().toString(); reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, className)); resources.add(className); } } // generate default constructors for suitable concrete @Path classes that don't have them generateDefaultConstructors(transformers, withoutDefaultCtor); checkParameterNames(index); registerContextProxyDefinitions(index, proxyDefinition); registerReflectionForSerialization(reflectiveClass, reflectiveHierarchy, combinedIndexBuildItem, beanArchiveIndexBuildItem); for (ClassInfo implementation : index.getAllKnownImplementors(ResteasyDotNames.DYNAMIC_FEATURE)) { reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, implementation.name().toString())); } Map<String, String> resteasyInitParameters = new HashMap<>(); registerProviders(resteasyInitParameters, reflectiveClass, unremovableBeans, jaxrsProvidersToRegisterBuildItem); if (!resources.isEmpty()) { resteasyInitParameters.put(ResteasyContextParameters.RESTEASY_SCANNED_RESOURCES, String.join(",", resources)); } resteasyInitParameters.put(ResteasyContextParameters.RESTEASY_SERVLET_MAPPING_PREFIX, path); if (appClass != null) { resteasyInitParameters.put(JAX_RS_APPLICATION_PARAMETER_NAME, appClass); } resteasyInitParameters.put("resteasy.injector.factory", QuarkusInjectorFactory.class.getName()); if (commonConfig.gzip.enabled && commonConfig.gzip.maxInput.isPresent()) { resteasyInitParameters.put(ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT, Integer.toString(commonConfig.gzip.maxInput.getAsInt())); } resteasyServerConfig.produce(new ResteasyServerConfigBuildItem(path, resteasyInitParameters)); } @BuildStep void processPathInterfaceImplementors(CombinedIndexBuildItem combinedIndexBuildItem, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, BuildProducer<AdditionalBeanBuildItem> additionalBeans) { // NOTE: we cannot process @Path interface implementors within the ResteasyServerCommonProcessor.build() method because of build cycles IndexView index = combinedIndexBuildItem.getIndex(); Set<DotName> pathInterfaces = new HashSet<>(); for (AnnotationInstance annotation : index.getAnnotations(ResteasyDotNames.PATH)) { if (annotation.target().kind() == AnnotationTarget.Kind.CLASS && Modifier.isInterface(annotation.target().asClass().flags())) { pathInterfaces.add(annotation.target().asClass().name()); } } if (pathInterfaces.isEmpty()) { return; } Set<ClassInfo> pathInterfaceImplementors = new HashSet<>(); for (DotName iface : pathInterfaces) { for (ClassInfo implementor : index.getAllKnownImplementors(iface)) { pathInterfaceImplementors.add(implementor); } } if (!pathInterfaceImplementors.isEmpty()) { AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder() .setDefaultScope(resteasyConfig.singletonResources ? BuiltinScope.SINGLETON.getName() : null) .setUnremovable(); for (ClassInfo implementor : pathInterfaceImplementors) { if (BuiltinScope.isDeclaredOn(implementor)) { // It has a built-in scope - just mark it as unremovable unremovableBeans .produce(new UnremovableBeanBuildItem(new BeanClassNameExclusion(implementor.name().toString()))); } else { // No built-in scope found - add as additional bean builder.addBeanClass(implementor.name().toString()); } } additionalBeans.produce(builder.build()); } } @Record(STATIC_INIT) @BuildStep ResteasyInjectionReadyBuildItem setupInjection(ResteasyServerCommonTemplate template, BeanContainerBuildItem beanContainerBuildItem, List<ProxyUnwrapperBuildItem> proxyUnwrappers) { List<Function<Object, Object>> unwrappers = new ArrayList<>(); for (ProxyUnwrapperBuildItem i : proxyUnwrappers) { unwrappers.add(i.getUnwrapper()); } template.setupIntegration(beanContainerBuildItem.getValue(), unwrappers); return new ResteasyInjectionReadyBuildItem(); } @BuildStep void beanDefiningAnnotations(BuildProducer<BeanDefiningAnnotationBuildItem> beanDefiningAnnotations) { beanDefiningAnnotations .produce(new BeanDefiningAnnotationBuildItem(ResteasyDotNames.PATH, resteasyConfig.singletonResources ? BuiltinScope.SINGLETON.getName() : null)); beanDefiningAnnotations .produce(new BeanDefiningAnnotationBuildItem(ResteasyDotNames.APPLICATION_PATH, BuiltinScope.SINGLETON.getName())); } @BuildStep AnnotationsTransformerBuildItem annotationTransformer() { return new AnnotationsTransformerBuildItem(new AnnotationsTransformer() { @Override public boolean appliesTo(Kind kind) { return kind == Kind.CLASS; } @Override public void transform(TransformationContext transformationContext) { ClassInfo clazz = transformationContext.getTarget().asClass(); if (clazz.classAnnotation(ResteasyDotNames.PROVIDER) != null && clazz.annotations().containsKey(DotNames.INJECT) && !BuiltinScope.isIn(clazz.classAnnotations())) { // A provider with an injection point but no built-in scope is @Singleton transformationContext.transform().add(BuiltinScope.SINGLETON.getName()).done(); } } }); } /** * Indicates that JAXB support should be enabled * * @return */ @BuildStep JaxbEnabledBuildItem enableJaxb() { return new JaxbEnabledBuildItem(); } private static void registerProviders(Map<String, String> resteasyInitParameters, BuildProducer<ReflectiveClassBuildItem> reflectiveClass, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, JaxrsProvidersToRegisterBuildItem jaxrsProvidersToRegisterBuildItem) { if (jaxrsProvidersToRegisterBuildItem.useBuiltIn()) { // if we find a wildcard media type, we just use the built-in providers resteasyInitParameters.put(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS, "true"); if (!jaxrsProvidersToRegisterBuildItem.getContributedProviders().isEmpty()) { resteasyInitParameters.put(ResteasyContextParameters.RESTEASY_PROVIDERS, String.join(",", jaxrsProvidersToRegisterBuildItem.getContributedProviders())); } } else { resteasyInitParameters.put(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS, "false"); resteasyInitParameters.put(ResteasyContextParameters.RESTEASY_PROVIDERS, String.join(",", jaxrsProvidersToRegisterBuildItem.getProviders())); } // register the providers for reflection for (String providerToRegister : jaxrsProvidersToRegisterBuildItem.getProviders()) { reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, providerToRegister)); } // special case: our config providers reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, ServletConfigSource.class, ServletContextConfigSource.class, FilterConfigSource.class)); // Providers that are also beans are unremovable unremovableBeans.produce(new UnremovableBeanBuildItem( b -> jaxrsProvidersToRegisterBuildItem.getProviders().contains(b.getBeanClass().toString()))); } private static void generateDefaultConstructors(BuildProducer<BytecodeTransformerBuildItem> transformers, Set<ClassInfo> withoutDefaultCtor) { for (ClassInfo classInfo : withoutDefaultCtor) { // keep it super simple - only generate default constructor is the object is a direct descendant of Object if (!(classInfo.superClassType() != null && classInfo.superClassType().name().equals(DotNames.OBJECT))) { return; } boolean hasNonJaxRSAnnotations = false; for (AnnotationInstance instance : classInfo.classAnnotations()) { if (!instance.name().toString().startsWith("javax.ws.rs")) { hasNonJaxRSAnnotations = true; break; } } // again keep it very very simple, if there are any non JAX-RS annotations, we don't generate the constructor if (hasNonJaxRSAnnotations) { continue; } final String name = classInfo.name().toString(); transformers .produce(new BytecodeTransformerBuildItem(name, new BiFunction<String, ClassVisitor, ClassVisitor>() { @Override public ClassVisitor apply(String className, ClassVisitor classVisitor) { ClassVisitor cv = new ClassVisitor(Opcodes.ASM6, classVisitor) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); MethodVisitor ctor = visitMethod(Modifier.PUBLIC, "<init>", "()V", null, null); ctor.visitCode(); ctor.visitVarInsn(Opcodes.ALOAD, 0); ctor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); ctor.visitInsn(Opcodes.RETURN); ctor.visitMaxs(1, 1); ctor.visitEnd(); } }; return cv; } })); } } private static void checkParameterNames(IndexView index) { OUTER: for (DotName annotationType : RESTEASY_PARAM_ANNOTATIONS) { Collection<AnnotationInstance> instances = index.getAnnotations(annotationType); for (AnnotationInstance instance : instances) { MethodParameterInfo param = instance.target().asMethodParameter(); if (param.name() == null) { log.warnv( "Detected RESTEasy annotation {0} on method parameter {1}.{2} with no name. Either specify its name," + " or tell your compiler to enable debug info (-g) or parameter names (-parameters). This message is only" + " logged for the first such parameter.", instance.name(), param.method().declaringClass(), param.method().name()); break OUTER; } } } } private static void registerContextProxyDefinitions(IndexView index, BuildProducer<SubstrateProxyDefinitionBuildItem> proxyDefinition) { // @Context uses proxies for interface injection for (AnnotationInstance annotation : index.getAnnotations(ResteasyDotNames.CONTEXT)) { DotName typeName = null; if (annotation.target().kind() == AnnotationTarget.Kind.METHOD) { MethodInfo method = annotation.target().asMethod(); if (method.parameters().size() == 1) { typeName = method.parameters().get(0).name(); } } else if (annotation.target().kind() == AnnotationTarget.Kind.FIELD) { typeName = annotation.target().asField().type().name(); } else if (annotation.target().kind() == AnnotationTarget.Kind.METHOD_PARAMETER) { int pos = annotation.target().asMethodParameter().position(); typeName = annotation.target().asMethodParameter().method().parameters().get(pos).name(); } if (typeName != null) { ClassInfo type = index.getClassByName(typeName); if (type != null) { if (Modifier.isInterface(type.flags())) { proxyDefinition.produce(new SubstrateProxyDefinitionBuildItem(type.toString())); } } else { //might be a framework class, which should be loadable try { Class<?> typeClass = Class.forName(typeName.toString()); if (typeClass.isInterface()) { proxyDefinition.produce(new SubstrateProxyDefinitionBuildItem(typeName.toString())); } } catch (Exception e) { //ignore } } } } } private static void registerReflectionForSerialization(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy, CombinedIndexBuildItem combinedIndexBuildItem, BeanArchiveIndexBuildItem beanArchiveIndexBuildItem) { IndexView index = combinedIndexBuildItem.getIndex(); IndexView beanArchiveIndex = beanArchiveIndexBuildItem.getIndex(); // required by Jackson reflectiveClass.produce(new ReflectiveClassBuildItem(true, false, "com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector", "com.fasterxml.jackson.databind.ser.std.SqlDateSerializer")); // This is probably redundant with the automatic resolution we do just below but better be safe for (AnnotationInstance annotation : index.getAnnotations(JSONB_ANNOTATION)) { if (annotation.target().kind() == AnnotationTarget.Kind.CLASS) { reflectiveClass .produce(new ReflectiveClassBuildItem(true, true, annotation.target().asClass().name().toString())); } } // Declare reflection for all the types implicated in the Rest end points (return types and parameters). // It might be needed for serialization. for (DotName annotationType : METHOD_ANNOTATIONS) { scanMethodParameters(annotationType, reflectiveHierarchy, index); scanMethodParameters(annotationType, reflectiveHierarchy, beanArchiveIndex); } // In the case of a constraint violation, these elements might be returned as entities and will be serialized reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, ViolationReport.class.getName())); reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, ResteasyConstraintViolation.class.getName())); } private static void scanMethodParameters(DotName annotationType, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy, IndexView index) { Collection<AnnotationInstance> instances = index.getAnnotations(annotationType); for (AnnotationInstance instance : instances) { MethodInfo method = instance.target().asMethod(); if (isReflectionDeclarationRequiredFor(method.returnType())) { reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(method.returnType(), index)); } for (short i = 0; i < method.parameters().size(); i++) { Type parameterType = method.parameters().get(i); if (isReflectionDeclarationRequiredFor(parameterType) && !hasAnnotation(method, i, ResteasyDotNames.CONTEXT)) { reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(parameterType, index)); } } } } private static boolean isReflectionDeclarationRequiredFor(Type type) { DotName className = getClassName(type); return className != null && !ResteasyDotNames.TYPES_IGNORED_FOR_REFLECTION.contains(className); } private static DotName getClassName(Type type) { switch (type.kind()) { case CLASS: case PARAMETERIZED_TYPE: return type.name(); case ARRAY: return getClassName(type.asArrayType().component()); default: return null; } } private static boolean hasAnnotation(MethodInfo method, short paramPosition, DotName annotation) { for (AnnotationInstance annotationInstance : method.annotations()) { AnnotationTarget target = annotationInstance.target(); if (target != null && target.kind() == Kind.METHOD_PARAMETER && target.asMethodParameter().position() == paramPosition && annotationInstance.name().equals(annotation)) { return true; } } return false; } private static RuntimeException createMultipleApplicationsException(Collection<AnnotationInstance> applicationPaths) { StringBuilder sb = new StringBuilder(); boolean first = true; for (AnnotationInstance annotationInstance : applicationPaths) { if (first) { first = false; } else { sb.append(","); } sb.append(annotationInstance.target().asClass().name().toString()); } return new RuntimeException("Multiple classes ( " + sb.toString() + ") have been annotated with @ApplicationPath which is currently not supported"); } }
package org.jboss.as.test.integration.web.security.servlet.methods; import java.io.IOException; import java.net.URL; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpTrace; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import static org.hamcrest.CoreMatchers.is; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import static org.junit.Assert.assertThat; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests whether the <deny-uncovered-http-methods/> tag in web.xml behavior is correct. * * @author Jan Tymel */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(WebTestsSecurityDomainSetup.class) public class DenyUncoveredHttpMethodsTestCase { @ArquillianResource(SecuredServlet.class) URL deploymentURL; @Test public void testCorrectUserAndPassword() throws Exception { HttpGet httpGet = new HttpGet(getURL()); HttpResponse response = getHttpResponse(httpGet); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_UNAUTHORIZED)); } @Test public void testHeadMethod() throws Exception { HttpHead httpHead = new HttpHead(getURL()); HttpResponse response = getHttpResponse(httpHead); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_UNAUTHORIZED)); } @Test @Ignore("WFCORE-1347") public void testTraceMethod() throws Exception { HttpTrace httpTrace = new HttpTrace(getURL()); HttpResponse response = getHttpResponse(httpTrace); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_METHOD_NOT_ALLOWED)); } @Test public void testPostMethod() throws Exception { HttpPost httpPost = new HttpPost(getURL()); HttpResponse response = getHttpResponse(httpPost); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } @Test public void testPutMethod() throws Exception { HttpPut httpPut = new HttpPut(getURL()); HttpResponse response = getHttpResponse(httpPut); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } @Test public void testDeleteMethod() throws Exception { HttpDelete httpDelete = new HttpDelete(getURL()); HttpResponse response = getHttpResponse(httpDelete); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } @Test public void testOptionsMethod() throws Exception { HttpOptions httpOptions = new HttpOptions(getURL()); HttpResponse response = getHttpResponse(httpOptions); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } /** * Tests whether the <deny-uncovered-http-methods/> tag filters methods before the servlet is called. This test creates * custom HTTP method and tries to invoke it. If <deny-uncovered-http-methods/> works correctly status code 403 should be * returned. 403 should be returned also in case the servlet returns anything else for unknown HTTP methods as well. * * @throws Exception */ @Test public void testCustomMethod() throws Exception { HttpUriRequest request = new HttpGet(getURL()) { @Override public String getMethod() { return "customMethod"; } }; HttpResponse response = getHttpResponse(request); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } private HttpResponse getHttpResponse(HttpUriRequest request) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); return response; } private int statusCodeOf(HttpResponse response) { return response.getStatusLine().getStatusCode(); } private String getURL() { return deploymentURL.toString() + "secured/"; } @Deployment public static WebArchive deployment() throws IOException { WebArchive war = ShrinkWrap.create(WebArchive.class, "deny-uncovered-http-methods.war"); war.addClass(SecuredServlet.class); Package warPackage = DenyUncoveredHttpMethodsTestCase.class.getPackage(); war.setWebXML(warPackage, "web.xml"); return war; } }
package org.opennms.features.topology.app.internal; import static org.junit.Assert.assertEquals; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.easymock.EasyMock; import org.junit.Ignore; import org.junit.Test; import org.opennms.features.topology.api.GraphContainer; import org.opennms.features.topology.app.internal.support.IconRepositoryManager; import com.vaadin.data.util.BeanItem; import com.vaadin.terminal.PaintException; import com.vaadin.terminal.PaintTarget; public class TopologyComponentTest { private class TestTopologyComponent extends TopologyComponent{ private static final long serialVersionUID = -442669265971260461L; public TestTopologyComponent(GraphContainer dataSource) { super(dataSource); } public Graph getGraph() { return super.getGraph(); } } @Test public void testTopologyComponentGraph() throws PaintException { PaintTarget target = EasyMock.createMock(PaintTarget.class); mockInitialSetup(target); mockDefaultGraph(target); mockActions(target); EasyMock.replay(target); TestTopologyProvider topoProvider = new TestTopologyProvider(); SimpleGraphContainer graphContainer = new SimpleGraphContainer(); graphContainer.setDataSource(topoProvider); TopologyComponent topoComponent = getTopologyComponent(graphContainer); topoComponent.paintContent(target); EasyMock.verify(target); } private TopologyComponent getTopologyComponent(GraphContainer dataSource) { TopologyComponent topologyComponent = new TopologyComponent(dataSource); topologyComponent.setIconRepoManager(new IconRepositoryManager()); return topologyComponent; } @Test public void testTopologyComponentGraphUpdate() throws PaintException { PaintTarget target = EasyMock.createMock(PaintTarget.class); mockInitialSetup(target); mockGraphTagStart(target); mockVertex(target); mockVertex(target); mockVertex(target); mockEdge(target); mockGraphTagEnd(target); mockActions(target); EasyMock.replay(target); TestTopologyProvider topoProvider = new TestTopologyProvider(); SimpleGraphContainer graphContainer = new SimpleGraphContainer(); graphContainer.setDataSource(topoProvider); TopologyComponent topoComponent = getTopologyComponent(graphContainer); topoProvider.addVertex(); topoComponent.paintContent(target); EasyMock.verify(target); } @Test public void testTopologyComponentGraphUpdateGroup() throws PaintException { PaintTarget target = EasyMock.createMock(PaintTarget.class); mockInitialSetup(target); mockGraphTagStart(target); mockGroup(target); mockVertex(target, 1); mockVertex(target, 1); mockEdge(target); mockGraphTagEnd(target); mockActions(target); EasyMock.replay(target); TestTopologyProvider topoProvider = new TestTopologyProvider(); SimpleGraphContainer graphContainer = new SimpleGraphContainer(); graphContainer.setDataSource(topoProvider); TopologyComponent topoComponent = getTopologyComponent(graphContainer); Collection<?> vertIds = topoProvider.getVertexIds(); Object groupId = topoProvider.addGroup("GroupIcon.jpg"); for(Object vertId : vertIds) { BeanItem<TestVertex> beanItem = topoProvider.getVertexItem(vertId); TestVertex v = beanItem.getBean(); if(v.isLeaf()) { topoProvider.setParent(vertId, groupId); } } topoComponent.paintContent(target); EasyMock.verify(target); } @Test @Ignore public void testTopologyComponentSendCorrectEdgeIds() throws PaintException { TestTopologyProvider topoProvider = new TestTopologyProvider(); SimpleGraphContainer graphContainer = new SimpleGraphContainer(); graphContainer.setDataSource(topoProvider); TopologyComponent topoComponent = getTopologyComponent(graphContainer); topoComponent.setIconRepoManager(new IconRepositoryManager()); Graph graph = topoComponent.getGraph(); List<Edge> edges = graph.getEdges(); assertEquals(1, edges.size()); Edge edge = edges.get(0); PaintTarget target = EasyMock.createMock(PaintTarget.class); mockedDefaultToprData(target); EasyMock.replay(target); topoComponent.paintContent(target); EasyMock.verify(target); System.err.println("\n****** Right before Creation of a Group ******\n"); Collection<?> vertIds = topoProvider.getVertexIds(); Object groupId = topoProvider.addGroup("GroupIcon.jpg"); for(Object vertId : vertIds) { TestVertex v = (TestVertex) ((BeanItem<TestVertex>) topoProvider.getVertexItem(vertId)).getBean(); if(v.isLeaf()) { topoProvider.setParent(vertId, groupId); } } PaintTarget target2 = EasyMock.createMock(PaintTarget.class); mockInitialSetup(target2); mockGraphTagStart(target2); for(Vertex g : graph.getVertices()) { if (!g.isLeaf()) { String key = g.getKey(); mockGroupWithKey(target2, key); } } for(Vertex v : graph.getVertices()) { if (v.isLeaf()) { String key = v.getKey(); mockVertexWithKey(target2, key); } } Map<Object, String> verticesKeyMapper = new HashMap<Object, String>(); for(Vertex v : graph.getVertices()) { verticesKeyMapper.put(v.getItemId(), v.getKey()); } for(Edge e: graph.getEdges()) { String sourceKey = verticesKeyMapper.get(edge.getSource().getItemId()); String targetKey = verticesKeyMapper.get(edge.getTarget().getItemId()); mockEdgeWithKeys(target2, edge.getKey(), sourceKey, targetKey); } mockGraphTagEnd(target2); mockActions(target2); EasyMock.replay(target2); topoComponent.paintContent(target2); EasyMock.verify(target2); } private void mockGroupWithKey(PaintTarget target, String key) throws PaintException { target.startTag("group"); target.addAttribute("key", key); target.addAttribute("x", 0); target.addAttribute("y", 0); target.addAttribute("selected", false); target.addAttribute(EasyMock.eq("iconUrl"), EasyMock.notNull(String.class)); target.addAttribute("semanticZoomLevel", 0); target.addAttribute(EasyMock.eq("label"), EasyMock.notNull(String.class)); target.addAttribute(EasyMock.eq("actionKeys"), EasyMock.aryEq(new Object[0])); target.endTag("group"); } private void mockedDefaultToprData(PaintTarget target) throws PaintException { mockInitialSetup(target); mockGraphTagStart(target); mockVertex(target); mockVertex(target); mockEdge(target); mockGraphTagEnd(target); mockActions(target); } private void mockGroup(PaintTarget target) throws PaintException { target.startTag("group"); target.addAttribute(EasyMock.eq("key"), EasyMock.notNull(String.class)); target.addAttribute("x", 0); target.addAttribute("y", 0); target.addAttribute("selected", false); target.addAttribute(EasyMock.eq("iconUrl"), EasyMock.notNull(String.class)); target.addAttribute("semanticZoomLevel", 0); target.addAttribute(EasyMock.eq("label"), EasyMock.notNull(String.class)); target.addAttribute(EasyMock.eq("actionKeys"), EasyMock.aryEq(new Object[0])); target.endTag("group"); } private void mockInitialSetup(PaintTarget target) throws PaintException { target.addAttribute("scale", 1.0); target.addAttribute("clientX", 0); target.addAttribute("clientY", 0); target.addAttribute("semanticZoomLevel", 0); target.addAttribute("panToSelection", false); target.addAttribute(EasyMock.eq("backgroundActions"), EasyMock.aryEq(new Object[0])); } private void mockDefaultGraph(PaintTarget target) throws PaintException { mockGraphTagStart(target); mockVertex(target); mockVertex(target); mockEdge(target); mockGraphTagEnd(target); } private void mockGraphTagEnd(PaintTarget target) throws PaintException { target.endTag("graph"); } private void mockGraphTagStart(PaintTarget target) throws PaintException { target.startTag("graph"); } private void mockActions(PaintTarget target) throws PaintException { target.startTag("actions"); target.endTag("actions"); } private void mockEdge(PaintTarget target) throws PaintException { target.startTag("edge"); target.addAttribute(eq("key"), EasyMock.notNull(String.class)); target.addAttribute(eq("source"), EasyMock.notNull(String.class)); target.addAttribute(eq("target"), EasyMock.notNull(String.class)); target.addAttribute(eq("actionKeys"), EasyMock.aryEq(new Object[0])); target.endTag("edge"); } private void mockEdgeWithKeys(PaintTarget target, String edgeKey, String sourceId, String targetId) throws PaintException { target.startTag("edge"); target.addAttribute("key", edgeKey); target.addAttribute("source", sourceId); target.addAttribute("target", targetId); target.addAttribute(eq("actionKeys"), EasyMock.aryEq(new Object[0])); target.endTag("edge"); } private void mockVertex(PaintTarget target) throws PaintException { mockVertex(target, 0); } private void mockVertex(PaintTarget target, int semanticZoomLevel) throws PaintException { target.startTag("vertex"); target.addAttribute(EasyMock.eq("key"), EasyMock.notNull(String.class)); target.addAttribute(eq("x"), EasyMock.anyInt()); target.addAttribute(eq("y"), EasyMock.anyInt()); target.addAttribute(eq("selected"), EasyMock.anyBoolean()); target.addAttribute(eq("iconUrl"), EasyMock.notNull(String.class)); target.addAttribute("semanticZoomLevel", semanticZoomLevel); if(semanticZoomLevel > 0) { target.addAttribute(EasyMock.eq("groupKey"), EasyMock.notNull(String.class)); } target.addAttribute(EasyMock.eq("label"), EasyMock.notNull(String.class)); target.addAttribute(eq("actionKeys"), EasyMock.aryEq(new Object[0])); target.endTag("vertex"); } private void mockVertexWithKey(PaintTarget target, String key) throws PaintException { target.startTag("vertex"); target.addAttribute("key", key); target.addAttribute(eq("x"), EasyMock.anyInt()); target.addAttribute(eq("y"), EasyMock.anyInt()); target.addAttribute(eq("selected"), EasyMock.anyBoolean()); target.addAttribute(eq("iconUrl"), EasyMock.notNull(String.class)); target.addAttribute("semanticZoomLevel", 1); target.addAttribute(EasyMock.eq("groupKey"), EasyMock.notNull(String.class)); target.addAttribute(eq("label"), EasyMock.notNull(String.class)); target.addAttribute(eq("actionKeys"), EasyMock.aryEq(new Object[0])); target.endTag("vertex"); } private String eq(String arg) { return EasyMock.eq(arg); } }
package com.sometrik.framework; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import com.sometrik.framework.NativeCommand.Selector; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.RelativeLayout; public class FWSimpleList extends LinearLayout implements NativeCommandHandler { private FrameWork frame; private LinearLayout.LayoutParams defaultListParams; private ArrayList<Sheet> sheets = new ArrayList<Sheet>(); private ArrayList<String> sheetMemory = new ArrayList<String>(); private String sheeticon_right = ""; private ViewStyleManager normalStyle, activeStyle, currentStyle; public FWSimpleList(FrameWork frame) { super(frame); this.frame = frame; defaultListParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); // defaultListParams.setMargins(0, 10, 0, 10); setOrientation(LinearLayout.VERTICAL); // setDividerDrawable(frame.getResources().getDrawable(android.R.drawable.divider_horizontal_bright)); final float scale = getContext().getResources().getDisplayMetrics().density; this.normalStyle = currentStyle = new ViewStyleManager(scale, true); this.activeStyle = new ViewStyleManager(scale, false); } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addChild(final View view) { view.setLayoutParams(defaultListParams); final int sheetNumber = sheets.size(); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("Click java sheet: " + sheetNumber); frame.intChangedEvent(System.currentTimeMillis() / 1000.0, view.getId(), 1, sheetNumber); } }); Sheet sheet = new Sheet((ViewGroup)view); sheets.add(sheet); if (sheetMemory.size() >= sheets.size()) { Log.d("adapter", "setting sheetMemory"); sheet.name.setText(sheetMemory.get(sheets.size() - 1)); } else { sheet.name.setText("TITLE"); } if (sheeticon_right != "") { System.out.println("setting sheeticon_right from memory"); sheet.setRightIcon(sheeticon_right); } else { System.out.println("no sheeticon_right in memory"); } addView(sheet.layout); } private ArrayList<Sheet> getEnabledSheets() { ArrayList<Sheet> enabledSheets = new ArrayList<Sheet>(); for (Sheet sheet : sheets) { if (!sheet.disabled) { enabledSheets.add(sheet); } } return enabledSheets; } private ArrayList<Sheet> getDisabledSheets(){ ArrayList<Sheet> disabledSheets = new ArrayList<Sheet>(); for (Sheet sheet : sheets) { if (sheet.disabled) { disabledSheets.add(sheet); } } return disabledSheets; } @Override public void addOption(int optionId, String text) { if (optionId < sheets.size()) { sheets.get(optionId).name.setText(text);; } sheetMemory.add(optionId, text); } @Override public void addColumn(String text, int columnType) { } @Override public void addData(String text, int row, int column, int sheet) { // TODO Auto-generated method stub } @Override public void setValue(String v) { } @Override public void setImage(byte[] bytes, int width, int height, Config config) { // TODO Auto-generated method stub } @Override public void setValue(int v) { // if (v == 1) { // frame.setCurrentView(this, true); // } else if (v == 2) { // frame.setCurrentView(this, false); } @Override public void reshape(int value, int size) { if (value < sheets.size()) { ViewGroup layout = sheets.get(value).layout; // add one because title layout won't be resized size++; if (layout.getChildCount() == size) { return; } ArrayList<View> viewsToBeRemoved = new ArrayList<View>(); for (int i = size; i < layout.getChildCount(); i++) { View view = layout.getChildAt(i); viewsToBeRemoved.add(view); } Iterator<View> i = viewsToBeRemoved.iterator(); while (i.hasNext()) { View v = i.next(); FrameWork.removeViewFromList(v.getId()); layout.removeView(v); } } else { ViewGroup layout = sheets.get(value).layout; for (int i = 0; i < layout.getChildCount(); i++) { } return; } } @Override public void reshape(int size) { System.out.println("reshape_table simple " + size); ArrayList<Sheet> enabledSheets = getEnabledSheets(); System.out.println("reshape_table simple " + size + " " + enabledSheets.size()); if (size == enabledSheets.size()) { return; } if (size < enabledSheets.size()) { for (int i = size; i < enabledSheets.size(); i++) { System.out.println("removing sheet " + i); sheets.get(i).disable(); } } if (size > enabledSheets.size()) { ArrayList<Sheet> disabledSheets = getDisabledSheets(); System.out.println("reshape_table simple disabled: " + disabledSheets.size()); int difference = size - enabledSheets.size(); for (int i = 0; i < difference; i++) { Sheet disabledSheet = disabledSheets.get(i); disabledSheet.enable(); } } invalidate(); } @Override public void setViewVisibility(boolean visible) { if (visible) { this.setVisibility(VISIBLE); } else { this.setVisibility(GONE); } } @Override public void setStyle(Selector selector, String key, String value) { if (selector == Selector.NORMAL) { normalStyle.setStyle(key, value); if (normalStyle == currentStyle) normalStyle.apply(this); } else if (selector == Selector.ACTIVE) { activeStyle.setStyle(key, value); if (activeStyle == currentStyle) activeStyle.apply(this); } if (key.equals("divider")) { if (value.equals("middle")) { // this.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); } else if (value.equals("end")) { // this.setShowDividers(LinearLayout.SHOW_DIVIDER_END); } else if (value.equals("beginning")) { // this.setShowDividers(LinearLayout.SHOW_DIVIDER_BEGINNING); } } else if (key.equals("sheeticon-right")) { System.out.println("setting right icon"); sheeticon_right = value; for (Sheet sheet : sheets) { sheet.setRightIcon(value); } } } @Override public void setError(boolean hasError, String errorText) { // TODO Auto-generated method stub } @Override public void clear() { reshape(0); } @Override public void flush() { // TODO Auto-generated method stub } @Override public int getElementId() { return getId(); } private class Sheet { private ViewGroup layout; private LinearLayout sheetLayout; private FWTextView name; private int restrictedSize = 1; private boolean disabled = false; private ImageView rightIconView; private void disable() { disabled = true; layout.setVisibility(GONE); } private void enable() { disabled = false; layout.setVisibility(VISIBLE); } private Sheet(ViewGroup view) { sheetLayout = new LinearLayout(frame); sheetLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); sheetLayout.setOrientation(LinearLayout.HORIZONTAL); sheetLayout.setFocusable(false); name = new FWTextView(frame, false); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); params.weight = 1; name.setTextSize(24); name.setTypeface(null, Typeface.BOLD); name.setLayoutParams(params); final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (41 * scale + 0.5f); name.setHeight(pixels); sheetLayout.addView(name); layout = view; view.addView(sheetLayout); } private void setRightIconText(RelativeLayout layout, ImageView iconView, String text) { FWTextView textView = new FWTextView(frame, false); RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); // listParams.addRule(RelativeLayout.LEFT_OF, iconView.getId()); textView.setLayoutParams(listParams); textView.setTextSize(13); textView.setId(845848); textView.setText("MORE"); textView.setTextColor(Color.parseColor("#c1272d")); final float scale = getContext().getResources().getDisplayMetrics().density; int topPadding = (int) (10 * scale + 0.5f); int rightPadding = (int) (38 * scale + 0.5f); textView.setGravity(Gravity.RIGHT); textView.setPadding(0, topPadding, rightPadding, 0); layout.addView(textView); } private void setRightIcon(String assetFilename) { System.out.println("setting right icon"); if (rightIconView == null) { rightIconView = new ImageView(frame); // LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); rightIconView.setScaleType(ScaleType.FIT_END); rightIconView.setId(99944); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); rightIconView.setLayoutParams(params); RelativeLayout iconLayout = new RelativeLayout(frame); LinearLayout.LayoutParams parentParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); parentParams.weight = 1; iconLayout.setLayoutParams(parentParams); iconLayout.setGravity(Gravity.RIGHT); setRightIconText(iconLayout, rightIconView, ""); iconLayout.addView(rightIconView); sheetLayout.addView(iconLayout); } try { AssetManager mgr = frame.getAssets(); InputStream stream = mgr.open(assetFilename); if (stream != null) { Bitmap bitmap = BitmapFactory.decodeStream(stream); rightIconView.setImageBitmap(bitmap); bitmap = null; } stream.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void deinitialize() { // TODO Auto-generated method stub } }
package org.openbmap.activity; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import org.mapsforge.core.model.BoundingBox; import org.mapsforge.core.model.LatLong; import org.mapsforge.map.android.graphics.AndroidGraphicFactory; import org.mapsforge.map.android.view.MapView; import org.mapsforge.map.layer.LayerManager; import org.mapsforge.map.layer.Layers; import org.mapsforge.map.layer.cache.TileCache; import org.mapsforge.map.layer.overlay.Marker; import org.mapsforge.map.model.common.Observer; import org.mapsforge.map.util.MapPositionUtil; import org.openbmap.Preferences; import org.openbmap.R; import org.openbmap.db.DataHelper; import org.openbmap.db.RadioBeaconContentProvider; import org.openbmap.db.Schema; import org.openbmap.db.model.CellRecord; import org.openbmap.heatmap.HeatLatLong; import org.openbmap.heatmap.HeatmapBuilder; import org.openbmap.heatmap.HeatmapBuilder.HeatmapBuilderListener; import org.openbmap.utils.MapUtils; import org.openbmap.utils.MediaScanner; import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; /** * Fragment for displaying cell detail information */ public class CellDetailsMap extends Fragment implements HeatmapBuilderListener, LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = CellDetailsMap.class.getSimpleName(); /** * Radius heat-map circles */ private static final float RADIUS = 50f; private CellRecord mCell; // [start] UI controls /** * MapView */ private MapView mapView; //[end] // [start] Map styles /** * Baselayer cache */ private TileCache tileCache; //[end] // [start] Dynamic map variables private ArrayList<HeatLatLong> points = new ArrayList<HeatLatLong>(); private boolean pointsLoaded = false; private boolean layoutInflated = false; private Observer mapObserver; private byte lastZoom; private LatLong target; private boolean updatePending; private Marker heatmapLayer; private byte initialZoom; private AsyncTask<Object, Integer, Boolean> builder; // [end] @Override public final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.tileCache = createTileCache(); } @Override public final View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { View view = inflater.inflate(R.layout.celldetailsmap, container, false); this.mapView = (MapView) view.findViewById(R.id.map); initMap(); return view; } @Override public final void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mapView.getLayerManager().getLayers().add(MapUtils.createTileRendererLayer( this.tileCache, this.mapView.getModel().mapViewPosition, getMapFile())); mCell = ((CellDetailsActivity) getActivity()).getCell(); getActivity().getSupportLoaderManager().initLoader(0, null, this); } @Override public final void onPause() { releaseMap(); super.onPause(); } @Override public final void onDestroy() { releaseMap(); super.onDestroy(); } @Override public final Loader<Cursor> onCreateLoader(final int arg0, final Bundle arg1) { // set query params: id and session id ArrayList<String> args = new ArrayList<String>(); String selectSql = ""; if (mCell != null && mCell.getCid() != -1 && !mCell.isCdma()) { // typical gsm/hdspa cells selectSql = Schema.COL_CELLID + " = ? AND " + Schema.COL_PSC + " = ?" ; args.add(String.valueOf(mCell.getCid())); args.add(String.valueOf(mCell.getPsc())); } else if (mCell != null && mCell.getCid() == -1 && !mCell.isCdma()) { // umts cells selectSql = Schema.COL_PSC + " = ?"; args.add(String.valueOf(mCell.getPsc())); } else if (mCell != null && mCell.isCdma() && !mCell.getBaseId().equals("-1") && !mCell.getNetworkId().equals("-1") && !mCell.getSystemId().equals("-1")) { // cdma cells selectSql = Schema.COL_BASEID + " = ? AND " + Schema.COL_NETWORKID + " = ? AND " + Schema.COL_SYSTEMID + " = ? AND " + Schema.COL_PSC + " = ?"; args.add(mCell.getBaseId()); args.add(mCell.getNetworkId()); args.add(mCell.getSystemId()); args.add(String.valueOf(mCell.getPsc())); } DataHelper dbHelper = new DataHelper(this.getActivity()); args.add(String.valueOf(dbHelper.getActiveSessionId())); if (selectSql.length() > 0) { selectSql += " AND "; } selectSql += Schema.COL_SESSION_ID + " = ?"; String[] projection = {Schema.COL_ID, Schema.COL_STRENGTHDBM, Schema.COL_TIMESTAMP, "begin_" + Schema.COL_LATITUDE, "begin_" + Schema.COL_LONGITUDE}; // query data from content provider CursorLoader cursorLoader = new CursorLoader(getActivity().getBaseContext(), RadioBeaconContentProvider.CONTENT_URI_CELL_EXTENDED, projection, selectSql, args.toArray(new String[args.size()]), Schema.COL_STRENGTHDBM + " DESC"); return cursorLoader; } @Override public final void onLoadFinished(final Loader<Cursor> loader, final Cursor cursor) { if (cursor != null && cursor.getCount() > 0) { int colLat = cursor.getColumnIndex("begin_" + Schema.COL_LATITUDE); int colLon = cursor.getColumnIndex("begin_" + Schema.COL_LONGITUDE); int colLevel = cursor.getColumnIndex(Schema.COL_STRENGTHDBM); while (cursor.moveToNext()) { //int intensity = (int) (HEAT_AMPLIFIER * (Math.min(cursor.getInt(colLevel) + MIN_HEAT, 0)) / -10f); int intensity = cursor.getInt(colLevel) / -1; points.add(new HeatLatLong(cursor.getDouble(colLat), cursor.getDouble(colLon), intensity)); } mapView.getModel().mapViewPosition.setCenter(points.get(points.size()-1)); pointsLoaded = true; proceedAfterHeatmapCompleted(); // update host activity ((CellDetailsActivity) getActivity()).setNoMeasurements(cursor.getCount()); } } private void proceedAfterHeatmapCompleted() { if (pointsLoaded && layoutInflated && !updatePending) { updatePending = true; clearLayer(); BoundingBox bbox = MapPositionUtil.getBoundingBox( mapView.getModel().mapViewPosition.getMapPosition(), mapView.getDimension()); target = mapView.getModel().mapViewPosition.getCenter(); initialZoom = mapView.getModel().mapViewPosition.getZoomLevel(); heatmapLayer = new Marker(target, null, 0, 0); mapView.getLayerManager().getLayers().add(heatmapLayer); builder = new HeatmapBuilder( CellDetailsMap.this, mapView.getWidth(), mapView.getHeight(), bbox, mapView.getModel().mapViewPosition.getZoomLevel(), RADIUS).execute(points); } else { Log.i(TAG, "Another heat-map is currently generated. Skipped"); } } /* (non-Javadoc) * @see org.openbmap.soapclient.HeatmapBuilder.HeatmapBuilderListener#onHeatmapCompleted(android.graphics.Bitmap) */ @Override public final void onHeatmapCompleted(final Bitmap backbuffer) { updatePending = false; // zoom level has changed in the mean time - regenerate if (mapView.getModel().mapViewPosition.getZoomLevel() != initialZoom) { Log.i(TAG, "Zoom level has changed - have to re-generate heat-map"); clearLayer(); proceedAfterHeatmapCompleted(); return; } BitmapDrawable drawable = new BitmapDrawable(backbuffer); org.mapsforge.core.graphics.Bitmap mfBitmap = AndroidGraphicFactory.convertToBitmap(drawable); heatmapLayer.setBitmap(mfBitmap); //saveHeatmapToFile(backbuffer); } /** * Error or aborted */ @Override public final void onHeatmapFailed() { updatePending = false; } /** * Sets map-related object to null to enable garbage collection. */ private void releaseMap() { Log.i(TAG, "Releasing map components"); if (mapObserver != null) { mapObserver = null; } if (mapView != null) { mapView.destroy(); } } /* (non-Javadoc) * @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.support.v4.content.Loader) */ @Override public void onLoaderReset(final Loader<Cursor> arg0) { } /** * Removes heatmap layer (if any) */ private void clearLayer() { if (heatmapLayer == null) { return; } if (mapView.getLayerManager().getLayers().indexOf(heatmapLayer) != -1) { mapView.getLayerManager().getLayers().remove(heatmapLayer); heatmapLayer = null; } } /** * Opens selected map file * @return a map file */ protected final File getMapFile() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); File mapFile = new File( Environment.getExternalStorageDirectory().getPath() + prefs.getString(Preferences.KEY_MAP_FOLDER, Preferences.VAL_MAP_FOLDER), prefs.getString(Preferences.KEY_MAP_FILE, Preferences.VAL_MAP_FILE)); return mapFile; } /** * Initializes map components */ @SuppressLint("NewApi") private void initMap() { // register for layout finalization - we need this to get width and height ViewTreeObserver vto = mapView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressLint("NewApi") @Override public void onGlobalLayout() { layoutInflated = true; proceedAfterHeatmapCompleted(); ViewTreeObserver obs = mapView.getViewTreeObserver(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { obs.removeOnGlobalLayoutListener(this); } else { obs.removeGlobalOnLayoutListener(this); } } }); // register for zoom changes this.mapObserver = new Observer() { @Override public void onChange() { byte zoom = mapView.getModel().mapViewPosition.getZoomLevel(); if (zoom != lastZoom) { // update overlays on zoom level changed Log.i(TAG, "New zoom level " + zoom + ", reloading map objects"); // cancel pending heat-maps if (builder != null) { builder.cancel(true); } clearLayer(); proceedAfterHeatmapCompleted(); lastZoom = zoom; } } }; this.mapView.getModel().mapViewPosition.addObserver(mapObserver); this.mapView.setClickable(true); this.mapView.getMapScaleBar().setVisible(true); LayerManager layerManager = this.mapView.getLayerManager(); Layers layers = layerManager.getLayers(); // remove all layers including base layer //layers.clear(); this.mapView.getModel().mapViewPosition.setZoomLevel((byte) 16); } /** * Creates a separate tile cache * @return */ protected final TileCache createTileCache() { return MapUtils.createExternalStorageTileCache(getActivity(), getClass().getSimpleName()); } /** * Saves heatmap to SD card * @param bitmap */ @SuppressLint("NewApi") private void saveHeatmapToFile(final Bitmap backbuffer) { try { FileOutputStream out = new FileOutputStream("/sdcard/result.png"); backbuffer.compress(Bitmap.CompressFormat.PNG, 90, out); out.close(); // rescan SD card on honeycomb devices // Otherwise files may not be visible when connected to desktop pc (MTP cache problem) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { Log.i(TAG, "Re-indexing SD card temp folder"); new MediaScanner(getActivity(), new File("/sdcard/")); } } catch (Exception e) { e.printStackTrace(); } } }
import java.util.*; /* * Commands: L,4 Commands: L,4 Commands: L,6 Commands: R,10 Commands: L,6 = A Commands: L,4 Commands: L,4 Commands: L,6 Commands: R,10 Commands: L,6 = A Commands: L,12 Commands: L,6 Commands: R,10 Commands: L,6 = B Commands: R,8 Commands: R,10 Commands: L,6 = C Commands: R,8 Commands: R,10 Commands: L,6 = C Commands: L,4 Commands: L,4 Commands: L,6 Commands: R,10 Commands: L,6 = A Commands: R,8 Commands: R,10 Commands: L,6 = C Commands: L,12 Commands: L,6 Commands: R,10 Commands: L,6 = B Commands: R,8 Commands: R,10 Commands: L,6 = C Commands: L,12 Commands: L,6 Commands: R,10 Commands: L,6 = B */ public class FunctionRoutine { public static final int NUMBER_OF_FUNCTIONS = 3; public static final int ROUTINE_A = 0; public static final int ROUTINE_B = 1; public static final int ROUTINE_C = 2; public static final int MAX_CHARACTERS = 20; public FunctionRoutine (Stack<String> pathTaken, boolean debug) { _path = pathTaken; _functions = new Vector<MovementRoutine>(); /* * Now convert the path into a series of commands * such as L,4 or R,8. */ _commands = getCommands(); _debug = debug; } public Vector<MovementRoutine> createMovementFunctions () { /* * Now turn the series of commands into functions * A, B and C based on repeated commands. * * There are only 3 possible functions. * * This means one function always starts at the beginning. * * One function always ends at the ending (!) assuming it's not a repeat * of the first. * * Then using both the first and the last fragment to find the third * and split the entire sequence into functions. */ String fullCommand = ""; for (int i = _commands.size() -1; i >= 0; i { fullCommand += _commands.elementAt(i); } System.out.println("Full command "+fullCommand); /* * Find repeated strings. Assume minimum of 2 commands. */ int commandStart = 0; int startString = 0; String str = fullCommand; System.out.println("fullCommand length "+fullCommand.length()); do { System.out.println("startString "+startString); if (startString != 0) str = fullCommand.substring(startString); System.out.println("str is "+str); MovementRoutine func = getMovementRoutine(str, commandStart, 2); _functions.add(func); System.out.println("Function is "+func+"\n"); commandStart += func.numberOfCommands(); startString += func.getLength(); System.out.println("Total commands used so far: "+commandStart); System.out.println("startString "+startString); } while (startString < fullCommand.length()); return _functions; } /* * Return a repeating function. Will return all repeating * functions given the input so we need to later figure out * the unique instances afterwards. * * fullCommand is the String to search. * startingCommand is the command from which to begin the search. * numberOfCommands is the number of commands to pull together. */ private MovementRoutine getMovementRoutine (String commandString, int startingCommand, int numberOfCommands) { System.out.println("getUniqueFunction searching "+commandString+" with "+numberOfCommands+" number of commands"); MovementRoutine routine = findRepeatRoutine(commandString, startingCommand, numberOfCommands); System.out.println("**got back "+routine); if (routine == null) { String repeat = getRemainingRoutine(startingCommand); routine = new MovementRoutine(repeat, _commands.size() - startingCommand); /* * Not a repeat but maybe it's part of an existing function? Or maybe * an existing routine is within the String? */ Vector<MovementRoutine> embedded = findEmbeddedRoutine(routine); System.out.println("After checking, commands used "+routine.numberOfCommands()); if (routine.numberOfCommands() > 0) { routine = findRoutineFromPartial(routine); } else routine = embedded.elementAt(embedded.size() -1); // the last entry; return routine; } else { /* * Is this a unique function? If so, add it to * the list. */ if (!_functions.contains(routine)) _functions.add(routine); return routine; } } private MovementRoutine findRoutineFromPartial (MovementRoutine toCheck) // return the full routine one way or another { Enumeration<MovementRoutine> iter = _functions.elements(); while (iter.hasMoreElements()) { MovementRoutine temp = iter.nextElement(); System.out.println("Comparing "+temp+" with "+toCheck); if (temp.containsRoutine(toCheck)) // since no duplicates we know this can only happen once per function { System.out.println("Found full routine "+temp+" for partial routine "+toCheck); return temp; } } return toCheck; } private Vector<MovementRoutine> findEmbeddedRoutine (MovementRoutine toCheck) { Vector<MovementRoutine> toReturn = new Vector<MovementRoutine>(); Enumeration<MovementRoutine> iter = _functions.elements(); while (iter.hasMoreElements()) { MovementRoutine temp = iter.nextElement(); if (toCheck.containsRoutine(temp)) // since no duplicates we know this can only happen once per function { toCheck.removeRoutine(temp); // update the routine contents along the way System.out.println("Found embedded routine "+temp); System.out.println("Remaining "+toCheck); } } return toReturn; } private String getRemainingRoutine (int start) { String str = ""; System.out.println("getRemainingRoutine pulling remaining commands from "+start); for (int i = start; i < _commands.size(); i++) { int commandNumber = _commands.size() - 1 - i; System.out.println("Adding command "+commandNumber); str += _commands.elementAt(commandNumber); } System.out.println("**Command string created: "+str); return str; } private MovementRoutine findRepeatRoutine (String commandString, int startingCommand, int numberOfCommands) { System.out.println("findRoutine searching "+commandString+" with "+numberOfCommands+" number of commands"); String repeat = getCommandString(startingCommand, numberOfCommands); if (commandString.indexOf(repeat, repeat.length()) != -1) // it repeats so try another command { System.out.println("Repeat: "+repeat); MovementRoutine next = findRepeatRoutine(commandString, startingCommand, numberOfCommands +1); if (next == null) return new MovementRoutine(repeat, numberOfCommands); else return next; } else System.out.println("Does not repeat: "+repeat); return null; } private String getCommandString (int start, int number) { String str = ""; System.out.println("getCommandString starting command "+start+" and number "+number); for (int i = start; i < (start + number); i++) { int commandNumber = _commands.size() - 1 - i; System.out.println("Adding command "+commandNumber); str += _commands.elementAt(commandNumber); } System.out.println("**Command string created: "+str); return str; } private Vector<String> getCommands () { Vector<String> commands = new Vector<String>(_path.size()); String pathElement = null; /* * Pop the track to reverse it and get commands from the * starting position. */ do { try { pathElement = _path.pop(); String str = pathElement.charAt(0)+","+pathElement.length(); commands.add(str); } catch (Exception ex) { pathElement = null; } } while (pathElement != null); if (_debug) { for (int i = commands.size() -1; i >= 0; i { System.out.println("Commands: "+commands.elementAt(i)); } } return commands; } private Stack<String> _path; private Vector<MovementRoutine>_functions; private Vector<String> _commands; private boolean _debug; }
package java.net; /** * This class represents an Internet Protocol (IP) address. * <p> * Applications should use the methods <code>getLocalHost</code>, * <code>getByName</code>, or <code>getAllByName</code> to * create a new <code>InetAddress</code> instance. * * @author Matthew Flanagan * @version $Revision$ $Date$ * @see java.net.InetAddress#getAllByName(java.lang.String) * @see java.net.InetAddress#getByName(java.lang.String) * @see java.net.InetAddress#getLocalHost() */ public final class InetAddress implements java.io.Serializable { String hostName; byte address[]; int family; /* * Load my net6 library into runtime. */ static { System.loadLibrary("net6"); } /** * Constructor for the Socket.accept() method. */ InetAddress() { System.out.println("CLASS: InetAddress.InetAddress()"); } /** * Creates an InetAddress with the specified host name and IP address. * @param hostName the specified host name * @param address the specified IP address. The address is expected in * network byte order. * @exception UnknownHostException If the address is unknown. */ InetAddress(String hostName, byte[] address) { this.hostName = hostName; this.address = address; System.out.println("CLASS: InetAddress.InetAddress("+hostName+",byte[])"); } /** * Utility routine to check if the InetAddress is a * IP multicast address. */ public boolean isMulticastAddress() { System.out.println("CLASS: InetAddress.isMulticastAddress()"); int len = address.length; /* IPv4 address check for class D address */ if (len == 4) return ((address[0] & 0xF0) == 0xE0); /* IPv6 address check */ if (len == 16) return (address[0] == (byte) 0xFF); /* address is not a Multicast Address */ return false; } /** * Returns the fully qualified host name for this address. * If the host is equal to null, then this address refers to any * of the local machine's available network addresses. * * @return the fully qualified host name for this address. */ public String getHostName() { System.out.println("CLASS: InetAddress.getHostName()"); if (hostName == null) { try { hostName = getHostByAddress(address); } catch (UnknownHostException he) { hostName = getHostAddress(); } } return hostName; } /** * Returns the raw IP address of this <code>InetAddress</code> * object. The result is in network byte order: the highest order * byte of the address is in <code>getAddress()[0]</code>. * * @return the raw IP address of this object. */ public byte[] getAddress() { System.out.println("CLASS: InetAddress.getAddress()"); return address; } /** * Returns the IPv4 address string "%d.%d.%d.%d" * OR the IPv6 colon separated format "%x:%x:..." * @return raw IP address in a string format */ public String getHostAddress() { int len = address.length; /* allocate room for result */ /* defined in <netinet/in.h> INET6_ADDRSTRLEN = 46 */ StringBuffer addrBuffer = new StringBuffer(46); System.out.println("CLASS: InetAddress.getHostAddress()"); /* We have an IPv6 address. * Return full address for now and don't worry about * special cases like: * - IPv4-mapped IPv6 addresses * - IPv4 compatible addresses * - :: substitution for zeros */ if (len == 16) { for (int i = 0; i < len; i += 2) { int x = ((address[i] & 0xFF) << 8) | (address[i+1] & 0xFF); addrBuffer.append(Integer.toHexString(x).toUpperCase()); if (i < 14) addrBuffer.append(":"); } } /* we have an IPv4 address */ if (len == 4) { for (int i = 0; i < len; i++) { addrBuffer.append(address[i] & 0xFF); if (i < 3) addrBuffer.append("."); } } return addrBuffer.toString(); } /** * Returns a hashcode for this IP address. * (a 32 bit integer) * * @return a hash code value for this IP address. */ public int hashCode() { System.out.println("CLASS: InetAddress.hashCode()"); int hash = 0; int i = 0; int len = address.length; if (len == 16) { /* only want the last 4 bytes of IPv6 address */ i = len - 4; } for ( ; i < len; i++) hash = (hash << 8) | (address[i] & 0xFF); return hash; } /** * Compares this object against the specified object. * The result is <code>true</code> if and only if the argument is * not <code>null</code> and it represents the same IP address as * this object. * <p> * Two instances of <code>InetAddress</code> represent the same IP * address if the length of the byte arrays returned by * <code>getAddress</code> is the same for both, and each of the * array components is the same for the byte arrays. * * @param obj the object to compare against. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. * @see java.net.InetAddress#getAddress() */ public boolean equals(Object obj) { System.out.println("CLASS: InetAddress.equals()"); if ( (obj != null) && (obj instanceof InetAddress) ) { byte addr[] = ((InetAddress)obj).getAddress(); if ( addr.length == address.length ) { for (int i = 0; i < address.length; i++) { if (address[i] != addr[i]) { return false; } } return true; } } return false; } /** * Converts this IP address to a <code>String</code>. * * @return a string representation of this IP address. */ public String toString() { System.out.println("CLASS: InetAddress.toString()"); return getHostName() + "/" + getHostAddress(); } private static InetAddress localHost = null; private static InetAddress loopbackHost; private static InetAddress anyLocalAddress; //private static byte[] loopbackAddress; static { //loopbackAddress = new byte[4]; /* a temporary hack to use only IPv4 loopback address */ //loopbackAddress[0] = 0x7F; //loopbackAddress[1] = 0x00; //loopbackAddress[2] = 0x00; //loopbackAddress[3] = 0x01; loopbackHost = new InetAddress("localhost", getLoopbackAddress()); anyLocalAddress = new InetAddress(null, getAnyLocalAddress()); } public static InetAddress getByName(String host) throws UnknownHostException { System.out.println("CLASS: InetAddress.getByName("+host+")"); if ( (host == null) || (host.length() == 0) ) { return loopbackHost; } else { byte[] addr = pton(host); if (addr != null) { return new InetAddress(null, addr); } else { return getAllByName(host)[0]; } } } public static InetAddress getAllByName(String host)[] throws UnknownHostException { System.out.println("CLASS: InetAddress.getAllByName("+host+")[]"); if (host == null || host.length() == 0) { throw new UnknownHostException(host == null ? "Null string" : host); } /* check if host is IP address */ byte[] addr = pton(host); if (addr != null) { InetAddress[] address = new InetAddress[1]; address[0] = getByName(host); return address; } else { byte[][] addresses = getAllHostAddresses(host); int len = addresses.length; int i = 0; InetAddress iAddresses[] = new InetAddress[len]; for ( ; i < len; i++) { iAddresses[i] = new InetAddress(host, addresses[i]); } return iAddresses; } } /** * Returns the local host. * * @return the IP address of the local host. * @exception UnknownHostException if no IP address for the * <code>host</code> could be found. */ public static InetAddress getLocalHost() throws UnknownHostException { System.out.println("CLASS: InetAddress.getLocalHost()"); SecurityManager s = System.getSecurityManager(); /* need to check if they are allowed to to do this */ if (localHost == null) { String host = getLocalHostName(); if (s != null) { try { s.checkConnect(host, -1); } catch (SecurityException se) { localHost = loopbackHost; return localHost; } } localHost = getByName(host); } return localHost; } /** * Checks if the host String is an IPv4 or IPv6 address * and returns it as a byte array otherwise it returns null * indicating that it was an ordinary host name. * @param host the host name to check * @returns a byte array of the address or null */ private static native byte[] pton(String host); private static native byte[] getLoopbackAddress(); private static native byte[] getAnyLocalAddress(); private static native String getLocalHostName(); private static native byte[][] getAllHostAddresses(String host) throws UnknownHostException; private static native String getHostByAddress(byte[] addr) throws UnknownHostException; }
package cl.json; import android.content.Intent; import android.content.ActivityNotFoundException; import android.net.Uri; import android.support.annotation.Nullable; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.Callback; import java.sql.SQLOutput; import java.util.ArrayList; import java.util.HashMap; import cl.json.social.EmailShare; import cl.json.social.FacebookShare; import cl.json.social.GenericShare; import cl.json.social.GooglePlusShare; import cl.json.social.ShareIntent; import cl.json.social.TwitterShare; import cl.json.social.WhatsAppShare; public class RNShareModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; private HashMap<String, ShareIntent> sharesExtra = new HashMap<String, ShareIntent>(); public RNShareModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; sharesExtra.put("generic", new GenericShare(this.reactContext)); sharesExtra.put("facebook", new FacebookShare(this.reactContext)); sharesExtra.put("twitter", new TwitterShare(this.reactContext)); sharesExtra.put("whatsapp",new WhatsAppShare(this.reactContext)); sharesExtra.put("googleplus",new GooglePlusShare(this.reactContext)); sharesExtra.put("email",new EmailShare(this.reactContext)); // add more customs single intent shares here } @Override public String getName() { return "RNShare"; } @ReactMethod public void open(ReadableMap options, @Nullable Callback failureCallback, @Nullable Callback successCallback) { try{ GenericShare share = new GenericShare(this.reactContext); share.open(options); successCallback.invoke("OK"); }catch(ActivityNotFoundException ex) { System.out.println("ERROR"); System.out.println(ex.getMessage()); failureCallback.invoke("not_available"); } } @ReactMethod public void shareSingle(ReadableMap options, @Nullable Callback failureCallback, @Nullable Callback successCallback) { System.out.println("SHARE SINGLE METHOD"); if (ShareIntent.hasValidKey("social", options) ) { try{ this.sharesExtra.get(options.getString("social")).open(options); successCallback.invoke("OK"); }catch(ActivityNotFoundException ex) { System.out.println("ERROR"); System.out.println(ex.getMessage()); failureCallback.invoke(ex.getMessage()); } } else { failureCallback.invoke("no exists social key"); } } }
package testPackage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Map; import java.util.ArrayList; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; import direnajDriver.*; /** Simple servlet for testing. * * Uses DirenajDataHandler from direnajAdapter package */ //@WebServlet("/test") public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); // getting parameters from html form Map<String, String[]> params = request.getParameterMap(); String userId = params.get("userID")[0]; String password = params.get("pass")[0]; String campaignId = params.get("campaignID")[0]; int skip = Integer.parseInt(params.get("skip")[0]); int limit = Integer.parseInt(params.get("limit")[0]); String operation = params.get("operationType")[0]; System.out.println(operation); // Start preparing objects // constructing the driver object that will handle our data retrieval // and processing requests, using DirenajDataHandler as a backbone DirenajDriver driver = new DirenajDriver(userId, password); ArrayList<String> tweetTexts = new ArrayList<String>(); ArrayList<ArrayList<String>> allTags = new ArrayList<ArrayList<String>>(); ArrayList<Map.Entry<String, Integer>> counts = new ArrayList<Map.Entry<String,Integer>>(); // building the result page String retHtmlStr = "<!DOCTYPE html>\n" + "<html>\n" + "<head><title>Direnaj Test Center</title></head>\n" + "<body bgcolor=\"#fdf5e6\">\n" + "<h1>DirenajDriver Test</h1>\n" + "<p>CampaignID : <b>" + campaignId + "</b> | Operation : <b>" + operation + "</b> | Limit : <b>" + limit + "</b></p><hr>\n"; try { if(operation.equals("getTags")) { allTags = driver.collectHashtags(campaignId, skip, limit); retHtmlStr += "<ul>"; for (ArrayList<String> singleTweetTags: allTags) { //if(singleTweetTags.size() != 0) { retHtmlStr += "<li>"; for(String tag : singleTweetTags) { retHtmlStr += tag + " - "; } retHtmlStr += "</li>"; } retHtmlStr += "</ul>"; } else if(operation.equals("getTagCounts")) { counts = driver.countHastags(campaignId, skip, limit); PrintWriter pw = new PrintWriter(new File("/tmp/tags.txt")); boolean skipFirst = true; retHtmlStr += "<table width=100% border=0><tr valign=top><td><ul>"; for(Map.Entry<String, Integer> entry : counts) { retHtmlStr += "<li><font size=\"2\">(" + entry.getKey() + " : " + entry.getValue() + ")</font></li>"; if(skipFirst) { skipFirst = false; continue; } else { pw.println(entry.getKey() + "\t" + entry.getValue()); } } retHtmlStr += "</ul></td><td align=right>"; pw.close(); String cmd = "java -jar /home/direnaj/direnaj/envs/staging/toolkit/DirenajToolkitService/WebContent/WEB-INF/lib/ibm-word-cloud.jar " + "-c /home/direnaj/direnaj/tools/caner.conf -w 800 -h 600 " + "-i /tmp/tags.txt " + "-o /home/direnaj/direnaj/tools/images/caner.png"; Process proc = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", cmd}); BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String line = null; while((line = br.readLine()) != null) { System.out.println(line); } proc.waitFor(); retHtmlStr += "<img src=\"images/caner.png\"/> </td></tr></table>"; } else if(operation.equals("getTweetTexts")) { tweetTexts = driver.collectTweetTexts(campaignId, skip, limit); retHtmlStr += "<ul>"; for(String tweetText : tweetTexts) { retHtmlStr += "<li><font size=\"2\">" + tweetText + "</font></li>"; } retHtmlStr += "</ul>"; } else if(operation.equals("getSingleTweet")) { retHtmlStr += driver.getSingleTweetInfo(campaignId, skip, limit); } else { retHtmlStr += "OPERATION NOT SUPPORTED!"; } } catch(Exception e) { out.println(e.getMessage()); out.close(); System.out.println(e); } out.println(retHtmlStr + "</body></html>"); out.close(); } }
package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Week; import org.jfree.data.time.Year; /** * Tests for the {@link Week} class. */ public class WeekTests extends TestCase { /** A week. */ private Week w1Y1900; /** A week. */ private Week w2Y1900; /** A week. */ private Week w51Y9999; /** A week. */ private Week w52Y9999; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(WeekTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public WeekTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.w1Y1900 = new Week(1, 1900); this.w2Y1900 = new Week(2, 1900); this.w51Y9999 = new Week(51, 9999); this.w52Y9999 = new Week(52, 9999); } /** * Tests the equals method. */ public void testEquals() { Week w1 = new Week(1, 2002); Week w2 = new Week(1, 2002); assertTrue(w1.equals(w2)); assertTrue(w2.equals(w1)); w1 = new Week(2, 2002); assertFalse(w1.equals(w2)); w2 = new Week(2, 2002); assertTrue(w1.equals(w2)); w1 = new Week(2, 2003); assertFalse(w1.equals(w2)); w2 = new Week(2, 2003); assertTrue(w1.equals(w2)); } /** * Request the week before week 1, 1900: it should be <code>null</code>. */ public void testW1Y1900Previous() { Week previous = (Week) this.w1Y1900.previous(); assertNull(previous); } /** * Request the week after week 1, 1900: it should be week 2, 1900. */ public void testW1Y1900Next() { Week next = (Week) this.w1Y1900.next(); assertEquals(this.w2Y1900, next); } /** * Request the week before w52, 9999: it should be week 51, 9999. */ public void testW52Y9999Previous() { Week previous = (Week) this.w52Y9999.previous(); assertEquals(this.w51Y9999, previous); } /** * Request the week after w52, 9999: it should be <code>null</code>. */ public void testW52Y9999Next() { Week next = (Week) this.w52Y9999.next(); assertNull(next); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { Week w1 = new Week(24, 1999); Week w2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(w1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); w2 = (Week) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(w1, w2); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashcode() { Week w1 = new Week(2, 2003); Week w2 = new Week(2, 2003); assertTrue(w1.equals(w2)); int h1 = w1.hashCode(); int h2 = w2.hashCode(); assertEquals(h1, h2); } /** * The {@link Week} class is immutable, so should not be {@link Cloneable}. */ public void testNotCloneable() { Week w = new Week(1, 1999); assertFalse(w instanceof Cloneable); } public void testWeek12005() { Week w1 = new Week(1, 2005); Calendar c1 = Calendar.getInstance( TimeZone.getTimeZone("Europe/London"), Locale.UK); c1.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104710400000L, w1.getFirstMillisecond(c1)); assertEquals(1105315199999L, w1.getLastMillisecond(c1)); Calendar c2 = Calendar.getInstance( TimeZone.getTimeZone("Europe/Paris"), Locale.FRANCE); c2.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104706800000L, w1.getFirstMillisecond(c2)); assertEquals(1105311599999L, w1.getLastMillisecond(c2)); Calendar c3 = Calendar.getInstance( TimeZone.getTimeZone("America/New_York"), Locale.US); assertEquals(1104037200000L, w1.getFirstMillisecond(c3)); assertEquals(1104641999999L, w1.getLastMillisecond(c3)); } public void testWeek532005() { Week w1 = new Week(53, 2004); Calendar c1 = Calendar.getInstance( TimeZone.getTimeZone("Europe/London"), Locale.UK); c1.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104105600000L, w1.getFirstMillisecond(c1)); assertEquals(1104710399999L, w1.getLastMillisecond(c1)); Calendar c2 = Calendar.getInstance( TimeZone.getTimeZone("Europe/Paris"), Locale.FRANCE); c2.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104102000000L, w1.getFirstMillisecond(c2)); assertEquals(1104706799999L, w1.getLastMillisecond(c2)); w1 = new Week(53, 2005); Calendar c3 = Calendar.getInstance( TimeZone.getTimeZone("America/New_York"), Locale.US); assertEquals(1135486800000L, w1.getFirstMillisecond(c3)); assertEquals(1136091599999L, w1.getLastMillisecond(c3)); } /** * A test case for bug 1448828. */ public void testBug1448828() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); try { Week w = new Week(new Date(1136109830000l), TimeZone.getTimeZone("GMT")); assertEquals(2005, w.getYearValue()); assertEquals(52, w.getWeek()); } finally { Locale.setDefault(saved); } } /** * A test case for bug 1498805. */ public void testBug1498805() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); try { TimeZone zone = TimeZone.getTimeZone("GMT"); GregorianCalendar gc = new GregorianCalendar(zone); gc.set(2005, Calendar.JANUARY, 1, 12, 0, 0); Week w = new Week(gc.getTime(), zone); assertEquals(53, w.getWeek()); assertEquals(new Year(2004), w.getYear()); } finally { Locale.setDefault(saved); } } /** * Some checks for the getFirstMillisecond() method. */ public void testGetFirstMillisecond() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Week w = new Week(3, 1970); assertEquals(946800000L, w.getFirstMillisecond()); Locale.setDefault(saved); TimeZone.setDefault(savedZone); } /** * Some checks for the getFirstMillisecond(TimeZone) method. */ public void testGetFirstMillisecondWithTimeZone() { Week w = new Week(47, 1950); Locale saved = Locale.getDefault(); Locale.setDefault(Locale.US); try { TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = new GregorianCalendar(zone); assertEquals(-603216000000L, w.getFirstMillisecond(c)); } finally { Locale.setDefault(saved); } // try null calendar boolean pass = false; try { w.getFirstMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getFirstMillisecond(TimeZone) method. */ public void testGetFirstMillisecondWithCalendar() { Week w = new Week(1, 2001); GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY); calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt")); assertEquals(978307200000L, w.getFirstMillisecond(calendar)); // try null calendar boolean pass = false; try { w.getFirstMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getLastMillisecond() method. */ public void testGetLastMillisecond() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Week w = new Week(31, 1970); assertEquals(18485999999L, w.getLastMillisecond()); Locale.setDefault(saved); TimeZone.setDefault(savedZone); } /** * Some checks for the getLastMillisecond(TimeZone) method. */ public void testGetLastMillisecondWithTimeZone() { Week w = new Week(2, 1950); Locale saved = Locale.getDefault(); Locale.setDefault(Locale.US); try { TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = new GregorianCalendar(zone); assertEquals(-629827200001L, w.getLastMillisecond(c)); } finally { Locale.setDefault(saved); } // try null calendar boolean pass = false; try { w.getLastMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getLastMillisecond(TimeZone) method. */ public void testGetLastMillisecondWithCalendar() { Week w = new Week(52, 2001); GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY); calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt")); assertEquals(1009756799999L, w.getLastMillisecond(calendar)); // try null calendar boolean pass = false; try { w.getLastMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getSerialIndex() method. */ public void testGetSerialIndex() { Week w = new Week(1, 2000); assertEquals(106001L, w.getSerialIndex()); w = new Week(1, 1900); assertEquals(100701L, w.getSerialIndex()); } /** * Some checks for the testNext() method. */ public void testNext() { Week w = new Week(12, 2000); w = (Week) w.next(); assertEquals(new Year(2000), w.getYear()); assertEquals(13, w.getWeek()); w = new Week(53, 9999); assertNull(w.next()); } /** * Some checks for the getStart() method. */ public void testGetStart() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.JANUARY, 16, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Week w = new Week(3, 2006); assertEquals(cal.getTime(), w.getStart()); Locale.setDefault(saved); } /** * Some checks for the getEnd() method. */ public void testGetEnd() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.JANUARY, 8, 23, 59, 59); cal.set(Calendar.MILLISECOND, 999); Week w = new Week(1, 2006); assertEquals(cal.getTime(), w.getEnd()); Locale.setDefault(saved); } /** * A test for a problem in constructing a new Week instance. */ public void testConstructor() { Locale savedLocale = Locale.getDefault(); TimeZone savedZone = TimeZone.getDefault(); Locale.setDefault(new Locale("da", "DK")); TimeZone.setDefault(TimeZone.getTimeZone("Europe/Copenhagen")); GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance( TimeZone.getDefault(), Locale.getDefault()); // first day of week is monday assertEquals(Calendar.MONDAY, cal.getFirstDayOfWeek()); cal.set(2007, Calendar.AUGUST, 26, 1, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date t = cal.getTime(); Week w = new Week(t, TimeZone.getTimeZone("Europe/Copenhagen")); assertEquals(34, w.getWeek()); Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("US/Detroit")); cal = (GregorianCalendar) Calendar.getInstance(TimeZone.getDefault()); // first day of week is Sunday assertEquals(Calendar.SUNDAY, cal.getFirstDayOfWeek()); cal.set(2007, Calendar.AUGUST, 26, 1, 0, 0); cal.set(Calendar.MILLISECOND, 0); t = cal.getTime(); w = new Week(t, TimeZone.getTimeZone("Europe/Copenhagen")); assertEquals(35, w.getWeek()); w = new Week(t, TimeZone.getTimeZone("Europe/Copenhagen"), new Locale("da", "DK")); assertEquals(34, w.getWeek()); Locale.setDefault(savedLocale); TimeZone.setDefault(savedZone); } }
package org.jgroups.tests; import org.jgroups.util.Util; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; /** * @author Bela Ban * @version $Id: LatencyTest.java,v 1.2 2007/05/04 12:48:52 belaban Exp $ */ public class LatencyTest { InetAddress GROUP=null; int PORT=7500; private void start(boolean sender, boolean local) throws Exception { GROUP=InetAddress.getByName("228.1.2.3"); long start; DatagramPacket send_packet, recv_packet; byte[] send_buf; byte[] recv_buf=new byte[2100]; if(local) { MulticastSocket send_sock=new MulticastSocket(PORT); send_sock.setTrafficClass(8); MulticastSocket recv_sock=new MulticastSocket(PORT); recv_sock.joinGroup(GROUP); recv_packet=new DatagramPacket(recv_buf, 0, recv_buf.length); for(int i=0; i < 10; i++) { start=System.currentTimeMillis(); send_buf=Util.objectToByteBuffer(start); send_packet=new DatagramPacket(send_buf, 0, send_buf.length, GROUP, PORT); send_sock.send(send_packet); recv_sock.receive(recv_packet); start=((Long)Util.objectFromByteBuffer(recv_buf, recv_packet.getOffset(), recv_packet.getLength())).longValue(); System.out.println("took " + (System.currentTimeMillis() - start) + " ms"); Util.sleep(1000); } } if(sender) { MulticastSocket send_sock=new MulticastSocket(PORT); send_sock.setTrafficClass(8); for(int i=0; i < 10; i++) { start=System.currentTimeMillis(); send_buf=Util.objectToByteBuffer(start); send_packet=new DatagramPacket(send_buf, 0, send_buf.length, GROUP, PORT); send_sock.send(send_packet); Util.sleep(1000); } } else { MulticastSocket recv_sock=new MulticastSocket(PORT); recv_sock.joinGroup(GROUP); recv_packet=new DatagramPacket(recv_buf, 0, recv_buf.length); for(;;) { recv_sock.receive(recv_packet); start=((Long)Util.objectFromByteBuffer(recv_buf, recv_packet.getOffset(), recv_packet.getLength())).longValue(); System.out.println("took " + (System.currentTimeMillis() - start) + " ms"); } } } public static void main(String[] args) throws Exception { boolean sender=false; boolean local=true; for(int i=0; i < args.length; i++) { if(args[i].equalsIgnoreCase("-sender")) { sender=true; continue; } if(args[i].equalsIgnoreCase("-local")) { local=true; continue; } help(); return; } new LatencyTest().start(sender, local); } private static void help() { System.out.println("LatencyTest [-sender] [-local (overrides -sender)]"); } }
// XMLTools.java package loci.formats; import java.io.*; import java.util.StringTokenizer; import javax.xml.parsers.*; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; public final class XMLTools { // -- Constructor -- private XMLTools() { } // -- Utility methods -- /** * Attempts to validate the given XML string using * Java's XML validation facility. Requires Java 1.5+. * @param xml The XML string to validate. */ public static void validateXML(String xml) { validateXML(xml, null); } /** * Attempts to validate the given XML string using * Java's XML validation facility. Requires Java 1.5+. * @param xml The XML string to validate. * @param label String describing the type of XML being validated. */ public static void validateXML(String xml, String label) { if (label == null) label = "XML"; // check Java version (XML validation only works in Java 1.5+) String version = System.getProperty("java.version"); int dot = version.indexOf("."); if (dot >= 0) dot = version.indexOf(".", dot + 1); float ver = Float.NaN; if (dot >= 0) { try { ver = Float.parseFloat(version.substring(0, dot)); } catch (NumberFormatException exc) { } } if (ver != ver) { LogTools.println("Warning: cannot determine if Java version\"" + version + "\" supports Java v1.5. XML validation may fail."); } if (ver < 1.5f) return; // do not attempt validation if not Java 1.5+ // get path to schema from root element using SAX LogTools.println("Parsing schema path"); ValidationSAXHandler saxHandler = new ValidationSAXHandler(); SAXParserFactory saxFactory = SAXParserFactory.newInstance(); Exception exception = null; try { SAXParser saxParser = saxFactory.newSAXParser(); InputStream is = new ByteArrayInputStream(xml.getBytes()); saxParser.parse(is, saxHandler); } catch (ParserConfigurationException exc) { exception = exc; } catch (SAXException exc) { exception = exc; } catch (IOException exc) { exception = exc; } if (exception != null) { LogTools.println("Error parsing schema path from " + label + ":"); LogTools.trace(exception); return; } String schemaPath = saxHandler.getSchemaPath(); if (schemaPath == null) { LogTools.println("No schema path found. Validation cannot continue."); return; } else LogTools.println(schemaPath); LogTools.println("Validating " + label); // use reflection to avoid compile-time dependency on optional // org.openmicroscopy.xml or javax.xml.validation packages ReflectedUniverse r = new ReflectedUniverse(); try { // look up a factory for the W3C XML Schema language r.setVar("xmlSchemaPath", "http: r.exec("import javax.xml.validation.SchemaFactory"); r.exec("factory = SchemaFactory.newInstance(xmlSchemaPath)"); // compile the schema r.exec("import java.net.URL"); r.setVar("schemaPath", schemaPath); r.exec("schemaLocation = new URL(schemaPath)"); r.exec("schema = factory.newSchema(schemaLocation)"); // HACK - workaround for weird Linux bug preventing use of // schema.newValidator() method even though it is "public final" r.setAccessibilityIgnored(true); // get a validator from the schema r.exec("validator = schema.newValidator()"); // prepare the XML source r.exec("import java.io.StringReader"); r.setVar("xml", xml); r.exec("reader = new StringReader(xml)"); r.exec("import org.xml.sax.InputSource"); r.exec("is = new InputSource(reader)"); r.exec("import javax.xml.transform.sax.SAXSource"); r.exec("source = new SAXSource(is)"); // validate the XML ValidationErrorHandler errorHandler = new ValidationErrorHandler(); r.setVar("errorHandler", errorHandler); r.exec("validator.setErrorHandler(errorHandler)"); r.exec("validator.validate(source)"); if (errorHandler.ok()) LogTools.println("No validation errors found."); } catch (ReflectException exc) { LogTools.println("Error validating " + label + ":"); LogTools.trace(exc); } } /** Indents XML to be more readable. */ public static String indentXML(String xml) { return indentXML(xml, 3); } /** Indents XML by the given spacing to be more readable. */ public static String indentXML(String xml, int spacing) { int indent = 0; StringBuffer sb = new StringBuffer(); StringTokenizer st = new StringTokenizer(xml, "<>", true); boolean element = false; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.equals("")) continue; if (token.equals("<")) { element = true; continue; } if (element && token.equals(">")) { element = false; continue; } if (element && token.startsWith("/")) indent -= spacing; for (int j=0; j<indent; j++) sb.append(" "); if (element) sb.append("<"); sb.append(token); if (element) sb.append(">"); sb.append("\n"); if (element && !token.startsWith("?") && !token.startsWith("/") && !token.endsWith("/")) { indent += spacing; } } return sb.toString(); } // -- Helper classes -- /** Used by validateXML to parse the XML block's schema path using SAX. */ private static class ValidationSAXHandler extends DefaultHandler { private String schemaPath; private boolean first; public String getSchemaPath() { return schemaPath; } public void startDocument() { schemaPath = null; first = true; } public void startElement(String uri, String localName, String qName, Attributes attributes) { if (!first) return; first = false; int len = attributes.getLength(); String xmlns = null, xsiSchemaLocation = null; for (int i=0; i<len; i++) { String name = attributes.getQName(i); if (name.equals("xmlns")) xmlns = attributes.getValue(i); int colon = name.lastIndexOf(":"); if (colon >= 0) name = name.substring(colon + 1); // strip namespace else if (name.equals("schemaLocation")) { xsiSchemaLocation = attributes.getValue(i); } } if (xmlns == null || xsiSchemaLocation == null) return; // not found StringTokenizer st = new StringTokenizer(xsiSchemaLocation); while (st.hasMoreTokens()) { String token = st.nextToken(); if (xmlns.equals(token)) { // next token is the actual schema path if (st.hasMoreTokens()) schemaPath = st.nextToken(); break; } } } } /** Used by validateXML to handle XML validation errors. */ private static class ValidationErrorHandler implements ErrorHandler { private boolean ok = true; public boolean ok() { return ok; } public void error(SAXParseException e) { LogTools.println("error: " + e.getMessage()); ok = false; } public void fatalError(SAXParseException e) { LogTools.println("fatal error: " + e.getMessage()); ok = false; } public void warning(SAXParseException e) { LogTools.println("warning: " + e.getMessage()); ok = false; } } }
package natlab; import java.util.TreeMap; import java.util.ArrayList; import java.io.*; import junit.framework.TestCase; import natlab.toolkits.analysis.AbstractNodeCaseHandler; import ast.*; public class RewritePassTestBase extends TestCase { protected Program parseFile( String fName ) throws Exception { FileReader fileReader = new FileReader( fName ); ArrayList<CompilationProblem> errList = new ArrayList<CompilationProblem>(); Program prog = Parse.parseFile( fName, fileReader, errList ); if( prog == null ) throw new Exception( "Error parsing file " +fName+ ":\n" + CompilationProblem.toStringAll( errList ) ); return prog; } public void assertEquiv( ASTNode actual, ASTNode expected ) { TreeAplhaEquivTester tester = new TreeAplhaEquivTester( actual, expected ); Boolean test = tester.testEquiv(); String msg = tester.getReason(); assertTrue( msg+ "\n" + "ACTUAL: \n\n"+ actual.getPrettyPrinted() + "\n\n"+ "EXPECTED: \n\n"+ expected.getPrettyPrinted() + "\n", test ); } /** * Class used to verify that two ASTs are structurally the same up * to alpha renaming. This should only be used for testing the * simplifying rewrites, not general transformations. */ class TreeAplhaEquivTester extends AbstractNodeCaseHandler { private TreeMap<String, String> nameEquivalence; private boolean fail = false; private ASTNode tree1, tree2, tree2Current; private String reason = ""; public TreeAplhaEquivTester( ASTNode tree1, ASTNode tree2 ) { this.tree1 = tree1; this.tree2 = tree2; } public boolean testEquiv() { tree2Current = tree2; nameEquivalence = new TreeMap<String, String>(); tree1.analyze(this); return !fail; } public String getReason() { return reason; } public void caseASTNode( ASTNode node ) { ASTNode tree1Next, tree2Next; ASTNode current = tree2Current; //Check if they are the same class if( current.getClass().isInstance(node) ){ int numChild = node.getNumChild(); if( numChild == current.getNumChild() ){ //if they are the same class and have the same //number of children, then loop each child and //check equiv for( int i=0; i<numChild; i++ ){ tree1Next = node.getChild(i); tree2Next = current.getChild(i); tree2Current = tree2Next; tree1Next.analyze(this); if( fail ) break; } } else{ // if they have differing number of children, // figure out a failure reason and fail. if( current instanceof List ){ reason = "Number of elements don't match for actual and expected lists\n"; } else reason = "Number of children don't match for actual subtree: \n\n"+ node.getPrettyPrinted() + "\n\n"+ "and expected subtree: \n\n" + current.getPrettyPrinted() + "\n"; reason += "\nNumbers of children are "+ numChild + " and "+current.getNumChild()+" respectively\n"; fail = true; } } // If they aren't the same class, figure out a failure // reason, except when one is a CheckScalarStmt else{ if( current instanceof List || node instanceof List ) reason = "Node types don't match for actual node: "+node+"\n\n"+ "and expected: "+ current +"\n"; //see if one is a CheckScalarStmt else if( current instanceof CheckScalarStmt || node instanceof CheckScalarStmt ){ //if they both are then check the parameter if( current instanceof CheckScalarStmt && node instanceof CheckScalarStmt ){ tree1Next = node.getChild(0); tree2Next = current.getChild(0); tree2Current = tree2Next; tree1Next.analyze(this); } //if only one is, make sure the other is a //ParameterizedExpr that looks like a CheckScalarStmt else{ tree1Next = null; tree2Next = null; if( current instanceof CheckScalarStmt ){ ParameterizedExpr paramExpr = getParamExpr( node ); if( paramExpr != null && checkIsScalar( paramExpr )){ tree1Next = paramExpr.getArg(0); tree2Next = current.getChild(0); } else{ fail = true; } } else{ ParameterizedExpr paramExpr = getParamExpr( current ); if( paramExpr != null && checkIsScalar( paramExpr )){ tree1Next = node.getChild(0); tree2Next = paramExpr.getArg(0); } else{ fail = true; } } if( fail ) reason = "check_scalar expected: \n\n"+ node.getPrettyPrinted() + "\n\n"+ "and expected subtree: \n\n" + current.getPrettyPrinted() + "\n"; else{ tree2Current = tree2Next; tree1Next.analyze(this); tree2Current = current; return; } } } else reason = "Node types don't match for actual subtree: \n\n"+ node.getPrettyPrinted() + "\n\n"+ "and expected subtree: \n\n" + current.getPrettyPrinted() + "\n"; fail = true; } tree2Current = current; } /** * Gets the ParameterizedExpr from a node if that node is an * expression statement, returns null otherwise. */ private ParameterizedExpr getParamExpr( ASTNode node ){ if( node instanceof ExprStmt ) if( node.getChild(0) instanceof ParameterizedExpr ) return (ParameterizedExpr)node.getChild(0); return null; } /** * Checks if a given {@code ParameterizedExpr} is a valid * {@code check_scalar} call. This is intended to deal with * the fact that {@code CheckScalarStmt} nodes can't be placed * in actual source code. */ private boolean checkIsScalar( ParameterizedExpr expr ) { if( expr.getTarget() instanceof NameExpr ){ NameExpr nameExpr = (NameExpr)expr.getTarget(); return nameExpr.getName().getID().equals("check_scalar") && expr.getNumArg() == 1; } else return false; } public void caseFunction( Function node ) { caseASTNode( node ); String name1 = node.getName(); String name2 = ((Function)tree2Current).getName(); if( name1.equals(name2) ){ if( nameEquivalence.containsKey( name1 ) ){ reason = "Function names don't match for actual subtree: \n\n"+ node.getPrettyPrinted() + "\n\n"+ "and expected subtree: \n\n" + tree2Current.getPrettyPrinted() + "\n"; fail = true; } else nameEquivalence.put( name1, name2 ); } } public void caseName( Name node ) { caseASTNode( node ); if( !fail ){ String name1 = node.getID(); String name2 = ((Name)tree2Current).getID(); if( nameEquivalence.containsKey( name1 ) ){ if( ! nameEquivalence.get( name1 ).equals( name2 ) ){ reason = "Names don't match for actual subtree: \n\n"+ node.getPrettyPrinted() + "\n\n"+ "and expected subtree: \n\n" + tree2Current.getPrettyPrinted() + "\n"; fail = true; } } else nameEquivalence.put( name1, name2 ); } } } }
package org.wso2.developerstudio.datamapper.diagram.edit.parts; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.eclipse.draw2d.Clickable; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.ImageFigure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.MarginBorder; import org.eclipse.draw2d.MouseEvent; import org.eclipse.draw2d.MouseListener; import org.eclipse.draw2d.MouseMotionListener; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.RectangleFigure; import org.eclipse.draw2d.Shape; import org.eclipse.draw2d.StackLayout; import org.eclipse.draw2d.ToolbarLayout; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.Request; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.LayoutEditPolicy; import org.eclipse.gef.editpolicies.NonResizableEditPolicy; import org.eclipse.gef.palette.PaletteContainer; import org.eclipse.gef.palette.ToolEntry; import org.eclipse.gef.requests.CreateRequest; import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IBorderItemEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles; import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator; import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure; import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.gmf.tooling.runtime.edit.policies.reparent.CreationEditPolicyWithCustomReparent; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.wso2.developerstudio.datamapper.PropertyKeyValuePair; import org.wso2.developerstudio.datamapper.TreeNode; import org.wso2.developerstudio.datamapper.diagram.edit.parts.custom.CustomNonResizableEditPolicyEx; import org.wso2.developerstudio.datamapper.diagram.part.DataMapperVisualIDRegistry; /** * @generated */ public class TreeNode3EditPart extends AbstractBorderedShapeEditPart { private static final String PARENT_ICON = "icons/gmf/parent.gif"; private static final String ARRAY_ICON = "icons/gmf/parent.gif"; private static final String ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM = "org.wso2.developerstudio.visualdatamapper.diagram"; private static final String JSON_SCHEMA_ARRAY_ITEMS_VALUE_TYPE = "items_value_type"; private static final String JSON_SCHEMA_OBJECT_VALUE_TYPE = "object_value_type"; private static final String JSON_SCHEMA_ARRAY_ITEMS_TYPE = "items_type"; private static final String NULL_VALUE = "null"; public static final String JSON_SCHEMA_TYPE = "type"; public static final String JSON_SCHEMA_ARRAY = "array"; public static final String JSON_SCHEMA_OBJECT = "object"; /** * @generated NOT */ List<IFigure> childrenIFigure; /** * @generated NOT */ boolean isActivated = false; /** * @generated NOT */ NodeFigure figure; /** * @generated */ public static final int VISUAL_ID = 3011; /** * @generated */ protected IFigure contentPane; /** * @generated */ protected IFigure primaryShape; /** * @generated */ public TreeNode3EditPart(View view) { super(view); } /** * @generated NOT */ @Override public void activate() { super.activate(); if (!isActivated) { List<IFigure> figures = new ArrayList<IFigure>(); childrenIFigure = new ArrayList<IFigure>(); int count = getPrimaryShape().getChildren().size(); for (int i = 0; i < count; i++) { IFigure figure = (IFigure) getPrimaryShape().getChildren().get(0); figures.add(figure); childrenIFigure.add(figure); getPrimaryShape().getChildren().remove(figure); } for (int i = 0; i < count; i++) { getPrimaryShape().getChildren().add(figures.get(i)); } ((Figure) (getPrimaryShape().getChildren().get(0))).setPreferredSize(100, 40); childrenIFigure.remove(childrenIFigure.size() - 1); isActivated = true; } } /** * @generated NOT */ protected void createDefaultEditPolicies() { installEditPolicy(EditPolicyRoles.CREATION_ROLE, new CreationEditPolicyWithCustomReparent( org.wso2.developerstudio.datamapper.diagram.part.DataMapperVisualIDRegistry.TYPED_INSTANCE)); super.createDefaultEditPolicies(); installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, new org.wso2.developerstudio.datamapper.diagram.edit.policies.TreeNode3ItemSemanticEditPolicy()); installEditPolicy(EditPolicyRoles.CANONICAL_ROLE, new org.wso2.developerstudio.datamapper.diagram.edit.policies.TreeNode3CanonicalEditPolicy()); installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy()); removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE); /* Disable dragging and resizing */ NonResizableEditPolicy selectionPolicy = new CustomNonResizableEditPolicyEx(); selectionPolicy.setDragAllowed(false); installEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE, selectionPolicy); /* remove balloon */ removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.POPUPBAR_ROLE); } /* * (non-Javadoc) * * @see org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart# * isSelectable() * */ @Override public boolean isSelectable() { return true; } /** * @generated NOT */ protected LayoutEditPolicy createLayoutEditPolicy() { org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() { protected EditPolicy createChildEditPolicy(EditPart child) { EditPolicy result = child.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE); if (result == null) { result = new NonResizableEditPolicy(); } return result; } protected Command getMoveChildrenCommand(Request request) { return null; } protected Command getCreateCommand(CreateRequest request) { return null; } }; return lep; } /** * @generated NOT */ protected IFigure createNodeShape() { return primaryShape = new TreeNodeFigure(); } /** * @generated */ public TreeNodeFigure getPrimaryShape() { return (TreeNodeFigure) primaryShape; } private EditPart getParentBox() { EditPart temp = this.getParent(); while ((!(temp instanceof DataMapperRootEditPart)) && (temp != null)) { if (temp instanceof InputEditPart || temp instanceof OutputEditPart) { break; } temp = temp.getParent(); } return temp; } /** * @generated */ protected boolean addFixedChild(EditPart childEditPart) { String type = getNodeType(); EditPart temp = this.getParentBox(); if (childEditPart instanceof TreeNodeName3EditPart) { ((TreeNodeName3EditPart) childEditPart).setLabel(getPrimaryShape().getFigureTreeNodeNameFigure()); return true; } if (childEditPart instanceof InNodeEditPart) { if (temp instanceof InputEditPart) { createEmptyInNode(childEditPart); } else { //If an element has children, then disable the innode connector arrow if (((TreeNode) ((View) getModel()).getElement()).getNode().size() > 0) { String value = getNodeValue(type); // If an element has values then enable the connector arrow if (StringUtils.isNotEmpty(value)) { return createInNode(childEditPart); }else { createEmptyInNode(childEditPart); } } else { if (type.equals(JSON_SCHEMA_OBJECT) || type.equals(JSON_SCHEMA_ARRAY)) { String itemsType = getItemsType(); // If an element has values then enable the connector // arrow if (itemsType.equals(NULL_VALUE)) { createEmptyInNode(childEditPart); } else { return createInNode(childEditPart); } } else { if (type.equals(NULL_VALUE)) { // If type is null, then disable the in node // connector createEmptyInNode(childEditPart); } else { return createInNode(childEditPart); } } } } } if (childEditPart instanceof OutNodeEditPart) { if (temp instanceof OutputEditPart) { createEmptyOutNode(childEditPart); } else { //If an element has children, then disable the outnode connector arrow if (((TreeNode) ((View) getModel()).getElement()).getNode().size() > 0) { String value = getNodeValue(type); // If an element has values then enable the connector arrow if (StringUtils.isNotEmpty(value)) { return createOutNode(childEditPart); }else { createEmptyOutNode(childEditPart); } } else { if (type.equals(JSON_SCHEMA_OBJECT) || type.equals(JSON_SCHEMA_ARRAY)) { String itemsType = getItemsType(); // If an element has values then enable the connector // arrow if (itemsType.equals(NULL_VALUE)) { createEmptyOutNode(childEditPart); } else { return createOutNode(childEditPart); } } else { if (type.equals(NULL_VALUE)) { // If type is null, then disable the out node // connector createEmptyOutNode(childEditPart); } else { return createOutNode(childEditPart); } } } } } return false; } public String getItemsType(){ String type = ""; for (PropertyKeyValuePair keyValue : (((TreeNode) ((View) getModel()).getElement()).getProperties())) { if (keyValue.getKey().equals(JSON_SCHEMA_ARRAY_ITEMS_TYPE)) { type = keyValue.getValue(); break; } } return type; } private void createEmptyInNode(EditPart childEditPart) { NodeFigure figureInput = (NodeFigure) ((InNodeEditPart) childEditPart).getFigure(); figureInput.removeAll(); Figure emptyFigure = new Figure(); figureInput.add(emptyFigure); } private void createEmptyOutNode(EditPart childEditPart) { NodeFigure figureInput = (NodeFigure) ((OutNodeEditPart) childEditPart).getFigure(); figureInput.removeAll(); Figure emptyFigure = new Figure(); figureInput.add(emptyFigure); } private boolean createInNode(EditPart childEditPart) { BorderItemLocator locator = new BorderItemLocator(getMainFigure(), PositionConstants.WEST); getBorderedFigure().getBorderItemContainer().add(((InNodeEditPart) childEditPart).getFigure(), locator); return true; } private boolean createOutNode(EditPart childEditPart) { BorderItemLocator locator = new BorderItemLocator(getMainFigure(), PositionConstants.EAST); getBorderedFigure().getBorderItemContainer().add(((OutNodeEditPart) childEditPart).getFigure(), locator); return true; } public String getNodeType() { String type = ""; for (PropertyKeyValuePair keyValue : (((TreeNode) ((View) getModel()).getElement()).getProperties())) { if (keyValue.getKey().equals(JSON_SCHEMA_TYPE)) { type = keyValue.getValue(); break; } } return type; } public String getNodeValue(String type) { String value = ""; if (type.equals(JSON_SCHEMA_ARRAY)) { for (PropertyKeyValuePair keyValue : (((TreeNode) ((View) getModel()).getElement()).getProperties())) { if (keyValue.getKey().equals(JSON_SCHEMA_ARRAY_ITEMS_VALUE_TYPE)) { value = keyValue.getValue(); break; } } } else if (type.equals(JSON_SCHEMA_OBJECT)) { for (PropertyKeyValuePair keyValue : (((TreeNode) ((View) getModel()).getElement()).getProperties())) { if (keyValue.getKey().equals(JSON_SCHEMA_OBJECT_VALUE_TYPE)) { value = keyValue.getValue(); break; } } } return value; } /** * @generated */ protected boolean removeFixedChild(EditPart childEditPart) { if (childEditPart instanceof TreeNodeName3EditPart) { return true; } if (childEditPart instanceof InNodeEditPart) { getBorderedFigure().getBorderItemContainer().remove(((InNodeEditPart) childEditPart).getFigure()); return true; } if (childEditPart instanceof OutNodeEditPart) { getBorderedFigure().getBorderItemContainer().remove(((OutNodeEditPart) childEditPart).getFigure()); return true; } return false; } /** * @generated */ protected void addChildVisual(EditPart childEditPart, int index) { if (addFixedChild(childEditPart)) { return; } super.addChildVisual(childEditPart, -1); } /** * @generated */ protected void removeChildVisual(EditPart childEditPart) { if (removeFixedChild(childEditPart)) { return; } super.removeChildVisual(childEditPart); } /** * @generated */ protected IFigure getContentPaneFor(IGraphicalEditPart editPart) { if (editPart instanceof IBorderItemEditPart) { return getBorderedFigure().getBorderItemContainer(); } return getContentPane(); } /** * @generated */ protected NodeFigure createNodePlate() { DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40); return result; } /** * Creates figure for this edit part. * * Body of this method does not depend on settings in generation model so * you may safely remove <i>generated</i> tag and modify it. * * @generated */ protected NodeFigure createMainFigure() { NodeFigure figure = createNodePlate(); figure.setLayoutManager(new StackLayout()); IFigure shape = createNodeShape(); figure.add(shape); contentPane = setupContentPane(shape); return figure; } /** * Default implementation treats passed figure as content pane. Respects * layout one may have set for generated figure. * * @param nodeShape * instance of generated figure class * @generated */ protected IFigure setupContentPane(IFigure nodeShape) { if (nodeShape.getLayoutManager() == null) { ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout(); layout.setSpacing(5); nodeShape.setLayoutManager(layout); } return nodeShape; // use nodeShape itself as contentPane } /** * @generated */ public IFigure getContentPane() { if (contentPane != null) { return contentPane; } return super.getContentPane(); } /** * @generated */ protected void setForegroundColor(Color color) { if (primaryShape != null) { primaryShape.setForegroundColor(color); } } /** * @generated */ protected void setBackgroundColor(Color color) { if (primaryShape != null) { primaryShape.setBackgroundColor(color); } } /** * @generated */ protected void setLineWidth(int width) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineWidth(width); } } /** * @generated */ protected void setLineType(int style) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineStyle(style); } } /** * @generated */ public EditPart getPrimaryChildEditPart() { return getChildBySemanticHint(DataMapperVisualIDRegistry.getType(TreeNodeName3EditPart.VISUAL_ID)); } /** * @generated NOT */ public class TreeNodeFigure extends RectangleFigure { private static final String ELEMENT_ICON = "icons/gmf/symbol_element_of.gif"; private static final String ARRAY_ICON = "icons/gmf/arrays.jpg"; private static final String OBJECT_ICON = "icons/gmf/object.jpg"; private static final String ATTRIBUTE_ICON = "icons/gmf/AttributeIcon.png"; private static final String ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM = "org.wso2.developerstudio.visualdatamapper.diagram"; private static final String JSON_SCHEMA_TYPE = "type"; private static final String JSON_SCHEMA_ARRAY = "array"; private static final String JSON_SCHEMA_OBJECT = "object"; private static final String PREFIX = "@"; /** * @generated */ private WrappingLabel fFigureTreeNodeNameFigure; /** * @generated NOT */ boolean isExpanded = true; /** * @generated NOT */ ClickNode clickNode; /** * @generated NOT */ public TreeNodeFigure() { ToolbarLayout layoutThis = new ToolbarLayout(); layoutThis.setStretchMinorAxis(true); layoutThis.setMinorAlignment(ToolbarLayout.ALIGN_TOPLEFT); // layoutThis.setSpacing(1); layoutThis.setVertical(true); this.setLayoutManager(layoutThis); this.setOpaque(false); this.setFill(false); this.setOutline(false); createContents(); } /** * @generated NOT */ private void createContents() { RectangleFigure figure = new RectangleFigure(); ToolbarLayout l = new ToolbarLayout(); l.setVertical(false); figure.setLayoutManager(l); figure.setPreferredSize(100, 3); figure.setBorder(null); figure.setOpaque(true); RectangleFigure figure2 = new RectangleFigure(); figure2.setBorder(null); figure2.setOpaque(true); ImageDescriptor mainImgDescCollapse = AbstractUIPlugin .imageDescriptorFromPlugin(ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM, ELEMENT_ICON);// plus ImageDescriptor attributeImgDesc = AbstractUIPlugin .imageDescriptorFromPlugin(ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM, ATTRIBUTE_ICON); ImageDescriptor arrayImgDesc = AbstractUIPlugin .imageDescriptorFromPlugin(ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM, ARRAY_ICON); ImageDescriptor objectImgDesc = AbstractUIPlugin .imageDescriptorFromPlugin(ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM, OBJECT_ICON); final ImageFigure mainImg = new ImageFigure(mainImgDescCollapse.createImage()); mainImg.setSize(new Dimension(10, 8)); ImageFigure attributeImg = new ImageFigure(attributeImgDesc.createImage()); // attribute // symbole // figure attributeImg.setSize(new Dimension(10, 8)); ImageFigure arrayImg = new ImageFigure(arrayImgDesc.createImage()); // array // symbole // figure arrayImg.setSize(new Dimension(10, 8)); ImageFigure objectImg = new ImageFigure(objectImgDesc.createImage()); // array // symbole // figure arrayImg.setSize(new Dimension(10, 8)); RectangleFigure mainImageRectangle = new RectangleFigure(); mainImageRectangle.setBackgroundColor(new Color(null, 255, 255, 255)); mainImageRectangle.setPreferredSize(new Dimension(10, 7)); mainImageRectangle.add(mainImg); mainImageRectangle.setBorder(new MarginBorder(1, 1, 1, 1)); RectangleFigure attributeImageRectangle = new RectangleFigure(); attributeImageRectangle.setBackgroundColor(new Color(null, 255, 255, 255)); attributeImageRectangle.setPreferredSize(new Dimension(10, 7)); attributeImageRectangle.add(attributeImg); mainImageRectangle.setBorder(new MarginBorder(1, 1, 1, 1)); RectangleFigure arrayImageRectangle = new RectangleFigure(); arrayImageRectangle.setBackgroundColor(new Color(null, 255, 255, 255)); arrayImageRectangle.setPreferredSize(new Dimension(10, 7)); arrayImageRectangle.add(attributeImg); arrayImageRectangle.setBorder(new MarginBorder(1, 1, 1, 1)); RectangleFigure objectImageRectangle = new RectangleFigure(); objectImageRectangle.setBackgroundColor(new Color(null, 255, 255, 255)); objectImageRectangle.setPreferredSize(new Dimension(10, 7)); objectImageRectangle.add(attributeImg); objectImageRectangle.setBorder(new MarginBorder(1, 1, 1, 1)); fFigureTreeNodeNameFigure = new WrappingLabel(); /* * String name = (((TreeNode) ((View) * getModel()).getElement()).getName()).split(",")[1]; int count = * Integer.parseInt((((TreeNode) ((View) * getModel()).getElement()).getName()) .split(",")[0]); */ String name = (((TreeNode) ((View) getModel()).getElement()).getName()); String type = null; for (PropertyKeyValuePair keyValue : (((TreeNode) ((View) getModel()).getElement()).getProperties())) { if (keyValue.getKey().equals(JSON_SCHEMA_TYPE)) { type = keyValue.getValue(); break; } } int count = ((TreeNode) ((View) getModel()).getElement()).getLevel(); fFigureTreeNodeNameFigure.setText(name); fFigureTreeNodeNameFigure.setForegroundColor(ColorConstants.black); fFigureTreeNodeNameFigure.setFont(new Font(null, "Arial", 10, SWT.BOLD)); String newName = null; if (StringUtils.isNotEmpty(name) && name.startsWith(PREFIX)) { String[] fullName = name.split(PREFIX); newName = fullName[1]; } else { newName = name; } figure2.setPreferredSize((count - 1) * 22, 3); final Label nodeLabel = new Label(); if (StringUtils.isNotEmpty(name) && name.startsWith(PREFIX)) { nodeLabel.setIcon(attributeImg.getImage()); } else if (type != null && type.equals(JSON_SCHEMA_ARRAY)) { nodeLabel.setIcon(arrayImg.getImage()); } else if (type != null && type.equals(JSON_SCHEMA_OBJECT)) { nodeLabel.setIcon(objectImg.getImage()); } else { nodeLabel.setIcon(mainImg.getImage()); } Display display = Display.getCurrent(); final Color black = display.getSystemColor(SWT.COLOR_BLACK); nodeLabel.setForegroundColor(black); nodeLabel.setText(newName); nodeLabel.setSize(new Dimension(100, 5)); this.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent me) { highlightElementOnSelection(); } @Override public void mouseEntered(MouseEvent me) { highlightElementOnSelection(); getEditDomain().getPaletteViewer().setActiveTool((ToolEntry) (((PaletteContainer) getEditDomain() .getPaletteViewer().getPaletteRoot().getChildren().get(1)).getChildren().get(0))); } @Override public void mouseExited(MouseEvent me) { removeHighlight(); getEditDomain().getPaletteViewer().setActiveTool(null); } @Override public void mouseHover(MouseEvent me) { highlightElementOnSelection(); } @Override public void mouseMoved(MouseEvent me) { } }); this.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent me) { removeHighlight(); } @Override public void mousePressed(MouseEvent me) { highlightElementOnSelection(); } @Override public void mouseDoubleClicked(MouseEvent me) { highlightElementOnSelection(); } }); figure.setOutline(false); figure2.setOutline(false); figure.add(figure2); figure.add(nodeLabel); figure.setFill(false); figure2.setFill(false); this.setFill(false); this.setOutline(false); this.add(figure); } /** * @generated */ public WrappingLabel getFigureTreeNodeNameFigure() { return fFigureTreeNodeNameFigure; } /** * @generated NOT */ public void repaint(boolean Expanded, ImageFigure image) { if (!Expanded) { clickNode.setContents(image); isExpanded = true; for (int i = childrenIFigure.size() - 1; i >= 0; i getPrimaryShape().getChildren().add(childrenIFigure.get(i)); } } else { clickNode.setContents(image); isExpanded = false; for (int i = 0; i < childrenIFigure.size(); i++) { getPrimaryShape().getChildren().remove(childrenIFigure.get(i)); } } } /** * @generated NOT */ public class ClickNode extends Clickable { public ClickNode(ImageFigure image) { this.setContents(image); } @Override protected void setContents(IFigure contents) { super.setContents(contents); } } public void renameElement(String name, String type) { ImageDescriptor mainImgDescCollapse = AbstractUIPlugin .imageDescriptorFromPlugin(ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM, ELEMENT_ICON); ImageDescriptor attributeImgDesc = AbstractUIPlugin .imageDescriptorFromPlugin(ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM, ATTRIBUTE_ICON); ImageDescriptor arrayImgDesc = AbstractUIPlugin .imageDescriptorFromPlugin(ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM, ARRAY_ICON); ImageDescriptor objectImgDesc = AbstractUIPlugin .imageDescriptorFromPlugin(ORG_WSO2_DEVELOPERSTUDIO_VISUALDATAMAPPER_DIAGRAM, OBJECT_ICON); final ImageFigure mainImg = new ImageFigure(mainImgDescCollapse.createImage()); mainImg.setSize(new Dimension(10, 8)); ImageFigure attributeImg = new ImageFigure(attributeImgDesc.createImage()); // attribute // symbole // figure attributeImg.setSize(new Dimension(10, 8)); ImageFigure arrayImg = new ImageFigure(arrayImgDesc.createImage()); // array // symbole // figure attributeImg.setSize(new Dimension(10, 8)); ImageFigure objectImg = new ImageFigure(objectImgDesc.createImage()); // object // symbole // figure attributeImg.setSize(new Dimension(10, 8)); Label nodeLabel = new Label(); String newName = null; if (StringUtils.isNotEmpty(name) && name.startsWith(PREFIX)) { String[] fullName = name.split(PREFIX); newName = fullName[1]; } else { newName = name; } if (StringUtils.isNotEmpty(name) && name.startsWith(PREFIX)) { nodeLabel.setIcon(attributeImg.getImage()); } else if (type != null && type.equals(JSON_SCHEMA_ARRAY)) { nodeLabel.setIcon(arrayImg.getImage()); } else if (type != null && type.equals(JSON_SCHEMA_OBJECT)) { nodeLabel.setIcon(objectImg.getImage()); } else { nodeLabel.setIcon(mainImg.getImage()); } Display display = Display.getCurrent(); Color black = display.getSystemColor(SWT.COLOR_BLACK); nodeLabel.setForegroundColor(black); nodeLabel.setText(newName); nodeLabel.setSize(new Dimension(100, 5)); RectangleFigure rectFigure = (RectangleFigure) this.getChildren().get(0); List<Figure> childrenList = rectFigure.getChildren(); rectFigure.remove(childrenList.get(1)); rectFigure.add(nodeLabel); } public void highlightElementOnSelection() { RectangleFigure rectFigure = (RectangleFigure) this.getChildren().get(0); List<Figure> childrenList = rectFigure.getChildren(); Display display = Display.getCurrent(); Color bckGrndColor = new Color(null, 0, 125, 133); Label newLabel = (Label) childrenList.get(1); newLabel.setForegroundColor(bckGrndColor); rectFigure.remove(childrenList.get(1)); rectFigure.add(newLabel); } public void removeHighlight() { RectangleFigure rectFigure = (RectangleFigure) this.getChildren().get(0); List<Figure> childrenList = rectFigure.getChildren(); Display display = Display.getCurrent(); Color bckGrndColor = display.getSystemColor(SWT.COLOR_BLACK); Label newLabel = (Label) childrenList.get(1); newLabel.setForegroundColor(bckGrndColor); rectFigure.remove(childrenList.get(1)); rectFigure.add(newLabel); } } public void renameElementItem(String newName, String type) { getPrimaryShape().renameElement(newName, type); } public void removeHighlightOnElem() { getPrimaryShape().removeHighlight(); } public void highlightElementItem() { getPrimaryShape().highlightElementOnSelection(); } }
package fr.obeo.dsl.debug.ide.ui.launch; import fr.obeo.dsl.debug.ide.Activator; import fr.obeo.dsl.debug.ide.launch.AbstractDSLLaunchConfigurationDelegate; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.ILaunchGroup; import org.eclipse.debug.ui.ILaunchShortcut; import org.eclipse.debug.ui.ILaunchShortcut2; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.ResourceUtil; /** * An UI implementation of {@link AbstractDSLLaunchConfigurationDelegate} with {@link ILaunchShortcut} * support. * * @author <a href="mailto:yvan.lussaud@obeo.fr">Yvan Lussaud</a> */ public abstract class AbstractDSLLaunchConfigurationDelegateUI extends AbstractDSLLaunchConfigurationDelegate implements ILaunchShortcut, ILaunchShortcut2 { @Override protected void launch(EObject firstInstruction, ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { Display.getDefault().syncExec(new Runnable() { public void run() { ExtendedImageRegistry.getInstance(); // initialize the image registry } }); super.launch(firstInstruction, configuration, mode, launch, monitor); } /** * {@inheritDoc} * * @see org.eclipse.debug.ui.ILaunchShortcut2#getLaunchConfigurations(org.eclipse.jface.viewers.ISelection) */ public ILaunchConfiguration[] getLaunchConfigurations(ISelection selection) { return getLaunchConfigurations(getLaunchableResource(selection)); } /** * {@inheritDoc} * * @see org.eclipse.debug.ui.ILaunchShortcut2#getLaunchConfigurations(org.eclipse.ui.IEditorPart) */ public ILaunchConfiguration[] getLaunchConfigurations(IEditorPart editorpart) { return getLaunchConfigurations(getLaunchableResource(editorpart)); } /** * {@inheritDoc} * * @see org.eclipse.debug.ui.ILaunchShortcut2#getLaunchableResource(org.eclipse.jface.viewers.ISelection) */ public IResource getLaunchableResource(ISelection selection) { IResource res = null; if (selection instanceof IStructuredSelection) { for (final Object element : ((IStructuredSelection)selection).toArray()) { if (element instanceof IFile) { res = (IResource)element; break; } else if (element instanceof EObject) { final URI resourceURI = ((EObject)element).eResource().getURI(); if (resourceURI.isPlatformResource()) { final String pathString = resourceURI.toPlatformString(true); res = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(pathString)); break; } } } } return res; } /** * {@inheritDoc} * * @see org.eclipse.debug.ui.ILaunchShortcut2#getLaunchableResource(org.eclipse.ui.IEditorPart) */ public IResource getLaunchableResource(IEditorPart editorpart) { return ResourceUtil.getFile(editorpart.getEditorInput()); } /** * {@inheritDoc} * * @see org.eclipse.debug.ui.ILaunchShortcut#launch(org.eclipse.jface.viewers.ISelection, * java.lang.String) */ public void launch(ISelection selection, String mode) { launch(getLaunchableResource(selection), getFirstInstruction(selection), mode); } /** * {@inheritDoc} * * @see org.eclipse.debug.ui.ILaunchShortcut#launch(org.eclipse.ui.IEditorPart, java.lang.String) */ public void launch(IEditorPart editor, String mode) { launch(getLaunchableResource(editor), getFirstInstruction(editor), mode); } /** * Get all {@link ILaunchConfiguration} that target the given {@link IResource}. * * @param resource * root file to execute * @return {@link ILaunchConfiguration}s using resource */ protected ILaunchConfiguration[] getLaunchConfigurations(IResource resource) { final List<ILaunchConfiguration> configurations = new ArrayList<ILaunchConfiguration>(); final ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType type = manager .getLaunchConfigurationType(getLaunchConfigurationTypeID()); // try to find existing configurations using the same file try { for (ILaunchConfiguration configuration : manager.getLaunchConfigurations(type)) { if (configuration.hasAttribute(AbstractDSLLaunchConfigurationDelegate.RESOURCE_URI)) { final String pathString = configuration.getAttribute( AbstractDSLLaunchConfigurationDelegate.RESOURCE_URI, ""); try { IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(pathString)); if (resource != null && resource.equals(file)) { configurations.add(configuration); } } catch (IllegalArgumentException e) { } } } } catch (CoreException e) { // could not load configurations, ignore e.toString(); } return configurations.toArray(new ILaunchConfiguration[configurations.size()]); } /** * Launch a resource. Try to launch using a launch configuration. Used for contextual launches * * @param file * source file * @param firstInstruction * the first {@link EObject instruction} * @param mode * launch mode */ public void launch(final IResource file, EObject firstInstruction, final String mode) { if (file instanceof IFile) { // try to save dirty editors PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().saveAllEditors(true); try { ILaunchConfiguration[] configurations = getLaunchConfigurations(file); if (configurations.length == 0) { // try to create a launch configuration configurations = createLaunchConfiguration(file, firstInstruction, mode); } // launch if (configurations.length == 1) { configurations[0].launch(mode, new NullProgressMonitor()); } else { // more than one configuration applies // open launch dialog for selection final ILaunchGroup group = DebugUITools.getLaunchGroup(configurations[0], mode); DebugUITools.openLaunchConfigurationDialogOnGroup(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), new StructuredSelection(configurations[0]), group.getIdentifier(), null); } } catch (CoreException e) { // could not create launch configuration, run file directly // try { // launch(firstInstruction, null, mode, null, new NullProgressMonitor()); // } catch (CoreException e1) { Activator.getDefault().error(e); } } } /** * Creates a {@link ILaunchConfiguration}. If the <code>firstInstruction</code> is <code>null</code> the * launch configuration dialog is opened. * * @param file * the selected model {@link IFile} * @param firstInstruction * the first {@link EObject instruction} or <code>null</code> for interactive selection * @param mode * the {@link ILaunchConfiguration#getModes() mode} * @return an array of possible {@link ILaunchConfiguration}, can be empty but not <code>null</code> * @throws CoreException * if {@link ILaunchConfiguration} initialization fails of models can't be loaded */ protected ILaunchConfiguration[] createLaunchConfiguration(final IResource file, EObject firstInstruction, final String mode) throws CoreException { final ILaunchConfiguration[] res; ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = manager.getLaunchConfigurationType(getLaunchConfigurationTypeID()); ILaunchConfigurationWorkingCopy configuration = type.newInstance(null, file.getName()); configuration.setMappedResources(new IResource[] {file, }); configuration.setAttribute(AbstractDSLLaunchConfigurationDelegate.RESOURCE_URI, file.getFullPath() .toString()); if (firstInstruction == null) { // open configuration for further editing final ILaunchGroup group = DebugUITools.getLaunchGroup(configuration, mode); if (group != null) { configuration.doSave(); DebugUITools.openLaunchConfigurationDialog(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), configuration, group.getIdentifier(), null); } res = new ILaunchConfiguration[] {}; } else { configuration.setAttribute(AbstractDSLLaunchConfigurationDelegate.FIRST_INSTRUCTION_URI, EcoreUtil.getURI(firstInstruction).toString()); // save and return new configuration configuration.doSave(); res = new ILaunchConfiguration[] {configuration, }; } return res; } /** * Gets the {@link ILaunchConfiguration} {@link ILaunchConfiguration#getType() type}. * * @return the {@link ILaunchConfiguration} {@link ILaunchConfiguration#getType() type} */ protected abstract String getLaunchConfigurationTypeID(); /** * Gets the first {@link EObject instruction} from the given {@link ISelection}. * * @param selection * the {@link ISelection} * @return the first {@link EObject instruction} from the given {@link ISelection} or <code>null</code> * for interactive selection */ protected abstract EObject getFirstInstruction(ISelection selection); /** * Gets the first {@link EObject instruction} from the given {@link IEditorPart}. * * @param editor * the {@link IEditorPart} * @return the first {@link EObject instruction} from the given {@link IEditorPart} or <code>null</code> * for interactive selection */ protected abstract EObject getFirstInstruction(IEditorPart editor); }
package com.perm.kate.api; import java.io.Serializable; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Attachment implements Serializable { private static final long serialVersionUID = 1L; public long id;//used only for wall post attached to message public String type; //photo,posted_photo,video,audio,link,note,app,poll,doc,geo,message,page public Photo photo; //public Photo posted_photo; public Video video; public Audio audio; public Link link; public Note note; public Graffiti graffiti; public VkApp app; public VkPoll poll; public Geo geo; public Document document; public Message message; public WallMessage wallMessage; public Page page; public static ArrayList<Attachment> parseAttachments(JSONArray attachments, long from_id, long copy_owner_id, JSONObject geo_json) throws JSONException { ArrayList<Attachment> attachments_arr=new ArrayList<Attachment>(); if(attachments!=null){ int size=attachments.length(); for(int j=0;j<size;++j){ Object att=attachments.get(j); if(att instanceof JSONObject==false) continue; JSONObject json_attachment=(JSONObject)att; Attachment attachment=new Attachment(); attachment.type=json_attachment.getString("type"); if(attachment.type.equals("photo") || attachment.type.equals("posted_photo")){ JSONObject x=json_attachment.optJSONObject("photo"); if(x!=null) attachment.photo=Photo.parse(x); } else if(attachment.type.equals("graffiti")) attachment.graffiti=Graffiti.parse(json_attachment.getJSONObject("graffiti")); else if(attachment.type.equals("link")) attachment.link=Link.parse(json_attachment.getJSONObject("link")); else if(attachment.type.equals("audio")) attachment.audio=Audio.parse(json_attachment.getJSONObject("audio")); else if(attachment.type.equals("note")) attachment.note=Note.parse(json_attachment.getJSONObject("note"), false); else if(attachment.type.equals("video")) attachment.video=Video.parseForAttachments(json_attachment.getJSONObject("video")); else if(attachment.type.equals("poll")){ attachment.poll=VkPoll.parse(json_attachment.getJSONObject("poll")); if(attachment.poll.owner_id==0){ if(copy_owner_id!=0) attachment.poll.owner_id=copy_owner_id; else attachment.poll.owner_id=from_id; } } else if(attachment.type.equals("doc")) attachment.document=Document.parse(json_attachment.getJSONObject("doc")); else if(attachment.type.equals("wall")) attachment.wallMessage=WallMessage.parse(json_attachment.getJSONObject("wall")); else if(attachment.type.equals("page")) attachment.page=Page.parseFromAttachment(json_attachment.getJSONObject("page")); attachments_arr.add(attachment); } } if(geo_json!=null){ Attachment a=new Attachment(); a.type="geo"; a.geo=Geo.parse(geo_json); attachments_arr.add(a); } return attachments_arr; } }
package org.springframework.cloud.contract.stubrunner.provider.wiremock; import com.github.jknack.handlebars.Helper; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer; import com.github.tomakehurst.wiremock.stubbing.StubMapping; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.contract.stubrunner.HttpServerStub; import org.springframework.cloud.contract.verifier.builder.handlebars.HandlebarsEscapeHelper; import org.springframework.cloud.contract.verifier.builder.handlebars.HandlebarsJsonPathHelper; import org.springframework.cloud.contract.wiremock.WireMockSpring; import org.springframework.util.ClassUtils; import org.springframework.util.SocketUtils; import org.springframework.util.StreamUtils; /** * Abstraction over WireMock as a HTTP Server Stub * * @author Marcin Grzejszczak * @since 1.1.0 */ public class WireMockHttpServerStub implements HttpServerStub { private static final Logger log = LoggerFactory.getLogger(WireMockHttpServerStub.class); private static final int INVALID_PORT = -1; private WireMockServer wireMockServer; private WireMockConfiguration config() { if (ClassUtils.isPresent("org.springframework.cloud.contract.wiremock.WireMockSpring", null)) { return WireMockSpring.options() .extensions(responseTemplateTransformer()); } return new WireMockConfiguration().extensions(responseTemplateTransformer()); } private ResponseTemplateTransformer responseTemplateTransformer() { return new ResponseTemplateTransformer(false, helpers()); } /** * Override this if you want to register your own helpers */ protected Map<String, Helper> helpers() { Map<String, Helper> helpers = new HashMap<>(); helpers.put(HandlebarsJsonPathHelper.NAME, new HandlebarsJsonPathHelper()); helpers.put(HandlebarsEscapeHelper.NAME, new HandlebarsEscapeHelper()); return helpers; } @Override public int port() { return isRunning() ? this.wireMockServer.port() : INVALID_PORT; } @Override public boolean isRunning() { return this.wireMockServer != null && this.wireMockServer.isRunning(); } @Override public HttpServerStub start() { if (isRunning()) { if (log.isDebugEnabled()) { log.info("The server is already running at port [" + port() + "]"); } return this; } return start(SocketUtils.findAvailableTcpPort()); } @Override public HttpServerStub start(int port) { this.wireMockServer = new WireMockServer(config().port(port)); this.wireMockServer.start(); return this; } @Override public HttpServerStub stop() { if (!isRunning()) { if (log.isDebugEnabled()) { log.warn("Trying to stop a non started server!"); } return this; } this.wireMockServer.stop(); return this; } @Override public HttpServerStub registerMappings(Collection<File> stubFiles) { if (!isRunning()) { throw new IllegalStateException("Server not started!"); } registerStubMappings(stubFiles); return this; } @Override public boolean isAccepted(File file) { return file.getName().endsWith(".json"); } StubMapping getMapping(File file) { try { return StubMapping.buildFrom(StreamUtils.copyToString( new FileInputStream(file), Charset.forName("UTF-8"))); } catch (IOException e) { throw new IllegalStateException("Cannot read file", e); } } private void registerStubMappings(Collection<File> stubFiles) { WireMock wireMock = new WireMock("localhost", port(), ""); registerDefaultHealthChecks(wireMock); registerStubs(stubFiles, wireMock); } private void registerDefaultHealthChecks(WireMock wireMock) { registerHealthCheck(wireMock, "/ping"); registerHealthCheck(wireMock, "/health"); } private void registerStubs(Collection<File> sortedMappings, WireMock wireMock) { for (File mappingDescriptor : sortedMappings) { try { wireMock.register(getMapping(mappingDescriptor)); if (log.isDebugEnabled()) { log.debug("Registered stub mappings from [" + mappingDescriptor + "]"); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to register the stub mapping [" + mappingDescriptor + "]", e); } } } } private void registerHealthCheck(WireMock wireMock, String url) { registerHealthCheck(wireMock, url, "OK"); } private void registerHealthCheck(WireMock wireMock, String url, String body) { wireMock.register( WireMock.get(WireMock.urlEqualTo(url)).willReturn(WireMock.aResponse().withBody(body).withStatus(200))); } }
package com.xpn.xwiki.user.impl.LDAP; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.model.EntityType; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.LocalDocumentReference; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.user.api.XWikiRightService; /** * Helper to manager LDAP profile XClass and XObject. * * @version $Id$ */ public class LDAPProfileXClass { public static final String LDAP_XCLASS = "XWiki.LDAPProfileClass"; public static final String LDAP_XFIELD_DN = "dn"; public static final String LDAP_XFIELDPN_DN = "LDAP DN"; public static final String LDAP_XFIELD_UID = "uid"; public static final String LDAP_XFIELDPN_UID = "LDAP user unique identifier"; public static final EntityReference LDAPPROFILECLASS_REFERENCE = new EntityReference("LDAPProfileClass", EntityType.DOCUMENT, new EntityReference("XWiki", EntityType.SPACE)); /** * The XWiki space where users are stored. */ private static final String XWIKI_USER_SPACE = "XWiki"; /** * Logging tool. */ private static final Logger LOGGER = LoggerFactory.getLogger(XWikiLDAPAuthServiceImpl.class); private XWikiContext context; private final BaseClass ldapClass; public LDAPProfileXClass(XWikiContext context) throws XWikiException { this.context = context; XWikiDocument ldapClassDoc = context.getWiki().getDocument(LDAPPROFILECLASS_REFERENCE, context); this.ldapClass = ldapClassDoc.getXClass(); boolean needsUpdate = this.ldapClass.addTextField(LDAP_XFIELD_DN, LDAP_XFIELDPN_DN, 80); needsUpdate |= this.ldapClass.addTextField(LDAP_XFIELD_UID, LDAP_XFIELDPN_UID, 80); if (ldapClassDoc.getCreatorReference() == null) { needsUpdate = true; ldapClassDoc.setCreator(XWikiRightService.SUPERADMIN_USER); } if (ldapClassDoc.getAuthorReference() == null) { needsUpdate = true; ldapClassDoc.setAuthorReference(ldapClassDoc.getCreatorReference()); } if (!ldapClassDoc.isHidden()) { needsUpdate = true; ldapClassDoc.setHidden(true); } if (needsUpdate) { context.getWiki().saveDocument(ldapClassDoc, "Update LDAP user profile class", context); } } /** * @param userDocument the user profile page. * @return the dn store in the user profile. Null if it can't find any or if it's empty. */ public String getDn(XWikiDocument userDocument) { BaseObject ldapObject = userDocument.getXObject(this.ldapClass.getDocumentReference()); return ldapObject == null ? null : getDn(ldapObject); } /** * @param ldapObject the ldap profile object. * @return the dn store in the user profile. Null if it can't find any or if it's empty. */ public String getDn(BaseObject ldapObject) { String dn = ldapObject.getStringValue(LDAP_XFIELD_DN); return dn.length() == 0 ? null : dn; } /** * @param userDocument the user profile page. * @return the uid store in the user profile. Null if it can't find any or if it's empty. */ public String getUid(XWikiDocument userDocument) { BaseObject ldapObject = userDocument.getXObject(this.ldapClass.getDocumentReference()); return ldapObject == null ? null : getUid(ldapObject); } /** * @param ldapObject the ldap profile object. * @return the uid store in the user profile. Null if it can't find any or if it's empty. */ public String getUid(BaseObject ldapObject) { String uid = ldapObject.getStringValue(LDAP_XFIELD_UID); return uid.length() == 0 ? null : uid; } /** * Update or create LDAP profile of an existing user profile with provided LDAP user informations. * * @param xwikiUserName the name of the XWiki user to update LDAP profile. * @param dn the dn to store in the LDAP profile. * @param uid the uid to store in the LDAP profile. * @throws XWikiException error when storing information in user profile. */ public void updateLDAPObject(String xwikiUserName, String dn, String uid) throws XWikiException { XWikiDocument userDocument = this.context.getWiki().getDocument(new LocalDocumentReference(XWIKI_USER_SPACE, xwikiUserName), this.context); boolean needsUpdate = updateLDAPObject(userDocument, dn, uid); if (needsUpdate) { this.context.getWiki().saveDocument(userDocument, "Update LDAP user profile", this.context); } } /** * Update LDAP profile object with provided LDAP user informations. * * @param userDocument the user profile page to update. * @param dn the dn to store in the LDAP profile. * @param uid the uid to store in the LDAP profile. * @return true if modifications has been made to provided user profile, false otherwise. */ public boolean updateLDAPObject(XWikiDocument userDocument, String dn, String uid) { BaseObject ldapObject = userDocument.getXObject(this.ldapClass.getDocumentReference(), true, this.context); Map<String, String> map = new HashMap<String, String>(); boolean needsUpdate = false; String objDn = getDn(ldapObject); if (!dn.equalsIgnoreCase(objDn)) { map.put(LDAP_XFIELD_DN, dn); needsUpdate = true; } String objUid = getUid(ldapObject); if (!uid.equalsIgnoreCase(objUid)) { map.put(LDAP_XFIELD_UID, uid); needsUpdate = true; } if (needsUpdate) { this.ldapClass.fromMap(map, ldapObject); } return needsUpdate; } /** * Search the XWiki storage for a existing user profile with provided LDAP user uid stored. * <p> * If more than one profile is found the first one in returned and an error is logged. * * @param uid the LDAP unique id. * @return the user profile containing LDAP uid. */ public XWikiDocument searchDocumentByUid(String uid) { XWikiDocument doc = null; List<XWikiDocument> documentList; try { // Search for uid in database, make sure to compare uids lower cased to make to to not take into account the // case since LDAP does not String sql = ", BaseObject as obj, StringProperty as prop where doc.fullName=obj.name and obj.className=? and obj.id=prop.id.id and prop.name=? and lower(prop.value)=?"; documentList = this.context .getWiki() .getStore() .searchDocuments(sql, false, false, false, 0, 0, Arrays.asList(LDAP_XCLASS, LDAP_XFIELD_UID, uid.toLowerCase()), this.context); } catch (XWikiException e) { LOGGER.error("Fail to search for document containing ldap uid [" + uid + "]", e); documentList = Collections.emptyList(); } if (documentList.size() > 1) { LOGGER.error("There is more than one user profile for LDAP uid [" + uid + "]"); } if (!documentList.isEmpty()) { doc = documentList.get(0); } return doc; } /** * Search the LDAP user DN stored in an existing user profile with provided LDAP user uid stored. * <p> * If more than one profile is found the first one in returned and an error is logged. * * @param uid the LDAP unique id. * @return the found LDAP DN, null if it can't find one or if it's empty. */ public String searchDn(String uid) { XWikiDocument document = searchDocumentByUid(uid); return document == null ? null : getDn(document); } }
package org.eclipse.birt.report.designer.ui.views.attributes.providers; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.AdvancePropertyPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.AlterPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.AutoTextPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.BookMarkExpressionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.BordersPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.CascadingParameterGroupI18nPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.CascadingParameterGroupPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.CellPaddingPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.CellPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ColumnPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ColumnSectionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.CommentsPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.DataPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.DataSetPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.DataSourcePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.DescriptionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ExpressionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.FormatDateTimeAttributePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.FormatNumberAttributePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.FormatStringAttributePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.GridPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.HeaderFooterPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.HyperLinkPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ImagePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ItemMarginPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.LabelI18nPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.LabelPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.LibraryPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ListPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ListingSectionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.MarginsPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.MasterPageGeneralPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.NamedExpressionsPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ParameterGroupI18nPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ParameterGroupPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ReferencePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ReportPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ResourcesPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.RowPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ScalarParameterI18nPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ScalarParameterPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.SectionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TOCExpressionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TablePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TemplateReportItemI18Page; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TemplateReportItemPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TextI18nPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TextPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.UserPropertiesPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.VisibilityPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.CategoryProvider; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DataSourceHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.MasterPageHandle; import org.eclipse.birt.report.model.api.TemplateElementHandle; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; /** * The default implement of ICategoryProviderFactory */ public class CategoryProviderFactory implements ICategoryProviderFactory { private static ICategoryProviderFactory instance = new CategoryProviderFactory( ); protected CategoryProviderFactory( ) { } /** * * @return The unique CategoryProviderFactory instance */ public static ICategoryProviderFactory getInstance( ) { return instance; } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.designer.ui.views.attributes.providers. * ICategoryProviderFactory#getCategoryProvider(java.lang.Object) */ public ICategoryProvider getCategoryProvider( Object model ) { if ( model instanceof DesignElementHandle ) { return getCategoryProvider( (DesignElementHandle) model ); } if ( model instanceof String ) { return getCategoryProvider( (String) model ); } if ( model instanceof List ) { List list = (List) model; if ( !list.isEmpty( ) ) { return getCategoryProvider( list.get( 0 ) ); } } return null; } public final static String CATEGORY_KEY_GENERAL = "General"; //$NON-NLS-1$ public final static String CATEGORY_KEY_PADDING = "Padding"; //$NON-NLS-1$ public final static String CATEGORY_KEY_FONT = "Font"; //$NON-NLS-1$ public final static String CATEGORY_KEY_BORDERS = "Borders"; //$NON-NLS-1$ public final static String CATEGORY_KEY_USERPROPERTIES = "UserProperties"; //$NON-NLS-1$ public final static String CATEGORY_KEY_NAMEDEXPRESSIONS = "NamedExpressions"; //$NON-NLS-1$ public final static String CATEGORY_KEY_VISIBILITY = "Visibility"; //$NON-NLS-1$ public final static String CATEGORY_KEY_FORMATNUMBER = "formatNumber"; //$NON-NLS-1$ public final static String CATEGORY_KEY_FORMATDATETIME = "formatDateTime"; //$NON-NLS-1$ public final static String CATEGORY_KEY_FORMATSTRING = "formatString"; //$NON-NLS-1$ public final static String CATEGORY_KEY_MARGIN = "Margin"; //$NON-NLS-1$ public final static String CATEGORY_KEY_HYPERLINK = "HyperLink"; //$NON-NLS-1$ public final static String CATEGORY_KEY_SECTION = "Section"; //$NON-NLS-1$ public final static String CATEGORY_KEY_TOC = "TOC"; //$NON-NLS-1$ public final static String CATEGORY_KEY_BOOKMARK = "Bookmark"; //$NON-NLS-1$ public final static String CATEGORY_KEY_REFERENCE = "Reference"; //$NON-NLS-1$ public final static String CATEGORY_KEY_ALTTEXT = "AltText"; //$NON-NLS-1$ public final static String CATEGORY_KEY_I18N = "I18n"; //$NON-NLS-1$ public final static String CATEGORY_KEY_DESCRIPTION = "Description"; //$NON-NLS-1$ public final static String CATEGORY_KEY_COMMENTS = "Comments"; //$NON-NLS-1$ public final static String CATEGORY_KEY_RESOURCES = "Resources"; //$NON-NLS-1$ public final static String CATEGORY_KEY_HEADER_FOOTER = "Header&Footer"; //$NON-NLS-1$ public final static String CATEGORY_KEY_EXPRESSION = "Expression"; //$NON-NLS-1$ public final static String CATEGORY_KEY_ADVANCEPROPERTY = "AdvanceProperty"; //$NON-NLS-1$ /** * CategoryHolder */ protected static class CategoryHolder { String[] keys; String[] labels; Class<?>[] pageClasses; public CategoryHolder( String[] key, String[] label, Class<?>[] pageClass ) { this.keys = key; this.labels = label; this.pageClasses = pageClass; } public String[] getKeys( ) { return keys; } public String[] getLabels( ) { return labels; } public Class[] getClasses( ) { return pageClasses; } /** * Replaces an existing entry of given key with new label and new page * class. * * @param targetKey * @param label * @param pageClass */ public void replace( String targetKey, String label, Class<?> pageClass ) { if ( targetKey == null || ( label == null && pageClass == null ) || keys == null ) { return; } int idx = -1; for ( int i = 0; i < keys.length; i++ ) { if ( targetKey.equals( keys[i] ) ) { idx = i; break; } } if ( idx == -1 ) { return; } if ( label != null && labels != null && idx < labels.length ) { labels[idx] = label; } if ( pageClass != null && pageClasses != null && idx < pageClasses.length ) { pageClasses[idx] = pageClass; } } /** * Inserts a new entry before an existing entry by given key. * * @param beforeKey * @param key * @param label * @param pageClass */ public void insertBefore( String beforeKey, String key, String label, Class<?> pageClass ) { // TODO optimize performance List<String> lkeys = null; List<String> llabels = null; List<Class<?>> lclasses = null; if ( keys == null ) { lkeys = new ArrayList<String>( ); } else { lkeys = new ArrayList<String>( Arrays.asList( keys ) ); } if ( labels == null ) { llabels = new ArrayList<String>( ); } else { llabels = new ArrayList<String>( Arrays.asList( labels ) ); } if ( pageClasses == null ) { lclasses = new ArrayList<Class<?>>( ); } else { lclasses = new ArrayList<Class<?>>( Arrays.asList( pageClasses ) ); } if ( beforeKey != null ) { int i = 0; for ( ; i < lkeys.size( ); i++ ) { if ( beforeKey.equals( lkeys.get( i ) ) ) { lkeys.add( i, key ); llabels.add( i, label ); lclasses.add( i, pageClass ); this.keys = lkeys.toArray( new String[lkeys.size( )] ); this.labels = llabels.toArray( new String[llabels.size( )] ); this.pageClasses = lclasses.toArray( new Class[lclasses.size( )] ); return; } } } // append to end. lkeys.add( key ); llabels.add( label ); lclasses.add( pageClass ); this.keys = lkeys.toArray( new String[lkeys.size( )] ); this.labels = llabels.toArray( new String[llabels.size( )] ); this.pageClasses = lclasses.toArray( new Class[lclasses.size( )] ); } } protected CategoryHolder getCategories( String elementName ) { if ( ReportDesignConstants.CELL_ELEMENT.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_PADDING, CATEGORY_KEY_BORDERS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "CellPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "CellPageGenerator.List.CellPadding" ), //$NON-NLS-1$ Messages.getString( "CellPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ CellPage.class, CellPaddingPage.class, BordersPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.COLUMN_ELEMENT.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "ColumnPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "ColumnPageGenerator.List.Visibility" ),//$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ ColumnPage.class, ColumnSectionPage.class, VisibilityPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.DATA_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_PADDING, CATEGORY_KEY_BORDERS, CATEGORY_KEY_MARGIN, CATEGORY_KEY_FORMATNUMBER, CATEGORY_KEY_FORMATDATETIME, CATEGORY_KEY_FORMATSTRING, CATEGORY_KEY_HYPERLINK, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "DataPageGenerator.List.General" ), //$NON-NLS-1$ // Messages.getString( "DataPageGenerator.List.Expression"), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.Padding" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.Margin" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.formatNumber" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.formatDateTime" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.formatString" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.HyperLink" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.Visibility" ),//$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.TOC" ),//$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ DataPage.class, // ExpressionPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, FormatNumberAttributePage.class, FormatDateTimeAttributePage.class, FormatStringAttributePage.class, HyperLinkPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.GRID_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_BORDERS, CATEGORY_KEY_MARGIN, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "GridPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "GridPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "GridPageGenerator.List.Margin" ), //$NON-NLS-1$ Messages.getString( "GridPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "GridPageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "GridPageGenerator.List.TOC" ), //$NON-NLS-1$ Messages.getString( "GridPageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ GridPage.class, BordersPage.class, ItemMarginPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.IMAGE_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_REFERENCE, CATEGORY_KEY_HYPERLINK, CATEGORY_KEY_ALTTEXT, CATEGORY_KEY_BORDERS, CATEGORY_KEY_MARGIN, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "ImagePageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ImagePageGenerator.List.Reference" ), //$NON-NLS-1$ Messages.getString( "ImagePageGenerator.List.HyperLink" ), //$NON-NLS-1$ Messages.getString( "ImagePageGenerator.List.AltText" ), //$NON-NLS-1$ Messages.getString( "ImagePageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "GridPageGenerator.List.Margin" ), //$NON-NLS-1$ Messages.getString( "ImagePageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "ImagePageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "ImagePageGenerator.List.TOC" ), //$NON-NLS-1$ Messages.getString( "ImagePageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ ImagePage.class, ReferencePage.class, HyperLinkPage.class, AlterPage.class, BordersPage.class, ItemMarginPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.LABEL_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_PADDING, CATEGORY_KEY_BORDERS, CATEGORY_KEY_MARGIN, CATEGORY_KEY_HYPERLINK, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_I18N, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "LabelPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.Padding" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.Margin" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.HyperLink" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.I18n" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.TOC" ), //$NON-NLS-1$ Messages.getString( "LabelPageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ LabelPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, HyperLinkPage.class, SectionPage.class, VisibilityPage.class, LabelI18nPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.LIBRARY_ELEMENT.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_DESCRIPTION, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_RESOURCES, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "ReportPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Description" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Resources" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ LibraryPage.class, DescriptionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, ResourcesPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.LIST_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_BORDERS, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "ListPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ListPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "ListPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "ListPageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "ListPageGenerator.List.TOC" ), //$NON-NLS-1$ Messages.getString( "ListPageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ ListPage.class, BordersPage.class, ListingSectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.REPORT_DESIGN_ELEMENT.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_DESCRIPTION, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_RESOURCES, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "ReportPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Description" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Resources" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ ReportPage.class, DescriptionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, ResourcesPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.ROW_ELEMENT.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_BORDERS, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "RowPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "RowPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "RowPageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "RowPageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ RowPage.class, BordersPage.class, SectionPage.class, VisibilityPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.SCALAR_PARAMETER_ELEMENT.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_I18N, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "ScalarParameterPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ScalarParameterPageGenerator.List.I18n" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ ScalarParameterPage.class, ScalarParameterI18nPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.PARAMETER_GROUP_ELEMENT.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_I18N, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "TextPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ScalarParameterPageGenerator.List.I18n" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ ParameterGroupPage.class, ParameterGroupI18nPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.CASCADING_PARAMETER_GROUP_ELEMENT.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_I18N, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "TextPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ScalarParameterPageGenerator.List.I18n" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ CascadingParameterGroupPage.class, CascadingParameterGroupI18nPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.TABLE_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_BORDERS, CATEGORY_KEY_MARGIN, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "TablePageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "TablePageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "TablePageGenerator.List.Marign" ), //$NON-NLS-1$ Messages.getString( "TablePageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "TablePageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "TablePageGenerator.List.TOC" ), //$NON-NLS-1$ Messages.getString( "TablePageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ TablePage.class, BordersPage.class, ItemMarginPage.class, ListingSectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.TEXT_DATA_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_EXPRESSION, CATEGORY_KEY_PADDING, CATEGORY_KEY_BORDERS, CATEGORY_KEY_MARGIN, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "TextPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "DataPageGenerator.List.Expression" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Padding" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Margin" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.TOC" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ TextPage.class, ExpressionPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.TEXT_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_PADDING, CATEGORY_KEY_BORDERS, CATEGORY_KEY_MARGIN, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_I18N, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "TextPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Padding" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Margin" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.I18n" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.TOC" ), //$NON-NLS-1$ Messages.getString( "TextPageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ TextPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, SectionPage.class, VisibilityPage.class, TextI18nPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } if ( ReportDesignConstants.AUTOTEXT_ITEM.equals( elementName ) ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_PADDING, CATEGORY_KEY_BORDERS, CATEGORY_KEY_MARGIN, CATEGORY_KEY_SECTION, CATEGORY_KEY_VISIBILITY, CATEGORY_KEY_TOC, CATEGORY_KEY_BOOKMARK, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_USERPROPERTIES, CATEGORY_KEY_NAMEDEXPRESSIONS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "AutoTextPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "AutoTextPageGenerator.List.Padding" ), //$NON-NLS-1$ Messages.getString( "AutoTextPageGenerator.List.Borders" ), //$NON-NLS-1$ Messages.getString( "AutoTextPageGenerator.List.Margin" ), //$NON-NLS-1$ Messages.getString( "AutoTextPageGenerator.List.Section" ), //$NON-NLS-1$ Messages.getString( "AutoTextPageGenerator.List.Visibility" ), //$NON-NLS-1$ Messages.getString( "AutoTextPageGenerator.List.TOC" ), //$NON-NLS-1$ Messages.getString( "AutoTextPageGenerator.List.Bookmark" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.UserProperties" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.NamedExpressions" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ AutoTextPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, AdvancePropertyPage.class, } ); } return null; } protected CategoryHolder getCategories( DesignElementHandle handle ) { if ( handle instanceof MasterPageHandle ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_MARGIN, CATEGORY_KEY_HEADER_FOOTER, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "MasterPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "MasterPageGenerator.List.Margins" ), //$NON-NLS-1$ Messages.getString( "MasterPageGenerator.List.Header&Footer" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ MasterPageGeneralPage.class, MarginsPage.class, HeaderFooterPage.class, CommentsPage.class, AdvancePropertyPage.class, } ); } if ( handle instanceof DataSetHandle ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "DataSetPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ DataSetPage.class, CommentsPage.class, AdvancePropertyPage.class, } ); } if ( handle instanceof DataSourceHandle ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "DataSourcePageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ DataSourcePage.class, CommentsPage.class, AdvancePropertyPage.class, } ); } if ( handle instanceof TemplateElementHandle ) { return new CategoryHolder( new String[]{ CATEGORY_KEY_GENERAL, CATEGORY_KEY_I18N, CATEGORY_KEY_COMMENTS, CATEGORY_KEY_ADVANCEPROPERTY, }, new String[]{ Messages.getString( "TemplateReportItemPageGenerator.List.General" ), //$NON-NLS-1$ Messages.getString( "TemplateReportItemPageGenerator.List.I18n" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.Comments" ), //$NON-NLS-1$ Messages.getString( "ReportPageGenerator.List.AdvancedProperty" ), //$NON-NLS-1$ }, new Class[]{ TemplateReportItemPage.class, TemplateReportItemI18Page.class, CommentsPage.class, AdvancePropertyPage.class, } ); } return getCategories( handle.getDefn( ).getName( ) ); } /** * Get CategoryProvider according to input element name */ protected ICategoryProvider getCategoryProvider( String elementName ) { CategoryHolder holder = getCategories( elementName ); if ( holder != null ) { return new CategoryProvider( holder.keys, holder.labels, holder.pageClasses ); } return null; } /** * Get the CategoryProvider according to input handle * * @param handle * @return */ protected ICategoryProvider getCategoryProvider( DesignElementHandle handle ) { CategoryHolder holder = getCategories( handle ); if ( holder != null ) { return new CategoryProvider( holder.keys, holder.labels, holder.pageClasses ); } return null; } }
package gov.nih.nci.cagrid.data.style.cacore32.helpers; import gov.nih.nci.cagrid.common.Utils; import gov.nih.nci.cagrid.data.common.CastorMappingUtil; import gov.nih.nci.cagrid.data.style.cacore32.encoding.SDK32EncodingUtils; import gov.nih.nci.cagrid.data.style.sdkstyle.helpers.PostCodegenHelper; import gov.nih.nci.cagrid.data.utilities.WsddUtil; import gov.nih.nci.cagrid.introduce.IntroduceConstants; import gov.nih.nci.cagrid.introduce.beans.extension.ServiceExtensionDescriptionType; import gov.nih.nci.cagrid.introduce.beans.service.ServiceType; import gov.nih.nci.cagrid.introduce.common.CommonTools; import gov.nih.nci.cagrid.introduce.common.ServiceInformation; import gov.nih.nci.cagrid.introduce.extension.CodegenExtensionException; import java.io.File; /** * SDK32PostCodegenHelper * Fixes stuff in the castor mapping * * @author David Ervin * * @created Aug 30, 2007 3:56:50 PM * @version $Id: SDK32PostCodegenHelper.java,v 1.2 2007-09-04 16:23:47 dervin Exp $ */ public class SDK32PostCodegenHelper extends PostCodegenHelper { public void codegenPostProcessStyle(ServiceExtensionDescriptionType desc, ServiceInformation info) throws Exception { super.codegenPostProcessStyle(desc, info); editWsddForCastorMappings(info); } private void editWsddForCastorMappings(ServiceInformation info) throws Exception { String mainServiceName = info.getIntroduceServiceProperties().getProperty( IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME); ServiceType mainService = CommonTools.getService(info.getServices(), mainServiceName); String servicePackageName = mainService.getPackageName(); String packageDir = servicePackageName.replace('.', File.separatorChar); // find the client source directory, where the client-config will be located File clientConfigFile = new File(info.getBaseDirectory().getAbsolutePath() + File.separator + "src" + File.separator + packageDir + File.separator + "client" + File.separator + "client-config.wsdd"); if (!clientConfigFile.exists()) { throw new CodegenExtensionException("Client config file " + clientConfigFile.getAbsolutePath() + " not found!"); } // fine the server-config.wsdd, located in the service's root directory File serverConfigFile = new File(info.getBaseDirectory().getAbsolutePath() + File.separator + "server-config.wsdd"); if (!serverConfigFile.exists()) { throw new CodegenExtensionException("Server config file " + serverConfigFile.getAbsolutePath() + " not found!"); } // edit the marshalling castor mapping to avoid serializing associations String marshallingXmlText = Utils.fileToStringBuffer( new File(CastorMappingUtil.getMarshallingCastorMappingFileName(info))).toString(); String editedMarshallingText = CastorMappingUtil.removeAssociationMappings(marshallingXmlText); String editedMarshallingFileName = CastorMappingUtil.getEditedMarshallingCastorMappingFileName(info); Utils.stringBufferToFile(new StringBuffer(editedMarshallingText), editedMarshallingFileName); // edit the UNmarshalling castor mapping to avoid DEserializing associations String unmarshallingXmlText = Utils.fileToStringBuffer( new File(CastorMappingUtil.getUnmarshallingCastorMappingFileName(info))).toString(); String editedUnmarshallingText = CastorMappingUtil.removeAssociationMappings(unmarshallingXmlText); String editedUnmarshallingFileName = CastorMappingUtil.getEditedUnmarshallingCastorMappingFileName(info); Utils.stringBufferToFile(new StringBuffer(editedUnmarshallingText), editedUnmarshallingFileName); // set properties in the client to use the edited marshaller WsddUtil.setGlobalClientParameter(clientConfigFile.getAbsolutePath(), SDK32EncodingUtils.CASTOR_MARSHALLER_PROPERTY, CastorMappingUtil.getEditedMarshallingCastorMappingName(info)); // and the edited unmarshaller WsddUtil.setGlobalClientParameter(clientConfigFile.getAbsolutePath(), SDK32EncodingUtils.CASTOR_UNMARSHALLER_PROPERTY, CastorMappingUtil.getEditedUnmarshallingCastorMappingName(info)); // set properties in the server to use the edited marshaller WsddUtil.setServiceParameter(serverConfigFile.getAbsolutePath(), info.getServices().getService(0).getName(), SDK32EncodingUtils.CASTOR_MARSHALLER_PROPERTY, CastorMappingUtil.getEditedMarshallingCastorMappingName(info)); // and the edited unmarshaller WsddUtil.setServiceParameter(serverConfigFile.getAbsolutePath(), info.getServices().getService(0).getName(), SDK32EncodingUtils.CASTOR_UNMARSHALLER_PROPERTY, CastorMappingUtil.getEditedUnmarshallingCastorMappingName(info)); } }
package org.nuxeo.ecm.platform.publisher.impl.service; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.common.utils.Path; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreInstance; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentLocation; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.repository.RepositoryManager; import org.nuxeo.ecm.platform.publisher.api.PublicationNode; import org.nuxeo.ecm.platform.publisher.api.PublicationTree; import org.nuxeo.ecm.platform.publisher.api.PublicationTreeNotAvailable; import org.nuxeo.ecm.platform.publisher.api.PublishedDocument; import org.nuxeo.ecm.platform.publisher.api.PublishedDocumentFactory; import org.nuxeo.ecm.platform.publisher.api.PublisherException; import org.nuxeo.ecm.platform.publisher.api.PublisherService; import org.nuxeo.ecm.platform.publisher.api.RemotePublicationTreeManager; import org.nuxeo.ecm.platform.publisher.descriptors.PublicationTreeConfigDescriptor; import org.nuxeo.ecm.platform.publisher.descriptors.PublicationTreeDescriptor; import org.nuxeo.ecm.platform.publisher.descriptors.PublishedDocumentFactoryDescriptor; import org.nuxeo.ecm.platform.publisher.helper.PublicationRelationHelper; import org.nuxeo.ecm.platform.publisher.rules.ValidatorsRule; import org.nuxeo.ecm.platform.publisher.rules.ValidatorsRuleDescriptor; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.model.ComponentContext; import org.nuxeo.runtime.model.ComponentInstance; import org.nuxeo.runtime.model.DefaultComponent; import org.nuxeo.runtime.transaction.TransactionHelper; /** * POJO implementation of the publisher service Implements both * {@link PublisherService} and {@link RemotePublicationTreeManager}. * * @author tiry */ public class PublisherServiceImpl extends DefaultComponent implements PublisherService, RemotePublicationTreeManager { protected static Map<String, PublicationTreeDescriptor> treeDescriptors = new HashMap<String, PublicationTreeDescriptor>(); protected static Map<String, PublishedDocumentFactoryDescriptor> factoryDescriptors = new HashMap<String, PublishedDocumentFactoryDescriptor>(); protected static Map<String, PublicationTreeConfigDescriptor> treeConfigDescriptors = new HashMap<String, PublicationTreeConfigDescriptor>(); protected static Map<String, ValidatorsRuleDescriptor> validatorsRuleDescriptors = new HashMap<String, ValidatorsRuleDescriptor>(); protected static Map<String, PublicationTreeConfigDescriptor> pendingDescriptors = new HashMap<String, PublicationTreeConfigDescriptor>(); private static final Log log = LogFactory.getLog(PublisherServiceImpl.class); protected static Map<String, PublicationTree> liveTrees = new HashMap<String, PublicationTree>(); // Store association between treeSid and CoreSession that was opened locally // for them : this unable proper cleanup of allocated sessions protected Map<String, String> remoteLiveTrees = new HashMap<String, String>(); public static final String TREE_EP = "tree"; public static final String TREE_CONFIG_EP = "treeInstance"; public static final String VALIDATORS_RULE_EP = "validatorsRule"; public static final String FACTORY_EP = "factory"; protected static final String ROOT_PATH_KEY = "RootPath"; protected static final String RELATIVE_ROOT_PATH_KEY = "RelativeRootPath"; @Override public void applicationStarted(ComponentContext context) throws Exception { if (TransactionHelper.startTransaction()) { try { doApplicationStarted(); } catch (Throwable e) { TransactionHelper.setTransactionRollbackOnly(); } finally { TransactionHelper.commitOrRollbackTransaction(); } } else { doApplicationStarted(); } } protected void doApplicationStarted() { ClassLoader jbossCL = Thread.currentThread().getContextClassLoader(); ClassLoader nuxeoCL = PublisherServiceImpl.class.getClassLoader(); try { Thread.currentThread().setContextClassLoader(nuxeoCL); log.info("Publisher Service initialization"); registerPendingDescriptors(); } catch (Exception e) { log.error("Unable to register pending descriptors", e); } finally { Thread.currentThread().setContextClassLoader(jbossCL); log.debug("JBoss ClassLoader restored"); } } @Override public void activate(ComponentContext context) throws Exception { liveTrees = new HashMap<String, PublicationTree>(); treeDescriptors = new HashMap<String, PublicationTreeDescriptor>(); factoryDescriptors = new HashMap<String, PublishedDocumentFactoryDescriptor>(); treeConfigDescriptors = new HashMap<String, PublicationTreeConfigDescriptor>(); validatorsRuleDescriptors = new HashMap<String, ValidatorsRuleDescriptor>(); pendingDescriptors = new HashMap<String, PublicationTreeConfigDescriptor>(); } // for testing cleanup public static int getLiveTreeCount() { return liveTrees.size(); } public static PublicationTree getTreeBySid(String sid) { return liveTrees.get(sid); } @Override public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) throws Exception { log.debug("Registry contribution for EP " + extensionPoint); if (TREE_EP.equals(extensionPoint)) { PublicationTreeDescriptor desc = (PublicationTreeDescriptor) contribution; treeDescriptors.put(desc.getName(), desc); } else if (TREE_CONFIG_EP.equals(extensionPoint)) { PublicationTreeConfigDescriptor desc = (PublicationTreeConfigDescriptor) contribution; registerTreeConfig(desc); } else if (FACTORY_EP.equals(extensionPoint)) { PublishedDocumentFactoryDescriptor desc = (PublishedDocumentFactoryDescriptor) contribution; factoryDescriptors.put(desc.getName(), desc); } else if (VALIDATORS_RULE_EP.equals(extensionPoint)) { ValidatorsRuleDescriptor desc = (ValidatorsRuleDescriptor) contribution; validatorsRuleDescriptors.put(desc.getName(), desc); } } protected void registerTreeConfig(PublicationTreeConfigDescriptor desc) { if (desc.getParameters().get("RelativeRootPath") != null) { pendingDescriptors.put(desc.getName(), desc); } else { treeConfigDescriptors.put(desc.getName(), desc); } } @Override public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) throws Exception { } protected String computeTreeSessionId(String treeConfigName, CoreSession coreSession) { return computeTreeSessionId(treeConfigName, coreSession.getSessionId()); } protected String computeTreeSessionId(String treeConfigName, String sid) { return treeConfigName + sid; } public List<String> getAvailablePublicationTree() { List<String> treeConfigs = new ArrayList<String>(); treeConfigs.addAll(treeConfigDescriptors.keySet()); return treeConfigs; } public Map<String, String> getAvailablePublicationTrees() { Map<String, String> trees = new HashMap<String, String>(); for (PublicationTreeConfigDescriptor desc : treeConfigDescriptors.values()) { String title = desc.getTitle() == null ? desc.getName() : desc.getTitle(); trees.put(desc.getName(), title); } return trees; } public PublicationTree getPublicationTree(String treeName, CoreSession coreSession, Map<String, String> params) throws ClientException, PublicationTreeNotAvailable { return getPublicationTree(treeName, coreSession, params, null); } public PublicationTree getPublicationTree(String treeName, CoreSession coreSession, Map<String, String> params, DocumentModel currentDocument) throws ClientException, PublicationTreeNotAvailable { PublicationTree tree = getOrBuildTree(treeName, coreSession, params); if (tree == null) { return null; } if (currentDocument != null) { tree.setCurrentDocument(currentDocument); } return new ProxyTree(tree, tree.getSessionId()); } public Map<String, String> initRemoteSession(String treeConfigName, Map<String, String> params) throws Exception { RepositoryManager rm = Framework.getService(RepositoryManager.class); CoreSession coreSession = null; if (rm != null) { // this session will be closed in the release method coreSession = rm.getDefaultRepository().open(); } PublicationTree tree = getPublicationTree(treeConfigName, coreSession, params); remoteLiveTrees.put(tree.getSessionId(), coreSession.getSessionId()); Map<String, String> res = new HashMap<String, String>(); res.put("sessionId", tree.getSessionId()); res.put("title", tree.getTitle()); res.put("nodeType", tree.getNodeType()); res.put("treeName", tree.getConfigName()); res.put("path", tree.getPath()); return res; } public void release(String sid) { PublicationTree tree; if (liveTrees.containsKey(sid)) { tree = liveTrees.get(sid); tree.release(); liveTrees.remove(sid); } if (remoteLiveTrees.containsKey(sid)) { // close here session opened for remote trees String sessionId = remoteLiveTrees.get(sid); CoreSession remoteSession = CoreInstance.getInstance().getSession( sessionId); CoreInstance.getInstance().close(remoteSession); remoteLiveTrees.remove(sid); } } public void releaseAllTrees(String sessionId) { for (String configName : treeConfigDescriptors.keySet()) { String treeid = computeTreeSessionId(configName, sessionId); release(treeid); } } protected PublicationTree getOrBuildTree(String treeConfigName, CoreSession coreSession, Map<String, String> params) throws PublicationTreeNotAvailable { String key = computeTreeSessionId(treeConfigName, coreSession); PublicationTree tree; if (liveTrees.containsKey(key)) { tree = liveTrees.get(key); } else { tree = buildTree(key, treeConfigName, coreSession, params); if (tree != null) liveTrees.put(key, tree); } return tree; } protected PublicationTree buildTree(String sid, String treeConfigName, CoreSession coreSession, Map<String, String> params) throws PublicationTreeNotAvailable { try { PublicationTreeConfigDescriptor config = getPublicationTreeConfigDescriptor(treeConfigName); Map<String, String> allParameters = computeAllParameters(config, params); PublicationTreeDescriptor treeDescriptor = getPublicationTreeDescriptor(config); PublishedDocumentFactory publishedDocumentFactory = getPublishedDocumentFactory( config, treeDescriptor, coreSession, allParameters); return getPublicationTree(treeDescriptor, sid, coreSession, allParameters, publishedDocumentFactory, config.getName(), config.getTitle()); } catch (PublisherException e) { log.error("Unable to build PublicationTree", e); return null; } } protected Map<String, String> computeAllParameters( PublicationTreeConfigDescriptor config, Map<String, String> params) { final Map<String, String> allParameters = config.getParameters(); if (params != null) { allParameters.putAll(params); } return allParameters; } protected PublishedDocumentFactory getPublishedDocumentFactory( PublicationTreeConfigDescriptor config, PublicationTreeDescriptor treeDescriptor, CoreSession coreSession, Map<String, String> params) throws PublisherException { PublishedDocumentFactoryDescriptor factoryDesc = getPublishedDocumentFactoryDescriptor( config, treeDescriptor); ValidatorsRule validatorsRule = getValidatorsRule(factoryDesc); PublishedDocumentFactory factory; try { factory = factoryDesc.getKlass().newInstance(); } catch (Exception e) { throw new PublisherException("Error while creating factory " + factoryDesc.getName(), e); } try { factory.init(coreSession, validatorsRule, params); } catch (Exception e) { throw new PublisherException("Error during Factory init", e); } return factory; } protected ValidatorsRule getValidatorsRule( PublishedDocumentFactoryDescriptor factoryDesc) throws PublisherException { String validatorsRuleName = factoryDesc.getValidatorsRuleName(); ValidatorsRule validatorsRule = null; if (validatorsRuleName != null) { ValidatorsRuleDescriptor validatorsRuleDesc = validatorsRuleDescriptors.get(validatorsRuleName); if (validatorsRuleDesc == null) { throw new PublisherException("Unable to find validatorsRule" + validatorsRuleName); } try { validatorsRule = validatorsRuleDesc.getKlass().newInstance(); } catch (Exception e) { throw new PublisherException( "Error while creating validatorsRule " + validatorsRuleName, e); } } return validatorsRule; } protected PublishedDocumentFactoryDescriptor getPublishedDocumentFactoryDescriptor( PublicationTreeConfigDescriptor config, PublicationTreeDescriptor treeDescriptor) throws PublisherException { String factoryName = config.getFactory(); if (factoryName == null) { factoryName = treeDescriptor.getFactory(); } PublishedDocumentFactoryDescriptor factoryDesc = factoryDescriptors.get(factoryName); if (factoryDesc == null) { throw new PublisherException("Unable to find factory" + factoryName); } return factoryDesc; } protected PublicationTreeConfigDescriptor getPublicationTreeConfigDescriptor( String treeConfigName) throws PublisherException { if (!treeConfigDescriptors.containsKey(treeConfigName)) { throw new PublisherException("Unknow treeConfig :" + treeConfigName); } return treeConfigDescriptors.get(treeConfigName); } protected PublicationTreeDescriptor getPublicationTreeDescriptor( PublicationTreeConfigDescriptor config) throws PublisherException { String treeImplName = config.getTree(); if (!treeDescriptors.containsKey(treeImplName)) { throw new PublisherException("Unknow treeImplementation :" + treeImplName); } return treeDescriptors.get(treeImplName); } protected PublicationTree getPublicationTree( PublicationTreeDescriptor treeDescriptor, String sid, CoreSession coreSession, Map<String, String> parameters, PublishedDocumentFactory factory, String configName, String treeTitle) throws PublisherException, PublicationTreeNotAvailable { PublicationTree treeImpl; try { treeImpl = treeDescriptor.getKlass().newInstance(); } catch (Exception e) { throw new PublisherException( "Error while creating tree implementation", e); } try { treeImpl.initTree(sid, coreSession, parameters, factory, configName, treeTitle); } catch (Exception e) { throw new PublicationTreeNotAvailable("Error during tree init", e); } return treeImpl; } public PublishedDocument publish(DocumentModel doc, PublicationNode targetNode) throws ClientException { return publish(doc, targetNode, null); } public PublishedDocument publish(DocumentModel doc, PublicationNode targetNode, Map<String, String> params) throws ClientException { PublicationTree tree = liveTrees.get(targetNode.getSessionId()); if (tree != null) { return tree.publish(doc, targetNode, params); } else { throw new ClientException( "Calling getChildrenNodes on a closed tree"); } } public void unpublish(DocumentModel doc, PublicationNode targetNode) throws ClientException { PublicationTree tree = liveTrees.get(targetNode.getSessionId()); if (tree != null) { tree.unpublish(doc, targetNode); } else { throw new ClientException( "Calling getChildrenNodes on a closed tree"); } } public void unpublish(String sid, PublishedDocument publishedDocument) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { tree.unpublish(publishedDocument); } else { throw new ClientException( "Calling getChildrenNodes on a closed tree"); } } public List<PublishedDocument> getChildrenDocuments(PublicationNode node) throws ClientException { PublicationTree tree = liveTrees.get(node.getSessionId()); if (tree != null) { return tree.getPublishedDocumentInNode(tree.getNodeByPath(node.getPath())); } else { throw new ClientException( "Calling getChildrenDocuments on a closed tree"); } } protected List<PublicationNode> makeRemotable(List<PublicationNode> nodes, String sid) throws ClientException { List<PublicationNode> remoteNodes = new ArrayList<PublicationNode>(); for (PublicationNode node : nodes) { remoteNodes.add(new ProxyNode(node, sid)); } return remoteNodes; } public List<PublicationNode> getChildrenNodes(PublicationNode node) throws ClientException { String sid = node.getSessionId(); PublicationTree tree = liveTrees.get(sid); if (tree != null) { return makeRemotable( tree.getNodeByPath(node.getPath()).getChildrenNodes(), sid); } else { throw new ClientException( "Calling getChildrenNodes on a closed tree"); } } public PublicationNode getParent(PublicationNode node) { String sid = node.getSessionId(); PublicationTree tree = liveTrees.get(sid); if (tree != null) { PublicationNode liveNode; try { liveNode = tree.getNodeByPath(node.getPath()).getParent(); if (liveNode == null) { return null; } return new ProxyNode(liveNode, sid); } catch (ClientException e) { log.error("Error while getting Parent", e); return null; } } else { log.error("Calling getParent on a closed tree"); return null; } } public PublicationNode getNodeByPath(String sid, String path) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return new ProxyNode(tree.getNodeByPath(path), sid); } else { throw new ClientException("Calling getNodeByPath on a closed tree"); } } public List<PublishedDocument> getExistingPublishedDocument(String sid, DocumentLocation docLoc) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.getExistingPublishedDocument(docLoc); } else { throw new ClientException("Calling getNodeByPath on a closed tree"); } } public List<PublishedDocument> getPublishedDocumentInNode( PublicationNode node) throws ClientException { String sid = node.getSessionId(); PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.getPublishedDocumentInNode(tree.getNodeByPath(node.getPath())); } else { throw new ClientException( "Calling getPublishedDocumentInNode on a closed tree"); } } public void setCurrentDocument(String sid, DocumentModel currentDocument) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { tree.setCurrentDocument(currentDocument); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public void validatorPublishDocument(String sid, PublishedDocument publishedDocument, String comment) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { tree.validatorPublishDocument(publishedDocument, comment); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public void validatorRejectPublication(String sid, PublishedDocument publishedDocument, String comment) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { tree.validatorRejectPublication(publishedDocument, comment); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public boolean canPublishTo(String sid, PublicationNode publicationNode) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.canPublishTo(publicationNode); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public boolean canUnpublish(String sid, PublishedDocument publishedDocument) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.canUnpublish(publishedDocument); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public boolean canManagePublishing(String sid, PublishedDocument publishedDocument) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.canManagePublishing(publishedDocument); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public boolean isPublishedDocument(DocumentModel documentModel) { return PublicationRelationHelper.isPublished(documentModel); } public PublicationTree getPublicationTreeFor(DocumentModel doc, CoreSession coreSession) throws ClientException { PublicationTree tree = null; try { tree = PublicationRelationHelper.getPublicationTreeUsedForPublishing( doc, coreSession); } catch (ClientException e) { log.debug("Unable to get PublicationTree for " + doc.getPathAsString() + ". Fallback on first PublicationTree accepting this document."); for (String treeName : treeConfigDescriptors.keySet()) { tree = getPublicationTree(treeName, coreSession, null); if (tree.isPublicationNode(doc)) { break; } } } return tree; } public boolean hasValidationTask(String sid, PublishedDocument publishedDocument) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.hasValidationTask(publishedDocument); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public PublishedDocument wrapToPublishedDocument(String sid, DocumentModel documentModel) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.wrapToPublishedDocument(documentModel); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public boolean isPublicationNode(String sid, DocumentModel documentModel) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.isPublicationNode(documentModel); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public PublicationNode wrapToPublicationNode(String sid, DocumentModel documentModel) throws ClientException { PublicationTree tree = liveTrees.get(sid); if (tree != null) { return tree.wrapToPublicationNode(documentModel); } else { throw new ClientException( "Calling validatorPublishDocument on a closed tree"); } } public PublicationNode wrapToPublicationNode(DocumentModel documentModel, CoreSession coreSession) throws ClientException, PublicationTreeNotAvailable { for (String name : getAvailablePublicationTree()) { PublicationTree tree = getPublicationTree(name, coreSession, null); PublicationTreeConfigDescriptor config = treeConfigDescriptors.get(tree.getConfigName()); if (!config.islocalSectionTree()) { // ignore all non local section tree continue; } if (tree.isPublicationNode(documentModel)) { return tree.wrapToPublicationNode(documentModel); } } return null; } protected void registerPendingDescriptors() throws Exception { // TODO what to do with multiple repositories? RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class); String repositoryName = repositoryManager.getDefaultRepository().getName(); List<DocumentModel> domains = new DomainsFinder(repositoryName).getDomains(); for (DocumentModel domain : domains) { registerTreeConfigFor(domain); } } public void registerTreeConfigFor(DocumentModel domain) throws ClientException { for (PublicationTreeConfigDescriptor desc : pendingDescriptors.values()) { PublicationTreeConfigDescriptor newDesc = new PublicationTreeConfigDescriptor( desc); String newTreeName = desc.getName() + "-" + domain.getName(); newDesc.setName(newTreeName); Path newPath = domain.getPath(); Map<String, String> parameters = newDesc.getParameters(); newPath = newPath.append(parameters.remove(RELATIVE_ROOT_PATH_KEY)); parameters.put(ROOT_PATH_KEY, newPath.toString()); parameters.put(PublisherService.DOMAIN_NAME_KEY, domain.getTitle()); treeConfigDescriptors.put(newDesc.getName(), newDesc); } } public void unRegisterTreeConfigFor(DocumentModel domain) { for (PublicationTreeConfigDescriptor desc : pendingDescriptors.values()) { String treeName = desc.getName() + "-" + domain.getName(); treeConfigDescriptors.remove(treeName); for (Iterator<String> it = liveTrees.keySet().iterator(); it.hasNext();) { String entry = it.next(); if (entry.startsWith(treeName)) { it.remove(); } } } } public Map<String, String> getParametersFor(String treeConfigName) { PublicationTreeConfigDescriptor desc = treeConfigDescriptors.get(treeConfigName); Map<String, String> parameters = new HashMap<String, String>(); if (desc != null) { parameters.putAll(desc.getParameters()); } return parameters; } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; public final class MainPanel extends JPanel { private MainPanel() { super(new GridLayout(1, 2)); JTree t = new JTree(makeDefaultTreeModel()); t.setComponentPopupMenu(new TreePopupMenu()); add(makeTitledPanel("Default", new JScrollPane(t))); DefaultTreeModel model = makeDefaultTreeModel(); JTree tree = new JTree(model); tree.setComponentPopupMenu(new TreePopupMenu()); //model.setAsksAllowsChildren(true); JPanel p = makeTitledPanel("setAsksAllowsChildren", new JScrollPane(tree)); JCheckBox check = new JCheckBox("setAsksAllowsChildren"); check.addActionListener(e -> { model.setAsksAllowsChildren(((JCheckBox) e.getSource()).isSelected()); tree.repaint(); }); p.add(check, BorderLayout.SOUTH); add(p); setPreferredSize(new Dimension(320, 240)); } private static JPanel makeTitledPanel(String title, JComponent c) { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder(title)); p.add(c); return p; } private static DefaultTreeModel makeDefaultTreeModel() { DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); DefaultMutableTreeNode parent; parent = new DefaultMutableTreeNode("colors"); root.add(parent); parent.add(new DefaultMutableTreeNode("blue", false)); parent.add(new DefaultMutableTreeNode("violet", false)); parent.add(new DefaultMutableTreeNode("red", false)); parent.add(new DefaultMutableTreeNode("yellow", false)); parent = new DefaultMutableTreeNode("sports"); root.add(parent); parent.add(new DefaultMutableTreeNode("basketball", false)); parent.add(new DefaultMutableTreeNode("soccer", false)); parent.add(new DefaultMutableTreeNode("football", false)); parent.add(new DefaultMutableTreeNode("hockey", false)); parent = new DefaultMutableTreeNode("food"); root.add(parent); parent.add(new DefaultMutableTreeNode("hot dogs", false)); parent.add(new DefaultMutableTreeNode("pizza", false)); parent.add(new DefaultMutableTreeNode("ravioli", false)); parent.add(new DefaultMutableTreeNode("bananas", false)); parent = new DefaultMutableTreeNode("test"); root.add(parent); return new DefaultTreeModel(root); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class TreePopupMenu extends JPopupMenu { protected TreePath path; private final Action addFolderAction = new AbstractAction("add folder") { @Override public void actionPerformed(ActionEvent e) { JTree tree = (JTree) getInvoker(); DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent(); DefaultMutableTreeNode child = new DefaultMutableTreeNode("New Folder", true); model.insertNodeInto(child, parent, parent.getChildCount()); tree.scrollPathToVisible(new TreePath(child.getPath())); } }; private final Action addItemAction = new AbstractAction("add item") { @Override public void actionPerformed(ActionEvent e) { JTree tree = (JTree) getInvoker(); DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent(); DefaultMutableTreeNode child = new DefaultMutableTreeNode("New Item", false); model.insertNodeInto(child, parent, parent.getChildCount()); tree.scrollPathToVisible(new TreePath(child.getPath())); } }; private final Action editNodeAction = new AbstractAction("edit") { protected final JTextField textField = new JTextField(24) { protected transient AncestorListener listener; @Override public void updateUI() { removeAncestorListener(listener); super.updateUI(); listener = new AncestorListener() { @Override public void ancestorAdded(AncestorEvent e) { requestFocusInWindow(); } @Override public void ancestorMoved(AncestorEvent e) { /* not needed */ } @Override public void ancestorRemoved(AncestorEvent e) { /* not needed */ } }; addAncestorListener(listener); } }; @Override public void actionPerformed(ActionEvent e) { Object node = path.getLastPathComponent(); if (node instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode leaf = (DefaultMutableTreeNode) node; textField.setText(leaf.getUserObject().toString()); JTree tree = (JTree) getInvoker(); int ret = JOptionPane.showConfirmDialog(tree, textField, "edit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (ret == JOptionPane.OK_OPTION) { Optional.ofNullable(textField.getText()) .filter(str -> !str.trim().isEmpty()) .ifPresent(str -> ((DefaultTreeModel) tree.getModel()).valueForPathChanged(path, str)); } } } }; private final Action removeNodeAction = new AbstractAction("remove") { @Override public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (!node.isRoot()) { JTree tree = (JTree) getInvoker(); DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); model.removeNodeFromParent(node); } } }; protected TreePopupMenu() { super(); add(addFolderAction); add(addItemAction); add(editNodeAction); addSeparator(); add(removeNodeAction); } @Override public void show(Component c, int x, int y) { if (c instanceof JTree) { JTree tree = (JTree) c; path = tree.getPathForLocation(x, y); Optional.ofNullable(path).ifPresent(treePath -> { DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); boolean flag = node.getAllowsChildren(); addFolderAction.setEnabled(flag); addItemAction.setEnabled(flag); super.show(c, x, y); }); } } }
package io.getlime.security.powerauth.lib.webflow.authentication.service; import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthResult; import io.getlime.security.powerauth.lib.webflow.authentication.model.response.WebSocketAuthorizationResponse; import io.getlime.security.powerauth.lib.webflow.authentication.model.response.WebSocketRegistrationResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageType; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; /** * Service that handles web socket to session pairing and notifying * clients about events. * * @author Petr Dvorak, petr@wultra.com */ @Service public class WebSocketMessageService { private final SimpMessagingTemplate websocket; private final OperationSessionService operationSessionService; /** * Service constructor. * @param websocket Web Socket simple messaging template. * @param operationSessionService Operation to session mapping service. */ @Autowired public WebSocketMessageService(SimpMessagingTemplate websocket, OperationSessionService operationSessionService) { this.websocket = websocket; this.operationSessionService = operationSessionService; } /** * Create a MessageHeaders object for session. * * @param webSocketSessionId WebSocket session ID. * @return Message headers. */ private MessageHeaders createHeaders(String webSocketSessionId) { SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); headerAccessor.setSessionId(webSocketSessionId); headerAccessor.setLeaveMutable(true); return headerAccessor.getMessageHeaders(); } /** * Notification of clients about completed authorization. * * @param operationId Operation ID. * @param authResult Authorization result. */ public void notifyAuthorizationComplete(String operationId, AuthResult authResult) { final String webSocketId = operationSessionService.generateOperationHash(operationId); final String sessionId = lookupWebSocketSessionId(webSocketId); WebSocketAuthorizationResponse authorizationResponse = new WebSocketAuthorizationResponse(); authorizationResponse.setWebSocketId(webSocketId); authorizationResponse.setAuthResult(authResult); if (sessionId != null) { websocket.convertAndSendToUser(sessionId, "/topic/authorization", authorizationResponse, createHeaders(sessionId)); } } /** * Sends a message about successful websocket registration to the user. * * @param operationHash Operation hash. * @param sessionId Session ID. * @param registrationSucceeded Whether Web Socket registration was successful. */ public void sendRegistrationMessage(String operationHash, String sessionId, boolean registrationSucceeded) { WebSocketRegistrationResponse registrationResponse = new WebSocketRegistrationResponse(); registrationResponse.setWebSocketId(operationHash); registrationResponse.setRegistrationSucceeded(registrationSucceeded); websocket.convertAndSendToUser(sessionId, "/topic/registration", registrationResponse, createHeaders(sessionId)); } /** * Get Web Socket session ID for given operation hash. * * @param operationHash Operation hash. * @return Web Socket session ID. */ public String lookupWebSocketSessionId(String operationHash) { return operationSessionService.lookupWebSocketSessionIdByOperationHash(operationHash); } /** * Store a mapping for new web socket identifier to the Web Socket session with given ID. * * @param operationHash Operation hash. * @param webSocketSessionId Web Socket Session ID. * @param clientIpAddress Remote client IP address. * @return Whether Web Socket registration was successful. */ public boolean registerWebSocketSession(String operationHash, String webSocketSessionId, String clientIpAddress) { return operationSessionService.registerWebSocketSession(operationHash, webSocketSessionId, clientIpAddress); } }
package gcm.gui.schematic; import gcm.gui.modelview.movie.MovieAppearance; import gcm.parser.GCMFile; import gcm.util.GlobalConstants; import java.awt.Color; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Hashtable; import java.util.Properties; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; import org.sbml.libsbml.Model; import org.sbml.libsbml.ModifierSpeciesReference; import org.sbml.libsbml.Reaction; import org.sbml.libsbml.SpeciesReference; import main.Gui; //import javax.xml.bind.JAXBElement.GlobalScope; import com.mxgraph.model.mxCell; import com.mxgraph.model.mxGeometry; import com.mxgraph.model.mxICell; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.util.mxConstants; import com.mxgraph.util.mxPoint; import com.mxgraph.view.mxGraph; import com.mxgraph.view.mxStylesheet; /** * @author Tyler tpatterson80@gmail.com * */ public class BioGraph extends mxGraph { private double DIS_BETWEEN_NEIGHBORING_EDGES = 35.0; private double SECOND_SELF_INFLUENCE_DISTANCE = 20; private HashMap<String, mxCell> speciesToMxCellMap; private HashMap<String, mxCell> reactionsToMxCellMap; private HashMap<String, mxCell> influencesToMxCellMap; private HashMap<String, mxCell> componentsToMxCellMap; private HashMap<String, mxCell> componentsConnectionsToMxCellMap; private HashMap<String, mxCell> drawnPromoterToMxCellMap; private HashMap<String, mxCell> gridRectangleToMxCellMap; mxCell cell = new mxCell(); private GCMFile gcm; public final String CELL_NOT_FULLY_CONNECTED = "cell not fully connected"; private final String CELL_VALUE_NOT_FOUND = "cell value not found"; // only bother the user about bad promoters once. //This should be improved to happen once per GCM file if this will be a common error. private int _badPromoters = 0; public boolean isBuilding = false; // Keep track of how many elements did not have positioning info. // This allows us to stack them in the topleft corner until they // are positioned by the user or a layout algorithm. int unpositionedSpeciesComponentCount = 0; /** * constructor * @param gcm */ public BioGraph(GCMFile gcm) { super(); // Turn editing off to prevent mxGraph from letting the user change the // label on the cell. We want to do this using the property windows. this.setCellsEditable(false); this.gcm = gcm; this.initializeMaps(); createStyleSheets(); } /** * sets the hash maps to null */ private void initializeMaps(){ speciesToMxCellMap = new HashMap<String, mxCell>(); reactionsToMxCellMap = new HashMap<String, mxCell>(); componentsToMxCellMap = new HashMap<String, mxCell>(); influencesToMxCellMap = new HashMap<String, mxCell>(); componentsConnectionsToMxCellMap = new HashMap<String, mxCell>(); drawnPromoterToMxCellMap = new HashMap<String, mxCell>(); gridRectangleToMxCellMap = new HashMap<String, mxCell>(); } //GRAPH BUILDING /** * appplies a layout to the graphComponent * * @param ident * @param graphComponent */ public void applyLayout(String ident, mxGraphComponent graphComponent){ Layouting.applyLayout(ident, this, graphComponent); } /** * Builds the graph based on the internal representation * @return */ public boolean buildGraph(){ this.isBuilding = true; // remove all the cells from the graph (vertices and edges) this.removeCells(this.getChildCells(this.getDefaultParent(), true, true)); initializeMaps(); assert(this.gcm != null); // Start an undo transaction this.getModel().beginUpdate(); boolean needsPositioning = false; unpositionedSpeciesComponentCount = 0; //createGraphCompartmentFromModel("default"); //put the grid cells in first so that they're below the other cells addGridCells(); // add species for(String sp : gcm.getSpecies().keySet()){ if(createGraphSpeciesFromModel(sp)) needsPositioning = true; } Model m = gcm.getSBMLDocument().getModel(); int x = 75; int y = 75; for (int i = 0; i < m.getNumReactions(); i++) { Reaction r = m.getReaction(i); if (gcm.getReactions().get(r.getId()) == null) { if (r.getNumModifiers() > 0 || (r.getNumReactants()>1 && r.getNumProducts()>1) || r.getNumReactants()==0 || r.getNumProducts()==0) { Properties prop = new Properties(); prop.setProperty("graphwidth", String.valueOf(GlobalConstants.DEFAULT_REACTION_WIDTH)); prop.setProperty("graphheight", String.valueOf(GlobalConstants.DEFAULT_REACTION_HEIGHT)); gcm.centerVertexOverPoint(prop, x, y); x+=75; y+=75; gcm.getReactions().put(r.getId(), prop); } } } // add reactions for(String sp : gcm.getReactions().keySet()){ if(createGraphReactionFromModel(sp)) needsPositioning = true; } // add all components for(String comp : gcm.getComponents().keySet()){ if(createGraphComponentFromModel(comp)) needsPositioning = true; } // add all the drawn promoters for(String prom : gcm.getPromoters().keySet()){ Properties pprop = gcm.getPromoters().get(prom); if(pprop.get(GlobalConstants.EXPLICIT_PROMOTER) != null && pprop.get(GlobalConstants.EXPLICIT_PROMOTER).equals(GlobalConstants.TRUE)){ //System.out.printf("Please draw this promoter!"); if(createGraphDrawnPromoterFromModel(prom)) needsPositioning = true; } } boolean needsRedrawn = false; // add all the edges. for(String inf : gcm.getInfluences().keySet()){ String ins = GCMFile.getInput(inf); String outs = GCMFile.getOutput(inf); if(ins.equals(GlobalConstants.NONE) || outs.equals(GlobalConstants.NONE)){ // a drawn-promoter edge Properties influence = gcm.getInfluences().get(inf); String promName = influence.getProperty(GlobalConstants.PROMOTER, ""); if(promName.equals("")){ if(_badPromoters++ == 0) JOptionPane.showMessageDialog(Gui.frame, "You have a default promoter that is connected to None. Because of this some edges are not being drawn in schematic. Please fix.\n"); continue; } Properties promProp = gcm.getPromoters().get(promName); // If an edge is found with a drawn promoter, // this is a recoverable error case. Flag the promoter as drawn, re-call this // function and bail. This will ensure that legacy gcm files and files // created with the other interface get built correctly. // make sure the promoter is set to be drawn. If not, set it and try this function again. if(!promProp.getProperty(GlobalConstants.EXPLICIT_PROMOTER, "").equals(GlobalConstants.TRUE)){ promProp.setProperty(GlobalConstants.EXPLICIT_PROMOTER, GlobalConstants.TRUE); needsRedrawn = true; // we can't draw this edge because the promoter isn't drawn. // It will be drawn in the next pass. continue; } // now draw the edge to the promoter if(ins.equals(GlobalConstants.NONE)){ // the output must be the species mxCell production = (mxCell)this.insertEdge(this.getDefaultParent(), inf, "", this.getDrawnPromoterCell(promName), this.getSpeciesCell(outs)); //updateProductionVisuals(inf); production.setStyle("PRODUCTION"); } else{ // the input must be the species this.insertEdge(this.getDefaultParent(), inf, "", this.getSpeciesCell(ins), this.getDrawnPromoterCell(promName)); updateInfluenceVisuals(inf); } } else{ // A normal, non-drawn promoter edge this.insertEdge(this.getDefaultParent(), inf, "", this.getSpeciesCell(ins), this.getSpeciesCell(outs) ); updateInfluenceVisuals(inf); } } //add reactions for (int i = 0; i < m.getNumReactions(); i++) { Reaction r = m.getReaction(i); if (gcm.getReactions().get(r.getId()) != null) { for (int j = 0; j < r.getNumReactants(); j++) { SpeciesReference s = r.getReactant(j); mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), s.getSpecies() + "__" + r.getId(), "", this.getSpeciesCell(s.getSpecies()), this.getReactionsCell(r.getId())); if (r.getReversible()) { if (s.getStoichiometry() != 1.0) cell.setValue(s.getStoichiometry()+",r"); else cell.setValue("r"); cell.setStyle("REACTION_EDGE;" + mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN + ";" + mxConstants.STYLE_STARTARROW + "=" + mxConstants.ARROW_OPEN); } else { if (s.getStoichiometry() != 1.0) cell.setValue(s.getStoichiometry()); cell.setStyle("REACTION_EDGE;" + mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN); } } for (int j = 0; j < r.getNumModifiers(); j++) { ModifierSpeciesReference s = r.getModifier(j); mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), s.getSpecies() + "__" + r.getId(), "", this.getSpeciesCell(s.getSpecies()), this.getReactionsCell(r.getId())); if (r.getReversible()) cell.setValue("m"); cell.setStyle("REACTION_EDGE;" + mxConstants.STYLE_ENDARROW + "=" + mxConstants.NONE); } for (int k = 0; k < r.getNumProducts(); k++) { SpeciesReference s = r.getProduct(k); mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), r.getId() + "__" + s.getSpecies(), "", this.getReactionsCell(r.getId()), this.getSpeciesCell(s.getSpecies())); if (r.getReversible()) { if (s.getStoichiometry() != 1.0) cell.setValue(s.getStoichiometry()+",p"); else cell.setValue("p"); cell.setStyle("REACTION_EDGE;" + mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN + ";" + mxConstants.STYLE_STARTARROW + "=" + mxConstants.ARROW_OPEN); } else { if (s.getStoichiometry() != 1.0) cell.setValue(s.getStoichiometry()); cell.setStyle("REACTION_EDGE;" + mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN); } } } else { for (int j = 0; j < r.getNumReactants(); j++) { SpeciesReference s1 = r.getReactant(j); for (int k = 0; k < r.getNumProducts(); k++) { SpeciesReference s2 = r.getProduct(k); mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), s1.getSpecies() + "_" + r.getId() + "_" + s2.getSpecies(), "", this.getSpeciesCell(s1.getSpecies()), this.getSpeciesCell(s2.getSpecies())); cell.setValue(r.getId()); if (r.getReversible()) { cell.setStyle("REACTION_EDGE;" + mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN + ";" + mxConstants.STYLE_STARTARROW + "=" + mxConstants.ARROW_OPEN); } else { cell.setStyle("REACTION_EDGE;" + mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN); } } } } } addEdgeOffsets(); this.getModel().endUpdate(); this.isBuilding = false; // if we found any incorrectly marked promoters we need to redraw. Do so now. // The promoters should all pass the second time. if(needsRedrawn){ return buildGraph(); } return needsPositioning; } /** * Loop through all the edges and add control points to reposition them * if they are laying over the top of any other edges. */ public void addEdgeOffsets(){ // Make a hash where the key is a string built from the ids of the source and destination // of all the edges. The source and destination will be sorted so that the same two // source-destination pair will always map to the same key. The value is a list // of edges. That way if there are ever more then one edge between pairs, // we can modify the geometry so they don't overlap. HashMap<String, Vector<mxCell>> edgeHash = new HashMap<String, Vector<mxCell>>(); // build a temporary structure mapping sets of edge endpoints to edges // map influences for(String inf:gcm.getInfluences().keySet()){ String endA = GCMFile.getInput(inf); String endB = GCMFile.getOutput(inf); // ignore anything connected directly to a drawn promoter if(endA.equals(GlobalConstants.NONE) || endB.equals(GlobalConstants.NONE)) continue; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(inf); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } Model m = gcm.getSBMLDocument().getModel(); for (int i = 0; i < m.getNumReactions(); i++) { Reaction r = m.getReaction(i); if (gcm.getReactions().get(r.getId()) != null) { for (int j = 0; j < r.getNumReactants(); j++) { SpeciesReference s = r.getReactant(j); String endA = s.getSpecies(); String endB = r.getId(); if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(s.getSpecies() + "__" + r.getId()); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } for (int j = 0; j < r.getNumModifiers(); j++) { ModifierSpeciesReference s = r.getModifier(j); String endA = s.getSpecies(); String endB = r.getId(); if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(s.getSpecies() + "__" + r.getId()); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } for (int k = 0; k < r.getNumProducts(); k++) { SpeciesReference s = r.getProduct(k); String endA = r.getId(); String endB = s.getSpecies(); if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(r.getId() + "__" + s.getSpecies()); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } } else { for (int j = 0; j < r.getNumReactants(); j++) { SpeciesReference s1 = r.getReactant(j); for (int k = 0; k < r.getNumProducts(); k++) { SpeciesReference s2 = r.getProduct(k); String endA = s1.getSpecies(); String endB = s2.getSpecies(); // ignore anything connected directly to a drawn promoter //if(endA.equals(GlobalConstants.NONE) || endB.equals(GlobalConstants.NONE)) // continue; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(s1.getSpecies() + "_" + r.getId() + "_" + s2.getSpecies()); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } } } } // map components edges Pattern getPropNamePattern = Pattern.compile("^type_([\\w\\_\\d]+)"); for(String compName:gcm.getComponents().keySet()){ Properties comp = gcm.getComponents().get(compName); for(Object propNameO:comp.keySet()){ String propName = propNameO.toString(); if(propName.startsWith("type_")){ Matcher matcher = getPropNamePattern.matcher(propName); matcher.find(); String compInternalName = matcher.group(1); String targetName = comp.get(compInternalName).toString(); String type = comp.get(propName).toString(); // Input or Output String key = compName + " "+type+" " + targetName; mxCell cell = componentsConnectionsToMxCellMap.get(key); String simpleKey = compName + " " + targetName; if(edgeHash.containsKey(simpleKey) == false) edgeHash.put(simpleKey, new Vector<mxCell>()); edgeHash.get(simpleKey).add(cell); } } } // loop through every set of edge endpoints and then move them if needed. for(Vector<mxCell> vec:edgeHash.values()){ if(vec.size() > 1){ mxCell source = (mxCell)vec.get(0).getSource(); mxCell target = (mxCell)vec.get(0).getTarget(); // find the end and center points mxGeometry t; t = source.getGeometry(); mxPoint sp = new mxPoint(t.getCenterX(), t.getCenterY()); t = target.getGeometry(); mxPoint tp = new mxPoint(t.getCenterX(), t.getCenterY()); mxPoint cp = new mxPoint((tp.getX()+sp.getX())/2.0, (tp.getY()+sp.getY())/2.0); // check for self-influence if(source == target){ mxCell c = vec.get(0); mxGeometry geom = c.getGeometry(); // set the self-influence's point to the left of the influence. // This causes the graph library to draw it rounded in that direction. mxPoint p = new mxPoint( cp.getX() - t.getWidth()/2-SECOND_SELF_INFLUENCE_DISTANCE, cp.getY() ); Vector<mxPoint> points = new Vector<mxPoint>(); points.add(p); geom.setPoints(points); c.setGeometry(geom); continue; } // make a unit vector that points in the direction perpendicular to the // direction from one endpoint to the other. 90 degrees rotated means flip // the x and y coordinates. mxPoint dVec = new mxPoint(-(sp.getY()-tp.getY()), sp.getX()-tp.getX()); double magnitude = Math.sqrt(dVec.getX()*dVec.getX() + dVec.getY()*dVec.getY()); // avoid divide-by-zero errors magnitude = Math.max(magnitude, .1); // normalize dVec.setX(dVec.getX()/magnitude); dVec.setY(dVec.getY()/magnitude); // loop through all the edges, create a new midpoint and apply it. // also move the edge center to the midpoint so that labels won't be // on top of each other. for(int i=0; i<vec.size(); i++){ double offset = i-(vec.size()-1.0)/2.0; mxCell edge = vec.get(i); //cell.setGeometry(new mxGeometry(0, 0, 100, 100)); mxGeometry geom = edge.getGeometry(); Vector<mxPoint> points = new Vector<mxPoint>(); mxPoint p = new mxPoint( cp.getX()+dVec.getX()*offset*DIS_BETWEEN_NEIGHBORING_EDGES, cp.getY()+dVec.getY()*offset*DIS_BETWEEN_NEIGHBORING_EDGES ); points.add(p); geom.setPoints(points); // geom.setX(p.getX()); // geom.setY(p.getY()); edge.setGeometry(geom); } } } // for(Object edgeo:this.getSelectionCell()){ // mxCell edge = (mxCell)edgeo; // int s = edge.getSource().getEdgeCount(); // int t = edge.getTarget().getEdgeCount() // if(edge.getSource().getEdgeCount() > 1 && edge.getTarget().getEdgeCount() > 1){ // // the source and target have multiple edges, now loop through them all... // //cell.setGeometry(new mxGeometry(0, 0, 100, 100)); // mxGeometry geom = new mxGeometry(); // Vector<mxPoint> points = new Vector<mxPoint>(); // mxPoint p = new mxPoint(50.0, 50.0); // points.add(p); // geom.setPoints(points); // edge.setGeometry(geom); } /** * adds grid rectangles via cell vertices */ public void addGridCells() { if (gcm.getGrid().isEnabled()) { int gridRows = gcm.getGrid().getNumRows(); int gridCols = gcm.getGrid().getNumCols(); double gridWidth = gcm.getGrid().getGridGeomWidth(); double gridHeight = gcm.getGrid().getGridGeomHeight(); //creates an mxCell/vertex for each grid rectangle //these are later accessible via ID via the hash map for (int row = 0; row < gridRows; ++row) { for (int col = 0; col < gridCols; ++col) { String id = "ROW" + row + "_COL" + col; Properties prop = new Properties(); prop.setProperty("Type", GlobalConstants.GRID_RECTANGLE); double currX = 15 + col*gridWidth; double currY = 15 + row*gridHeight; CellValueObject cvo = new CellValueObject(id, prop); Object vertex = this.insertVertex(this.getDefaultParent(), id, cvo, currX, currY, gridWidth, gridHeight); mxCell cell = (mxCell)vertex; cell.setConnectable(false); cell.setStyle("GRID_RECTANGLE"); gridRectangleToMxCellMap.put(id, cell); } } } } //POSITION UPDATING /** * Called after a layout is chosen and applied. * Updates the gcm's postitioning using the * positioning on the graph. */ public void updateAllSpeciesPosition(){ for(mxCell cell:this.speciesToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.reactionsToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.componentsToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.drawnPromoterToMxCellMap.values()){ updateInternalPosition(cell); } } /** * Given a cell that must be a species or component, * update the internal model to reflect it's coordinates. * Called when a cell is dragged with the GUI. */ public void updateInternalPosition(mxCell cell){ Properties prop = ((CellValueObject)cell.getValue()).prop; mxGeometry geom = cell.getGeometry(); prop.setProperty("graphx", String.valueOf(geom.getX())); prop.setProperty("graphy", String.valueOf(geom.getY())); prop.setProperty("graphwidth", String.valueOf(geom.getWidth())); prop.setProperty("graphheight", String.valueOf(geom.getHeight())); } /** * Given a species, component, or drawn promoter cell, position it * using the properties. */ private boolean sizeAndPositionFromProperties(mxCell cell, Properties prop){ double x = Double.parseDouble(prop.getProperty("graphx", "-9999")); double y = Double.parseDouble(prop.getProperty("graphy", "-9999"));; double width = Double.parseDouble(prop.getProperty("graphwidth", String.valueOf(GlobalConstants.DEFAULT_SPECIES_WIDTH)));; double height = Double.parseDouble(prop.getProperty("graphheight", String.valueOf(GlobalConstants.DEFAULT_SPECIES_HEIGHT))); /* String id = !(prop.getProperty(GlobalConstants.NAME, "").equals("")) ? prop.getProperty(GlobalConstants.NAME) : !prop.getProperty("ID", "").equals("") ? prop.getProperty("ID", ""): prop.getProperty("label"); */ boolean needsPositioning = false; if(x < -9998 || y < -9998){ unpositionedSpeciesComponentCount += 1; needsPositioning = true; // Line the unpositioned species up nicely. The mod is there as a rough // and dirty way to prevent // them going off the bottom or right hand side of the screen. x = (unpositionedSpeciesComponentCount%50) * 20; y = (unpositionedSpeciesComponentCount%10) * (GlobalConstants.DEFAULT_SPECIES_HEIGHT + 10); } cell.setGeometry(new mxGeometry(x, y, width, height)); return needsPositioning; } //GET METHODS /** * returns GlobalConstants.SPECIES, GlobalConstants.COMPONENT, GlobalConstants.INFLUENCE, or GlobalConstants.COMPONENT_CONNECTION. * @param cell */ public String getCellType(mxCell cell){ if(cell.isEdge()){ String sourceType = getCellType(cell.getSource()); String targetType = getCellType(cell.getTarget()); if(sourceType == CELL_VALUE_NOT_FOUND || targetType == CELL_VALUE_NOT_FOUND){ return CELL_NOT_FULLY_CONNECTED; } else if(sourceType == GlobalConstants.COMPONENT || targetType == GlobalConstants.COMPONENT){ return GlobalConstants.COMPONENT_CONNECTION; } else if(sourceType == GlobalConstants.PROMOTER && targetType == GlobalConstants.SPECIES){ return GlobalConstants.PRODUCTION; } else if (sourceType == GlobalConstants.SPECIES && targetType == GlobalConstants.SPECIES && (gcm.getSBMLDocument().getModel().getNumReactions() > 0) && cell.getValue() != null && (gcm.getSBMLDocument().getModel().getReaction((String)cell.getValue()) != null)) { return GlobalConstants.REACTION_EDGE; } else if (sourceType == GlobalConstants.REACTION || targetType == GlobalConstants.REACTION) { return GlobalConstants.REACTION_EDGE; } else { return GlobalConstants.INFLUENCE; } } //cell is a vertex else{ Properties prop = ((CellValueObject)(cell.getValue())).prop; if(gcm.getSpecies().containsValue(prop)) return GlobalConstants.SPECIES; else if(gcm.getComponents().containsValue(prop)) return GlobalConstants.COMPONENT; else if(gcm.getPromoters().containsValue(prop)) return GlobalConstants.PROMOTER; else if(gcm.getReactions().containsValue(prop)) return GlobalConstants.REACTION; else if (prop.getProperty("Type").equals(GlobalConstants.GRID_RECTANGLE)) return GlobalConstants.GRID_RECTANGLE; else return CELL_VALUE_NOT_FOUND; } } /** * * @param cell * @return */ public String getCellType(mxICell cell) { return getCellType((mxCell)cell); } /** * Given a cell, return the list that it belongs to. */ public HashMap<String, Properties> getPropertiesList(mxCell cell){ String type = this.getCellType(cell); if(type == GlobalConstants.SPECIES) return gcm.getSpecies(); else if(type == GlobalConstants.COMPONENT) return gcm.getComponents(); else if(type == GlobalConstants.INFLUENCE) return gcm.getInfluences(); else if(type == GlobalConstants.COMPONENT_CONNECTION) return null; // Component connection don't have properties else if(type == GlobalConstants.PRODUCTION) return null; // Production connection don't have properties else if(type == GlobalConstants.PROMOTER) return gcm.getPromoters(); else if(type == GlobalConstants.REACTION) return gcm.getReactions(); else if(type == GlobalConstants.REACTION_EDGE) return null; else if(type == GlobalConstants.GRID_RECTANGLE) return null; else throw new Error("Invalid type: " + type); } /** * A convenience function * @param cell * @return */ public Properties getCellProperties(mxCell cell){ if(cell.getId() == null || getPropertiesList(cell) == null) return null; return getPropertiesList(cell).get(cell.getId()); } /** * * @param cell * @return */ public Properties getCellProperties(mxICell cell){ return getCellProperties((mxCell)cell); } /** * * @param id * @return */ public mxCell getSpeciesCell(String id){ return speciesToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getReactionsCell(String id){ return reactionsToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getComponentCell(String id){ return componentsToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getDrawnPromoterCell(String id){ return drawnPromoterToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getInfluence(String id){ return (influencesToMxCellMap.get(id)); } /** * returns the mxCell corresponding to the id passed in * this mxCell is a grid rectangle on the grid * * @param id the id of the grid rectangle's cell * @return the corresponding cell */ public mxCell getGridRectangleCellFromID(String id) { return gridRectangleToMxCellMap.get(id); } /** * returns if the cell is selectable or not * * @param cell the cell that is or isn't selectable */ @Override public boolean isCellSelectable(Object cell) { mxCell tempCell = (mxCell)cell; //if it's a grid cell, it's not selectable //otherwise, do the default behavior if (tempCell.getStyle().equals("GRID_RECTANGLE")) return false; return isCellsSelectable(); } //GRAPH PART CREATION /** * * @param id * @return */ private boolean createGraphComponentFromModel(String id){ //{invb={ID=invb, gcm=inv.gcm} //{invb={ID=invb, gcm=inv.gcm}, i1={b=S3, ID=i1, a=S1, gcm=inv.gcm, type_b=Output, type_a=Input}} boolean needsPositioning = false; Properties prop = gcm.getComponents().get(id); double x = Double.parseDouble(prop.getProperty("graphx", "-9999")); double y = Double.parseDouble(prop.getProperty("graphy", "-9999"));; double width = Double.parseDouble(prop.getProperty("graphwidth", String.valueOf(GlobalConstants.DEFAULT_COMPONENT_WIDTH)));; double height = Double.parseDouble(prop.getProperty("graphheight", String.valueOf(GlobalConstants.DEFAULT_COMPONENT_HEIGHT))); //set the correct compartment status GCMFile compGCMFile = new GCMFile(gcm.getPath()); boolean compart = false; File compFile = new File(gcm.getPath() + File.separator + prop.getProperty("gcm")); if (compGCMFile != null && compFile.exists()) { compGCMFile.load(gcm.getPath() + File.separator + prop.getProperty("gcm")); compart = compGCMFile.getIsWithinCompartment(); } else { JOptionPane.showMessageDialog(Gui.frame, "A model definition cannot be found for " + prop.getProperty("gcm") + ".\nDropping component from the schematic.\n", "Warning", JOptionPane.WARNING_MESSAGE); return false; } prop.setProperty("compartment", Boolean.toString(compart)); if(x < -9998 || y < -9998){ unpositionedSpeciesComponentCount += 1; needsPositioning = true; // Line the unpositioned species up nicely. The mod is there as a rough // and dirty way to prevent // them going off the bottom or right hand side of the screen. x = (unpositionedSpeciesComponentCount%50) * 20; y = (unpositionedSpeciesComponentCount%10) * (GlobalConstants.DEFAULT_SPECIES_HEIGHT + 10); } String label = id + "\n" + prop.getProperty("gcm").replace(".gcm", ""); CellValueObject cvo = new CellValueObject(label, prop); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, x, y, width, height); this.componentsToMxCellMap.put(id, (mxCell)insertedVertex); //pass whether or not the component is a compartment, as the styles are different this.setComponentStyles(id, compart); // now draw the edges that connect the component for (Object propName : prop.keySet()) { if (!propName.toString().equals("gcm") && !propName.toString().equals(GlobalConstants.ID) && prop.keySet().contains("type_" + propName)) { Object createdEdge; if (prop.getProperty("type_" + propName).equals("Output")) { // output, the arrow should point out to the species createdEdge = this.insertEdge(this.getDefaultParent(), "", "", insertedVertex, this.getSpeciesCell(prop.getProperty(propName.toString()).toString())); String key = id + " Output " + prop.getProperty(propName.toString()).toString(); componentsConnectionsToMxCellMap.put(key, (mxCell)createdEdge); } else { // input, the arrow should point in from the species createdEdge = this.insertEdge(this.getDefaultParent(), "", "", this.getSpeciesCell(prop.getProperty(propName.toString()).toString()), insertedVertex); String key = id + " Input " + prop.getProperty(propName.toString()).toString(); componentsConnectionsToMxCellMap.put(key, (mxCell)createdEdge); } this.updateComponentConnectionVisuals((mxCell)createdEdge, propName.toString()); } } return needsPositioning; } /** * creates a vertex on the graph using the internal model. * @param id * * @return: A bool, true if the species had to be positioned. */ private boolean createGraphSpeciesFromModel(String sp){ Properties prop = gcm.getSpecies().get(sp); String id = prop.getProperty("ID"); String type = prop.getProperty("Type") .replace(GlobalConstants.DIFFUSIBLE, " (D)").replace(GlobalConstants.SPASTIC, " (C)"); if (id==null) { id = prop.getProperty("label"); } String label = id + '\n' + type; CellValueObject cvo = new CellValueObject(label, prop); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.speciesToMxCellMap.put(id, (mxCell)insertedVertex); this.setSpeciesStyles(sp); return sizeAndPositionFromProperties((mxCell)insertedVertex, prop); } /** * creates a vertex on the graph using the internal model. * @param id * * @return: A bool, true if the reaction had to be positioned. */ private boolean createGraphReactionFromModel(String id){ Properties prop = gcm.getReactions().get(id); CellValueObject cvo = new CellValueObject(id, prop); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.reactionsToMxCellMap.put(id, (mxCell)insertedVertex); this.setReactionStyles(id); return sizeAndPositionFromProperties((mxCell)insertedVertex, prop); } /** * Creates a drawn promoter using the internal model * @param pname * @return */ private boolean createGraphDrawnPromoterFromModel(String pname){ Properties prop = gcm.getPromoters().get(pname); if(prop == null){ throw new Error("No promoter could be found that matches the name " + pname); } String id = prop.getProperty("ID", ""); if (id==null) { id = prop.getProperty("label", ""); } CellValueObject cvo = new CellValueObject(id, prop); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.drawnPromoterToMxCellMap.put(id, (mxCell)insertedVertex); this.setDrawnPromoterStyles(pname); return sizeAndPositionFromProperties((mxCell)insertedVertex, prop); } /** * creates an edge between two graph entities */ @Override public Object insertEdge(Object parent, String id, Object value, Object source, Object target, String style){ Object ret = super.insertEdge(parent, id, value, source, target, style); this.influencesToMxCellMap.put(id, (mxCell)ret); return ret; } //VISUALS /** * Given an id, update the style of the influence based on the internal model. */ private void updateInfluenceVisuals(String id){ Properties prop = gcm.getInfluences().get(id); //gcm.getSBMLDocument().getModel(); if(prop == null) throw new Error("Invalid id '"+id+"'. Valid ids were:" + String.valueOf(gcm.getInfluences().keySet())); // build the edge style String style = "defaultEdge;" + mxConstants.STYLE_ENDARROW + "="; if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.ACTIVATION)) style = "ACTIVATION"; else if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.REPRESSION)) style = "REPRESSION"; else if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.COMPLEX)) style = "COMPLEX"; else style = "DEFAULT"; // apply the style mxCell cell = this.getInfluence(id); cell.setStyle(style); // apply the promoter name as a label, only if the promoter isn't drawn. if(gcm.influenceHasExplicitPromoter(id) == false) cell.setValue(prop.getProperty(GlobalConstants.PROMOTER)); }; /** * * @param cell * @param label */ public void updateComponentConnectionVisuals(mxCell cell, String label){ //cell.setStyle(mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN); cell.setStyle("COMPONENT_EDGE"); cell.setValue("Port " + label); // position the label as intelligently as possible mxGeometry geom = cell.getGeometry(); if(this.getCellType(cell.getSource()) == GlobalConstants.COMPONENT){ geom.setX(-.6); } else{ geom.setX(.6); } cell.setGeometry(geom); } /** * Builds the style sheets that will be used by the graph. */ public void createStyleSheets(){ mxStylesheet stylesheet = this.getStylesheet(); //species Hashtable<String, Object> style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE); style.put(mxConstants.STYLE_OPACITY, 50); style.put(mxConstants.STYLE_FILLCOLOR, "#5CB4F2"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_ROUNDED, true); stylesheet.putCellStyle("SPECIES", style); //reactions style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_ELLIPSE); style.put(mxConstants.STYLE_OPACITY, 50); style.put(mxConstants.STYLE_FILLCOLOR, "#C7007B"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); stylesheet.putCellStyle("REACTION", style); //components style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE); style.put(mxConstants.STYLE_OPACITY, 50); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_ROUNDED, false); style.put(mxConstants.STYLE_FILLCOLOR, "#87F274"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); stylesheet.putCellStyle("COMPONENT", style); //grid components style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_ROUNDED, false); style.put(mxConstants.STYLE_FILLCOLOR, "#87F274"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); stylesheet.putCellStyle("GRIDCOMPONENT", style); //compartments style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE); style.put(mxConstants.STYLE_OPACITY, 50); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_ROUNDED, true); style.put(mxConstants.STYLE_FILLCOLOR, "#87F274"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); stylesheet.putCellStyle("COMPARTMENT", style); //grid compartments style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_ROUNDED, true); style.put(mxConstants.STYLE_FILLCOLOR, "#87F274"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); stylesheet.putCellStyle("GRIDCOMPARTMENT", style); //grid rectangle style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_ROUNDED, false); style.put(mxConstants.STYLE_FILLCOLOR, "none"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); style.put(mxConstants.STYLE_MOVABLE, false); style.put(mxConstants.STYLE_RESIZABLE, false); style.put(mxConstants.STYLE_NOLABEL, true); stylesheet.putCellStyle("GRID_RECTANGLE", style); //component edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_FILLCOLOR, "#FFAA00"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); style.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_OPEN); stylesheet.putCellStyle("COMPONENT_EDGE", style); //production edge (promoter to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_FILLCOLOR, "#34BA04"); style.put(mxConstants.STYLE_STROKECOLOR, "#34BA04"); style.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_OPEN); style.put(mxConstants.STYLE_EDGE, mxConstants.EDGESTYLE_ENTITY_RELATION); stylesheet.putCellStyle("PRODUCTION", style); //activation edge (species to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_FILLCOLOR, "#34BA04"); style.put(mxConstants.STYLE_STROKECOLOR, "#34BA04"); style.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_BLOCK); stylesheet.putCellStyle("ACTIVATION", style); //repression edge (species to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_FILLCOLOR, "#FA2A2A"); style.put(mxConstants.STYLE_STROKECOLOR, "#FA2A2A"); style.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_OVAL); stylesheet.putCellStyle("REPRESSION", style); //complex formation edge (species to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_FILLCOLOR, "#4E5D9C"); style.put(mxConstants.STYLE_STROKECOLOR, "#4E5D9C"); style.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_DIAMOND); style.put(mxConstants.STYLE_DASHED, "true"); stylesheet.putCellStyle("COMPLEX", style); //reaction edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_FILLCOLOR, "#F2861B"); style.put(mxConstants.STYLE_STROKECOLOR, "#F2861B"); style.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_OPEN); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("REACTION_EDGE", style); //default edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_FILLCOLOR, "#000000"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); style.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_CLASSIC); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("DEFAULT", style); //explicit promoter style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RHOMBUS); style.put(mxConstants.STYLE_OPACITY, 50); style.put(mxConstants.STYLE_FONTCOLOR, "#000000"); style.put(mxConstants.STYLE_FILLCOLOR, "#F00E0E"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); stylesheet.putCellStyle("EXPLICIT_PROMOTER", style); } //STYLE SETTING /** * * @param id */ private void setSpeciesStyles(String id){ String style="SPECIES;"; mxCell cell = this.getSpeciesCell(id); cell.setStyle(style); } /** * * @param id */ private void setReactionStyles(String id){ String style="REACTION;"; mxCell cell = this.getReactionsCell(id); cell.setStyle(style); } /** * * @param id * @param compart */ private void setComponentStyles(String id, boolean compart){ String style = ""; if (gcm.getGrid().isEnabled()) { if (compart) style = "GRIDCOMPARTMENT;"; else style = "GRIDCOMPONENT;"; } else { if (compart) style = "COMPARTMENT;"; else style = "COMPONENT;"; } mxCell cell = this.getComponentCell(id); cell.setStyle(style); } /** * * @param id */ private void setDrawnPromoterStyles(String id){ String style="EXPLICIT_PROMOTER"; mxCell cell = this.getDrawnPromoterCell(id); cell.setStyle(style); } //ANIMATION public void setSpeciesAnimationValue(String species, MovieAppearance appearance){ mxCell cell = this.speciesToMxCellMap.get(species); Properties prop = gcm.getSpecies().get(species); assert(prop != null); setCellAnimationValue(cell, appearance, prop); } public void setComponentAnimationValue(String component, MovieAppearance appearance){ mxCell cell = this.componentsToMxCellMap.get(component); Properties prop = gcm.getComponents().get(component); assert(prop != null); setCellAnimationValue(cell, appearance, prop); } public void setGridRectangleAnimationValue(String gridLocation, MovieAppearance appearance) { mxCell cell = this.gridRectangleToMxCellMap.get(gridLocation); setCellAnimationValue(cell, appearance, null); } /** * Applies the MovieAppearance to the cell * @param cell * @param appearance * @param properties */ private void setCellAnimationValue(mxCell cell, MovieAppearance appearance, Properties prop){ if(appearance == null) return; // color String newStyle = cell.getStyle() + ";"; if(appearance.color != null){ newStyle += mxConstants.STYLE_FILLCOLOR + "=" + Integer.toHexString(appearance.color.getRGB()) + ";"; newStyle += mxConstants.STYLE_OPACITY + "=" + 75; } // opacity if(appearance.opacity != null){ if(newStyle == null) newStyle = ""; else newStyle += ";"; double op = (appearance.opacity) * 100.0; newStyle += mxConstants.STYLE_OPACITY + "=" + String.valueOf(op); } if(newStyle != null) cell.setStyle(newStyle); // size if(appearance.size != null){ double gcmX = Double.parseDouble( prop.getProperty("graphx", String.valueOf(GlobalConstants.DEFAULT_COMPONENT_WIDTH))); double gcmY = Double.parseDouble( prop.getProperty("graphy", String.valueOf(GlobalConstants.DEFAULT_SPECIES_HEIGHT))); double gcmWidth = Double.parseDouble( prop.getProperty("graphwidth", String.valueOf(GlobalConstants.DEFAULT_COMPONENT_WIDTH))); double gcmHeight = Double.parseDouble( prop.getProperty("graphheight", String.valueOf(GlobalConstants.DEFAULT_SPECIES_HEIGHT))); double aspect_ratio = gcmHeight / gcmWidth; double centerX = gcmX + gcmWidth/2.0; double centerY = gcmY + gcmHeight/2.0; mxGeometry startG = cell.getGeometry(); startG.setWidth(appearance.size); startG.setHeight(appearance.size * aspect_ratio); startG.setX(centerX - startG.getWidth()/2.0); startG.setY(centerY - startG.getHeight()/2.0); } } //CELL VALUE OBJECT CLASS /** * The object that gets set as the mxCell value object. * It is basically a way to store a property and label. */ public class CellValueObject extends Object implements Serializable{ private static final long serialVersionUID = 918273645; public Properties prop; public String label; @Override public String toString(){ return this.label; } /** * * @param oos * @throws IOException */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(label); oos.writeObject(prop); } /** * * @param ois * @throws ClassNotFoundException * @throws IOException */ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { label = ois.readObject().toString(); prop = (Properties)ois.readObject(); } /** * * * @param label * @param prop */ public CellValueObject(String label, Properties prop){ if(prop == null || label == null) throw new Error("Neither Properties nor label can not be null!"); this.label = label; this.prop = prop; } } //FUNCTIONS THAT TYLER COMMENTED OUT THAT WILL PROBABLY NEVER BE USED // /** // * Overwrite the parent insertVertex and additionally put the vertex into our hashmap. // * @return // */ // public Object insertVertex(Object parent, String id, Object value, double x, double y, double width, double height){ // Object ret = super.insertVertex(parent, id, value, x, y, width, height); // this.speciesToMxCellMap.put(id, (mxCell)ret); // return ret; // /** // * returns the name of the component-to-species connection // * @param compName // * @param speciesName // * @return // */ // /* // private String getComponentConnectionName(String compName, String speciesName){ // return compName + " (component connection) " + speciesName; // } // */ // /** // * creates a vertex on the graph using the internal model. // * @param id // * // * @return: A bool, true if the species had to be positioned. // */ // /* // private boolean createGraphCompartmentFromModel(String sp){ // Properties prop = new Properties(); // String id = sp; // CellValueObject cvo = new CellValueObject(id, prop); // Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); // this.speciesToMxCellMap.put(id, (mxCell)insertedVertex); // // this.setSpeciesStyles(sp); // // return sizeAndPositionFromProperties((mxCell)insertedVertex, prop); // } // */ // /** // * called after a species is deleted. Make sure to delete it from // * the internal model. // * @param id // */ // public void speciesRemoved(String id){ // this.speciesToMxCellMap.remove(id); // public void influenceRemoved(String id){ // this.influencesToMxCellMap.remove(id); }
package org.eclipse.birt.report.item.crosstab.internal.ui.dialogs; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.aggregation.AggregationManager; import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction; import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn; import org.eclipse.birt.report.data.adapter.api.AdapterException; import org.eclipse.birt.report.data.adapter.api.CubeQueryUtil; import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil; import org.eclipse.birt.report.data.adapter.api.DataRequestSession; import org.eclipse.birt.report.data.adapter.api.DataSessionContext; import org.eclipse.birt.report.data.adapter.api.IModelAdapter; import org.eclipse.birt.report.data.adapter.api.IModelAdapter.ExpressionLocation; import org.eclipse.birt.report.data.adapter.api.timeFunction.IArgumentInfo; import org.eclipse.birt.report.data.adapter.api.timeFunction.IArgumentInfo.Period_Type; import org.eclipse.birt.report.data.adapter.api.timeFunction.ITimeFunction; import org.eclipse.birt.report.data.adapter.api.timeFunction.TimeFunctionManager; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.data.ui.util.DataUtil; import org.eclipse.birt.report.designer.internal.ui.data.DataService; import org.eclipse.birt.report.designer.internal.ui.data.function.layout.IArgumentLayout; import org.eclipse.birt.report.designer.internal.ui.dialogs.AbstractBindingDialogHelper; import org.eclipse.birt.report.designer.internal.ui.dialogs.ResourceEditDialog; import org.eclipse.birt.report.designer.internal.ui.dialogs.expression.ExpressionButton; import org.eclipse.birt.report.designer.internal.ui.swt.custom.CLabel; import org.eclipse.birt.report.designer.internal.ui.util.ExpressionButtonUtil; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages; import org.eclipse.birt.report.designer.ui.dialogs.IExpressionProvider; import org.eclipse.birt.report.designer.ui.util.ExceptionUtil; import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory; import org.eclipse.birt.report.designer.util.ColorManager; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants; import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabViewHandle; import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle; import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle; import org.eclipse.birt.report.item.crosstab.core.util.CrosstabUtil; import org.eclipse.birt.report.item.crosstab.internal.ui.editors.model.CrosstabAdaptUtil; import org.eclipse.birt.report.model.api.AggregationArgumentHandle; import org.eclipse.birt.report.model.api.CalculationArgumentHandle; import org.eclipse.birt.report.model.api.ComputedColumnHandle; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.ExpressionHandle; import org.eclipse.birt.report.model.api.ExpressionType; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.IResourceLocator; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument; import org.eclipse.birt.report.model.api.elements.structures.CalculationArgument; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.extension.ExtendedElementException; import org.eclipse.birt.report.model.api.metadata.IChoice; import org.eclipse.birt.report.model.api.metadata.IChoiceSet; import org.eclipse.birt.report.model.api.olap.CubeHandle; import org.eclipse.birt.report.model.api.olap.DimensionHandle; import org.eclipse.birt.report.model.api.olap.LevelHandle; import org.eclipse.birt.report.model.api.olap.MeasureGroupHandle; import org.eclipse.birt.report.model.api.olap.MeasureHandle; import org.eclipse.birt.report.model.elements.interfaces.ICubeModel; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; public class CrosstabBindingDialogHelper extends AbstractBindingDialogHelper { protected static final String NAME = Messages.getString( "BindingDialogHelper.text.Name" ); //$NON-NLS-1$ protected static final String DATA_TYPE = Messages.getString( "BindingDialogHelper.text.DataType" ); //$NON-NLS-1$ protected static final String FUNCTION = Messages.getString( "BindingDialogHelper.text.Function" ); //$NON-NLS-1$ protected static final String DATA_FIELD = Messages.getString( "BindingDialogHelper.text.DataField" ); //$NON-NLS-1$ protected static final String FILTER_CONDITION = Messages.getString( "BindingDialogHelper.text.Filter" ); //$NON-NLS-1$ protected static final String AGGREGATE_ON = Messages.getString( "BindingDialogHelper.text.AggOn" ); //$NON-NLS-1$ protected static final String EXPRESSION = Messages.getString( "BindingDialogHelper.text.Expression" ); //$NON-NLS-1$ protected static final String ALL = Messages.getString( "CrosstabBindingDialogHelper.AggOn.All" ); //$NON-NLS-1$ protected static final String DISPLAY_NAME = Messages.getString( "BindingDialogHelper.text.displayName" ); //$NON-NLS-1$ protected static final String DISPLAY_NAME_ID = Messages.getString( "BindingDialogHelper.text.displayNameID" ); //$NON-NLS-1$ protected static final String DEFAULT_ITEM_NAME = Messages.getString( "BindingDialogHelper.bindingName.dataitem" ); //$NON-NLS-1$ protected static final String DEFAULT_AGGREGATION_NAME = Messages.getString( "BindingDialogHelper.bindingName.aggregation" ); //$NON-NLS-1$ private static final String DEFAULT_TIMEPERIOD_NAME = Messages.getString( "CrosstabBindingDialogHelper.bindngName.timeperiod" ); //$NON-NLS-1$ private static final String CALCULATION_TYPE = Messages.getString( "CrosstabBindingDialogHelper.calculation.label" ); //$NON-NLS-1$ private static final String CALCULATION_GROUP = Messages.getString( "CrosstabBindingDialogHelper.calculation.group" ); //$NON-NLS-1$ private static final String EMPTY_STRING = ""; //$NON-NLS-1$ protected static final IChoiceSet DATA_TYPE_CHOICE_SET = DEUtil.getMetaDataDictionary( ) .getStructure( ComputedColumn.COMPUTED_COLUMN_STRUCT ) .getMember( ComputedColumn.DATA_TYPE_MEMBER ) .getAllowedChoices( ); protected static final IChoice[] DATA_TYPE_CHOICES = DATA_TYPE_CHOICE_SET.getChoices( null ); protected String[] dataTypes = ChoiceSetFactory.getDisplayNamefromChoiceSet( DATA_TYPE_CHOICE_SET ); private Text txtName, txtFilter, txtExpression; private Text dateText; private Combo cmbType, cmbFunction, cmbAggOn, calculationType, timeDimension; private Composite paramsComposite; private Group calculationComposite; private Map<String, Control> paramsMap = new HashMap<String, Control>( ); private Map<String, String> paramsValueMap = new HashMap<String, String>( ); private Composite composite; private Text txtDisplayName, txtDisplayNameID; private ComputedColumn newBinding; private CLabel messageLine; private Label lbName, lbDisplayNameID; private Object container; private Button btnDisplayNameID, btnRemoveDisplayNameID; private List<ITimeFunction> times; private Button todayButton, dateSelectionButton, recentButton; private Map<String, Control> calculationParamsMap = new HashMap<String, Control>( ); private Map<String, String> calculationParamsValueMap = new HashMap<String, String>( ); private boolean isStatic = true; public void createContent( Composite parent ) { composite = parent; ( (GridLayout) composite.getLayout( ) ).numColumns = 4; lbName = new Label( composite, SWT.NONE ); lbName.setText( NAME ); txtName = new Text( composite, SWT.BORDER ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 3; gd.widthHint = 250; txtName.setLayoutData( gd ); // WidgetUtil.createGridPlaceholder( composite, 1, false ); txtName.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); } } ); lbDisplayNameID = new Label( composite, SWT.NONE ); lbDisplayNameID.setText( DISPLAY_NAME_ID ); lbDisplayNameID.addTraverseListener( new TraverseListener( ) { public void keyTraversed( TraverseEvent e ) { if ( e.detail == SWT.TRAVERSE_MNEMONIC && e.doit ) { e.detail = SWT.TRAVERSE_NONE; if ( btnDisplayNameID.isEnabled( ) ) { openKeySelectionDialog( ); } } } } ); txtDisplayNameID = new Text( composite, SWT.BORDER | SWT.READ_ONLY ); txtDisplayNameID.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); } } ); txtDisplayNameID.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); btnDisplayNameID = new Button( composite, SWT.NONE ); btnDisplayNameID.setEnabled( getAvailableResourceUrls( ) != null && getAvailableResourceUrls( ).length > 0 ? true : false ); btnDisplayNameID.setText( "..." ); //$NON-NLS-1$ btnDisplayNameID.setToolTipText( Messages.getString( "ResourceKeyDescriptor.button.browse.tooltip" ) ); //$NON-NLS-1$ btnDisplayNameID.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { openKeySelectionDialog( ); } } ); btnRemoveDisplayNameID = new Button( composite, SWT.NONE ); btnRemoveDisplayNameID.setImage( ReportPlatformUIImages.getImage( ISharedImages.IMG_TOOL_DELETE ) ); btnRemoveDisplayNameID.setToolTipText( Messages.getString( "ResourceKeyDescriptor.button.reset.tooltip" ) ); //$NON-NLS-1$ btnRemoveDisplayNameID.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { txtDisplayNameID.setText( EMPTY_STRING ); txtDisplayName.setText( EMPTY_STRING ); updateRemoveBtnState( ); } } ); new Label( composite, SWT.NONE ).setText( DISPLAY_NAME ); txtDisplayName = new Text( composite, SWT.BORDER ); gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 3; txtDisplayName.setLayoutData( gd ); txtDisplayName.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); } } ); // WidgetUtil.createGridPlaceholder( composite, 1, false ); new Label( composite, SWT.NONE ).setText( DATA_TYPE ); cmbType = new Combo( composite, SWT.BORDER | SWT.READ_ONLY ); cmbType.setLayoutData( gd ); cmbType.setVisibleItemCount( 30 ); cmbType.addSelectionListener( new SelectionListener( ) { public void widgetDefaultSelected( SelectionEvent arg0 ) { validate( ); } public void widgetSelected( SelectionEvent arg0 ) { modifyDialogContent( ); validate( ); } } ); if ( isTimePeriod( ) ) { createCalculationSelection( composite ); } // WidgetUtil.createGridPlaceholder( composite, 1, false ); if ( isAggregate( ) ) { createAggregateSection( composite ); } else { createCommonSection( composite ); } if ( isTimePeriod( ) ) { new Label( composite, SWT.NONE ).setText( Messages.getString( "CrosstabBindingDialogHelper.timedimension.label" ) ); //$NON-NLS-1$ timeDimension = new Combo( composite, SWT.BORDER | SWT.READ_ONLY ); timeDimension.setLayoutData( gd ); timeDimension.setVisibleItemCount( 30 ); timeDimension.addSelectionListener( new SelectionListener( ) { public void widgetDefaultSelected( SelectionEvent arg0 ) { validate( ); } public void widgetSelected( SelectionEvent arg0 ) { handleTimeDimensionSelectEvent( ); modifyDialogContent( ); validate( ); } } ); createDataSelection( composite ); } createMessageSection( composite ); gd = new GridData( GridData.FILL_BOTH ); composite.setLayoutData( gd ); setContentSize( composite ); } private void createDataSelection( Composite composite ) { Label referDataLabel = new Label( composite, SWT.NONE ); referDataLabel.setText( Messages.getString( "CrosstabBindingDialogHelper.referencedate.label" ) ); //$NON-NLS-1$ GridData gd = new GridData( ); gd.verticalAlignment = SWT.BEGINNING; referDataLabel.setLayoutData( gd ); Composite radioContainer = new Composite( composite, SWT.NONE ); GridLayout layout = new GridLayout( ); gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 3; radioContainer.setLayoutData( gd ); layout = new GridLayout( ); layout.marginWidth = layout.marginHeight = 0; layout.numColumns = 2; radioContainer.setLayout( layout ); todayButton = new Button( radioContainer, SWT.RADIO ); todayButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { if ( !isStatic ) { isStatic = true; initCalculationTypeCombo( getTimeDimsionName( ) ); } modifyDialogContent( ); validate( ); } } ); todayButton.setText( Messages.getString( "CrosstabBindingDialogHelper.today.label" ) ); //$NON-NLS-1$ todayButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1)); dateSelectionButton = new Button( radioContainer, SWT.RADIO ); dateSelectionButton.setText( Messages.getString( "CrosstabBindingDialogHelper.thisdate.label" ) ); //$NON-NLS-1$ dateSelectionButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { if ( !isStatic ) { isStatic = true; initCalculationTypeCombo( getTimeDimsionName( ) ); } modifyDialogContent( ); validate( ); } } ); Composite dateSelecionContainer = new Composite( radioContainer, SWT.NONE ); GridData gridData = new GridData(GridData.FILL_HORIZONTAL ); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; dateSelecionContainer.setLayoutData( gridData ); layout = new GridLayout( ); layout.marginWidth = layout.marginHeight = 0; layout.horizontalSpacing = 0; layout.numColumns = 2; dateSelecionContainer.setLayout( layout ); dateText = new Text( dateSelecionContainer, SWT.BORDER ); dateText.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); } } ); dateText.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); if ( expressionProvider == null ) { if ( isAggregate( ) ) expressionProvider = new CrosstabAggregationExpressionProvider( this.bindingHolder, this.binding ); else expressionProvider = new CrosstabBindingExpressionProvider( this.bindingHolder, this.binding ); } ExpressionButton button = ExpressionButtonUtil.createExpressionButton( dateSelecionContainer, dateText, expressionProvider, this.bindingHolder, true, SWT.PUSH ); dateText.setData( ExpressionButtonUtil.EXPR_TYPE, ExpressionType.CONSTANT ); button.refresh( ); new Label(radioContainer, SWT.NONE); Label dateFormatLbl = new Label( radioContainer, SWT.NONE ); dateFormatLbl.setText(Messages.getString("CrosstabBindingDialogHelper.thisdate.example.label")); //$NON-NLS-1$ dateFormatLbl.setForeground( ColorManager.getColor( 128, 128, 128 ) ); dateFormatLbl.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); recentButton = new Button( radioContainer, SWT.RADIO ); recentButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { if ( isStatic ) { isStatic = false; initCalculationTypeCombo( getTimeDimsionName( ) ); } modifyDialogContent( ); validate( ); } } ); recentButton.setText( Messages.getString( "CrosstabBindingDialogHelper.recentday.description" ) ); //$NON-NLS-1$ recentButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 3, 1)); } private void handleTimeDimensionSelectEvent( ) { String dimensionName = getTimeDimsionName( ); initCalculationTypeCombo( dimensionName ); boolean inUseDimsion = isUseDimension( dimensionName ); if ( inUseDimsion ) { recentButton.setEnabled( true ); } else { recentButton.setEnabled( false ); } } private boolean isUseDimension( String dimensionName ) { boolean inUseDimsion = false; CrosstabReportItemHandle crosstab = getCrosstabReportItemHandle( ); int count = crosstab.getDimensionCount( ICrosstabConstants.COLUMN_AXIS_TYPE ); for ( int i = 0; i < count; i++ ) { if ( crosstab.getDimension( ICrosstabConstants.COLUMN_AXIS_TYPE, i ).getCubeDimension( ).getName( ) .equals( dimensionName ) ) { inUseDimsion = true; } } count = crosstab.getDimensionCount( ICrosstabConstants.ROW_AXIS_TYPE ); for ( int i = 0; i < count; i++ ) { if ( crosstab.getDimension( ICrosstabConstants.ROW_AXIS_TYPE, i ).getCubeDimension( ).getName( ) .equals( dimensionName ) ) { inUseDimsion = true; } } return inUseDimsion; } private void initCalculationTypeCombo( String dimensionName ) { DimensionHandle handle = getCrosstabReportItemHandle( ).getCube( ) .getDimension( dimensionName ); String cal = calculationType.getText( ); isStatic = true; if ( recentButton.getSelection( ) ) { isStatic = false; } times = TimeFunctionManager.getCalculationTypes( handle, getUseLevels( dimensionName ), isStatic ); String[] items = new String[times.size( )]; String[] names = new String[times.size( )]; for ( int i = 0; i < times.size( ); i++ ) { items[i] = times.get( i ).getDisplayName( ); names[i] = times.get( i ).getName( ); } calculationType.setItems( items ); if ( getBinding( ) == null ) { if ( cal != null && getItemIndex( items, cal ) >= 0 ) { calculationType.select( getItemIndex( items, cal ) ); } else { calculationType.select( 0 ); } handleCalculationSelectEvent( ); } else { if ( cal != null && getItemIndex( items, cal ) >= 0 ) { calculationType.select( getItemIndex( items, cal ) ); } else { ITimeFunction function = getTimeFunctionByDisplaName( getBinding( ).getCalculationType( ) ); if (function == null) { return; } String name = function.getName( ); int itemIndex = getItemIndex( names, name ); if ( itemIndex >= 0 ) { calculationType.select( itemIndex ); } else { calculationType.select( 0 ); } } handleCalculationSelectEvent( ); ITimeFunction function = getTimeFunctionByIndex( calculationType.getSelectionIndex( ) ); List<IArgumentInfo> infos = function.getArguments( ); for ( int i = 0; i < infos.size( ); i++ ) { String argName = infos.get( i ).getName( ); String argValue = calculationParamsValueMap.get( argName ); if ( calculationParamsMap.containsKey( argName ) ) { if ( getArgumentValue( getBinding( ), argName ) != null ) { Control control = calculationParamsMap.get( argName ); ExpressionHandle obj = (ExpressionHandle) getArgumentValue( getBinding( ), argName ); if ( infos.get( i ).getPeriodChoices( ) == null || infos.get( i ).getPeriodChoices( ).isEmpty( ) ) { initExpressionButtonControl( control, obj ); } else { // Period_Type type = (Period_Type)obj; Combo combo = (Combo) control; String str = obj.getStringExpression( ); if ( str == null || str.length( ) == 0 ) { combo.select( 0 ); } else { int comboIndex = getItemIndex( combo.getItems( ), str ); if ( comboIndex >= 0 ) { combo.select( comboIndex ); } else { combo.select( 0 ); } } } // restore arg value if ( control instanceof Text && argValue != null ) { ((Text)control).setText(argValue); } } } } // init args } } private static ExpressionButton getExpressionButton( Control control ) { Object button = control.getData( ExpressionButtonUtil.EXPR_BUTTON ); if ( button instanceof ExpressionButton ) { return ( (ExpressionButton) button ); } return null; } public static void initExpressionButtonControl( Control control, ExpressionHandle value ) { ExpressionButton button = getExpressionButton( control ); if ( button != null && button.getExpressionHelper( ) != null ) { button.getExpressionHelper( ).setExpressionType( value == null || value.getType( ) == null ? UIUtil.getDefaultScriptType( ) : (String) value.getType( ) ); String stringValue = value == null || value.getExpression( ) == null ? "" : (String) value.getExpression( ); //$NON-NLS-1$ button.getExpressionHelper( ).setExpression( stringValue ); button.refresh( ); } } private List<String> getUseLevels( String dimensionName ) { List<String> retValue = new ArrayList<String>( ); DimensionViewHandle viewHandle = getCrosstabReportItemHandle( ).getDimension( dimensionName ); if ( viewHandle == null ) { return retValue; } int count = viewHandle.getLevelCount( ); for ( int i = 0; i < count; i++ ) { LevelViewHandle levelHandle = viewHandle.getLevel( i ); retValue.add( levelHandle.getCubeLevel( ).getName( ) ); } return retValue; } private CrosstabReportItemHandle getCrosstabReportItemHandle( ) { try { return (CrosstabReportItemHandle) ( ( (ExtendedItemHandle) bindingHolder ).getReportItem( ) ); } catch ( ExtendedElementException e ) { return null; } } private Object getArgumentValue( ComputedColumnHandle handle, String name ) { Iterator iter = handle.calculationArgumentsIterator( ); while ( iter.hasNext( ) ) { CalculationArgumentHandle argument = (CalculationArgumentHandle) iter.next( ); if ( name.equals( argument.getName( ) ) ) { return argument.getValue( ); } } return null; } private String getTimeDimsionName( ) { String dimensionName = timeDimension.getText( ); return dimensionName; // Set<IDimLevel> sets; // try // sets = ExpressionUtil.getReferencedDimLevel( dimensionName ); // catch ( CoreException e ) // return null; // Iterator<IDimLevel> iter = sets.iterator( ); // if ( iter.hasNext( ) ) // return iter.next( ).getDimensionName( ); // return null; } private void createCalculationSelection( Composite composite ) { calculationComposite = new Group( composite, SWT.NONE ); calculationComposite.setText( CALCULATION_GROUP ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = 4; //gridData.exclude = true; calculationComposite.setLayoutData( gridData ); GridLayout layout = new GridLayout( ); // layout.horizontalSpacing = layout.verticalSpacing = 0; //layout.marginWidth = layout.marginHeight = 0; layout.numColumns = 5; Layout parentLayout = calculationComposite.getParent( ).getLayout( ); if ( parentLayout instanceof GridLayout ) layout.horizontalSpacing = ( (GridLayout) parentLayout ).horizontalSpacing; calculationComposite.setLayout( layout ); Label calculationLable = new Label( calculationComposite, SWT.NONE ); calculationLable.setText( CALCULATION_TYPE ); GridData gd = new GridData( ); gd.widthHint = lbName.computeSize( SWT.DEFAULT, SWT.DEFAULT ).x - layout.marginWidth - 3; calculationLable.setLayoutData( gd ); calculationType = new Combo( calculationComposite, SWT.BORDER | SWT.READ_ONLY ); gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 4; calculationType.setLayoutData( gd ); calculationType.setVisibleItemCount( 30 ); calculationType.addSelectionListener( new SelectionListener( ) { public void widgetDefaultSelected( SelectionEvent arg0 ) { validate( ); } public void widgetSelected( SelectionEvent arg0 ) { handleCalculationSelectEvent( ); modifyDialogContent( ); validate( ); } } ); } private void handleCalculationSelectEvent( ) { Control[] children = calculationComposite.getChildren( ); for ( int i = 2; i < children.length; i++ ) { children[i].dispose( ); } ITimeFunction function = getTimeFunctionByIndex( calculationType.getSelectionIndex( ) ); if ( function == null ) { // ( (GridData) calculationComposite.getLayoutData( ) ).heightHint = 0; // ( (GridData) calculationComposite.getLayoutData( ) ).exclude = true; // calculationComposite.setVisible( false ); } else { calculationParamsMap.clear( ); List<IArgumentInfo> infos = function.getArguments( ); if ( infos == null || infos.size( ) == 0 ) { //( (GridData) calculationComposite.getLayoutData( ) ).heightHint = 0; //( (GridData) calculationComposite.getLayoutData( ) ).exclude = true; //calculationComposite.setVisible( false ); } else { List<IArgumentLayout> argLayouts = DataService.getInstance().getArgumentLayout(function, infos); ( (GridData) calculationComposite.getLayoutData( ) ).exclude = false; ( (GridData) calculationComposite.getLayoutData( ) ).heightHint = SWT.DEFAULT; calculationComposite.setVisible( true ); int width = 0; if ( calculationComposite.getParent( ).getLayout( ) instanceof GridLayout ) { Control[] controls = calculationComposite.getParent( ) .getChildren( ); for ( int i = 0; i < controls.length; i++ ) { if ( controls[i] instanceof Label && ( (GridData) controls[i].getLayoutData( ) ).horizontalSpan == 1 ) { int labelWidth = controls[i].getBounds( ).width - controls[i].getBorderWidth( ) * 2; if ( labelWidth > width ) width = labelWidth; } } } for ( int i = 0; i < infos.size( ); i++ ) { IArgumentInfo info = infos.get( i ); IArgumentLayout argLayout = argLayouts.get(i); int layoutHint = argLayout.getLayoutHint(); final List<Period_Type> types = info.getPeriodChoices( ); final String name = info.getName( ); final String displayName = info.getDisplayName(); Label lblParam = null; if(IArgumentLayout.ALIGN_BLOCK == layoutHint) { createPeriodLabelPart(lblParam, displayName, false); createPeriodPart(name, types, 4); } else if (IArgumentLayout.ALIGN_INLINE_BEFORE == layoutHint) { createPeriodLabelPart(lblParam, displayName, false); createPeriodPart(name, types, 1); } else if (IArgumentLayout.LIGN_INLINEL_AFTER == layoutHint) { createPeriodPart(name, types, 1); createPeriodLabelPart(lblParam, displayName, true); } else if (IArgumentLayout.ALIGN_INLINE_NONE == layoutHint) { createPeriodPart(name, types, 2); } } } } composite.layout( true, true ); setContentSize( composite ); } /** * Creates the label control part of an argument info. * @param lblParam The Label control * @param displayName The display text * @param width the width hint of the control * @param isPlacedAfter before or after the Period part */ private void createPeriodLabelPart(Label lblParam, String displayName, boolean isPlacedAfter) { lblParam = new Label( calculationComposite, SWT.NONE ); lblParam.setText( displayName + (isPlacedAfter ? "" : ":") ); //$NON-NLS-1$ //$NON-NLS-2$ //if ( !infos.get( i ).isOptional( ) ) // lblParam.setText( "*" + lblParam.getText( ) ); GridData gd = new GridData( ); gd.widthHint = lblParam.computeSize( SWT.DEFAULT, SWT.DEFAULT ).x; //if ( gd.widthHint < width ) // gd.widthHint = width; lblParam.setLayoutData( gd ); } /** * Creates the Period control part of an argument info. * @param name The name of the argument info * @param types The period types * @param numColumns Number of columns the control takes */ private void createPeriodPart(final String name, List<Period_Type> types, int numColumns) { if ( types != null && types.size( ) > 0 ) { final Combo cmbDataField = new Combo( calculationComposite, SWT.BORDER | SWT.READ_ONLY ); cmbDataField.setLayoutData( GridDataFactory.fillDefaults( ) .grab( true, false ) .span( numColumns, 1 ) .create( ) ); cmbDataField.setVisibleItemCount( 30 ); initCalculationDataFields( cmbDataField, name, types ); cmbDataField.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); calculationParamsValueMap.put( name, cmbDataField.getText( ) ); } } ); calculationParamsMap.put( name, cmbDataField ); } else { final Text txtParam = new Text( calculationComposite, SWT.BORDER ); initCalculationTextFild( txtParam, name ); txtParam.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); calculationParamsValueMap.put( name, txtParam.getText( ) ); } } ); GridData gridData = new GridData( SWT.FILL, SWT.FILL, true, false ); //gridData.horizontalIndent = 0; //gridData.horizontalSpan = 2; txtParam.setLayoutData( gridData ); createExpressionButton( calculationComposite, txtParam ); calculationParamsMap.put( name, txtParam ); } } private void initCalculationTextFild( Text txtParam, String name ) { if ( calculationParamsValueMap.containsKey( name ) ) { txtParam.setText( calculationParamsValueMap.get( name ) ); return; } } private void initCalculationDataFields( Combo cmbDataField, String name, List<Period_Type> list ) { String[] strs = new String[list.size( )]; for ( int i = 0; i < list.size( ); i++ ) { strs[i] = list.get( i ).displayName( ); } cmbDataField.setItems( strs ); if ( calculationParamsValueMap.containsKey( name ) ) { cmbDataField.setText( calculationParamsValueMap.get( name ) ); return; } cmbDataField.select( 0 ); } private ITimeFunction getTimeFunctionByIndex( int index ) { if ( times == null ) { return null; } if ( index < 0 || index >= times.size( ) ) { return null; } return times.get( index ); } private ITimeFunction getTimeFunctionByDisplaName( String name ) { if ( times == null ) { return null; } for ( int i = 0; i < times.size( ); i++ ) { if ( times.get( i ).getName( ).equals( name ) ) { return times.get( i ); } } return null; } private void openKeySelectionDialog( ) { ResourceEditDialog dlg = new ResourceEditDialog( composite.getShell( ), Messages.getString( "ResourceKeyDescriptor.title.SelectKey" ) ); //$NON-NLS-1$ dlg.setResourceURLs( getResourceURLs( ) ); if ( dlg.open( ) == Window.OK ) { String[] result = (String[]) dlg.getDetailResult( ); txtDisplayNameID.setText( result[0] ); txtDisplayName.setText( result[1] ); updateRemoveBtnState( ); } } private boolean hasInitDialog = false; public void initDialog( ) { cmbType.setItems( dataTypes ); txtDisplayName.setFocus( ); if ( isAggregate( ) ) { initFunction( ); initFilter( ); // if (!isTimePeriod( )) { initAggOn( ); } } if ( isTimePeriod( ) ) { initTimeDimension( ); initReferenceDate( ); initCalculationTypeCombo( getTimeDimsionName( ) ); } if ( getBinding( ) == null )// create { if ( cmbType.getSelectionIndex( ) < 0 ) { setTypeSelect( dataTypes[0] ); } if ( isTimePeriod( ) ) { this.newBinding = StructureFactory.newComputedColumn( getBindingHolder( ), DEFAULT_TIMEPERIOD_NAME ); } else { this.newBinding = StructureFactory.newComputedColumn( getBindingHolder( ), isAggregate( ) ? DEFAULT_AGGREGATION_NAME : DEFAULT_ITEM_NAME ); } setName( this.newBinding.getName( ) ); } else { setName( getBinding( ).getName( ) ); setDisplayName( getBinding( ).getDisplayName( ) ); setDisplayNameID( getBinding( ).getDisplayNameID( ) ); if ( getBinding( ).getDataType( ) != null ) if ( DATA_TYPE_CHOICE_SET.findChoice( getBinding( ).getDataType( ) ) != null ) setTypeSelect( DATA_TYPE_CHOICE_SET.findChoice( getBinding( ).getDataType( ) ) .getDisplayName( ) ); else cmbType.setText( "" ); //$NON-NLS-1$ if ( getBinding( ).getExpression( ) != null ) setDataFieldExpression( getBinding( ) ); } if ( this.getBinding( ) != null ) { this.txtName.setEnabled( false ); } validate( ); hasInitDialog = true; composite.getShell( ).pack( ); } private void initReferenceDate( ) { String dimensionName = getTimeDimsionName( ); boolean inUseDimsion = isUseDimension( dimensionName ); if ( getBinding( ) == null ) // new Relative Time Period { ExtendedItemHandle handle = (ExtendedItemHandle) getBindingHolder( ) ; List<ComputedColumnHandle> dimensionHandle = new ArrayList(); for (Iterator<ComputedColumnHandle> iter = handle.columnBindingsIterator(); iter.hasNext();) { ComputedColumnHandle cHandle = iter.next(); if (cHandle.getTimeDimension() != null && !cHandle.getTimeDimension().equals(EMPTY_STRING)) { dimensionHandle.add(0, cHandle); } } if(0 == dimensionHandle.size() || !setRefDate(dimensionHandle.get(0), inUseDimsion)) { todayButton.setSelection( true ); } } else // edit Relative Time Period { setRefDate(getBinding(), inUseDimsion); } if ( inUseDimsion ) { recentButton.setEnabled( true ); } else { recentButton.setEnabled( false ); } } private boolean setRefDate (ComputedColumnHandle handle, boolean inUseDimsion) { String type = handle.getReferenceDateType( ); if (type == null) return false; if ( DesignChoiceConstants.REFERENCE_DATE_TYPE_TODAY.equals( type ) ) { todayButton.setSelection( true ); return true; } else if ( DesignChoiceConstants.REFERENCE_DATE_TYPE_FIXED_DATE.equals( type ) ) { dateSelectionButton.setSelection( true ); ExpressionHandle value = handle.getReferenceDateValue( ); dateText.setText( value == null || value.getExpression( ) == null ? "" : (String) value.getExpression( ) ); //$NON-NLS-1$ dateText.setData( ExpressionButtonUtil.EXPR_TYPE, value == null || value.getType( ) == null ? ExpressionType.CONSTANT : (String) value.getType( ) ); ExpressionButton button = (ExpressionButton) dateText.getData( ExpressionButtonUtil.EXPR_BUTTON ); if ( button != null ) button.refresh( ); return true; } else if ( DesignChoiceConstants.REFERENCE_DATE_TYPE_ENDING_DATE_IN_DIMENSION.equals( type ) ) { if(getBinding() == null && !inUseDimsion ) { return false; } else { recentButton.setSelection( true ); return true; } } return false; } private void initTimeDimension( ) { String[] strs = getTimeDimensions( ); timeDimension.setItems( strs ); if ( getBinding( ) == null ) { String str = getFirstUseDimensonDisplayName( ); if ( str != null && str.length( ) > 0 ) { int itemIndex = getItemIndex( strs, str ); if ( itemIndex >= 0 ) { timeDimension.select( itemIndex ); } else { timeDimension.select( 0 ); } } else { timeDimension.select( 0 ); } } else { String value = getBinding( ).getTimeDimension( ); int itemIndex = getItemIndex( strs, value ); timeDimension.select( itemIndex ); } } private String getFirstUseDimensonDisplayName( ) { CrosstabReportItemHandle crosstab = getCrosstabReportItemHandle( ); int count = crosstab.getDimensionCount( ICrosstabConstants.COLUMN_AXIS_TYPE ); for ( int i = 0; i < count; i++ ) { DimensionViewHandle viewHandle = crosstab.getDimension( ICrosstabConstants.COLUMN_AXIS_TYPE, i ); if ( isAvaliableTimeDimension( viewHandle.getCubeDimension( ) ) ) { // return ExpressionUtil.createJSDimensionExpression( // viewHandle.getCubeDimension( ) // .getName( ), // null ); return viewHandle.getCubeDimension( ).getName( ); } } count = crosstab.getDimensionCount( ICrosstabConstants.ROW_AXIS_TYPE ); for ( int i = 0; i < count; i++ ) { DimensionViewHandle viewHandle = crosstab.getDimension( ICrosstabConstants.ROW_AXIS_TYPE, i ); if ( isAvaliableTimeDimension( viewHandle.getCubeDimension( ) ) ) { // return ExpressionUtil.createJSDimensionExpression( // viewHandle.getCubeDimension( ) // .getName( ), // null ); return viewHandle.getCubeDimension( ).getName( ); } } return null; } private boolean isAvaliableTimeDimension( DimensionHandle dimension ) { if ( CrosstabAdaptUtil.isTimeDimension( dimension ) ) { DimensionViewHandle viewHandle = getCrosstabReportItemHandle( ).getDimension( dimension.getName( ) ); if ( viewHandle == null ) { int count = dimension.getDefaultHierarchy( ).getLevelCount( ); if ( count == 0 ) { return false; } LevelHandle levelHandle = dimension.getDefaultHierarchy( ) .getLevel( 0 ); if ( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_YEAR.equals( levelHandle.getDateTimeLevelType( ) ) ) { return true; } } else { int count = viewHandle.getLevelCount( ); if ( count == 0 ) { return false; } LevelViewHandle levelViewHandle = viewHandle.getLevel( 0 ); if ( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_YEAR.equals( levelViewHandle.getCubeLevel( ) .getDateTimeLevelType( ) ) ) { return true; } } } return false; } private String[] getTimeDimensions( ) { List<String> strs = new ArrayList<String>( ); CrosstabReportItemHandle crosstab = getCrosstabReportItemHandle( ); CubeHandle cube = crosstab.getCube( ); List list = cube.getPropertyHandle( ICubeModel.DIMENSIONS_PROP ) .getContents( ); for ( int i = 0; i < list.size( ); i++ ) { DimensionHandle dimension = (DimensionHandle) list.get( i ); if ( isAvaliableTimeDimension( dimension ) ) { // strs.add( ExpressionUtil.createJSDimensionExpression( // dimension.getName( ), // null ) ); strs.add( dimension.getName( ) ); } } return strs.toArray( new String[strs.size( )] ); } private void initAggOn( ) { try { CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) getBindingHolder( ) ).getReportItem( ); String[] aggOns = getAggOns( xtabHandle ); cmbAggOn.setItems( aggOns ); String aggstr = ""; //$NON-NLS-1$ if ( getBinding( ) != null ) { List aggOnList = getBinding( ).getAggregateOnList( ); int i = 0; for ( Iterator iterator = aggOnList.iterator( ); iterator.hasNext( ); ) { if ( i > 0 ) aggstr += ","; //$NON-NLS-1$ String name = (String) iterator.next( ); aggstr += name; i++; } } else if ( isTimePeriod( ) ) { List rowLevelList = getCrosstabViewHandleLevels( xtabHandle, ICrosstabConstants.ROW_AXIS_TYPE ); List columnLevelList = getCrosstabViewHandleLevels( xtabHandle, ICrosstabConstants.COLUMN_AXIS_TYPE ); if ( rowLevelList.size( ) != 0 && columnLevelList.size( ) == 0 ) { aggstr = (String) rowLevelList.get( rowLevelList.size( ) - 1 ); } else if ( rowLevelList.size( ) == 0 && columnLevelList.size( ) != 0 ) { aggstr = (String) columnLevelList.get( columnLevelList.size( ) - 1 ); } else if ( rowLevelList.size( ) != 0 && columnLevelList.size( ) != 0 ) { aggstr = (String) rowLevelList.get( rowLevelList.size( ) - 1 ) + "," + (String) columnLevelList.get( columnLevelList.size( ) - 1 ); } } else if ( getDataItemContainer( ) instanceof AggregationCellHandle ) { AggregationCellHandle cellHandle = (AggregationCellHandle) getDataItemContainer( ); if ( cellHandle.getAggregationOnRow( ) != null ) { aggstr += cellHandle.getAggregationOnRow( ).getFullName( ); if ( cellHandle.getAggregationOnColumn( ) != null ) { aggstr += ","; //$NON-NLS-1$ } } if ( cellHandle.getAggregationOnColumn( ) != null ) { aggstr += cellHandle.getAggregationOnColumn( ) .getFullName( ); } } else if ( container instanceof AggregationCellHandle ) { AggregationCellHandle cellHandle = (AggregationCellHandle) container; if ( cellHandle.getAggregationOnRow( ) != null ) { aggstr += cellHandle.getAggregationOnRow( ).getFullName( ); if ( cellHandle.getAggregationOnColumn( ) != null ) { aggstr += ","; //$NON-NLS-1$ } } if ( cellHandle.getAggregationOnColumn( ) != null ) { aggstr += cellHandle.getAggregationOnColumn( ) .getFullName( ); } } String[] strs = aggstr.split( "," );//$NON-NLS-1$ String temAddOns = "";//$NON-NLS-1$ if ( strs != null && strs.length > 1 ) { for ( int i = strs.length - 1; i >= 0; i { temAddOns = temAddOns + strs[i]; if ( i != 0 ) { temAddOns = temAddOns + ",";//$NON-NLS-1$ } } } for ( int j = 0; j < aggOns.length; j++ ) { if ( aggOns[j].equals( aggstr ) ) { cmbAggOn.select( j ); return; } if ( aggOns[j].equals( temAddOns ) ) { cmbAggOn.select( j ); return; } } cmbAggOn.select( 0 ); } catch ( ExtendedElementException e ) { ExceptionUtil.handle( e ); } } private String[] getAggOns( CrosstabReportItemHandle xtabHandle ) { List rowLevelList = getCrosstabViewHandleLevels( xtabHandle, ICrosstabConstants.ROW_AXIS_TYPE ); List columnLevelList = getCrosstabViewHandleLevels( xtabHandle, ICrosstabConstants.COLUMN_AXIS_TYPE ); List aggOnList = new ArrayList( ); aggOnList.add( ALL ); for ( Iterator iterator = rowLevelList.iterator( ); iterator.hasNext( ); ) { String name = (String) iterator.next( ); aggOnList.add( name ); } for ( Iterator iterator = columnLevelList.iterator( ); iterator.hasNext( ); ) { String name = (String) iterator.next( ); aggOnList.add( name ); } for ( Iterator iterator = rowLevelList.iterator( ); iterator.hasNext( ); ) { String name = (String) iterator.next( ); for ( Iterator iterator2 = columnLevelList.iterator( ); iterator2.hasNext( ); ) { String name2 = (String) iterator2.next( ); aggOnList.add( name + "," + name2 ); //$NON-NLS-1$ } } return (String[]) aggOnList.toArray( new String[aggOnList.size( )] ); } private List getCrosstabViewHandleLevels( CrosstabReportItemHandle xtab, int type ) { List levelList = new ArrayList( ); CrosstabViewHandle viewHandle = xtab.getCrosstabView( type ); if ( viewHandle != null ) { int dimensions = viewHandle.getDimensionCount( ); for ( int i = 0; i < dimensions; i++ ) { DimensionViewHandle dimension = viewHandle.getDimension( i ); int levels = dimension.getLevelCount( ); for ( int j = 0; j < levels; j++ ) { LevelViewHandle level = dimension.getLevel( j ); if ( level.getCubeLevel( ) != null ) { levelList.add( level.getCubeLevel( ).getFullName( ) ); } } } } return levelList; } private void initFilter( ) { ExpressionButtonUtil.initExpressionButtonControl( txtFilter, binding, ComputedColumn.FILTER_MEMBER ); } private void initFunction( ) { cmbFunction.setItems( getFunctionDisplayNames( ) ); // cmbFunction.add( NULL, 0 ); if ( binding == null ) { cmbFunction.select( 0 ); handleFunctionSelectEvent( ); return; } try { String functionString = getFunctionDisplayName( DataAdapterUtil.adaptModelAggregationType( binding.getAggregateFunction( ) ) ); int itemIndex = getItemIndex( getFunctionDisplayNames( ), functionString ); cmbFunction.select( itemIndex ); handleFunctionSelectEvent( ); } catch ( AdapterException e ) { ExceptionUtil.handle( e ); } // List args = getFunctionArgs( functionString ); // bindingColumn.argumentsIterator( ) for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); ) { AggregationArgumentHandle arg = (AggregationArgumentHandle) iterator.next( ); String argName = DataAdapterUtil.adaptArgumentName( arg.getName( ) ); if ( paramsMap.containsKey( argName ) ) { if ( arg.getValue( ) != null ) { Control control = paramsMap.get( argName ); ExpressionButtonUtil.initExpressionButtonControl( control, arg, AggregationArgument.VALUE_MEMBER ); } } } } private String[] getFunctionDisplayNames( ) { IAggrFunction[] choices = getFunctions( ); if ( choices == null ) return new String[0]; String[] displayNames = new String[choices.length]; for ( int i = 0; i < choices.length; i++ ) { displayNames[i] = choices[i].getDisplayName( ); } return displayNames; } private IAggrFunction getFunctionByDisplayName( String displayName ) { IAggrFunction[] choices = getFunctions( ); if ( choices == null ) return null; for ( int i = 0; i < choices.length; i++ ) { if ( choices[i].getDisplayName( ).equals( displayName ) ) { return choices[i]; } } return null; } private String getFunctionDisplayName( String function ) { try { return DataUtil.getAggregationManager( ) .getAggregation( function ) .getDisplayName( ); } catch ( BirtException e ) { ExceptionUtil.handle( e ); return null; } } private IAggrFunction[] getFunctions( ) { try { List aggrInfoList = DataUtil.getAggregationManager( ) .getAggregations( AggregationManager.AGGR_XTAB ); return (IAggrFunction[]) aggrInfoList.toArray( new IAggrFunction[0] ); } catch ( BirtException e ) { ExceptionUtil.handle( e ); return new IAggrFunction[0]; } } private String getDataTypeDisplayName( String dataType ) { for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ ) { if ( dataType.equals( DATA_TYPE_CHOICES[i].getName( ) ) ) { return DATA_TYPE_CHOICES[i].getDisplayName( ); } } return ""; //$NON-NLS-1$ } private void initTextField( Text txtParam, IParameterDefn param ) { if ( paramsValueMap.containsKey( param.getName( ) ) ) { txtParam.setText( paramsValueMap.get( param.getName( ) ) ); return; } if ( binding != null ) { for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); ) { AggregationArgumentHandle arg = (AggregationArgumentHandle) iterator.next( ); if ( arg.getName( ).equals( param.getName( ) ) ) { if ( arg.getValue( ) != null ) txtParam.setText( arg.getValue( ) ); return; } } } } /** * fill the cmbDataField with binding holder's bindings * * @param param */ private void initDataFields( Combo cmbDataField, IParameterDefn param ) { List<String> datas = getMesures( ); datas.addAll( getDatas( ) ); String[] items = datas.toArray( new String[datas.size( )] ); cmbDataField.setItems( items ); if ( paramsValueMap.containsKey( param.getName( ) ) ) { cmbDataField.setText( paramsValueMap.get( param.getName( ) ) ); return; } if ( binding != null ) { for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); ) { AggregationArgumentHandle arg = (AggregationArgumentHandle) iterator.next( ); if ( arg.getName( ).equals( param.getName( ) ) ) { if ( arg.getValue( ) != null ) { for ( int i = 0; i < items.length; i++ ) { if ( items[i].equals( arg.getValue( ) ) ) { cmbDataField.select( i ); return; } } cmbDataField.setText( arg.getValue( ) ); return; } } } // backforward compatble if ( binding.getExpression( ) != null ) { for ( int i = 0; i < items.length; i++ ) { if ( items[i].equals( binding.getExpression( ) ) ) { cmbDataField.select( i ); } } } } } private List<String> getMesures( ) { List<String> measures = new ArrayList<String>( ); try { CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) getBindingHolder( ) ).getReportItem( ); measures.add( "" ); //$NON-NLS-1$ // for ( int i = 0; i < xtabHandle.getMeasureCount( ); i++ ) // MeasureViewHandle mv = xtabHandle.getMeasure( i ); // if ( mv instanceof ComputedMeasureViewHandle ) // continue; // measures.add( DEUtil.getExpression( mv.getCubeMeasure( ) ) ); CubeHandle cubeHandle = xtabHandle.getCube( ); List children = cubeHandle.getContents( CubeHandle.MEASURE_GROUPS_PROP ); for (int i=0; i<children.size( ); i++) { MeasureGroupHandle group = (MeasureGroupHandle)children.get( i ); List measreHandles = group.getContents( MeasureGroupHandle.MEASURES_PROP ); for (int j=0; j<measreHandles.size( ); j++) { MeasureHandle measure = (MeasureHandle)measreHandles.get( j ); String str = DEUtil.getExpression( measure ); if (!measures.contains( str )) { measures.add( str ); } } } } catch ( ExtendedElementException e ) { } return measures; } private List<String> getDatas( ) { List<String> datas = new ArrayList<String>( ); try { CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) getBindingHolder( ) ).getReportItem( ); try { IBinding[] aggregateBindings = CubeQueryUtil.getAggregationBindings( getCrosstabBindings( xtabHandle ) ); for ( IBinding binding : aggregateBindings ) { if ( getBinding( ) == null || !getBinding( ).getName( ) .equals( binding.getBindingName( ) ) ) datas.add( ExpressionUtil.createJSDataExpression( binding.getBindingName( ) ) ); } } catch ( AdapterException e ) { } catch ( BirtException e ) { } } catch ( ExtendedElementException e ) { } return datas; } private IBinding[] getCrosstabBindings( CrosstabReportItemHandle xtabHandle ) throws BirtException { Iterator bindingItr = ( (ExtendedItemHandle) xtabHandle.getModelHandle( ) ).columnBindingsIterator( ); ModuleHandle module = ( (ExtendedItemHandle) xtabHandle.getModelHandle( ) ).getModuleHandle( ); List<IBinding> bindingList = new ArrayList<IBinding>( ); if ( bindingItr != null ) { Map cache = new HashMap( ); List rowLevelNameList = new ArrayList( ); List columnLevelNameList = new ArrayList( ); DataRequestSession session = DataRequestSession.newSession( new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION ) ); try { IModelAdapter modelAdapter = session.getModelAdaptor( ); while ( bindingItr.hasNext( ) ) { ComputedColumnHandle column = (ComputedColumnHandle) bindingItr.next( ); // now user dte model adpater to transform the binding IBinding binding; try { binding = modelAdapter.adaptBinding( column, ExpressionLocation.CUBE ); } catch ( Exception e ) { continue; } if ( binding == null ) { continue; } // still need add aggregateOn field List aggrList = column.getAggregateOnList( ); if ( aggrList != null ) { for ( Iterator aggrItr = aggrList.iterator( ); aggrItr.hasNext( ); ) { String baseLevel = (String) aggrItr.next( ); CrosstabUtil.addHierachyAggregateOn( module, binding, baseLevel, rowLevelNameList, columnLevelNameList, cache ); } } bindingList.add( binding ); } } finally { session.shutdown( ); } } return bindingList.toArray( new IBinding[bindingList.size( )] ); } private void setDataFieldExpression( ComputedColumnHandle binding ) { if ( binding.getExpression( ) != null ) { if ( isAggregate( ) ) { IAggrFunction function = getFunctionByDisplayName( cmbFunction.getText( ) ); if ( function != null ) { IParameterDefn[] params = function.getParameterDefn( ); for ( final IParameterDefn param : params ) { if ( param.isDataField( ) ) { Control control = paramsMap.get( param.getName( ) ); if ( ExpressionButtonUtil.getExpressionButton( control ) != null ) { ExpressionButtonUtil.initExpressionButtonControl( control, binding, ComputedColumn.EXPRESSION_MEMBER ); } else { if ( control instanceof Combo ) { ( (Combo) control ).setText( binding.getExpression( ) ); } else if ( control instanceof CCombo ) { ( (CCombo) control ).setText( binding.getExpression( ) ); } else if ( control instanceof Text ) { ( (Text) control ).setText( binding.getExpression( ) ); } } } } } } else { if ( txtExpression != null && !txtExpression.isDisposed( ) ) { ExpressionButtonUtil.initExpressionButtonControl( txtExpression, binding, ComputedColumn.EXPRESSION_MEMBER ); } } } } private void setName( String name ) { if ( name != null && txtName != null ) txtName.setText( name ); } private void setDisplayName( String displayName ) { if ( displayName != null && txtDisplayName != null ) txtDisplayName.setText( displayName ); } private void setDisplayNameID( String displayNameID ) { if ( displayNameID != null && txtDisplayNameID != null ) txtDisplayNameID.setText( displayNameID ); } private void setTypeSelect( String typeSelect ) { if ( cmbType != null ) { if ( typeSelect != null ) cmbType.select( getItemIndex( cmbType.getItems( ), typeSelect ) ); else cmbType.select( 0 ); } } private int getItemIndex( String[] items, String item ) { for ( int i = 0; i < items.length; i++ ) { if ( items[i].equals( item ) ) return i; } return -1; } private void createAggregateSection( Composite composite ) { new Label( composite, SWT.NONE ).setText( FUNCTION ); cmbFunction = new Combo( composite, SWT.BORDER | SWT.READ_ONLY ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 3; cmbFunction.setLayoutData( gd ); cmbFunction.setVisibleItemCount( 30 ); // WidgetUtil.createGridPlaceholder( composite, 1, false ); cmbFunction.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { handleFunctionSelectEvent( ); modifyDialogContent( ); validate( ); } } ); paramsComposite = new Composite( composite, SWT.NONE ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = 4; gridData.exclude = true; paramsComposite.setLayoutData( gridData ); GridLayout layout = new GridLayout( ); // layout.horizontalSpacing = layout.verticalSpacing = 0; layout.marginWidth = layout.marginHeight = 0; layout.numColumns = 4; Layout parentLayout = paramsComposite.getParent( ).getLayout( ); if ( parentLayout instanceof GridLayout ) layout.horizontalSpacing = ( (GridLayout) parentLayout ).horizontalSpacing; paramsComposite.setLayout( layout ); new Label( composite, SWT.NONE ).setText( FILTER_CONDITION ); txtFilter = new Text( composite, SWT.BORDER ); gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = 2; txtFilter.setLayoutData( gridData ); txtFilter.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); } } ); //createExpressionButton( composite, txtFilter ); IExpressionProvider filterExpressionProvider = new CrosstabAggregationExpressionProvider( this.bindingHolder, this.binding ) { protected List getChildrenList( Object parent ) { List children = super.getChildrenList( parent ); List retValue = new ArrayList( ); retValue.addAll( children ); if (parent instanceof MeasureGroupHandle) { for (int i=0; i<children.size( ); i++) { Object obj = children.get( i ); if (obj instanceof MeasureHandle && ((MeasureHandle)obj).isCalculated( )) { retValue.remove( obj ); } } } return retValue; } }; ExpressionButtonUtil.createExpressionButton( composite, txtFilter, filterExpressionProvider, this.bindingHolder ); // if (!isTimePeriod( )) { Label lblAggOn = new Label( composite, SWT.NONE ); lblAggOn.setText( AGGREGATE_ON ); gridData = new GridData( ); gridData.verticalAlignment = GridData.BEGINNING; lblAggOn.setLayoutData( gridData ); cmbAggOn = new Combo( composite, SWT.BORDER | SWT.READ_ONLY ); gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = 3; cmbAggOn.setLayoutData( gridData ); cmbAggOn.setVisibleItemCount( 30 ); cmbAggOn.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { modifyDialogContent( ); } } ); } } private void createCommonSection( Composite composite ) { new Label( composite, SWT.NONE ).setText( EXPRESSION ); txtExpression = new Text( composite, SWT.BORDER ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 2; txtExpression.setLayoutData( gd ); createExpressionButton( composite, txtExpression ); txtExpression.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); } } ); } private void createMessageSection( Composite composite ) { messageLine = new CLabel( composite, SWT.LEFT ); GridData layoutData = new GridData( GridData.FILL_HORIZONTAL ); layoutData.horizontalSpan = 4; messageLine.setLayoutData( layoutData ); } protected void handleFunctionSelectEvent( ) { Control[] children = paramsComposite.getChildren( ); for ( int i = 0; i < children.length; i++ ) { children[i].dispose( ); } IAggrFunction function = getFunctionByDisplayName( cmbFunction.getText( ) ); if ( function != null ) { paramsMap.clear( ); IParameterDefn[] params = function.getParameterDefn( ); if ( params.length > 0 ) { ( (GridData) paramsComposite.getLayoutData( ) ).exclude = false; ( (GridData) paramsComposite.getLayoutData( ) ).heightHint = SWT.DEFAULT; int width = 0; if ( paramsComposite.getParent( ).getLayout( ) instanceof GridLayout ) { Control[] controls = paramsComposite.getParent( ) .getChildren( ); for ( int i = 0; i < controls.length; i++ ) { if ( controls[i] instanceof Label && ( (GridData) controls[i].getLayoutData( ) ).horizontalSpan == 1 ) { int labelWidth = controls[i].getBounds( ).width - controls[i].getBorderWidth( ) * 2; if ( labelWidth > width ) width = labelWidth; } } } for ( final IParameterDefn param : params ) { Label lblParam = new Label( paramsComposite, SWT.NONE ); lblParam.setText( param.getDisplayName( ) + ":" ); //$NON-NLS-1$ //if ( !param.isOptional( ) ) // lblParam.setText( "*" + lblParam.getText( ) ); GridData gd = new GridData( ); gd.widthHint = lblParam.computeSize( SWT.DEFAULT, SWT.DEFAULT ).x; if ( gd.widthHint < width ) gd.widthHint = width; lblParam.setLayoutData( gd ); if ( param.isDataField( ) ) { final Combo cmbDataField = new Combo( paramsComposite, SWT.BORDER ); cmbDataField.setLayoutData( GridDataFactory.fillDefaults( ) .grab( true, false ) .span( 3, 1 ) .create( ) ); cmbDataField.setVisibleItemCount( 30 ); initDataFields( cmbDataField, param ); cmbDataField.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); paramsValueMap.put( param.getName( ), cmbDataField.getText( ) ); } } ); paramsMap.put( param.getName( ), cmbDataField ); } else { final Text txtParam = new Text( paramsComposite, SWT.BORDER ); initTextField( txtParam, param ); txtParam.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { modifyDialogContent( ); validate( ); paramsValueMap.put( param.getName( ), txtParam.getText( ) ); } } ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalIndent = 0; gridData.horizontalSpan = 2; txtParam.setLayoutData( gridData ); createExpressionButton( paramsComposite, txtParam ); paramsMap.put( param.getName( ), txtParam ); } } } else { ( (GridData) paramsComposite.getLayoutData( ) ).heightHint = 0; // ( (GridData) paramsComposite.getLayoutData( ) ).exclude = // true; } // this.cmbDataField.setEnabled( function.needDataField( ) ); try { cmbType.setText( getDataTypeDisplayName( DataAdapterUtil.adapterToModelDataType( DataUtil.getAggregationManager( ) .getAggregation( function.getName( ) ) .getDataType( ) ) ) ); } catch ( BirtException e ) { ExceptionUtil.handle( e ); } } else { ( (GridData) paramsComposite.getLayoutData( ) ).heightHint = 0; ( (GridData) paramsComposite.getLayoutData( ) ).exclude = true; // new Label( argsComposite, SWT.NONE ).setText( "no args" ); } composite.layout( true, true ); setContentSize( composite ); } private void createExpressionButton( final Composite parent, final Control control ) { if ( expressionProvider == null ) { if ( isAggregate( ) ) expressionProvider = new CrosstabAggregationExpressionProvider( this.bindingHolder, this.binding ); else expressionProvider = new CrosstabBindingExpressionProvider( this.bindingHolder, this.binding ); } ExpressionButtonUtil.createExpressionButton( parent, control, expressionProvider, this.bindingHolder ); } public void validate( ) { if ( txtName != null && ( txtName.getText( ) == null || txtName.getText( ) .trim( ) .equals( "" ) ) ) //$NON-NLS-1$ { dialog.setCanFinish( false ); } else if ( txtExpression != null && ( txtExpression.getText( ) == null || txtExpression.getText( ) .trim( ) .equals( "" ) ) ) //$NON-NLS-1$ { dialog.setCanFinish( false ); } else { if ( this.binding == null )// create bindnig, we should check if // the binding name already exists. { for ( Iterator iterator = this.bindingHolder.getColumnBindings( ) .iterator( ); iterator.hasNext( ); ) { ComputedColumnHandle computedColumn = (ComputedColumnHandle) iterator.next( ); if ( computedColumn.getName( ).equals( txtName.getText( ) ) ) { dialog.setCanFinish( false ); this.messageLine.setText( Messages.getFormattedString( "BindingDialogHelper.error.nameduplicate", //$NON-NLS-1$ new Object[]{ txtName.getText( ) } ) ); this.messageLine.setImage( PlatformUI.getWorkbench( ) .getSharedImages( ) .getImage( ISharedImages.IMG_OBJS_ERROR_TSK ) ); return; } } } // bugzilla 273368 // if expression is "measure['...']", aggregation do not support // IAggrFunction.RUNNING_AGGR function if ( isAggregate( ) ) { IAggrFunction function = getFunctionByDisplayName( cmbFunction.getText( ) ); IParameterDefn[] params = function.getParameterDefn( ); if ( params.length > 0 ) { for ( final IParameterDefn param : params ) { if ( param.isDataField( ) ) { Combo cmbDataField = (Combo) paramsMap.get( param.getName( ) ); String expression = cmbDataField.getText( ); DataRequestSession session = null; try { session = DataRequestSession.newSession( new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION ) ); if ( session.getCubeQueryUtil( ) .getReferencedMeasureName( expression ) != null && function.getType( ) == IAggrFunction.RUNNING_AGGR ) { dialog.setCanFinish( false ); this.messageLine.setText( Messages.getFormattedString( "BindingDialogHelper.error.improperexpression", //$NON-NLS-1$ new Object[]{ function.getName( ) } ) ); this.messageLine.setImage( PlatformUI.getWorkbench( ) .getSharedImages( ) .getImage( ISharedImages.IMG_OBJS_ERROR_TSK ) ); return; } dialog.setCanFinish( true ); } catch ( Exception e ) { } finally { if ( session != null ) { session.shutdown( ); } } } } } } dialogCanFinish( ); this.messageLine.setText( "" ); //$NON-NLS-1$ this.messageLine.setImage( null ); if ( txtExpression != null && ( txtExpression.getText( ) == null || txtExpression.getText( ) .trim( ) .equals( "" ) ) ) //$NON-NLS-1$ { dialog.setCanFinish( false ); return; } if ( isAggregate( ) ) { try { IAggrFunction aggregation = DataUtil.getAggregationManager( ) .getAggregation( getFunctionByDisplayName( cmbFunction.getText( ) ).getName( ) ); if ( aggregation.getParameterDefn( ).length > 0 ) { IParameterDefn[] parameters = aggregation.getParameterDefn( ); for ( IParameterDefn param : parameters ) { if ( !param.isOptional( ) ) { String paramValue = getControlValue( paramsMap.get( param.getName( ) ) ); if ( paramValue == null || paramValue.trim( ).equals( "" ) ) //$NON-NLS-1$ { dialog.setCanFinish( false ); return; } } } } } catch ( BirtException e ) { // TODO show error message in message panel } } if ( isTimePeriod( ) ) { ITimeFunction timeFunction = getTimeFunctionByIndex( calculationType.getSelectionIndex( ) ); if (timeFunction != null) { List<IArgumentInfo> infos = timeFunction.getArguments( ); for ( int i = 0; i < infos.size( ); i++ ) { String paramValue = getControlValue( calculationParamsMap.get( infos.get( i ) .getName( ) ) ); if ( paramValue == null || paramValue.trim( ).equals( "" ) && !infos.get( i ).isOptional( ) ) //$NON-NLS-1$ { dialog.setCanFinish( false ); return; } } String dimensionName = getTimeDimsionName( ); if ( !isUseDimension( dimensionName ) && recentButton.getSelection( ) ) { this.messageLine.setText( Messages.getString( "CrosstabBindingDialogHelper.timeperiod.wrongdate" ) ); //$NON-NLS-1$ this.messageLine.setImage( PlatformUI.getWorkbench( ) .getSharedImages( ) .getImage( ISharedImages.IMG_OBJS_ERROR_TSK ) ); dialog.setCanFinish( false ); return; } if ( dateSelectionButton.getSelection( ) && ( dateText.getText( ) == null || dateText.getText( ) .trim( ) .equals( "" ) ) ) //$NON-NLS-1$ { dialog.setCanFinish( false ); return; } } } dialogCanFinish( ); } updateRemoveBtnState( ); } private void dialogCanFinish( ) { if ( !hasModified && isEditModal( ) ) dialog.setCanFinish( false ); else dialog.setCanFinish( true ); } public boolean differs( ComputedColumnHandle binding ) { if ( isAggregate( ) ) { if ( !strEquals( binding.getName( ), txtName.getText( ) ) ) return true; if ( !strEquals( binding.getDisplayName( ), txtDisplayName.getText( ) ) ) return true; if ( !strEquals( binding.getDisplayNameID( ), txtDisplayNameID.getText( ) ) ) return true; if ( !strEquals( binding.getDataType( ), getDataType( ) ) ) return true; try { if ( !strEquals( DataAdapterUtil.adaptModelAggregationType( binding.getAggregateFunction( ) ), getFunctionByDisplayName( cmbFunction.getText( ) ).getName( ) ) ) return true; } catch ( AdapterException e ) { } if ( !exprEquals( (Expression) binding.getExpressionProperty( ComputedColumn.FILTER_MEMBER ) .getValue( ), ExpressionButtonUtil.getExpression( txtFilter ) ) ) return true; if ( /* !isTimePeriod( ) && */!strEquals( cmbAggOn.getText( ), DEUtil.getAggregateOn( binding ) ) ) return true; IAggrFunction function = getFunctionByDisplayName( cmbFunction.getText( ) ); if ( function != null ) { IParameterDefn[] params = function.getParameterDefn( ); for ( final IParameterDefn param : params ) { if ( paramsMap.containsKey( param.getName( ) ) ) { Expression paramValue = ExpressionButtonUtil.getExpression( paramsMap.get( param.getName( ) ) ); for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); ) { AggregationArgumentHandle handle = (AggregationArgumentHandle) iterator.next( ); if ( param.getName( ).equals( handle.getName( ) ) && !exprEquals( (Expression) handle.getExpressionProperty( AggregationArgument.VALUE_MEMBER ) .getValue( ), paramValue ) ) { return true; } } if ( param.isDataField( ) && binding.getExpression( ) != null && !exprEquals( (Expression) binding.getExpressionProperty( ComputedColumn.EXPRESSION_MEMBER ) .getValue( ), paramValue ) ) { return true; } } } } } else { if ( !strEquals( txtName.getText( ), binding.getName( ) ) ) return true; if ( !strEquals( txtDisplayName.getText( ), binding.getDisplayName( ) ) ) return true; if ( !strEquals( txtDisplayNameID.getText( ), binding.getDisplayNameID( ) ) ) return true; if ( !strEquals( getDataType( ), binding.getDataType( ) ) ) return true; if ( !exprEquals( ExpressionButtonUtil.getExpression( txtExpression ), (Expression) binding.getExpressionProperty( ComputedColumn.EXPRESSION_MEMBER ) .getValue( ) ) ) return true; } return false; } private boolean exprEquals( Expression left, Expression right ) { if ( left == null && right == null ) { return true; } else if ( left == null && right != null ) { return right.getExpression( ) == null; } else if ( left != null && right == null ) { return left.getExpression( ) == null; } else if ( left.getStringExpression( ) == null && right.getStringExpression( ) == null ) return true; else if ( strEquals( left.getStringExpression( ), right.getStringExpression( ) ) && strEquals( left.getType( ), right.getType( ) ) ) return true; return false; } private String getControlValue( Control control ) { if ( control instanceof Text ) { return ( (Text) control ).getText( ); } else if ( control instanceof Combo ) { return ( (Combo) control ).getText( ); } return null; } private boolean strEquals( String left, String right ) { if ( left == right ) return true; if ( left == null ) return "".equals( right ); //$NON-NLS-1$ if ( right == null ) return "".equals( left ); //$NON-NLS-1$ return left.equals( right ); } private String getDataType( ) { for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ ) { if ( DATA_TYPE_CHOICES[i].getDisplayName( ) .equals( cmbType.getText( ) ) ) { return DATA_TYPE_CHOICES[i].getName( ); } } return ""; //$NON-NLS-1$ } public ComputedColumnHandle editBinding( ComputedColumnHandle binding ) throws SemanticException { if ( isAggregate( ) ) { binding.setDisplayName( txtDisplayName.getText( ) ); binding.setDisplayNameID( txtDisplayNameID.getText( ) ); for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ ) { if ( DATA_TYPE_CHOICES[i].getDisplayName( ) .equals( cmbType.getText( ) ) ) { binding.setDataType( DATA_TYPE_CHOICES[i].getName( ) ); break; } } binding.setAggregateFunction( getFunctionByDisplayName( cmbFunction.getText( ) ).getName( ) ); ExpressionButtonUtil.saveExpressionButtonControl( txtFilter, binding, ComputedColumn.FILTER_MEMBER ); binding.clearAggregateOnList( ); // if (!isTimePeriod( )) { String aggStr = cmbAggOn.getText( ); StringTokenizer token = new StringTokenizer( aggStr, "," ); //$NON-NLS-1$ while ( token.hasMoreTokens( ) ) { String agg = token.nextToken( ); if ( !agg.equals( ALL ) ) binding.addAggregateOn( agg ); } } // remove expression created in old version. binding.setExpression( null ); binding.clearArgumentList( ); for ( Iterator iterator = paramsMap.keySet( ).iterator( ); iterator.hasNext( ); ) { String arg = (String) iterator.next( ); String value = getControlValue( paramsMap.get( arg ) ); if ( value != null ) { AggregationArgument argHandle = StructureFactory.createAggregationArgument( ); argHandle.setName( arg ); if ( ExpressionButtonUtil.getExpressionButton( paramsMap.get( arg ) ) != null ) { ExpressionButtonUtil.saveExpressionButtonControl( paramsMap.get( arg ), argHandle, AggregationArgument.VALUE_MEMBER ); } else { Expression expression = new Expression( value, ExpressionType.JAVASCRIPT ); argHandle.setExpressionProperty( AggregationArgument.VALUE_MEMBER, expression ); } binding.addArgument( argHandle ); } } } else { for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ ) { if ( DATA_TYPE_CHOICES[i].getDisplayName( ) .equals( cmbType.getText( ) ) ) { binding.setDataType( DATA_TYPE_CHOICES[i].getName( ) ); break; } } binding.setDisplayName( txtDisplayName.getText( ) ); binding.setDisplayNameID( txtDisplayNameID.getText( ) ); if ( ExpressionButtonUtil.getExpressionButton( txtExpression ) != null ) { ExpressionButtonUtil.saveExpressionButtonControl( txtExpression, binding, ComputedColumn.EXPRESSION_MEMBER ); } else { Expression expression = new Expression( getControlValue( txtExpression ), ExpressionType.JAVASCRIPT ); binding.setExpressionProperty( AggregationArgument.VALUE_MEMBER, expression ); } } if ( isTimePeriod( ) ) { ITimeFunction timeFunction = getTimeFunctionByIndex( calculationType.getSelectionIndex( ) ); String dimensionName = timeDimension.getText( ); // Expression dimensionExpression = new Expression( dimensionName, // ExpressionType.JAVASCRIPT ); // binding.setExpressionProperty( // ComputedColumn.TIME_DIMENSION_MEMBER, // dimensionExpression ); binding.setTimeDimension( dimensionName ); binding.setCalculationType( timeFunction.getName( ) ); binding.setProperty( ComputedColumn.CALCULATION_ARGUMENTS_MEMBER, null ); // save the args for ( Iterator iterator = calculationParamsMap.keySet( ).iterator( ); iterator.hasNext( ); ) { CalculationArgument argument = StructureFactory.createCalculationArgument( ); String arg = (String) iterator.next( ); argument.setName( arg ); String value = getControlValue( calculationParamsMap.get( arg ) ); if ( value != null ) { if ( ExpressionButtonUtil.getExpressionButton( calculationParamsMap.get( arg ) ) != null ) { Expression expr = getExpressionByControl( calculationParamsMap.get( arg ) ); argument.setValue( expr ); } else { Expression expr = new Expression( value, ExpressionType.JAVASCRIPT ); argument.setValue( expr ); } binding.addCalculationArgument( argument ); } } // add refred day if ( todayButton.getSelection( ) ) { binding.setReferenceDateType( DesignChoiceConstants.REFERENCE_DATE_TYPE_TODAY ); } else if ( dateSelectionButton.getSelection( ) ) { binding.setReferenceDateType( DesignChoiceConstants.REFERENCE_DATE_TYPE_FIXED_DATE ); ExpressionButtonUtil.saveExpressionButtonControl( dateText, binding, ComputedColumn.REFERENCE_DATE_VALUE_MEMBER ); } else if ( recentButton.getSelection( ) ) { binding.setReferenceDateType( DesignChoiceConstants.REFERENCE_DATE_TYPE_ENDING_DATE_IN_DIMENSION ); } } return binding; } public static Expression getExpressionByControl( Control control ) throws SemanticException { ExpressionButton button = getExpressionButton( control ); if ( button != null && button.getExpressionHelper( ) != null ) { Expression expression = new Expression( button.getExpressionHelper( ) .getExpression( ), button.getExpressionHelper( ).getExpressionType( ) ); return expression; } return null; } public ComputedColumnHandle newBinding( ReportItemHandle bindingHolder, String name ) throws SemanticException { ComputedColumn column = StructureFactory.newComputedColumn( bindingHolder, name == null ? txtName.getText( ) : name ); ComputedColumnHandle binding = DEUtil.addColumn( bindingHolder, column, true ); return editBinding( binding ); } public void setContainer( Object container ) { this.container = container; } public boolean canProcessAggregation( ) { return true; } private URL[] getAvailableResourceUrls( ) { List<URL> urls = new ArrayList<URL>( ); String[] baseNames = getBaseNames( ); if ( baseNames == null ) return urls.toArray( new URL[0] ); else { for ( int i = 0; i < baseNames.length; i++ ) { URL url = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .findResource( baseNames[i], IResourceLocator.MESSAGE_FILE ); if ( url != null ) urls.add( url ); } return urls.toArray( new URL[0] ); } } private String[] getBaseNames( ) { List<String> resources = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .getIncludeResources( ); if ( resources == null ) return null; else return resources.toArray( new String[0] ); } private URL[] getResourceURLs( ) { String[] baseNames = getBaseNames( ); if ( baseNames == null ) return null; else { URL[] urls = new URL[baseNames.length]; for ( int i = 0; i < baseNames.length; i++ ) { urls[i] = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .findResource( baseNames[i], IResourceLocator.MESSAGE_FILE ); } return urls; } } private void updateRemoveBtnState( ) { btnRemoveDisplayNameID.setEnabled( txtDisplayNameID.getText( ) .equals( EMPTY_STRING ) ? false : true ); } private boolean isEditModal = false; public void setEditModal( boolean isEditModal ) { this.isEditModal = isEditModal; } public boolean isEditModal( ) { return isEditModal; } private void modifyDialogContent( ) { if ( hasInitDialog && isEditModal( ) && hasModified == false ) { hasModified = true; validate( ); } } private boolean hasModified = false; }
package com.bitdubai.sub_app.developer.fragment; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.bitdubai.fermat_api.layer.pip_actor.developer.ClassHierarchyLevels; import com.bitdubai.sub_app.developer.R; import com.bitdubai.fermat_api.layer.all_definition.enums.Addons; import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins; import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogLevel; import com.bitdubai.fermat_api.layer.pip_actor.developer.LogTool; import com.bitdubai.fermat_api.layer.pip_actor.developer.ToolManager; import com.bitdubai.sub_app.developer.common.Loggers; import com.bitdubai.sub_app.developer.common.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LogToolsFragment extends Fragment { private Map<String, List<ClassHierarchyLevels>> pluginClasses; //List<LoggerPluginClassHierarchy> loggerPluginClassHierarchy; private static final String ARG_POSITION = "position"; View rootView; private LogTool logTool; private static Platform platform = new Platform(); private List<Loggers> lstLoggers; private GridView gridView; public static LogToolsFragment newInstance(int position) { LogToolsFragment f = new LogToolsFragment(); Bundle b = new Bundle(); b.putInt(ARG_POSITION, position); f.setArguments(b); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { ToolManager toolManager = platform.getToolManager(); try { logTool = toolManager.getLogTool(); } catch (Exception e) { showMessage("CantGetToolManager - " + e.getMessage()); e.printStackTrace(); } } catch (Exception ex) { showMessage("Unexpected error get tool manager - " + ex.getMessage()); ex.printStackTrace(); } pluginClasses = new HashMap<String,List<ClassHierarchyLevels>>(); /** * I will load the list of classes that will be used in other fragments. */ } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; String selectedWord = ((TextView) info.targetView).getText().toString(); menu.setHeaderTitle(selectedWord); menu.add(LogLevel.NOT_LOGGING.toString()); menu.add(LogLevel.MINIMAL_LOGGING.toString()); menu.add(LogLevel.MODERATE_LOGGING.toString()); menu.add(LogLevel.AGGRESSIVE_LOGGING.toString()); } public boolean onContextItemSelected(MenuItem item) { /* AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); Object item = getListAdapter().getItem(info.position);*/ AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); String selectedWord = ((TextView) info.targetView).getText().toString(); if (item.getTitle() == LogLevel.NOT_LOGGING.toString()) { changeLogLevel(LogLevel.NOT_LOGGING, selectedWord); } else if (item.getTitle() == LogLevel.MINIMAL_LOGGING.toString()) { changeLogLevel(LogLevel.MINIMAL_LOGGING, selectedWord); } else if (item.getTitle() == LogLevel.MODERATE_LOGGING.toString()) { changeLogLevel(LogLevel.MODERATE_LOGGING, selectedWord); } else if (item.getTitle() == LogLevel.AGGRESSIVE_LOGGING.toString()) { changeLogLevel(LogLevel.AGGRESSIVE_LOGGING, selectedWord); } else { return false; } return true; } private void changeLogLevel(LogLevel logLevel, String resource) { try { //String name = resource.split(" - ")[0]; // String type = resource.split(" - ")[1]; // if (type.equals("Addon")) { // Addons addon = Addons.getByKey(name); // logTool.setLogLevel(addon, logLevel); // } else // por ahora no tengo como detectar si es un plug in o no.if (type.equals("Plugin")) Plugins plugin = Plugins.getByKey("Bitcoin Crypto Network"); //logTool.setLogLevel(plugin, logLevel); /** * Now I must look in pluginClasses map the match of the selected class to pass the full path */ HashMap<String, LogLevel> data = new HashMap<String, LogLevel>(); for (ClassHierarchyLevels c : pluginClasses.get(plugin.getKey())){ if (c.getLevel3().equals(resource)) data.put(c.getFullPath(), logLevel); if (c.getLevel2().equals(resource)) data.put(c.getFullPath(), logLevel); if (c.getLevel1().equals(resource)) data.put(c.getFullPath(), logLevel); } logTool.setNewLogLevelInClass(plugin, data); //TextView labelDatabase = (TextView) rootView.findViewById(R.id.labelLog); //labelDatabase.setVisibility(View.GONE); LogToolsFragment logToolsFragment = new LogToolsFragment(); FragmentTransaction FT = getFragmentManager().beginTransaction(); FT.replace(R.id.logContainer, logToolsFragment); FT.commit(); } catch (Exception e) { System.out.println("*********** soy un error " + e.getMessage()); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_log_tools, container, false); lstLoggers=new ArrayList<Loggers>(); try { // Get ListView object from xml gridView = (GridView) rootView.findViewById(R.id.gridView); List<Plugins> plugins = logTool.getAvailablePluginList(); List<Addons> addons = logTool.getAvailableAddonList(); List<String> list = new ArrayList<>(); for(Plugins plugin : plugins){ list.add(plugin.getKey()); //+" - Plugin || LogLevel: "+logTool.getLogLevel(plugin)); /** * I will get the list of the available classes on the plug in */ String level1=""; String level2=""; String toReplace = ""; List<ClassHierarchyLevels> newList = new ArrayList<ClassHierarchyLevels>(); //esto es sacar con getClassesHierarchy for (ClassHierarchyLevels classes : logTool.getClassesHierarchyPlugins(plugin)){ //loading de loggers class Loggers log = new Loggers(); log.level0=plugin.getKey(); log.level1=classes.getLevel1(); log.level2=classes.getLevel2(); log.level3=classes.getLevel3(); log.fullPath=classes.getFullPath(); log.type=Loggers.TYPE_PLUGIN; log.picture="plugin"; lstLoggers.add(log); /** * I insert the modified class in a new map with the plug in and the classes. */ //newList.add(classes); } } for(Addons addon : addons) { //list.add(plugin.getKey()); //+" - Plugin || LogLevel: "+logTool.getLogLevel(plugin)); /** * I will get the list of the available classes on the plug in */ String level1 = ""; String level2 = ""; String toReplace = ""; List<ClassHierarchyLevels> newList = new ArrayList<ClassHierarchyLevels>(); //esto es sacar con getClassesHierarchy for (ClassHierarchyLevels classes : logTool.getClassesHierarchyAddons(addon)) { //loading de loggers class Loggers log = new Loggers(); log.level0 = addon.getKey(); log.level1 = classes.getLevel1(); log.level2 = classes.getLevel2(); log.level3 = classes.getLevel3(); log.fullPath = classes.getFullPath(); log.type = Loggers.TYPE_ADDON; log.picture = "addon"; lstLoggers.add(log); /** * I insert the modified class in a new map with the plug in and the classes. */ //newList.add(classes); } /*for(Addons addon : addons){ list.add(addon.getKey() + " - Addon || LogLevel: " + logTool.getLogLevel(addon)); } String[] availableResources; if (list.size() > 0) { availableResources = new String[list.size()]; for(int i = 0; i < list.size() ; i++) { availableResources[i] = list.get(i); } } else { availableResources = new String[0]; }*/ //ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity().getApplicationContext(), // android.R.layout.simple_list_item_1, android.R.id.text1, availableResources); //listView.setAdapter(adapter); //registerForContextMenu(listView); Configuration config = getResources().getConfiguration(); if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { gridView.setNumColumns(6); } else { gridView.setNumColumns(3); } //@SuppressWarnings("unchecked") AppListAdapter _adpatrer = new AppListAdapter(getActivity(), R.layout.shell_wallet_desktop_front_grid_item, lstLoggers); _adpatrer.notifyDataSetChanged(); gridView.setAdapter(_adpatrer); }}catch (Exception e){ showMessage("LogTools Fragment onCreateView Exception - " + e.getMessage()); e.printStackTrace(); } /*} catch (Exception e) { showMessage("LogTools Fragment onCreateView Exception - " + e.getMessage()); e.printStackTrace(); }*/ return rootView; } //show alert private void showMessage(String text) { AlertDialog alertDialog = new AlertDialog.Builder(this.getActivity()).create(); alertDialog.setTitle("Warning"); alertDialog.setMessage(text); alertDialog.setButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); //alertDialog.setIcon(R.drawable.icon); alertDialog.show(); } public class AppListAdapter extends ArrayAdapter<Loggers> { public AppListAdapter(Context context, int textViewResourceId, List<Loggers> objects) { super(context, textViewResourceId, objects); } @Override public View getView(final int position, View convertView, ViewGroup parent) { final Loggers item = getItem(position); ViewHolder holder; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Service.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.shell_wallet_desktop_front_grid_item, parent, false); holder = new ViewHolder(); holder.imageView = (ImageView) convertView.findViewById(R.id.image_view); holder.imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getContext(),item.fullPath,Toast.LENGTH_SHORT); //Resource item=(Resource) gridView.getItemAtPosition(position); //DatabaseToolsDatabaseListFragment databaseToolsDatabaseListFragment = new DatabaseToolsDatabaseListFragment(); //databaseToolsDatabaseListFragment.setResource(item); //FragmentTransaction FT = getFragmentManager().beginTransaction(); //FT.add(databaseToolsDatabaseListFragment, TAG_DATABASE_TOOLS_FRAGMENT); //FT.replace(R.id.hola, databaseToolsDatabaseListFragment); //FT.commit(); } }); holder.companyTextView = (TextView) convertView.findViewById(R.id.company_text_view); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.companyTextView.setText(item.level0); // holder.companyTextView.setTypeface(MyApplication.getDefaultTypeface()); switch (item.picture) { case "plugin": holder.imageView.setImageResource(R.drawable.addon); holder.imageView.setTag("CPWWRWAKAV1M|1"); break; case "addon": holder.imageView.setImageResource(R.drawable.plugin); holder.imageView.setTag("CPWWRWAKAV1M|2"); break; default: holder.imageView.setImageResource(R.drawable.fermat); holder.imageView.setTag("CPWWRWAKAV1M|3"); break; } return convertView; } } /** * ViewHolder. */ private class ViewHolder { public ImageView imageView; public TextView companyTextView; } }
package org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.ovirt.engine.core.common.businessentities.DisplayType; import org.ovirt.engine.core.common.businessentities.GraphicsType; import org.ovirt.engine.core.common.businessentities.VmWatchdogType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel; import org.ovirt.engine.ui.uicommonweb.models.vms.UnitVmModel; import org.ovirt.engine.ui.uicommonweb.models.vms.VmModelBehaviorBase; import org.ovirt.engine.ui.uicompat.Event; import org.ovirt.engine.ui.uicompat.EventArgs; import org.ovirt.engine.ui.uicompat.IEventListener; public class NonClusterModelBehaviorBase extends VmModelBehaviorBase<UnitVmModel> { @Override public void initialize(SystemTreeItemModel systemTreeSelectedItem) { super.initialize(systemTreeSelectedItem); getModel().getIsVirtioScsiEnabled().setIsAvailable(true); getModel().getIsVirtioScsiEnabled().setEntity(false); getModel().getMemoryBalloonDeviceEnabled().setIsAvailable(true); getModel().updateWatchdogItems(new HashSet<VmWatchdogType>(Arrays.asList(VmWatchdogType.values()))); // no cluster data - init list to 'use cluster default' option getModel().getEmulatedMachine().setItems(Arrays.asList("")); //$NON-NLS-1$ getModel().getCustomCpu().setItems(Arrays.asList("")); //$NON-NLS-1$ } protected void initDisplayTypes(DisplayType selected, UnitVmModel.GraphicsTypes selectedGrahicsTypes) { getModel().getDisplayType().getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { enableSinglePCI(getModel().getDisplayType().getSelectedItem() == DisplayType.qxl); getModel().getDisplayType().getSelectedItem(); DisplayTypeChange(getModel().getDisplayType().getSelectedItem()); } private void DisplayTypeChange(DisplayType selectedItem ) { if(selectedItem.name().equals(DisplayType.cirrus.name())){ getModel().getGraphicsType().setItems( Arrays.asList(UnitVmModel.GraphicsTypes.VNC) ); }else if(selectedItem.name().equals(DisplayType.qxl.name()) || selectedItem.name().equals(DisplayType.vga.name())){ getModel().getGraphicsType().setItems( Arrays.asList( UnitVmModel.GraphicsTypes.SPICE, UnitVmModel.GraphicsTypes.VNC, UnitVmModel.GraphicsTypes.SPICE_AND_VNC ) ); } } }); List<Pair<GraphicsType, DisplayType>> allGraphicsAndDisplays = new ArrayList<Pair<GraphicsType, DisplayType>>(); for (GraphicsType graphicsType : GraphicsType.values()) { for (DisplayType displayType : DisplayType.values()) { allGraphicsAndDisplays.add(new Pair<GraphicsType, DisplayType>( graphicsType, displayType )); } } getModel().initDisplayModels(allGraphicsAndDisplays); initGraphicsModel(selectedGrahicsTypes); if (getModel().getDisplayType().getItems().contains(selected)) { getModel().getDisplayType().setSelectedItem(selected); } } private void initGraphicsModel(UnitVmModel.GraphicsTypes selectedGrahicsTypes) { List graphicsTypes = new ArrayList(); graphicsTypes.add(UnitVmModel.GraphicsTypes.VNC); getModel().getGraphicsType().setItems(graphicsTypes); } @Override protected Version getClusterCompatibilityVersion() { return latestCluster(); } @Override public void postDataCenterWithClusterSelectedItemChanged() { } @Override public void defaultHost_SelectedItemChanged() { } @Override public void provisioning_SelectedItemChanged() { } @Override public int getMaxNameLength() { return UnitVmModel.VM_TEMPLATE_AND_INSTANCE_TYPE_NAME_MAX_LIMIT; } }
package fr.phan.damapping.intellij.plugin.integration.provider; import fr.phan.damapping.annotation.Mapper; import fr.phan.damapping.intellij.plugin.integration.psiparsing.PsiParsingService; import fr.phan.damapping.intellij.plugin.integration.psiparsing.PsiParsingServiceImpl; import fr.phan.damapping.processor.model.DASourceClass; import fr.phan.damapping.processor.sourcegenerator.DefaultFileGeneratorContext; import fr.phan.damapping.processor.sourcegenerator.FileGeneratorContext; import fr.phan.damapping.processor.sourcegenerator.SourceGenerationService; import fr.phan.damapping.processor.sourcegenerator.SourceGenerationServiceImpl; import fr.phan.damapping.processor.sourcegenerator.SourceGenerator; import fr.phan.damapping.processor.sourcegenerator.SourceWriterDelegate; import fr.phan.damapping.processor.validator.DASourceClassValidator; import fr.phan.damapping.processor.validator.DASourceClassValidatorImpl; import fr.phan.damapping.processor.validator.ValidationError; import java.io.BufferedWriter; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Set; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.Lists; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.Project; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementFinder; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiImportList; import com.intellij.psi.PsiImportStatement; import com.intellij.psi.PsiJavaCodeReferenceElement; import com.intellij.psi.PsiJavaFile; import com.intellij.psi.PsiPackage; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.Processor; import org.codehaus.groovy.runtime.StringBufferWriter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class DAMappingElementFinder extends PsiElementFinder { private static final Logger LOGGER = Logger.getInstance(DAMappingAugmentProvider.class.getName()); private static final String MAPPER_INTERFACE_SUFFIX = "Mapper"; private static final int MAPPER_INTERFACE_SUFFIX_LENGTH = MAPPER_INTERFACE_SUFFIX.length(); private static final String MAPPER_FACTORY_INTERFACE_SUFFIX = "MapperFactory"; private static final int MAPPER_FACTORY_INTERFACE_SUFFIX_LENGTH = MAPPER_FACTORY_INTERFACE_SUFFIX.length(); private static final String MAPPER_ANNOTATION_TEXT = "@" + Mapper.class.getSimpleName(); private static final String MAPPER_QUALIFIED_ANNOTATION_TEXT = "@" + Mapper.class.getName(); private final PsiParsingService parsingService; private final DASourceClassValidator sourceClassValidator; private final SourceGenerationService sourceGenerationService; public DAMappingElementFinder() { this(new PsiParsingServiceImpl(), new DASourceClassValidatorImpl(), new SourceGenerationServiceImpl()); } public DAMappingElementFinder(PsiParsingService parsingService, DASourceClassValidator sourceClassValidator, SourceGenerationService sourceGenerationService) { this.parsingService = parsingService; this.sourceClassValidator = sourceClassValidator; this.sourceGenerationService = sourceGenerationService; LOGGER.debug("DAMappingElementFinder created"); } @Nullable @Override public PsiClass findClass(@NotNull String qualifiedName, final @NotNull GlobalSearchScope scope) { SearchedClassType searchedClassType = computeSearchedClassType(qualifiedName); if (searchedClassType == null) { LOGGER.debug(String.format("class %s is not a class generated by DAMapping", qualifiedName)); return null; } String mapperFile = extractMapperQualifiedName(qualifiedName, searchedClassType); PsiClass psiClass = retrieveSourceclass(mapperFile, scope); if (psiClass == null) { LOGGER.debug(String.format("Class %s not found", mapperFile)); return null; } if (!hasMapperAnnotation(psiClass)) { LOGGER.debug(String.format("Class %s is not annoted with @Mapper", mapperFile)); return null; } DASourceClass daSourceClass = parsingService.parse(psiClass); try { sourceClassValidator.validate(daSourceClass); } catch (ValidationError validationError) { LOGGER.error("Validation failed", validationError); return null; } try { PsiClassGeneratorDelegate delegate = new PsiClassGeneratorDelegate(scope.getProject(), psiClass); switch (searchedClassType) { case MAPPER_INTERFACE: sourceGenerationService.generateMapperInterface( new DefaultFileGeneratorContext(daSourceClass), delegate ); break; case MAPPER_FACTORY_INTERFACE: sourceGenerationService.generateMapperFactoryInterface( new DefaultFileGeneratorContext(daSourceClass), delegate ); break; } return delegate.getGeneratedPsiClass(); } catch (IOException e) { LOGGER.error("Failed to generate source files"); } return null; } private boolean hasMapperAnnotation(PsiClass psiClass) { if (psiClass.getModifierList() == null || psiClass.getModifierList().getAnnotations() == null) { return false; } // look for annotation @Mapper or @com.google.common.base.Function on class if (!FluentIterable.from(Arrays.asList(psiClass.getModifierList().getAnnotations())) .filter(new Predicate<PsiAnnotation>() { @Override public boolean apply(@javax.annotation.Nullable PsiAnnotation psiAnnotation) { return psiAnnotation != null && (MAPPER_ANNOTATION_TEXT.equals(psiAnnotation.getText()) || MAPPER_QUALIFIED_ANNOTATION_TEXT.equals(psiAnnotation.getText())); } } ).first().isPresent()) { return false; } // look for the import of Guava's Function for (PsiElement fileElement : psiClass.getParent().getChildren()) { if (fileElement instanceof PsiImportList) { for (PsiElement importListElement : fileElement.getChildren()) { if (importListElement instanceof PsiImportStatement) { for (PsiElement element : importListElement.getChildren()) { if (element instanceof PsiJavaCodeReferenceElement) { if (Function.class.getName().equals(element.getText())) { return true; } } } } } } } return false; // ((PsiJavaFile)psiPackage.getDirectories(scope)[0].getFiles()[0]).getClasses()[0].getModifierList() // .getAnnotations()[0].getText() = "@Mapper" // ((PsiJavaFile)psiPackage.getDirectories(scope)[0].getFiles()[0]).getClasses()[0].getParent().getChildren()[0] // .getChildren() : import list to filter on type PsiImportStatement // PsiImportStatement to filter on PsiImportStatement.getChildren() : type PsiJavaCodeReferenceElement // PsiJavaCodeReferenceElement to filter on getText() = Function.class.getName() } private String extractMapperQualifiedName(String qualifiedName, @NotNull SearchedClassType searchedClassType) { switch (searchedClassType) { case MAPPER_INTERFACE: return qualifiedName.substring(0, qualifiedName.length() - MAPPER_INTERFACE_SUFFIX_LENGTH); case MAPPER_FACTORY_INTERFACE: return qualifiedName.substring(0, qualifiedName.length() - MAPPER_FACTORY_INTERFACE_SUFFIX_LENGTH); default: throw new NullPointerException("SearchedClassType can not be null"); } } private SearchedClassType computeSearchedClassType(String qualifiedName) { if (qualifiedName.endsWith(MAPPER_INTERFACE_SUFFIX)) { return SearchedClassType.MAPPER_INTERFACE; } if (qualifiedName.endsWith(MAPPER_FACTORY_INTERFACE_SUFFIX)) { return SearchedClassType.MAPPER_FACTORY_INTERFACE; } return null; } private static enum SearchedClassType { MAPPER_INTERFACE, MAPPER_FACTORY_INTERFACE } private static class PsiClassGeneratorDelegate implements SourceWriterDelegate { private final Project project; private final PsiElement psiElement; private PsiClass generatedPsiClass; private PsiClassGeneratorDelegate(Project project, PsiElement psiElement) { this.project = project; this.psiElement = psiElement; } private PsiClass getGeneratedPsiClass() { return generatedPsiClass; } @Override public void generateFile(SourceGenerator sourceGenerator, FileGeneratorContext context) throws IOException { StringBuffer buffer = new StringBuffer(); sourceGenerator.writeFile(new BufferedWriter(new StringBufferWriter(buffer)), context); PsiJavaFile psiJavaFile = (PsiJavaFile) PsiFileFactory.getInstance(project) .createFileFromText(sourceGenerator.fileName(context), JavaFileType.INSTANCE, buffer.toString() ); this.generatedPsiClass = psiJavaFile.getClasses()[0]; // this.generatedPsiClass = JavaPsiFacade.getElementFactory(project) // .createClassFromText(buffer.toString(), // psiElement /*TODO verify what is this second argument*/ } } private PsiClass retrieveSourceclass(String mapperFile, GlobalSearchScope scope) { return JavaPsiFacade.getInstance(scope.getProject()).findClass(mapperFile, scope); } @NotNull @Override public PsiClass[] findClasses(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) { return new PsiClass[0]; // TODO call findClass and return array never containing null } @Nullable @Override public PsiPackage findPackage(@NotNull String qualifiedName) { return super.findPackage(qualifiedName); // use super method because we do not generate any new package } @NotNull @Override public PsiPackage[] getSubPackages(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { return super.getSubPackages(psiPackage, scope); // use super method because we do not generate any new package } @NotNull @Override public PsiClass[] getClasses(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { List<PsiClass> res = Lists.newArrayList(); for (PsiDirectory dir : psiPackage.getDirectories(scope)) { if (dir.getVirtualFile().getFileType() == FileTypes.ARCHIVE) { continue; } for (PsiFile psiFile : dir.getFiles()) { if (!(psiFile instanceof PsiJavaFile)) { continue; } PsiClass psiClass = ((PsiJavaFile) psiFile).getClasses()[0]; // assuming the first class if the public class if (!hasMapperAnnotation(psiClass)) { // class is not annoted, ignore it continue; } // TODO : should we filter out the Mapper and MapperFactory classes from existing source files ? DASourceClass daSourceClass = parsingService.parse(psiClass); try { sourceClassValidator.validate(daSourceClass); } catch (ValidationError validationError) { LOGGER.debug(String.format("Failed to validate class %s", psiClass.getQualifiedName()), validationError); continue; } try { DefaultFileGeneratorContext generatorContext = new DefaultFileGeneratorContext(daSourceClass); PsiClassGeneratorDelegate delegate = new PsiClassGeneratorDelegate(scope.getProject(), psiClass); sourceGenerationService.generateMapperInterface(generatorContext, delegate); PsiClass mapperPsiClass = delegate.getGeneratedPsiClass(); res.add(mapperPsiClass); if (sourceGenerationService.shouldGenerateMapperFactoryInterface(generatorContext)) { delegate = new PsiClassGeneratorDelegate(scope.getProject(), psiClass); sourceGenerationService.generateMapperFactoryInterface(generatorContext, delegate); res.add(delegate.getGeneratedPsiClass()); } } catch (IOException e) { LOGGER.error("Failed to generate source files"); } } } return res.toArray(new PsiClass[res.size()]); } @NotNull @Override public Set<String> getClassNames(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { return super.getClassNames(psiPackage, scope ); // super method uses getClasses(PsiPackage, GlobalSearchScope) in a way that suits us } @Override public boolean processPackageDirectories(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiDirectory> consumer) { return super.processPackageDirectories(psiPackage, scope, consumer ); // don't know what's that method for, use supermethod for now } @NotNull @Override public PsiClass[] getClasses(@Nullable String className, @NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { return super.getClasses(className, psiPackage, scope ); // super method uses getClasses(PsiPackage, GlobalSearchScope) in a way that suits us } }
package org.carlspring.strongbox.artifact.locator.handlers; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; import org.carlspring.strongbox.providers.io.RepositoryPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author mtodorov * @author stodorov */ public class ArtifactLocationReportOperation extends AbstractArtifactLocationHandler { private static final Logger logger = LoggerFactory.getLogger(ArtifactLocationReportOperation.class); private RepositoryPath previousPath; public ArtifactLocationReportOperation() { } public ArtifactLocationReportOperation(RepositoryPath basePath) { setBasePath(basePath); } public void execute(RepositoryPath path) throws IOException { List<Path> filePathList = Files.walk(path) .filter(p -> !p.getFileName().startsWith(".pom")) .sorted() .collect(Collectors.toList()); RepositoryPath parentPath = path.getParent().toAbsolutePath(); if (filePathList.isEmpty()) { return; } // Don't enter visited paths (i.e. version directories such as 1.2, 1.3, 1.4...) if (getVisitedRootPaths().containsKey(parentPath) && getVisitedRootPaths().get(parentPath).contains(path)) { return; } if (logger.isDebugEnabled()) { // We're using System.out.println() here for clarity and due to the length of the lines System.out.println(parentPath); } // The current directory is out of the tree if (previousPath != null && !parentPath.startsWith(previousPath)) { getVisitedRootPaths().remove(previousPath); previousPath = parentPath; } if (previousPath == null) { previousPath = parentPath; } List<RepositoryPath> versionDirectories = getVersionDirectories(parentPath); if (versionDirectories != null) { getVisitedRootPaths().put(parentPath, versionDirectories); System.out.println(path.getParent()); } } }
package org.eclipse.birt.report.designer.internal.ui.views.attributes.page; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.ColorPropertyDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.ComboPropertyDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.TextPropertyDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.UnitPropertyDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.ColorSection; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.ComboSection; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.SeperatorSection; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.TextSection; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.UnitSection; import org.eclipse.birt.report.model.api.MasterPageHandle; import org.eclipse.birt.report.model.api.SimpleMasterPageHandle; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; /** * The general attribute page of MasterPage element. */ public class MasterPageGeneralPage extends AttributePage { private UnitSection heightSection; private ComboPropertyDescriptorProvider typeProvider; private UnitSection widthSection; public void buildUI( Composite parent ) { super.buildUI( parent ); container.setLayout( WidgetUtil.createGridLayout( 6, 15 ) ); TextPropertyDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( MasterPageHandle.NAME_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setWidth( 200 ); nameSection.setGridPlaceholder( 4, true ); addSection( PageSectionId.MASTER_PAGE_NAME, nameSection ); SeperatorSection seperatorSection = new SeperatorSection( container, SWT.HORIZONTAL ); addSection( PageSectionId.MASTER_PAGE_SEPERATOR, seperatorSection ); UnitPropertyDescriptorProvider headHeightProvider = new UnitPropertyDescriptorProvider( SimpleMasterPageHandle.HEADER_HEIGHT_PROP, ReportDesignConstants.SIMPLE_MASTER_PAGE_ELEMENT ); UnitSection headHeightSection = new UnitSection( headHeightProvider.getDisplayName( ), container, true ); headHeightSection.setProvider( headHeightProvider ); headHeightSection.setWidth( 200 ); headHeightSection.setLayoutNum( 2 ); addSection( PageSectionId.MASTER_PAGE_HEAD_HEIGHT, headHeightSection ); ColorPropertyDescriptorProvider colorProvider = new ColorPropertyDescriptorProvider( StyleHandle.BACKGROUND_COLOR_PROP, ReportDesignConstants.STYLE_ELEMENT ); ColorSection colorSection = new ColorSection( colorProvider.getDisplayName( ), container, true ); colorSection.setProvider( colorProvider ); colorSection.setWidth( 200 ); colorSection.setLayoutNum( 4 ); colorSection.setGridPlaceholder( 2, true ); addSection( PageSectionId.MASTER_PAGE_COLOR, colorSection ); UnitPropertyDescriptorProvider footHeightProvider = new UnitPropertyDescriptorProvider( SimpleMasterPageHandle.FOOTER_HEIGHT_PROP, ReportDesignConstants.SIMPLE_MASTER_PAGE_ELEMENT ); UnitSection footHeightSection = new UnitSection( footHeightProvider.getDisplayName( ), container, true ); footHeightSection.setProvider( footHeightProvider ); footHeightSection.setWidth( 200 ); footHeightSection.setLayoutNum( 2 ); addSection( PageSectionId.MASTER_PAGE_FOOT_HEIGHT, footHeightSection ); ComboPropertyDescriptorProvider orientationProvider = new ComboPropertyDescriptorProvider( MasterPageHandle.ORIENTATION_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); ComboSection orientationSection = new ComboSection( orientationProvider.getDisplayName( ), container, true ); orientationSection.setProvider( orientationProvider ); orientationSection.setLayoutNum( 4 ); orientationSection.setGridPlaceholder( 2, true ); orientationSection.setWidth( 200 ); addSection( PageSectionId.MASTER_PAGE_ORIENTATION, orientationSection ); SeperatorSection seperatorSection1 = new SeperatorSection( container, SWT.HORIZONTAL ); addSection( PageSectionId.MASTER_PAGE_SEPERATOR_1, seperatorSection1 ); UnitPropertyDescriptorProvider widthProvider = new UnitPropertyDescriptorProvider( MasterPageHandle.WIDTH_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); widthSection = new UnitSection( widthProvider.getDisplayName( ), container, true ); widthSection.setProvider( widthProvider ); widthSection.setWidth( 200 ); widthSection.setLayoutNum( 2 ); addSection( PageSectionId.MASTER_PAGE_WIDTH, widthSection ); typeProvider = new ComboPropertyDescriptorProvider( MasterPageHandle.TYPE_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); ComboSection typeSection = new ComboSection( typeProvider.getDisplayName( ), container, true ); typeSection.setProvider( typeProvider ); typeSection.setGridPlaceholder( 2, true ); typeSection.setLayoutNum( 4 ); typeSection.setWidth( 200 ); addSection( PageSectionId.MASTER_PAGE_TYPE, typeSection ); UnitPropertyDescriptorProvider heightProvider = new UnitPropertyDescriptorProvider( MasterPageHandle.HEIGHT_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); heightSection = new UnitSection( heightProvider.getDisplayName( ), container, true ); heightSection.setProvider( heightProvider ); heightSection.setWidth( 200 ); heightSection.setGridPlaceholder( 4, true ); addSection( PageSectionId.MASTER_PAGE_HEIGHT, heightSection ); // WidgetUtil.buildGridControl( container, propertiesMap, // ReportDesignConstants.MASTER_PAGE_ELEMENT, // MasterPageHandle.NAME_PROP, 1, false ); // WidgetUtil.buildGridControl( container, propertiesMap, // ReportDesignConstants.STYLE_ELEMENT, // StyleHandle.BACKGROUND_COLOR_PROP, 1, false ); // WidgetUtil.createGridPlaceholder( container, 1, true ); /* * WidgetUtil.buildGridControl( container, propertiesMap, * ReportDesignConstants.MASTER_PAGE_ELEMENT, * MasterPageHandle.ORIENTATION_PROP, 1, false ); * * Label separator = new Label( container, SWT.SEPARATOR | * SWT.HORIZONTAL ); GridData data = new GridData( ); * data.horizontalSpan = 5; data.grabExcessHorizontalSpace = false; * data.horizontalAlignment = GridData.FILL; separator.setLayoutData( * data ); * * WidgetUtil.buildGridControl( container, propertiesMap, * ReportDesignConstants.MASTER_PAGE_ELEMENT, * MasterPageHandle.TYPE_PROP, 1, false ); pageSizeDescriptor = * (IPropertyDescriptor) propertiesMap.get( MasterPageHandle.TYPE_PROP ); * * WidgetUtil.createGridPlaceholder( container, 3, false ); * * widthPane = (Composite) WidgetUtil.buildGridControl( container, * propertiesMap, ReportDesignConstants.MASTER_PAGE_ELEMENT, * MasterPageHandle.WIDTH_PROP, 1, false ); * * heightPane = (Composite) WidgetUtil.buildGridControl( container, * propertiesMap, ReportDesignConstants.MASTER_PAGE_ELEMENT, * MasterPageHandle.HEIGHT_PROP, 1, false ); */ createSections( ); layoutSections( ); } public void refresh( ) { super.refresh( ); if ( typeProvider.load( ) .equals( DesignChoiceConstants.PAGE_SIZE_CUSTOM ) ) { widthSection.getUnitComboControl( ).setReadOnly( false ); heightSection.getUnitComboControl( ).setReadOnly( false ); } else { widthSection.getUnitComboControl( ).setReadOnly( true ); heightSection.getUnitComboControl( ).setReadOnly( true ); } } public void postElementEvent( ) { refresh( ); } }
package org.onlab.netty; import java.io.IOException; /** * Internal message representation with additional attributes * for supporting, synchronous request/reply behavior. */ public final class InternalMessage implements Message { public static final String REPLY_MESSAGE_TYPE = "NETTY_MESSAGIG_REQUEST_REPLY"; private long id; private Endpoint sender; private String type; private Object payload; private transient NettyMessagingService messagingService; // TODO: add transient payload serializer or change payload type to // byte[], ByteBuffer, etc. // Must be created using the Builder. private InternalMessage() {} public long id() { return id; } public String type() { return type; } public Endpoint sender() { return sender; } @Override public Object payload() { return payload; } protected void setMessagingService(NettyMessagingService messagingService) { this.messagingService = messagingService; } @Override public void respond(Object data) throws IOException { Builder builder = new Builder(messagingService); InternalMessage message = builder.withId(this.id) // FIXME: Sender should be messagingService.localEp. .withSender(this.sender) .withPayload(data) .withType(REPLY_MESSAGE_TYPE) .build(); messagingService.sendAsync(sender, message); } /** * Builder for InternalMessages. */ public static final class Builder { private InternalMessage message; public Builder(NettyMessagingService messagingService) { message = new InternalMessage(); message.messagingService = messagingService; } public Builder withId(long id) { message.id = id; return this; } public Builder withType(String type) { message.type = type; return this; } public Builder withSender(Endpoint sender) { message.sender = sender; return this; } public Builder withPayload(Object payload) { message.payload = payload; return this; } public InternalMessage build() { return message; } } }
package org.drools.planner.examples.nurserostering.persistence; import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import org.drools.planner.examples.common.business.SolutionBusiness; import org.drools.planner.examples.nurserostering.app.NurseRosteringApp; /** * @author Geoffrey De Smet */ public class NurseRosteringEvaluatorHelper { private static final String INPUT_FILE_PREFIX = "long01"; private static final String OUTPUT_FILE_SUFFIX = "_tmp"; private static final String DEFAULT_LINE_CONTAINS_FILTER = null; public static void main(String[] args) { String lineContainsFilter; if (args.length > 0) { lineContainsFilter = args[0]; } else { lineContainsFilter = DEFAULT_LINE_CONTAINS_FILTER; } NurseRosteringApp nurseRosteringApp = new NurseRosteringApp(); SolutionBusiness solutionBusiness = nurseRosteringApp.createSolutionBusiness(); Process process = null; try { File inputFile = new File(solutionBusiness.getImportDataDir(), INPUT_FILE_PREFIX + ".xml").getCanonicalFile(); File outputFile = new File(solutionBusiness.getExportDataDir(), INPUT_FILE_PREFIX + OUTPUT_FILE_SUFFIX + ".xml").getCanonicalFile(); File evaluatorDir = new File("local/competition/nurserostering/"); String command = "java -jar evaluator.jar " + inputFile.getAbsolutePath() + " " + outputFile.getAbsolutePath(); process = Runtime.getRuntime().exec(command, null, evaluatorDir); EvaluatorSummaryFilterOutputStream out = new EvaluatorSummaryFilterOutputStream(outputFile.getName(), lineContainsFilter); IOUtils.copy(process.getInputStream(), out); IOUtils.copy(process.getErrorStream(), System.err); out.writeResults(); } catch (IOException e) { throw new IllegalStateException(e); } finally { if (process != null) { process.destroy(); } } } private static class EvaluatorSummaryFilterOutputStream extends OutputStream { private String name; private String lineContainsFilter; private StringBuilder lineBuffer = new StringBuilder(120); private Map<String, int[]> excessMap = new LinkedHashMap<String, int[]>(); private String lastEmployeeCode = null; private EvaluatorSummaryFilterOutputStream(String name, String lineContainsFilter) { super(); this.name = name; this.lineContainsFilter = lineContainsFilter; } public void write(int c) throws IOException { if (c == '\n') { String line = lineBuffer.toString(); lineBuffer.delete(0, lineBuffer.length()); processLine(line); } else { lineBuffer.append((char) c); } } private void processLine(String line) { int employeeIndex = line.indexOf("Employee: "); if (employeeIndex >= 0) { lastEmployeeCode = line.substring(employeeIndex).replaceAll("Employee: (.+)", "$1"); } else if (line.contains("Penalty:")) { lastEmployeeCode = null; } if (lineContainsFilter == null || line.contains(lineContainsFilter)) { int excessIndex = line.indexOf("excess = "); if (excessIndex >= 0) { String key = line.substring(0, excessIndex); int value = Integer.parseInt(line.substring(excessIndex).replaceAll("excess = (\\d+) .*", "$1")); int[] excess = excessMap.get(key); if (excess == null) { excess = new int[]{0, value}; excessMap.put(key, excess); } else { excess[0]++; excess[1] += value; } } if (lastEmployeeCode != null) { System.out.print("E(" + lastEmployeeCode + ") "); } System.out.println(line); } } public void writeResults() { System.out.println("EvaluatorHelper results for " + name); if (lineContainsFilter != null) { System.out.println("with lineContainsFilter (" + lineContainsFilter + ")"); } for (Map.Entry<String, int[]> entry : excessMap.entrySet()) { int[] excess = entry.getValue(); System.out.println(entry.getKey() + " count = " + excess[0] + " total = " + excess[1]); } } } }
package com.thinkbiganalytics.ingest; import com.thinkbiganalytics.hive.util.HiveUtils; import com.thinkbiganalytics.util.ColumnSpec; import com.thinkbiganalytics.util.PartitionBatch; import com.thinkbiganalytics.util.PartitionSpec; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.List; import java.util.Vector; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Merge or Sync from a table into a target table. Dedupes and uses partition strategy of the target table. Sync will completely replace the target table with the contents from the source. Merge will * append the data into the target table adhering to partitions if defined. If Dedupe is specified then duplicates will be stripped. */ public class TableMergeSyncSupport implements Serializable { public static Logger logger = LoggerFactory.getLogger(TableMergeSyncSupport.class); protected Connection conn; public TableMergeSyncSupport(Connection conn) { Validate.notNull(conn); this.conn = conn; } public void enableDynamicPartitions() { doExecuteSQL("set hive.exec.dynamic.partition=true"); doExecuteSQL("set hive.exec.dynamic.partition.mode=nonstrict"); } /** * Performs a sync replacing all data in the target table. A temporary table is created with the new data, old table dropped and the temporary table renamed to become the new table. This causes a * very brief lapse for consumers between when the table is dropped and the rename. * * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param partitionSpec the partition specification * @param feedPartitionValue the source processing partition value */ public void doSync(@Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final PartitionSpec partitionSpec, @Nonnull final String feedPartitionValue) throws SQLException { Validate.notEmpty(sourceSchema); Validate.notEmpty(sourceTable); Validate.notEmpty(targetSchema); Validate.notEmpty(targetTable); Validate.notNull(partitionSpec); Validate.notNull(feedPartitionValue); // Extract the existing HDFS location of data String refTableLocation = extractTableLocation(targetSchema, targetTable); // 1. Create a temporary "sync" table for storing our latest snapshot String syncTableLocation = deriveSyncTableLocation(targetTable, refTableLocation); String syncTable = createSyncTable(targetSchema, targetTable, syncTableLocation); // 2. Populate the temporary "sync" table final String[] selectFields = getSelectFields(sourceSchema, sourceTable, targetSchema, syncTable, partitionSpec); final String syncSQL = partitionSpec.isNonPartitioned() ? generateSyncNonPartitionQuery(selectFields, sourceSchema, sourceTable, targetSchema, syncTable, feedPartitionValue) : generateSyncDynamicPartitionQuery(selectFields, partitionSpec, sourceSchema, sourceTable, targetSchema, syncTable, feedPartitionValue); doExecuteSQL(syncSQL); // 3. Drop the sync table. Since it is a managed table it will drop the old data dropTable(targetSchema, targetTable); // 4. Rename the sync table renameTable(targetSchema, syncTable, targetTable); } /** * Performs the doMerge and insert into the target table from the source table. * * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param partitionSpec the partition specification * @param feedPartitionValue the source processing partition value * @param shouldDedupe whether to perform dedupe during merge */ public List<PartitionBatch> doMerge(@Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final PartitionSpec partitionSpec, @Nonnull final String feedPartitionValue, final boolean shouldDedupe) { List<PartitionBatch> batches = null; Validate.notEmpty(sourceSchema); Validate.notEmpty(sourceTable); Validate.notEmpty(targetSchema); Validate.notEmpty(targetTable); Validate.notNull(partitionSpec); Validate.notNull(feedPartitionValue); final String[] selectFields = getSelectFields(sourceSchema, sourceTable, targetSchema, targetTable, partitionSpec); final String sql; if (partitionSpec.isNonPartitioned()) { if (shouldDedupe) { if (hasProcessingDttm(selectFields)) { sql = generateMergeNonPartitionQueryWithDedupe(selectFields, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue); } else { sql = generateMergeNonPartitionQueryWithDedupeNoProcessingDttm(selectFields, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue); } } else { sql = generateMergeNonPartitionQuery(selectFields, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue); } } else { if (shouldDedupe) { batches = createPartitionBatches(partitionSpec, sourceSchema, sourceTable, feedPartitionValue); // Newer tables with processing_dttm in target will always be unique so requires additional handling if (hasProcessingDttm(selectFields)) { sql = generateMergeWithDedupePartitionQuery(selectFields, partitionSpec, batches, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue); } else { sql = generateMergeWithDedupePartitionQueryNoProcessingDttm(selectFields, partitionSpec, batches, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue); } } else { sql = generateMergeWithPartitionQuery(selectFields, partitionSpec, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue); } } doExecuteSQL(sql); return batches; } private boolean hasProcessingDttm(String[] selectFields) { return Arrays.asList(selectFields).stream().anyMatch( v-> ("`processing_dttm`".equals(v))); } /** * Updates any rows matching the same primary key, otherwise inserts the value into the appropriate partition. * * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param partitionSpec the partition specification * @param feedPartitionValue the source processing partition value * @param columnSpecs the columns to join on */ public void doPKMerge(@Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final PartitionSpec partitionSpec, @Nonnull final String feedPartitionValue, @Nonnull final ColumnSpec[] columnSpecs) { Validate.notEmpty(sourceSchema); Validate.notEmpty(sourceTable); Validate.notEmpty(targetSchema); Validate.notEmpty(targetTable); Validate.notNull(partitionSpec); Validate.notNull(feedPartitionValue); Validate.notEmpty(columnSpecs); final String[] selectFields = getSelectFields(sourceSchema, sourceTable, targetSchema, targetTable, partitionSpec); final String sql = partitionSpec.isNonPartitioned() ? generatePKMergeNonPartitionQuery(selectFields, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue, columnSpecs) : generatePKMergePartitionQuery(selectFields, partitionSpec, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue, columnSpecs); doExecuteSQL(sql); } /** * Create a new table like the old table with the new location. * * @param schema the schema or database name for the reference table * @param table the name of the reference table * @param syncTableLocation the HDFS location for the reference table * @return the new table name */ private String createSyncTable(@Nonnull final String schema, @Nonnull final String table, @Nonnull final String syncTableLocation) throws SQLException { final String syncTable = table + "_" + System.currentTimeMillis(); final String createSQL = "create table " + HiveUtils.quoteIdentifier(schema, syncTable) + " like " + HiveUtils.quoteIdentifier(schema, table) + " location " + HiveUtils.quoteString(syncTableLocation); doExecuteSQL(createSQL); return syncTable; } /** * Drop table removing the data. * * @param schema the schema or database name containing the table * @param table the name of the table */ public void dropTable(@Nonnull final String schema, @Nonnull final String table) { // Make managed to remove the old data String makeManagedSQL = "alter table " + HiveUtils.quoteIdentifier(schema, table) + " SET TBLPROPERTIES ('EXTERNAL'='FALSE')"; doExecuteSQL(makeManagedSQL); String sql = "DROP TABLE " + HiveUtils.quoteIdentifier(schema, table); doExecuteSQL(sql); } /** * Renames the specified table. * * @param schema the schema or database name containing the tables * @param oldName the name of the table to be renamed * @param newName the new name for the table */ public void renameTable(@Nonnull final String schema, @Nonnull final String oldName, @Nonnull final String newName) { final String sql = "alter table " + HiveUtils.quoteIdentifier(schema, oldName) + " RENAME TO " + HiveUtils.quoteIdentifier(schema, newName); doExecuteSQL(sql); } /** * Create a new HDFS location for the target data * * @param table the name of the table * @param oldLocation the old location * @return the new HDFS location */ private String deriveSyncTableLocation(String table, String oldLocation) { String[] parts = oldLocation.split("/"); parts[parts.length - 1] = table + "_" + System.currentTimeMillis(); return StringUtils.join(parts, "/"); } /** * Extract the HDFS location of the table data. * * @param schema the schema or database name * @param table the table name * @return the HDFS location of the table data */ private String extractTableLocation(@Nonnull final String schema, @Nonnull final String table) throws SQLException { doExecuteSQL("use " + HiveUtils.quoteIdentifier(schema)); try (final Statement st = conn.createStatement()) { ResultSet rs = doSelectSQL(st, "show table extended like " + HiveUtils.quoteIdentifier(table)); while (rs.next()) { String value = rs.getString(1); if (value.startsWith("location:")) { return value.substring(9); } } } throw new RuntimeException("Unable to identify HDFS location property of table [" + table + "]"); } /** * Generates a sync query for inserting from a source table into the target table with no partitions. * * @param selectFields the list of fields in the select clause of the source table * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param feedPartitionValue the source processing partition value * @return the sql string */ protected String generateSyncNonPartitionQuery(@Nonnull final String[] selectFields, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue) { final String selectSQL = StringUtils.join(selectFields, ","); return "insert overwrite table " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " select " + selectSQL + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " where processing_dttm = " + HiveUtils.quoteString(feedPartitionValue); } /** * Generates a merge query for inserting overwriting from a source table into the target table appending to any partitions. * * @param selectFields the list of fields in the select clause of the source table * @param spec the partition specification * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param feedPartitionValue the source processing partition value * @return the sql string */ protected String generateMergeWithPartitionQuery(@Nonnull final String[] selectFields, @Nonnull final PartitionSpec spec, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue) { final String selectSQL = StringUtils.join(selectFields, ","); return "insert into table " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " " + spec.toDynamicPartitionSpec() + " select " + selectSQL + "," + spec.toDynamicSelectSQLSpec() + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " " + " where processing_dttm = " + HiveUtils.quoteString(feedPartitionValue); } /* Produces a where clause that limits to the impacted partitions of the target table */ private String targetPartitionsWhereClause(List<PartitionBatch> batches) { List<String> targetPartitionsItems = new Vector<>(); for (PartitionBatch batch : batches) { targetPartitionsItems.add("(" + batch.getPartitionSpec().toTargetSQLWhere(batch.getPartitionValues()) + ")"); } return (targetPartitionsItems.size() == 0 ? null : StringUtils.join(targetPartitionsItems.toArray(new String[0]), " or ")); } /** * Generates a merge query for inserting overwriting from a source table into the target table appending to any partitions * uses the batch identifier processing_dttm to determine whether a new record should be inserted so only new, distinct records will be * inserted. * * @param selectFields the list of fields in the select clause of the source table * @param spec the partition specification * @param batches the partitions of the source table * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param feedPartitionValue the source processing partition value * @return the sql string */ protected String generateMergeWithDedupePartitionQuery(@Nonnull final String[] selectFields, @Nonnull final PartitionSpec spec, @Nonnull final List<PartitionBatch> batches, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue) { // Strip processing_dttm for the distinct since it will always be different String[] distinctSelectFields = Arrays.asList(selectFields).stream().filter( v-> !("`processing_dttm`".equals(v))).collect(Collectors.toList()).toArray(new String[0]); final String selectAggregateSQL = StringUtils.join(distinctSelectFields, ",")+", min(processing_dttm) processing_dttm, "+spec.toPartitionSelectSQL(); final String groupBySQL = StringUtils.join(distinctSelectFields, ",")+","+spec.toPartitionSelectSQL(); final String selectSQL = StringUtils.join(selectFields, ","); final String targetPartitionWhereClause = targetPartitionsWhereClause(batches); final StringBuilder sb = new StringBuilder(); sb.append("insert into table ").append(HiveUtils.quoteIdentifier(targetSchema, targetTable)).append(" ") .append(spec.toDynamicPartitionSpec()) .append("select ").append(selectAggregateSQL).append(" from (") .append(" select ").append(selectSQL).append(",").append(spec.toDynamicSelectSQLSpec()) .append(" from ").append(HiveUtils.quoteIdentifier(sourceSchema, sourceTable)).append(" ") .append(" where ") .append(" processing_dttm = ").append(HiveUtils.quoteString(feedPartitionValue)) .append(" union all ") .append(" select ").append(selectSQL).append(",").append(spec.toPartitionSelectSQL()) .append(" from ").append(HiveUtils.quoteIdentifier(targetSchema, targetTable)).append(" "); if (targetPartitionWhereClause != null) { sb.append(" where (").append(targetPartitionWhereClause).append(")"); } sb.append(") t group by "+groupBySQL).append(" having min(processing_dttm) = ").append(HiveUtils.quoteString(feedPartitionValue)); return sb.toString(); } /** * Generates a merge query for inserting overwriting from a source table into the target table appending to any partitions * * @param selectFields the list of fields in the select clause of the source table * @param spec the partition specification * @param batches the partitions of the source table * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param feedPartitionValue the source processing partition value * @return the sql string */ protected String generateMergeWithDedupePartitionQueryNoProcessingDttm(@Nonnull final String[] selectFields, @Nonnull final PartitionSpec spec, @Nonnull final List<PartitionBatch> batches, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue) { final String selectSQL = StringUtils.join(selectFields, ","); final String targetPartitionWhereClause = targetPartitionsWhereClause(batches); final StringBuilder sb = new StringBuilder(); sb.append("insert overwrite table ").append(HiveUtils.quoteIdentifier(targetSchema, targetTable)).append(" ") .append(spec.toDynamicPartitionSpec()) .append("select DISTINCT ").append(selectSQL).append(",").append(spec.toPartitionSelectSQL()).append(" from (") .append(" select ").append(selectSQL).append(",").append(spec.toDynamicSelectSQLSpec()) .append(" from ").append(HiveUtils.quoteIdentifier(sourceSchema, sourceTable)).append(" ") .append(" where ") .append(" processing_dttm = ").append(HiveUtils.quoteString(feedPartitionValue)) .append(" union all ") .append(" select ").append(selectSQL).append(",").append(spec.toPartitionSelectSQL()) .append(" from ").append(HiveUtils.quoteIdentifier(targetSchema, targetTable)).append(" "); if (targetPartitionWhereClause != null) { sb.append(" where (").append(targetPartitionWhereClause).append(")"); } sb.append(") t"); return sb.toString(); } /** * Generates a dynamic partition sync query for inserting overwriting from a source table into the target table adhering to partitions. * * @param selectFields the list of fields in the select clause of the source table * @param spec the partition specification or null if none * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param feedPartitionValue the source processing partition value * @return the sql string */ protected String generateSyncDynamicPartitionQuery(@Nonnull final String[] selectFields, @Nonnull final PartitionSpec spec, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue) { final String selectSQL = StringUtils.join(selectFields, ","); return "insert overwrite table " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " " + spec.toDynamicPartitionSpec() + " select " + selectSQL + "," + spec.toDynamicSelectSQLSpec() + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " where processing_dttm = " + HiveUtils.quoteString(feedPartitionValue); } /** * Generates a query for merging from a source table into the target table with no partitions. * * @param selectFields the list of fields in the select clause of the source table * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param feedPartitionValue the source processing partition value * @return the sql string */ protected String generateMergeNonPartitionQueryWithDedupe(@Nonnull final String[] selectFields, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue) { String[] distinctSelectFields = Arrays.asList(selectFields).stream().filter( v-> !("`processing_dttm`".equals(v))).collect(Collectors.toList()).toArray(new String[0]); final String selectAggregateSQL = StringUtils.join(distinctSelectFields, ",")+", min(processing_dttm) processing_dttm"; final String selectSQL = StringUtils.join(selectFields, ","); final String groupBySQL = StringUtils.join(distinctSelectFields, ","); return "insert into table " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " " + "select " + selectAggregateSQL + " from (" + " select " + selectSQL + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " where processing_dttm = " + HiveUtils.quoteString(feedPartitionValue) + " " + " union all " + " select " + selectSQL + " from " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + ") x group by " + groupBySQL + " having min(processing_dttm) = " + HiveUtils.quoteString(feedPartitionValue); } /** * Generates a query for merging from a source table into the target table with no partitions. * * @param selectFields the list of fields in the select clause of the source table * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param feedPartitionValue the source processing partition value * @return the sql string */ protected String generateMergeNonPartitionQueryWithDedupeNoProcessingDttm(@Nonnull final String[] selectFields, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue) { final String selectSQL = StringUtils.join(selectFields, ","); return "insert overwrite table " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " " + "select " + selectSQL + " from (" + " select " + selectSQL + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " where processing_dttm = " + HiveUtils.quoteString(feedPartitionValue) + " " + " union all " + " select " + selectSQL + " from " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + ") x group by " + selectSQL; } /** * Generates a query for merging from a source table into the target table with no partitions. * * @param selectFields the list of fields in the select clause of the source table * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param targetSchema the schema or database name of the target table * @param targetTable the target table name * @param feedPartitionValue the source processing partition value * @return the sql string */ protected String generateMergeNonPartitionQuery(@Nonnull final String[] selectFields, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue) { final String selectSQL = StringUtils.join(selectFields, ","); return "insert into " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " " + " select " + selectSQL + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " where processing_dttm = " + HiveUtils.quoteString(feedPartitionValue); } /** * Generates a query two merge two tables without partitions on a primary key. * * @param selectFields the list of fields in the select clause of the source table * @param sourceSchema the name of the source table schema or database * @param sourceTable the source table * @param targetSchema the name of the target table schema or database * @param targetTable the target table * @param feedPartitionValue the partition of the source table to use * @param columnSpecs the column specifications * @return the sql */ protected String generatePKMergeNonPartitionQuery(@Nonnull final String[] selectFields, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue, @Nonnull final ColumnSpec[] columnSpecs) { // Include alias String selectSQL = StringUtils.join(selectFields, ","); String[] selectFieldsWithAlias = selectFieldsForAlias(selectFields, "a"); String selectSQLWithAlias = StringUtils.join(selectFieldsWithAlias, ","); String joinOnClause = ColumnSpec.toPrimaryKeyJoinSQL(columnSpecs, "a", "b"); String[] primaryKeys = ColumnSpec.toPrimaryKeys(columnSpecs); String anyPK = primaryKeys[0]; String sbSourceQuery = "select " + selectSQL + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " where processing_dttm= " + HiveUtils.quoteString(feedPartitionValue); // First finds all records in valid // Second finds all records in target that should be preserved for impacted partitions return "insert overwrite table " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " " + "select " + selectSQL + " from (" + " select " + selectSQL + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " a" + " where " + " a.processing_dttm = " + HiveUtils.quoteString(feedPartitionValue) + " union " + " select " + selectSQLWithAlias + " from " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " a left outer join (" + sbSourceQuery + ") b " + " on (" + joinOnClause + ")" + " where " + " (b." + anyPK + " is null)) t"; } /** * Generates a query two merge two tables containing partitions on a primary key. * * @param selectFields the list of fields in the select clause of the source table * @param partitionSpec partition specification * @param sourceSchema the name of the source table schema or database * @param sourceTable the source table * @param targetSchema the name of the target table schema or database * @param targetTable the target table * @param feedPartitionValue the partition of the source table to use * @param columnSpecs the column specifications * @return the sql */ protected String generatePKMergePartitionQuery(@Nonnull final String[] selectFields, @Nonnull final PartitionSpec partitionSpec, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue, @Nonnull final ColumnSpec[] columnSpecs) { // Include alias String selectSQL = StringUtils.join(selectFields, ","); String[] selectFieldsWithAlias = selectFieldsForAlias(selectFields, "a"); String selectSQLWithAlias = StringUtils.join(selectFieldsWithAlias, ","); String joinOnClause = ColumnSpec.toPrimaryKeyJoinSQL(columnSpecs, "a", "b"); String[] primaryKeys = ColumnSpec.toPrimaryKeys(columnSpecs); PartitionSpec partitionSpecWithAlias = partitionSpec.newForAlias("a"); String anyPK = primaryKeys[0]; List<PartitionBatch> batches = createPartitionBatchesforPKMerge(partitionSpec, sourceSchema, sourceTable, targetSchema, targetTable, feedPartitionValue, joinOnClause); String targetPartitionWhereClause = targetPartitionsWhereClause(PartitionBatch.toPartitionBatchesForAlias(batches, "a")); // TODO: If the records matching the primary key between the source and target are in a different partition // AND the matching records are the only remaining records of the partition, then the following sql will fail to overwrite the // remaining record. We need to detect this and then delete partition? This is a complex scenario.. String sbSourceQuery = "select " + selectSQL + "," + partitionSpec.toDynamicSelectSQLSpec() + " from " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " where processing_dttm = " + HiveUtils.quoteString(feedPartitionValue); // First finds all records in valid // Second finds all records in target that should be preserved for impacted partitions StringBuilder sb = new StringBuilder(); sb.append("insert overwrite table ").append(HiveUtils.quoteIdentifier(targetSchema, targetTable)).append(" ") .append(partitionSpec.toDynamicPartitionSpec()) .append("select ").append(selectSQL).append(",").append(partitionSpec.toPartitionSelectSQL()).append(" from (") .append(" select ").append(selectSQLWithAlias).append(",").append(partitionSpecWithAlias.toDynamicSelectSQLSpec()) .append(" from ").append(HiveUtils.quoteIdentifier(sourceSchema, sourceTable)).append(" a") .append(" where ") .append(" a.processing_dttm = ").append(HiveUtils.quoteString(feedPartitionValue)) .append(" union all ") .append(" select ").append(selectSQLWithAlias).append(",").append(partitionSpecWithAlias.toDynamicSelectSQLSpec()) .append(" from ").append(HiveUtils.quoteIdentifier(targetSchema, targetTable)).append(" a left outer join (").append(sbSourceQuery).append(") b ") .append(" on (").append(joinOnClause).append(")") .append(" where ") .append(" (b.").append(anyPK).append(" is null)"); if (targetPartitionWhereClause != null) { sb.append(" and (").append(targetPartitionWhereClause).append(")"); } sb.append(") t"); return sb.toString(); } /** * Finds all partitions that contain matching keys. * * @param spec the partition spec * @param sourceSchema the name of the source table schema or database * @param sourceTable the source table * @param targetSchema the name of the target table schema or database * @param targetTable the target table * @param feedPartitionValue the partition of the source table to use * @param joinOnClause the JOIN clause for the source and target tables * @return the matching partitions */ protected List<PartitionBatch> createPartitionBatchesforPKMerge(@Nonnull final PartitionSpec spec, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nonnull final String feedPartitionValue, @Nonnull final String joinOnClause) { List<PartitionBatch> v; PartitionSpec aliasSpecA = spec.newForAlias("a"); // Find all partitions that contain matching keys String sql = "select " + aliasSpecA.toPartitionSelectSQL() + ", count(0)" + " from " + HiveUtils.quoteIdentifier(targetSchema, targetTable) + " a join " + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " b" + " on " + joinOnClause + " where b.processing_dttm = '" + feedPartitionValue + "'" + " group by " + aliasSpecA.toPartitionSelectSQL(); try (final Statement st = conn.createStatement()) { logger.info("Selecting target partitions query [" + sql + "]"); ResultSet rs = doSelectSQL(st, sql); v = toPartitionBatches(spec, rs); } catch (SQLException e) { logger.error("Failed to select partition batches SQL {} with error {}", sql, e); throw new RuntimeException("Failed to select partition batches", e); } return v; } protected void doExecuteSQL(String sql) { try (final Statement st = conn.createStatement()) { logger.info("Executing doMerge batch sql {}", sql); st.execute(sql); } catch (SQLException e) { logger.error("Failed to execute {} with error {}", sql, e); throw new RuntimeException("Failed to execute query", e); } } protected ResultSet doSelectSQL(Statement st, String sql) throws SQLException { logger.info("Executing sql select {}", sql); return st.executeQuery(sql); } /* Generates batches of partitions in the source table */ protected List<PartitionBatch> toPartitionBatches(PartitionSpec spec, ResultSet rs) throws SQLException { Vector<PartitionBatch> v = new Vector<>(); int count = rs.getMetaData().getColumnCount(); while (rs.next()) { String[] values = new String[count]; for (int i = 1; i <= count; i++) { Object oVal = rs.getObject(i); String sVal = (oVal == null ? "" : oVal.toString()); values[i - 1] = StringUtils.defaultString(sVal, ""); } Long numRecords = rs.getLong(count); v.add(new PartitionBatch(numRecords, spec, values)); } logger.info("Number of partitions [" + v.size() + "]"); return v; } /** * Generates batches of partitions in the source table. * * @param spec the partition specification * @param sourceSchema the schema or database name of the source table * @param sourceTable the source table name * @param feedPartition the source processing partition value */ protected List<PartitionBatch> createPartitionBatches(@Nonnull final PartitionSpec spec, @Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String feedPartition) { List<PartitionBatch> v; String sql = ""; try (final Statement st = conn.createStatement()) { sql = spec.toDistinctSelectSQL(sourceSchema, sourceTable, feedPartition); logger.info("Executing batch query [" + sql + "]"); ResultSet rs = doSelectSQL(st, sql); v = toPartitionBatches(spec, rs); } catch (SQLException e) { logger.error("Failed to select partition batches SQL {} with error {}", sql, e); throw new RuntimeException("Failed to select partition batches", e); } return v; } /** * Returns the list of columns that are common to both the source and target tables. * * <p>The column names are quoted and escaped for use in a SQL query.</p> * * @param sourceSchema the name of the source table schema or database * @param sourceTable the name of the source table * @param targetSchema the name of the target table schema or database * @param targetTable the name of the target table * @param partitionSpec the partition specifications, or {@code null} if none * @return the columns for a SELECT statement */ protected String[] getSelectFields(@Nonnull final String sourceSchema, @Nonnull final String sourceTable, @Nonnull final String targetSchema, @Nonnull final String targetTable, @Nullable final PartitionSpec partitionSpec) { List<String> srcFields = resolveTableSchema(sourceSchema, sourceTable); List<String> destFields = resolveTableSchema(targetSchema, targetTable); // Find common fields destFields.retainAll(srcFields); // Eliminate any partition columns if (partitionSpec != null) { destFields.removeAll(partitionSpec.getKeyNames()); } String[] fields = destFields.toArray(new String[0]); for (int i = 0; i < fields.length; i++) { fields[i] = HiveUtils.quoteIdentifier(fields[i]); } return fields; } private String[] selectFieldsForAlias(String[] selectFields, String alias) { return Arrays.stream(selectFields).map(s -> alias + "." + s).toArray(String[]::new); } /** * Retrieves the schema of the specified table. * * @param schema the database name * @param table the table name * @return the list of columns */ protected List<String> resolveTableSchema(@Nonnull final String schema, @Nonnull final String table) { List<String> columnSet = new Vector<>(); try (final Statement st = conn.createStatement()) { // Use default database to resolve ambiguity between schema.table and table.column st.execute("use default"); String ddl = "desc " + HiveUtils.quoteIdentifier(schema, table); logger.info("Resolving table schema [{}]", ddl); ResultSet rs = doSelectSQL(st, ddl); while (rs.next()) { // First blank row is start of partition info if (StringUtils.isEmpty(rs.getString(1))) { break; } columnSet.add(rs.getString(1)); } } catch (SQLException e) { throw new RuntimeException("Failed to inspect schema", e); } return columnSet; } }
package org.safehaus.subutai.core.dispatcher.rest; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import javax.ws.rs.core.Response; import org.eclipse.jetty.server.Request; import org.safehaus.subutai.common.protocol.BatchRequest; import org.safehaus.subutai.common.util.JsonUtil; import org.safehaus.subutai.core.dispatcher.api.CommandDispatcher; import org.apache.cxf.message.Message; import org.apache.cxf.phase.PhaseInterceptorChain; import org.apache.cxf.transport.http.AbstractHTTPDestination; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class RestServiceImpl implements RestService { private static final Logger LOG = Logger.getLogger( RestServiceImpl.class.getName() ); private final CommandDispatcher dispatcher; private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); public RestServiceImpl( final CommandDispatcher dispatcher ) { this.dispatcher = dispatcher; } @Override public Response processResponses( final String responses ) { try { Set<org.safehaus.subutai.common.protocol.Response> resps = gson.fromJson( responses, new TypeToken<LinkedHashSet<org.safehaus.subutai.common.protocol.Response>>() {}.getType() ); dispatcher.processResponses( resps ); return Response.ok().build(); } catch ( RuntimeException e ) { return Response.serverError().entity( e.getMessage() ).build(); } } @Override public Response executeRequests( final String ownerId, final String requests ) { try { Message message = PhaseInterceptorChain.getCurrentMessage(); Request request = ( Request ) message.get( AbstractHTTPDestination.HTTP_REQUEST ); // String ip = request.getRemoteAddr(); //for now set IP to local subutai //TODO remove this in production String ip = getLocalIp(); UUID ownrId = JsonUtil.fromJson( ownerId, UUID.class ); Set<BatchRequest> reqs = gson.fromJson( requests, new TypeToken<Set<BatchRequest>>() {}.getType() ); dispatcher.executeRequests( ip, ownrId, reqs ); return Response.ok().build(); } catch ( RuntimeException e ) { return Response.serverError().entity( e.getMessage() ).build(); } } private String getLocalIp() { Enumeration<NetworkInterface> n = null; try { n = NetworkInterface.getNetworkInterfaces(); for (; n.hasMoreElements(); ) { NetworkInterface e = n.nextElement(); Enumeration<InetAddress> a = e.getInetAddresses(); for (; a.hasMoreElements(); ) { InetAddress addr = a.nextElement(); if ( addr.getHostAddress().startsWith( "172" ) ) { return addr.getHostAddress(); } } } } catch ( SocketException e ) { } return "172.16.192.64"; } }
package org.safehaus.subutai.core.container.impl.container; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import org.safehaus.subutai.common.command.Command; import org.safehaus.subutai.common.command.RequestBuilder; import org.safehaus.subutai.core.container.api.container.ContainerManager; import org.safehaus.subutai.core.container.api.lxcmanager.*; import org.safehaus.subutai.core.registry.api.Template; import org.safehaus.subutai.core.container.impl.strategy.PlacementStrategyFactory; import org.safehaus.subutai.common.protocol.Agent; import org.safehaus.subutai.common.protocol.PlacementStrategy; import org.safehaus.subutai.common.settings.Common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ContainerManagerImpl extends ContainerManagerBase { private static final Logger logger = LoggerFactory.getLogger(ContainerManager.class); private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); // number sequences for template names used for new clone name generation private ConcurrentMap<String, AtomicInteger> sequences; private ExecutorService executor; public void init() { sequences = new ConcurrentHashMap<>(); executor = Executors.newCachedThreadPool(); } public void destroy() { sequences.clear(); } @Override public Set<Agent> clone(UUID envId, String templateName, int nodesCount, Collection<Agent> hosts, PlacementStrategy... strategy) throws LxcCreateException { // restrict metrics to provided hosts only Map<Agent, ServerMetric> metrics = lxcManager.getPhysicalServerMetrics(); if (hosts != null && !hosts.isEmpty()) { Iterator<Agent> it = metrics.keySet().iterator(); while (it.hasNext()) { if (!hosts.contains(it.next())) { it.remove(); } } } LxcPlacementStrategy st = PlacementStrategyFactory.create(nodesCount, strategy); st.calculatePlacement(metrics); Map<Agent, Integer> slots = st.getPlacementDistribution(); int totalSlots = 0; for (int slotCount : slots.values()) { totalSlots += slotCount; } if (totalSlots == 0) { throw new LxcCreateException("Lxc placement strategy returned empty set"); } if (totalSlots < nodesCount) { throw new LxcCreateException(String.format("Only %d containers can be created", totalSlots)); } // clone specified number of instances and store their names Map<String, Set<String>> cloneNames = new HashMap<>(); Set<String> existingContainerNames = getContainerNames(hosts); List<ContainerInfo> lxcInfos = new ArrayList<>(); for (Map.Entry<Agent, Integer> e : slots.entrySet()) { Set<String> hostCloneNames = new HashSet<>(); for (int i = 0; i < e.getValue(); i++) { String newContainerName = nextHostName(templateName, existingContainerNames); hostCloneNames.add(newContainerName); } cloneNames.put(e.getKey().getHostname(), hostCloneNames); ContainerInfo lxcInfo = new ContainerInfo(e.getKey(), hostCloneNames); lxcInfos.add(lxcInfo); } if (!lxcInfos.isEmpty()) { CompletionService<ContainerInfo> completer = new ExecutorCompletionService<>(executor); //launch create commands for (ContainerInfo lxcInfo : lxcInfos) { completer.submit(new ContainerActor(lxcInfo, this, ContainerAction.CREATE, templateName)); } //wait for completion try { for (ContainerInfo ignored : lxcInfos) { Future<ContainerInfo> future = completer.take(); future.get(); } } catch (InterruptedException | ExecutionException ignore) { } boolean result = true; for (ContainerInfo lxcInfo : lxcInfos) { result &= lxcInfo.isResult(); } if (!result) { throw new LxcCreateException( String.format("Not all lxcs created. Use LXC module to cleanup %s", cloneNames)); } } else { throw new LxcCreateException("Empty container infos provided"); } boolean result = true; long waitStart = System.currentTimeMillis(); Set<Agent> clones = new HashSet<>(); while (!Thread.interrupted()) { result = true; outerloop: for (Set<String> names : cloneNames.values()) { for (String cloneName : names) { Agent lxcAgent = agentManager.getAgentByHostname(cloneName); if (lxcAgent == null) { result = false; break outerloop; } else { clones.add(lxcAgent); } } } if (result) { break; } else { if (System.currentTimeMillis() - waitStart > Common.LXC_AGENT_WAIT_TIMEOUT_SEC * 1000) { break; } else { try { Thread.sleep(1000); } catch (InterruptedException ex) { break; } } } } if (!result) { //destroy clones Set<String> names = new HashSet<>(); for (String key : cloneNames.keySet()) { names.addAll(cloneNames.get(key)); } try { clonesDestroyByHostname(names); } catch (LxcDestroyException ignore) { } throw new LxcCreateException( String.format("Waiting interval for lxc agents timed out. Use LXC module to cleanup nodes %s", cloneNames)); } try { if (envId != null) { saveNodeGroup(envId, templateName, clones, strategy); } } catch (Exception ex) { logger.error("Failed to save nodes info", ex); } return clones; } @Override public Set<Agent> clone(String templateName, int nodesCount, Collection<Agent> hosts, PlacementStrategy... strategy) throws LxcCreateException { return clone(null, templateName, nodesCount, hosts, strategy); } @Override public boolean attachAndExecute(Agent physicalHost, String cloneName, String cmd) { return attachAndExecute(physicalHost, cloneName, cmd, 30, TimeUnit.SECONDS); } @Override public boolean attachAndExecute(Agent physicalHost, String cloneName, String cmd, long t, TimeUnit unit) { if (cmd == null || cmd.isEmpty()) { return false; } // synopsis: // lxc-attach {-n name} [-a arch] [-e] [-s namespaces] [-R] [--keep-env] [--clear-env] [-- command] int timeout = (int) unit.toSeconds(t); Command comm = commandRunner.createCommand( new RequestBuilder("lxc-attach -n " + cloneName + " -- " + cmd).withTimeout(timeout), new HashSet<>(Arrays.asList(physicalHost))); commandRunner.runCommand(comm); return comm.hasSucceeded(); } @Override public void cloneDestroy(final String hostName, final String cloneName) throws LxcDestroyException { boolean result = templateManager.cloneDestroy(hostName, cloneName); if (!result) { throw new LxcDestroyException(String.format("Error destroying container %s", cloneName)); } } @Override public void clonesDestroy(final String hostName, final Set<String> cloneNames) throws LxcDestroyException { boolean result = templateManager.cloneDestroy(hostName, cloneNames); if (!result) { throw new LxcDestroyException( String.format("Not all containers from %s are destroyed. Use LXC module to cleanup", cloneNames)); } } @Override public void clonesCreate(final String hostName, final String templateName, final Set<String> cloneNames) throws LxcCreateException { //TODO: check envId boolean result = templateManager.clone(hostName, templateName, cloneNames, "test"); if (!result) { throw new LxcCreateException( String.format("Not all containers from %s : %s are created. Use LXC module to cleanup", hostName, cloneNames)); } } @Override public void clonesDestroyByHostname(final Set<String> cloneNames) throws LxcDestroyException { if (cloneNames == null || cloneNames.isEmpty()) { throw new LxcDestroyException("Clone names is empty or null"); } Set<Agent> lxcAgents = new HashSet<>(); for (String lxcHostname : cloneNames) { if (lxcHostname != null) { Agent lxcAgent = agentManager.getAgentByHostname(lxcHostname); if (lxcAgent == null) { throw new LxcDestroyException(String.format("Lxc %s is not connected", lxcHostname)); } lxcAgents.add(lxcAgent); } } clonesDestroy(lxcAgents); } @Override public void clonesDestroy(Set<Agent> lxcAgents) throws LxcDestroyException { if (lxcAgents == null || lxcAgents.isEmpty()) { throw new LxcDestroyException("LxcAgents is null or empty"); } Map<Agent, Set<Agent>> families = new HashMap<>(); for (Agent lxcAgent : lxcAgents) { if (lxcAgent != null) { Agent parentAgent = agentManager.getAgentByHostname(lxcAgent.getParentHostName()); if (parentAgent == null) { throw new LxcDestroyException( String.format("Physical parent of %s is not connected", lxcAgent.getHostname())); } Set<Agent> lxcChildren = families.get(parentAgent); if (lxcChildren == null) { lxcChildren = new HashSet<>(); families.put(parentAgent, lxcChildren); } lxcChildren.add(lxcAgent); } } cloneDestroy(families); } private void cloneDestroy(Map<Agent, Set<Agent>> agentFamilies) throws LxcDestroyException { Map<Agent, Set<String>> families = new HashMap<>(); for (Map.Entry<Agent, Set<Agent>> entry : agentFamilies.entrySet()) { Agent physicalAgent = entry.getKey(); if (physicalAgent != null) { Set<Agent> lxcChildren = entry.getValue(); Set<String> lxcHostnames = families.get(physicalAgent); if (lxcHostnames == null) { lxcHostnames = new HashSet<>(); families.put(physicalAgent, lxcHostnames); } for (Agent lxcAgent : lxcChildren) { if (lxcAgent != null) { lxcHostnames.add(lxcAgent.getHostname()); } } } } clonesDestroy(families); } private void clonesDestroy(Map<Agent, Set<String>> agentFamilies) throws LxcDestroyException { if (agentFamilies == null || agentFamilies.isEmpty()) { throw new LxcDestroyException("Agent Families is null or empty"); } List<ContainerInfo> lxcInfos = new ArrayList<>(); for (Map.Entry<Agent, Set<String>> family : agentFamilies.entrySet()) { Agent physicalAgent = family.getKey(); if (physicalAgent != null) { ContainerInfo lxcInfo = new ContainerInfo(physicalAgent, family.getValue()); lxcInfos.add(lxcInfo); } } if (!lxcInfos.isEmpty()) { CompletionService<ContainerInfo> completer = new ExecutorCompletionService<>(executor); //launch destroy commands for (ContainerInfo lxcInfo : lxcInfos) { completer.submit(new ContainerActor(lxcInfo, this, ContainerAction.DESTROY)); } //wait for completion try { for (ContainerInfo ignored : lxcInfos) { Future<ContainerInfo> future = completer.take(); future.get(); } } catch (InterruptedException | ExecutionException ignore) { } boolean result = true; for (ContainerInfo lxcInfo : lxcInfos) { result &= lxcInfo.isResult(); } if (!result) { throw new LxcDestroyException("Not all lxcs destroyed. Use LXC module to cleanup"); } } else { throw new LxcDestroyException("Empty child lxcs provided"); } } private String nextHostName(String templateName, Set<String> existingNames) { AtomicInteger i = sequences.putIfAbsent(templateName, new AtomicInteger()); if (i == null) { i = sequences.get(templateName); } while (true) { String name = templateName + i.incrementAndGet(); if (!existingNames.contains(name)) { return name; } } } private Set<String> getContainerNames(Collection<Agent> hostsToCheck) { Map<String, EnumMap<LxcState, List<String>>> map = lxcManager.getLxcOnPhysicalServers(); if (hostsToCheck != null && !hostsToCheck.isEmpty()) { Iterator<String> it = map.keySet().iterator(); while (it.hasNext()) { String hostname = it.next(); boolean hostIncluded = false; for (Agent agent : hostsToCheck) { if (agent.getHostname().equalsIgnoreCase(hostname)) { hostIncluded = true; break; } } if (!hostIncluded) { it.remove(); } } } Set<String> lxcHostNames = new HashSet<>(); for (EnumMap<LxcState, List<String>> lxcsOnOneHost : map.values()) { for (List<String> hosts : lxcsOnOneHost.values()) { lxcHostNames.addAll(hosts); } } return lxcHostNames; } private void saveNodeGroup(UUID envId, String templateName, Set<Agent> agents, PlacementStrategy... strategy) { String cql = "INSERT INTO nodes(uuid, env_id, info) VALUES(?, ?, ?)"; NodeInfo group = new NodeInfo(); group.setEnvId(envId); group.setTemplateName(templateName); if (strategy == null || strategy.length == 0) { strategy = new PlacementStrategy[] { PlacementStrategyFactory.getDefaultStrategyType() }; } group.setStrategy(EnumSet.of(strategy[0], strategy)); Template template = templateRegistry.getTemplate(templateName); group.setProducts(template.getProducts()); for (Agent a : agents) { group.setInstanceId(a.getUuid()); dbManager.executeUpdate(cql, a.getUuid().toString(), envId.toString(), gson.toJson(group)); } } }
package org.safehaus.subutai.plugin.hadoop.impl.handler; import java.util.Iterator; import java.util.UUID; import org.safehaus.subutai.common.exception.ClusterSetupException; import org.safehaus.subutai.common.protocol.AbstractOperationHandler; import org.safehaus.subutai.common.protocol.Agent; import org.safehaus.subutai.common.protocol.ClusterSetupStrategy; import org.safehaus.subutai.common.tracker.ProductOperation; import org.safehaus.subutai.plugin.hadoop.api.HadoopClusterConfig; import org.safehaus.subutai.plugin.hadoop.impl.HadoopImpl; import com.google.common.base.Strings; public class InstallOperationHandler extends AbstractOperationHandler<HadoopImpl> { private final ProductOperation productOperation; private final HadoopClusterConfig config; public InstallOperationHandler( HadoopImpl manager, HadoopClusterConfig config ) { super( manager, config.getClusterName() ); this.config = config; productOperation = manager.getTracker().createProductOperation( HadoopClusterConfig.PRODUCT_KEY, String.format( "Installing %s", HadoopClusterConfig.PRODUCT_KEY ) ); } @Override public UUID getTrackerId() { return productOperation.getId(); } @Override public void run() { if ( Strings.isNullOrEmpty( config.getClusterName() ) || config.getCountOfSlaveNodes() == null || config.getCountOfSlaveNodes() <= 0 ) { productOperation.addLogFailed( "Malformed configuration\nInstallation aborted" ); return; } if ( manager.getCluster( config.getClusterName() ) != null ) { productOperation.addLogFailed( String.format( "Cluster with name '%s' already exists\nInstallation aborted", config.getClusterName() ) ); return; } setup(); } private void setup() { try { ClusterSetupStrategy setupStrategy = manager.getClusterSetupStrategy( productOperation, config ); setupStrategy.setup(); productOperation.addLogDone( String.format( "Cluster %s set up successfully", clusterName ) ); } catch ( ClusterSetupException e ) { productOperation.addLogFailed( String.format( "Failed to setup Hadoop cluster %s : %s", clusterName, e.getMessage() ) ); } } }
package org.nuxeo.ecm.platform.pictures.tiles.service.test; import static org.junit.Assert.assertNotNull; import java.io.File; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.nuxeo.common.utils.FileUtils; import org.nuxeo.ecm.core.api.Blob; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.impl.blob.FileBlob; import org.nuxeo.ecm.core.storage.sql.SQLRepositoryTestCase; import org.nuxeo.ecm.platform.pictures.tiles.api.PictureTiles; import org.nuxeo.ecm.platform.pictures.tiles.api.adapter.PictureTilesAdapter; public class TestAdapters extends SQLRepositoryTestCase { @Before public void setUp() throws Exception { super.setUp(); deployBundle("org.nuxeo.ecm.platform.types.api"); deployBundle("org.nuxeo.ecm.platform.commandline.executor"); deployBundle("org.nuxeo.ecm.platform.picture.api"); deployBundle("org.nuxeo.ecm.platform.picture.core"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-framework.xml"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-contrib.xml"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-adapter-contrib.xml"); openSession(); } @After public void tearDown() throws Exception { closeSession(); super.tearDown(); } @Test public void testAdapter() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel doc = session.createDocumentModel(root.getPathAsString(), "file", "File"); doc.setProperty("dublincore", "title", "MyDoc"); doc.setProperty("dublincore", "coverage", "MyDocCoverage"); doc.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); doc.setProperty("file", "content", image); doc.setProperty("file", "filename", "test.jpg"); doc = session.createDocument(doc); session.save(); assertTilingIsWorkingFor(doc); } protected void assertTilingIsWorkingFor(DocumentModel doc) throws Exception { PictureTilesAdapter tilesAdapter = doc.getAdapter(PictureTilesAdapter.class); assertNotNull(tilesAdapter); PictureTiles tiles = tilesAdapter.getTiles(255, 255, 15); assertNotNull(tiles); PictureTiles tiles2 = tilesAdapter.getTiles(255, 255, 20); assertNotNull(tiles2); } @Test public void testAdapterOnPicture() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel picture = session.createDocumentModel( root.getPathAsString(), "picture1", "Picture"); picture.setProperty("dublincore", "description", "test picture"); picture.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); List<Map<String, Object>> viewsList = getDefaultViewsList(image); picture.getProperty("picture:views").setValue(viewsList); picture = session.createDocument(picture); session.save(); assertTilingIsWorkingFor(picture); } @Test public void testAdapterOnPictureWithOriginalJpegView() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel picture = session.createDocumentModel( root.getPathAsString(), "picture1", "Picture"); picture.setProperty("dublincore", "description", "test picture"); picture.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); List<Map<String, Object>> viewsList = getDefaultViewsList(image); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "OriginalJpeg"); map.put("description", "OriginalJpeg Size"); map.put("filename", "test.jpg"); map.put("tag", "originalJpeg"); map.put("width", 3872); map.put("height", 2592); image.setFilename("OriginalJpeg" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); picture.getProperty("picture:views").setValue(viewsList); picture = session.createDocument(picture); session.save(); assertTilingIsWorkingFor(picture); } protected List<Map<String, Object>> getDefaultViewsList(Blob image) { List<Map<String, Object>> viewsList = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "Medium"); map.put("description", "Medium Size"); map.put("filename", "test.jpg"); map.put("tag", "medium"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Medium" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); map = new HashMap<String, Object>(); map.put("title", "Original"); map.put("description", "Original Size"); map.put("filename", "test.jpg"); map.put("tag", "original"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Original" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); map = new HashMap<String, Object>(); map.put("title", "Thumbnail"); map.put("description", "Thumbnail Size"); map.put("filename", "test.jpg"); map.put("tag", "thumbnail"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Thumbnail" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); return viewsList; } }
package org.csstudio.display.builder.representation.javafx.widgets; import org.csstudio.display.builder.model.DirtyFlag; import org.csstudio.display.builder.model.WidgetProperty; import org.csstudio.display.builder.model.util.VTypeUtil; import org.csstudio.display.builder.model.widgets.ScrollBarWidget; import org.diirt.vtype.Display; import org.diirt.vtype.VType; import org.diirt.vtype.ValueUtil; import javafx.beans.value.ObservableValue; import javafx.geometry.Orientation; import javafx.scene.control.ScrollBar; import javafx.scene.input.KeyEvent; /** Creates JavaFX item for model widget * @author Amanda Carpenter */ //TODO: represent show_value_tip //value tip: when incr/decr, appears "behind" (left/right by incr/decr) //TODO: Investigate error: "Invalid setting for pv_name_patches" after "Connecting Widget 'Scrollbar' (scrollbar) to loc://boolTest" public class ScrollBarRepresentation extends JFXBaseRepresentation<ScrollBar, ScrollBarWidget> { private final DirtyFlag dirty_style = new DirtyFlag(); private final DirtyFlag dirty_value = new DirtyFlag(); private volatile double min = 0.0; private volatile double max = 100.0; @Override protected ScrollBar createJFXNode() throws Exception { ScrollBar scrollbar = new ScrollBar(); scrollbar.setOrientation(model_widget.displayHorizontal().getValue() ? Orientation.VERTICAL : Orientation.HORIZONTAL); scrollbar.setFocusTraversable(true); scrollbar.setOnKeyPressed((final KeyEvent event) -> { switch (event.getCode()) { case DOWN: jfx_node.decrement(); break; case UP: jfx_node.increment(); break; case PAGE_UP: //In theory, this may be unsafe; i.e. if max/min are changed //at runtime. jfx_node.adjustValue(max); break; case PAGE_DOWN: jfx_node.adjustValue(min); break; default: break; } }); limitsChanged(null, null, null); return scrollbar; } @Override protected void registerListeners() { super.registerListeners(); model_widget.positionWidth().addUntypedPropertyListener(this::styleChanged); model_widget.behaviorLimitsFromPV().addUntypedPropertyListener(this::limitsChanged); model_widget.behaviorMinimum().addUntypedPropertyListener(this::limitsChanged); model_widget.behaviorMaximum().addUntypedPropertyListener(this::limitsChanged); model_widget.displayHorizontal().addPropertyListener(this::styleChanged); model_widget.behaviorBarLength().addPropertyListener(this::styleChanged); model_widget.behaviorStepIncrement().addPropertyListener(this::styleChanged); model_widget.behaviorPageIncrement().addPropertyListener(this::styleChanged); //Since both the widget's PV value and the ScrollBar node's value property might be //written to independently during runtime, both must be listened to. Since ChangeListeners //only fire with an actual change, the listeners will not endlessly trigger each other. model_widget.runtimeValue().addPropertyListener(this::valueChanged); jfx_node.valueProperty().addListener(this::nodeValueChanged); } private void styleChanged(final WidgetProperty<?> property, final Object old_value, final Object new_value) { dirty_style.mark(); toolkit.scheduleUpdate(this); } private void limitsChanged(final WidgetProperty<?> property, final Object old_value, final Object new_value) { double min_val = model_widget.behaviorMinimum().getValue(); double max_val = model_widget.behaviorMaximum().getValue(); if (model_widget.behaviorLimitsFromPV().getValue()) { //Try to get display range from PV final Display display_info = ValueUtil.displayOf(model_widget.runtimeValue().getValue()); if (display_info != null) { min_val = display_info.getLowerDisplayLimit(); max_val = display_info.getUpperDisplayLimit(); } } //If invalid limits, fall back to 0..100 range if (min_val >= max_val) { min_val = 0.0; max_val = 100.0; } min = min_val; max = max_val; dirty_style.mark(); toolkit.scheduleUpdate(this); } private void nodeValueChanged(ObservableValue<? extends Number> property, Number old_value, Number new_value) { toolkit.fireWrite(model_widget, new_value); } private void valueChanged(final WidgetProperty<? extends VType> property, final VType old_value, final VType new_value) { dirty_value.mark(); toolkit.scheduleUpdate(this); } @Override public void updateChanges() { super.updateChanges(); if (dirty_style.checkAndClear()) { jfx_node.setPrefHeight(model_widget.positionHeight().getValue()); jfx_node.setPrefWidth(model_widget.positionWidth().getValue()); jfx_node.setMin(min); jfx_node.setMax(max); jfx_node.setOrientation(model_widget.displayHorizontal().getValue() ? Orientation.HORIZONTAL : Orientation.VERTICAL); jfx_node.setUnitIncrement(model_widget.behaviorStepIncrement().getValue()); jfx_node.setBlockIncrement(model_widget.behaviorPageIncrement().getValue()); jfx_node.setVisibleAmount(model_widget.behaviorBarLength().getValue()); } if (dirty_value.checkAndClear()) { double newval = VTypeUtil.getValueNumber( model_widget.runtimeValue().getValue() ).doubleValue(); if (newval < min) newval = min; else if (newval > max) newval = max; jfx_node.setValue(newval); } } }
package org.csstudio.utility.ldapUpdater.service.impl; import static org.csstudio.utility.ldap.service.util.LdapUtils.createLdapName; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsControlsConfiguration.COMPONENT; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsControlsConfiguration.FACILITY; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsControlsConfiguration.IOC; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsControlsConfiguration.RECORD; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsControlsConfiguration.UNIT; import static org.csstudio.utility.ldapUpdater.preferences.LdapUpdaterPreference.IOC_DBL_DUMP_PATH; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.naming.InvalidNameException; import javax.naming.NamingException; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import org.apache.log4j.Logger; import org.csstudio.domain.desy.time.TimeInstant; import org.csstudio.platform.logging.CentralLogger; import org.csstudio.utility.ldap.model.IOC; import org.csstudio.utility.ldap.model.Record; import org.csstudio.utility.ldap.treeconfiguration.LdapEpicsControlsConfiguration; import org.csstudio.utility.ldap.treeconfiguration.LdapEpicsControlsFieldsAndAttributes; import org.csstudio.utility.ldap.utils.LdapNameUtils; import org.csstudio.utility.ldapUpdater.LdapUpdaterUtil; import org.csstudio.utility.ldapUpdater.UpdaterLdapConstants; import org.csstudio.utility.ldapUpdater.files.HistoryFileAccess; import org.csstudio.utility.ldapUpdater.files.HistoryFileContentModel; import org.csstudio.utility.ldapUpdater.files.RecordsFileContentParser; import org.csstudio.utility.ldapUpdater.service.ILdapFacade; import org.csstudio.utility.ldapUpdater.service.ILdapUpdaterService; import org.csstudio.utility.ldapUpdater.service.LdapFacadeException; import org.csstudio.utility.treemodel.ContentModel; import org.csstudio.utility.treemodel.INodeComponent; import com.google.inject.Inject; /** * LDAP Updater access class to encapsulate specific updater access. * * @author bknerr * @author $Author$ * @version $Revision$ * @since 13.04.2010 */ public final class LdapUpdaterServiceImpl implements ILdapUpdaterService { public static final Logger LOG = CentralLogger.getInstance().getLogger(LdapUpdaterServiceImpl.class); /** * Update Result. * * @author bknerr * @author $Author$ * @version $Revision$ * @since 13.04.2010 */ private static class UpdateIOCResult { private final int _numOfRecsWritten; private final boolean _noError; private final int _numOfRecsInFile; private final int _numOfRecsInLDAP; public UpdateIOCResult(final int numOfRecsInFile, final int numOfRecsWritten, final int numOfRecordsInLDAP, final boolean noError) { _numOfRecsInFile = numOfRecsInFile; _numOfRecsWritten = numOfRecsWritten; _numOfRecsInLDAP = numOfRecordsInLDAP; _noError = noError; } public int getNumOfRecsInFile() { return _numOfRecsInFile; } public int getNumOfRecsWritten() { return _numOfRecsWritten; } public boolean hasNoError() { return _noError; } public int getNumOfRecsInLDAP() { return _numOfRecsInLDAP; } } private final ILdapFacade _facade; /** * Don't instantiate. */ @Inject public LdapUpdaterServiceImpl(@Nonnull final ILdapFacade facade) { _facade = facade; } private boolean isIOCFileNewerThanHistoryEntry(@Nonnull final IOC ioc, @Nonnull final HistoryFileContentModel historyFileModel) { final TimeInstant lastBootTime = ioc.getLastBootTime(); if (lastBootTime != null) { final TimeInstant timeFromHistoryFile = historyFileModel.getTimeForRecord(ioc.getName()); if (timeFromHistoryFile != null) { return lastBootTime.isAfter(timeFromHistoryFile); } } return true; } /** * {@inheritDoc} */ @Override public void tidyUpLDAPFromIOCList(@Nonnull final Map<String, INodeComponent<LdapEpicsControlsConfiguration>> iocsFromLdap, @Nonnull final Map<String, IOC> iocMapFromFS) throws LdapFacadeException { for (final INodeComponent<LdapEpicsControlsConfiguration> iocFromLdap : iocsFromLdap.values()) { final String iocFromLdapName = iocFromLdap.getName(); final String facFromLdapName = LdapNameUtils.getValueOfRdnType(iocFromLdap.getLdapName(), FACILITY.getNodeTypeName()); if (facFromLdapName == null) { LOG.warn("Facility name could not be retrieved for " + iocFromLdap.getLdapName().toString()); continue; } if (iocMapFromFS.containsKey(iocFromLdapName)) { final Set<Record> validRecords = getBootRecordsFromIocFile(iocFromLdapName); _facade.tidyUpIocEntryInLdap(iocFromLdapName, facFromLdapName, validRecords); } else { // LDAP entry is not contained in current IOC directory - is considered obsolete! _facade.removeIocEntryFromLdap(iocFromLdapName, facFromLdapName); } } } @Nonnull private UpdateIOCResult updateIocInLdapWithRecordsFromBootFile(@Nonnull final Map<String, INodeComponent<LdapEpicsControlsConfiguration>> recordMapFromLdap, @Nonnull final INodeComponent<LdapEpicsControlsConfiguration> iocFromLDAP) throws LdapFacadeException { final String iocName = iocFromLDAP.getName(); final Set<Record> recordsFromFile = getBootRecordsFromIocFile(iocName); final StringBuilder forbiddenRecords = new StringBuilder(); LOG.info( "Process IOC " + iocName + "\t\t #records " + recordsFromFile.size()); int numOfRecsWritten = 0; try { for (final Record recFromFile : recordsFromFile) { if (!recordMapFromLdap.containsKey(recFromFile.getName())) { numOfRecsWritten += createNewRecordEntry(iocFromLDAP, forbiddenRecords, recFromFile); } } LdapUpdaterUtil.sendUnallowedCharsNotification(iocFromLDAP, iocName, forbiddenRecords); } catch (final NamingException e) { throw new LdapFacadeException("LDAP name creation failed on updating records for IOC " + iocName, e); } return new UpdateIOCResult(recordsFromFile.size(), numOfRecsWritten, -1, true); } /** * Retrieves valid records for an IOC from the IOC file. * @param iocName the ioc file name * @return a set of contained records * @throws LdapFacadeException */ @Override @Nonnull public SortedSet<Record> getBootRecordsFromIocFile(@Nonnull final String iocName) throws LdapFacadeException { final File dumpPath = IOC_DBL_DUMP_PATH.getValue(); final RecordsFileContentParser parser = new RecordsFileContentParser(); try { parser.parseFile(new File(dumpPath, iocName + UpdaterLdapConstants.RECORDS_FILE_SUFFIX)); } catch (final IOException e) { throw new LdapFacadeException("Failure on parsing contents of record file " + iocName , e); } return parser.getRecords(); } private int createNewRecordEntry(@Nonnull final INodeComponent<LdapEpicsControlsConfiguration> iocFromLDAP, @Nonnull final StringBuilder forbiddenRecords, @Nonnull final Record recordFromFS) throws InvalidNameException, LdapFacadeException { final String recordFromFSName = recordFromFS.getName(); LOG.info("New record for LDAP: " + recordFromFSName); if (!LdapNameUtils.filterName(recordFromFSName)) { final LdapName newLdapName = new LdapName(iocFromLDAP.getLdapName().getRdns()); newLdapName.add(new Rdn(RECORD.getNodeTypeName(), recordFromFSName)); if (!_facade.createLdapRecord(newLdapName)) { LOG.error("Error while updating LDAP record for " + recordFromFSName + "\nProceed with next record."); } return 1; } else { LOG.warn("Record " + recordFromFSName + " could not be written. Unallowed characters!"); forbiddenRecords.append(recordFromFSName + "\n"); } return 0; } /** * This method compares the contents of the current LDAP hierarchy with the contents found in * the directory, where the IOC files reside. The contents of the ioc list are firstly checked * whether they are more recent than those stored in the history file, if not so the ioc file * has already been processed. If so, the LDAP is updated with the newer content of the ioc * files conservatively, i.e. by adding references to records, but not removing entries * from the LDAP in case the corresponding file does not exist in the ioc directory. * @param iocs the current LDAP content model * @param iocMap * the list of ioc filenames as found in the ioc directory * @param historyFileModel * the contents of the history file * @throws LdapFacadeException */ @Override public void updateLDAPFromIOCList(@Nonnull final Map<String, INodeComponent<LdapEpicsControlsConfiguration>> iocMapFromLdap, @Nonnull final Map<String, IOC> iocMapFromFS, @Nonnull final HistoryFileContentModel historyFileModel) throws LdapFacadeException { for (final Entry<String, IOC> entry : iocMapFromFS.entrySet()) { final String iocFromFSName = entry.getKey(); final IOC iocFromFS = entry.getValue(); if (historyFileModel.contains(iocFromFSName)) { if (!isIOCFileNewerThanHistoryEntry(iocFromFS, historyFileModel)) { LOG.debug("IOC file for " + iocFromFSName + " is not newer than history file time stamp."); continue; } } // else means 'new IOC file in directory' createOrUpdateIocInLdap(iocMapFromLdap.get(iocFromFSName), iocFromFS); } } private void createOrUpdateIocInLdap(@Nullable final INodeComponent<LdapEpicsControlsConfiguration> pIocFromLdap, @Nonnull final IOC iocFromFS) throws LdapFacadeException { INodeComponent<LdapEpicsControlsConfiguration> iocFromLdap = pIocFromLdap; if (iocFromLdap == null) { iocFromLdap = createIocInLdap(iocFromFS); } final LdapName iocFromLdapName = iocFromLdap.getLdapName(); final Map<String, INodeComponent<LdapEpicsControlsConfiguration>> recordMapFromLdap = _facade.retrieveRecordsForIOC(iocFromLdapName); final UpdateIOCResult updateResult = updateIocInLdapWithRecordsFromBootFile(recordMapFromLdap, iocFromLdap); // TODO (bknerr) : does only make sense when the update process has been stopped if (updateResult.hasNoError()) { HistoryFileAccess.appendLineToHistfile(iocFromFS.getName(), updateResult.getNumOfRecsWritten(), updateResult.getNumOfRecsInFile(), updateResult.getNumOfRecsInLDAP() ); } } @Nonnull private INodeComponent<LdapEpicsControlsConfiguration> createIocInLdap(@Nonnull final IOC iocFromFS) throws LdapFacadeException { final String iocName = iocFromFS.getName(); LOG.info("IOC " + iocName + " (from file system) does not yet exist in LDAP - added to facility MISC.\n"); final LdapName middleName = createLdapName(COMPONENT.getNodeTypeName(), LdapEpicsControlsFieldsAndAttributes.ECOM_EPICS_IOC_FIELD_VALUE, FACILITY.getNodeTypeName(), UpdaterLdapConstants.FACILITY_MISC_FIELD_VALUE); LdapName iocFromLdapName; try { iocFromLdapName = (LdapName) new LdapName(middleName.getRdns()).add(new Rdn(IOC.getNodeTypeName(), iocName)); final LdapName fullLdapName = (LdapName) new LdapName(iocFromLdapName.getRdns()).add(0, new Rdn(UNIT.getNodeTypeName(), UNIT.getUnitTypeValue())); _facade.createLdapIoc(fullLdapName, iocFromFS.getLastBootTime()); return _facade.retrieveIOC(fullLdapName); } catch (final InvalidNameException e) { throw new LdapFacadeException("Invalid name on creating new LDAP IOC.", e); } } /** * {@inheritDoc} */ @Override @Nonnull public ContentModel<LdapEpicsControlsConfiguration> retrieveIOCs() throws LdapFacadeException { return _facade.retrieveIOCs(); } /** * {@inheritDoc} */ @Override public void removeIocEntryFromLdap(@Nonnull final String iocName, @Nonnull final String facilityName) throws LdapFacadeException { _facade.removeIocEntryFromLdap(iocName, facilityName); } /** * {@inheritDoc} */ @Override public void tidyUpIocEntryInLdap(@Nonnull final String iocName, @Nonnull final String facilityName, @Nonnull final Set<Record> validRecords) throws LdapFacadeException { _facade.tidyUpIocEntryInLdap(iocName, facilityName, validRecords); } }
package com.yahoo.tensor.functions; import com.google.common.collect.ImmutableList; import com.yahoo.tensor.DimensionSizes; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorAddress; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.TypeResolver; import com.yahoo.tensor.evaluation.EvaluationContext; import com.yahoo.tensor.evaluation.Name; import com.yahoo.tensor.evaluation.TypeContext; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * Concatenation of two tensors along an (indexed) dimension * * @author bratseth */ public class Concat<NAMETYPE extends Name> extends PrimitiveTensorFunction<NAMETYPE> { static class CellVector { ArrayList<Double> values = new ArrayList<>(); void setValue(int ccDimIndex, double value) { while (values.size() <= ccDimIndex) { values.add(0.0); } values.set(ccDimIndex, value); } } static class CellVectorMap { Map<TensorAddress, CellVector> map = new HashMap<>(); CellVector lookupCreate(TensorAddress addr) { if (map.containsKey(addr)) { return map.get(addr); } else { CellVector result = new CellVector(); map.put(addr, result); return result; } } } static class CellVectorMapMap { Map<TensorAddress, CellVectorMap> map = new HashMap<>(); CellVectorMap lookupCreate(TensorAddress addr) { if (map.containsKey(addr)) { return map.get(addr); } else { CellVectorMap result = new CellVectorMap(); map.put(addr, result); return result; } } int concatDimensionSize() { Set<Integer> sizes = new HashSet<>(); map.forEach((m, cells) -> cells.map.forEach((e, cell) -> sizes.add(cell.values.size()))); if (sizes.isEmpty()) { return 1; } if (sizes.size() == 1) { return sizes.iterator().next(); } throw new IllegalArgumentException("inconsistent size of concat dimension, had "+sizes.size()+" different values"); } } enum DimType { common, separate, concat } static class SplitHow { List<DimType> handleDims = new ArrayList<>(); long numCommon() { return handleDims.stream().filter(t -> (t == DimType.common)).count(); } long numSeparate() { return handleDims.stream().filter(t -> (t == DimType.separate)).count(); } } static class ConcatPlan { final TensorType resultType; final String concatDimension; SplitHow aHow = new SplitHow(); SplitHow bHow = new SplitHow(); enum CombineHow { left, right, both, concat } List<CombineHow> combineHow = new ArrayList<>(); TensorAddress combine(TensorAddress match, TensorAddress leftOnly, TensorAddress rightOnly, int concatDimIdx) { String[] labels = new String[resultType.rank()]; int out = 0; int m = 0; int a = 0; int b = 0; for (var how : combineHow) { switch (how) { case left: labels[out++] = leftOnly.label(a++); break; case right: labels[out++] = rightOnly.label(b++); break; case both: labels[out++] = match.label(m++); break; case concat: labels[out++] = String.valueOf(concatDimIdx); break; } } return TensorAddress.of(labels); } void aOnly(String dimName) { if (dimName.equals(concatDimension)) { aHow.handleDims.add(DimType.concat); combineHow.add(CombineHow.concat); } else { aHow.handleDims.add(DimType.separate); combineHow.add(CombineHow.left); } } void bOnly(String dimName) { if (dimName.equals(concatDimension)) { bHow.handleDims.add(DimType.concat); combineHow.add(CombineHow.concat); } else { bHow.handleDims.add(DimType.separate); combineHow.add(CombineHow.right); } } void bothAandB(String dimName) { if (dimName.equals(concatDimension)) { aHow.handleDims.add(DimType.concat); bHow.handleDims.add(DimType.concat); combineHow.add(CombineHow.concat); } else { aHow.handleDims.add(DimType.common); bHow.handleDims.add(DimType.common); combineHow.add(CombineHow.both); } } ConcatPlan(TensorType aType, TensorType bType, String concatDimension) { this.resultType = TypeResolver.concat(aType, bType, concatDimension); this.concatDimension = concatDimension; var aDims = aType.dimensions(); var bDims = bType.dimensions(); int i = 0; int j = 0; while (i < aDims.size() && j < bDims.size()) { String aName = aDims.get(i).name(); String bName = bDims.get(j).name(); int cmp = aName.compareTo(bName); if (cmp == 0) { bothAandB(aName); ++i; ++j; } else if (cmp < 0) { aOnly(aName); ++i; } else { bOnly(bName); ++j; } } while (i < aDims.size()) { aOnly(aDims.get(i++).name()); } while (j < bDims.size()) { bOnly(bDims.get(j++).name()); } if (combineHow.size() < resultType.rank()) { var idx = resultType.indexOfDimension(concatDimension); combineHow.add(idx.get(), CombineHow.concat); } } Tensor mergeSides(CellVectorMapMap a, CellVectorMapMap b) { var builder = Tensor.Builder.of(resultType); int aConcatSize = a.concatDimensionSize(); for (var entry : a.map.entrySet()) { TensorAddress match = entry.getKey(); if (b.map.containsKey(match)) { var lhs = entry.getValue(); var rhs = b.map.get(match); lhs.map.forEach((leftOnly, leftCells) -> { rhs.map.forEach((rightOnly, rightCells) -> { for (int i = 0; i < leftCells.values.size(); i++) { TensorAddress addr = combine(match, leftOnly, rightOnly, i); builder.cell(addr, leftCells.values.get(i)); } for (int i = 0; i < rightCells.values.size(); i++) { TensorAddress addr = combine(match, leftOnly, rightOnly, i + aConcatSize); builder.cell(addr, rightCells.values.get(i)); } }); }); } } return builder.build(); } } CellVectorMapMap analyse(Tensor side, SplitHow how) { var iter = side.cellIterator(); String[] commonLabels = new String[(int)how.numCommon()]; String[] separateLabels = new String[(int)how.numSeparate()]; CellVectorMapMap result = new CellVectorMapMap(); while (iter.hasNext()) { var cell = iter.next(); var addr = cell.getKey(); long ccDimIndex = 0; int matchIdx = 0; int separateIdx = 0; for (int i = 0; i < how.handleDims.size(); i++) { switch (how.handleDims.get(i)) { case common: commonLabels[matchIdx++] = addr.label(i); break; case separate: separateLabels[separateIdx++] = addr.label(i); break; case concat: ccDimIndex = addr.numericLabel(i); break; } } TensorAddress commonAddr = TensorAddress.of(commonLabels); TensorAddress separateAddr = TensorAddress.of(separateLabels); result.lookupCreate(commonAddr).lookupCreate(separateAddr).setValue((int)ccDimIndex, cell.getValue()); } return result; } private final TensorFunction<NAMETYPE> argumentA, argumentB; private final String dimension; public Concat(TensorFunction<NAMETYPE> argumentA, TensorFunction<NAMETYPE> argumentB, String dimension) { Objects.requireNonNull(argumentA, "The first argument tensor cannot be null"); Objects.requireNonNull(argumentB, "The second argument tensor cannot be null"); Objects.requireNonNull(dimension, "The dimension cannot be null"); this.argumentA = argumentA; this.argumentB = argumentB; this.dimension = dimension; } @Override public List<TensorFunction<NAMETYPE>> arguments() { return ImmutableList.of(argumentA, argumentB); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { if (arguments.size() != 2) throw new IllegalArgumentException("Concat must have 2 arguments, got " + arguments.size()); return new Concat<>(arguments.get(0), arguments.get(1), dimension); } @Override public PrimitiveTensorFunction<NAMETYPE> toPrimitive() { return new Concat<>(argumentA.toPrimitive(), argumentB.toPrimitive(), dimension); } @Override public String toString(ToStringContext context) { return "concat(" + argumentA.toString(context) + ", " + argumentB.toString(context) + ", " + dimension + ")"; } @Override public TensorType type(TypeContext<NAMETYPE> context) { return TypeResolver.concat(argumentA.type(context), argumentB.type(context), dimension); } @Override public Tensor evaluate(EvaluationContext<NAMETYPE> context) { Tensor a = argumentA.evaluate(context); Tensor b = argumentB.evaluate(context); // if (a instanceof IndexedTensor && b instanceof IndexedTensor) { // return oldEvaluate(a, b); ConcatPlan plan = new ConcatPlan(a.type(), b.type(), dimension); CellVectorMapMap aInfo = analyse(a, plan.aHow); CellVectorMapMap bInfo = analyse(b, plan.bHow); return plan.mergeSides(aInfo, bInfo); } private Tensor oldEvaluate(Tensor a, Tensor b) { TensorType concatType = TypeResolver.concat(a.type(), b.type(), dimension); a = ensureIndexedDimension(dimension, a, concatType.valueType()); b = ensureIndexedDimension(dimension, b, concatType.valueType()); IndexedTensor aIndexed = (IndexedTensor) a; // If you get an exception here you have implemented a mixed tensor IndexedTensor bIndexed = (IndexedTensor) b; DimensionSizes concatSize = concatSize(concatType, aIndexed, bIndexed, dimension); Tensor.Builder builder = Tensor.Builder.of(concatType, concatSize); long aDimensionLength = aIndexed.type().indexOfDimension(dimension).map(d -> aIndexed.dimensionSizes().size(d)).orElseThrow(RuntimeException::new); int[] aToIndexes = mapIndexes(a.type(), concatType); int[] bToIndexes = mapIndexes(b.type(), concatType); concatenateTo(aIndexed, bIndexed, aDimensionLength, concatType, aToIndexes, bToIndexes, builder); concatenateTo(bIndexed, aIndexed, 0, concatType, bToIndexes, aToIndexes, builder); return builder.build(); } private void concatenateTo(IndexedTensor a, IndexedTensor b, long offset, TensorType concatType, int[] aToIndexes, int[] bToIndexes, Tensor.Builder builder) { Set<String> otherADimensions = a.type().dimensionNames().stream().filter(d -> !d.equals(dimension)).collect(Collectors.toSet()); for (Iterator<IndexedTensor.SubspaceIterator> ia = a.subspaceIterator(otherADimensions); ia.hasNext();) { IndexedTensor.SubspaceIterator iaSubspace = ia.next(); TensorAddress aAddress = iaSubspace.address(); for (Iterator<IndexedTensor.SubspaceIterator> ib = b.subspaceIterator(otherADimensions); ib.hasNext();) { IndexedTensor.SubspaceIterator ibSubspace = ib.next(); while (ibSubspace.hasNext()) { Tensor.Cell bCell = ibSubspace.next(); TensorAddress combinedAddress = combineAddresses(aAddress, aToIndexes, bCell.getKey(), bToIndexes, concatType, offset, dimension); if (combinedAddress == null) continue; // incompatible builder.cell(combinedAddress, bCell.getValue()); } iaSubspace.reset(); } } } private Tensor ensureIndexedDimension(String dimensionName, Tensor tensor, TensorType.Value combinedValueType) { Optional<TensorType.Dimension> dimension = tensor.type().dimension(dimensionName); if ( dimension.isPresent() ) { if ( ! dimension.get().isIndexed()) throw new IllegalArgumentException("Concat in dimension '" + dimensionName + "' requires that dimension to be indexed or absent, " + "but got a tensor with type " + tensor.type()); return tensor; } else { // extend tensor with this dimension if (tensor.type().dimensions().stream().anyMatch(d -> ! d.isIndexed())) throw new IllegalArgumentException("Concat requires an indexed tensor, " + "but got a tensor with type " + tensor.type()); Tensor unitTensor = Tensor.Builder.of(new TensorType.Builder(combinedValueType) .indexed(dimensionName, 1) .build()) .cell(1,0) .build(); return tensor.multiply(unitTensor); } } /** Returns the concrete (not type) dimension sizes resulting from combining a and b */ private DimensionSizes concatSize(TensorType concatType, IndexedTensor a, IndexedTensor b, String concatDimension) { DimensionSizes.Builder concatSizes = new DimensionSizes.Builder(concatType.dimensions().size()); for (int i = 0; i < concatSizes.dimensions(); i++) { String currentDimension = concatType.dimensions().get(i).name(); long aSize = a.type().indexOfDimension(currentDimension).map(d -> a.dimensionSizes().size(d)).orElse(0L); long bSize = b.type().indexOfDimension(currentDimension).map(d -> b.dimensionSizes().size(d)).orElse(0L); if (currentDimension.equals(concatDimension)) concatSizes.set(i, aSize + bSize); else if (aSize != 0 && bSize != 0 && aSize!=bSize ) concatSizes.set(i, Math.min(aSize, bSize)); else concatSizes.set(i, Math.max(aSize, bSize)); } return concatSizes.build(); } /** * Combine two addresses, adding the offset to the concat dimension * * @return the combined address or null if the addresses are incompatible * (in some other dimension than the concat dimension) */ private TensorAddress combineAddresses(TensorAddress a, int[] aToIndexes, TensorAddress b, int[] bToIndexes, TensorType concatType, long concatOffset, String concatDimension) { long[] combinedLabels = new long[concatType.dimensions().size()]; Arrays.fill(combinedLabels, -1); int concatDimensionIndex = concatType.indexOfDimension(concatDimension).get(); mapContent(a, combinedLabels, aToIndexes, concatDimensionIndex, concatOffset); // note: This sets a nonsensical value in the concat dimension boolean compatible = mapContent(b, combinedLabels, bToIndexes, concatDimensionIndex, concatOffset); // ... which is overwritten by the right value here if ( ! compatible) return null; return TensorAddress.of(combinedLabels); } /** * Returns the an array having one entry in order for each dimension of fromType * containing the index at which toType contains the same dimension name. * That is, if the returned array contains n at index i then * fromType.dimensions().get(i).name.equals(toType.dimensions().get(n).name()) * If some dimension in fromType is not present in toType, the corresponding index will be -1 */ // TODO: Stolen from join private int[] mapIndexes(TensorType fromType, TensorType toType) { int[] toIndexes = new int[fromType.dimensions().size()]; for (int i = 0; i < fromType.dimensions().size(); i++) toIndexes[i] = toType.indexOfDimension(fromType.dimensions().get(i).name()).orElse(-1); return toIndexes; } /** * Maps the content in the given list to the given array, using the given index map. * * @return true if the mapping was successful, false if one of the destination positions was * occupied by a different value */ private boolean mapContent(TensorAddress from, long[] to, int[] indexMap, int concatDimension, long concatOffset) { for (int i = 0; i < from.size(); i++) { int toIndex = indexMap[i]; if (concatDimension == toIndex) { to[toIndex] = from.numericLabel(i) + concatOffset; } else { if (to[toIndex] != -1 && to[toIndex] != from.numericLabel(i)) return false; to[toIndex] = from.numericLabel(i); } } return true; } }
package org.mozartoz.truffle.nodes.builtins; import org.mozartoz.truffle.nodes.OzNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeChildren; import com.oracle.truffle.api.dsl.Specialization; public abstract class ThreadBuiltins { @Builtin(name = "create", proc = true) @GenerateNodeFactory @NodeChild("target") public static abstract class CreateThreadNode extends OzNode { @Specialization Object createThread(Object target) { return unimplemented(); } } @Builtin(name = "is") @GenerateNodeFactory @NodeChild("value") public static abstract class IsThreadNode extends OzNode { @Specialization Object isThread(Object value) { return unimplemented(); } } @Builtin(name = "this") @GenerateNodeFactory public static abstract class ThisThreadNode extends OzNode { @Specialization Object thisThread() { return unimplemented(); } } @GenerateNodeFactory @NodeChild("thread") public static abstract class GetPriorityNode extends OzNode { @Specialization Object getPriority(Object thread) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChildren({ @NodeChild("thread"), @NodeChild("priority") }) public static abstract class SetPriorityNode extends OzNode { @Specialization Object setPriority(Object thread, Object priority) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChildren({ @NodeChild("thread"), @NodeChild("exception") }) public static abstract class InjectExceptionNode extends OzNode { @Specialization Object injectException(Object thread, Object exception) { return unimplemented(); } } @GenerateNodeFactory @NodeChild("thread") public static abstract class StateNode extends OzNode { @Specialization Object state(Object thread) { return unimplemented(); } } }
package org.xwiki.extension.job.internal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import org.xwiki.extension.job.JobProgress; import org.xwiki.extension.job.JobStatus; import org.xwiki.extension.job.Request; import org.xwiki.logging.LogLevel; import org.xwiki.logging.LogQueue; import org.xwiki.logging.LoggerManager; import org.xwiki.logging.event.LogEvent; import org.xwiki.observation.ObservationManager; /** * Default implementation of {@link JobStatus}. * * @param <R> * @version $Id$ */ public class DefaultJobStatus<R extends Request> implements JobStatus { /** * Used register itself to receive logging and progress related events. */ private ObservationManager observationManager; /** * Used to isolate job related log. */ private LoggerManager loggerManager; /** * General state of the job. */ private State state; /** * Request provided when starting thee job. */ private R request; /** * Log sent during job execution. */ private LogQueue logs = new LogQueue(); /** * Take care of progress related events to produce a progression information usually used in a progress bar. */ private DefaultJobProgress progress; /** * @param request the request provided when started the job * @param id the unique id of the job * @param observationManager the observation manager component * @param loggerManager the logger manager component */ public DefaultJobStatus(R request, String id, ObservationManager observationManager, LoggerManager loggerManager) { this.request = request; this.observationManager = observationManager; this.loggerManager = loggerManager; this.progress = new DefaultJobProgress(id); } /** * Start listening to events. */ void startListening() { this.observationManager.addListener(this.progress); this.loggerManager.pushLogQueue(this.logs); } /** * Stop listening to events. */ void stopListening() { this.loggerManager.popLogListener(); this.observationManager.removeListener(this.progress.getName()); } // JobStatus /** * {@inheritDoc} * * @see org.xwiki.extension.job.JobStatus#getState() */ @Override public State getState() { return this.state; } /** * @param state the general state of the job */ public void setState(State state) { this.state = state; } /** * {@inheritDoc} * * @see org.xwiki.extension.job.JobStatus#getRequest() */ public R getRequest() { return this.request; } /** * {@inheritDoc} * * @see org.xwiki.extension.job.JobStatus#getLog() */ public ConcurrentLinkedQueue<LogEvent> getLog() { return this.logs; } /** * {@inheritDoc} * * @see org.xwiki.extension.job.JobStatus#getLog(org.xwiki.logging.LogLevel) */ public List<LogEvent> getLog(LogLevel level) { List<LogEvent> levelLogs = new ArrayList<LogEvent>(); for (LogEvent log : this.logs) { if (log.getLevel() == level) { levelLogs.add(log); } } return levelLogs; } /** * {@inheritDoc} * * @see org.xwiki.extension.job.JobStatus#getProgress() */ public JobProgress getProgress() { return this.progress; } }
package water; import java.util.Arrays; import water.H2ONode.H2Okey; import water.init.JarHash; import water.nbhm.NonBlockingHashMap; import water.util.Log; public abstract class Paxos { // Whether or not we have common knowledge public static volatile boolean _commonKnowledge = false; // Whether or not we're allowing distributed-writes. The cloud is not // allowed to change shape once we begin writing. public static volatile boolean _cloudLocked = false; public static final NonBlockingHashMap<H2Okey,H2ONode> PROPOSED = new NonBlockingHashMap<>(); // This is a packet announcing what Cloud this Node thinks is the current // Cloud, plus other status bits static synchronized int doHeartbeat( H2ONode h2o ) { // Kill somebody if the jar files mismatch. Do not attempt to deal with // mismatched jars. if(!H2O.ARGS.client && !h2o._heartbeat._client) { // don't check md5 for client nodes if (!h2o._heartbeat.check_jar_md5()) { System.out.println("Jar check fails; my hash=" + Arrays.toString(JarHash.JARHASH)); System.out.println("Jar check fails; received hash=" + Arrays.toString(h2o._heartbeat._jar_md5)); if (H2O.CLOUD.size() > 1) { Log.warn("Killing " + h2o + " because of H2O version mismatch (md5 differs)."); UDPRebooted.T.mismatch.send(h2o); } else { H2O.die("Attempting to join " + h2o + " with an H2O version mismatch (md5 differs). (Is H2O already running?) Exiting."); } return 0; } }else{ if (!h2o._heartbeat.check_jar_md5()) { // we do not want to disturb the user in this case // Just report that client with different md5 tried to connect ListenerService.getInstance().report("client_wrong_md5", new Object[]{h2o._heartbeat._jar_md5}); } } if(h2o._heartbeat._cloud_name_hash != H2O.SELF._heartbeat._cloud_name_hash){ // ignore requests from this node as they are coming from different cluster return 0; } // Update manual flatfile in case of flatfile is enabled if (H2O.isFlatfileEnabled()) { if (!H2O.ARGS.client && h2o._heartbeat._client && !H2O.isNodeInFlatfile(h2o)) { // A new client was reported to this node so we propagate this information to all nodes in the cluster, to this // as well UDPClientEvent.ClientEvent.Type.CONNECT.broadcast(h2o); } else if (H2O.ARGS.client && !H2O.isNodeInFlatfile(h2o)) { // This node is a client and using a flatfile to figure out a topology of the cluster. The flatfile passed to the // client is always modified at the start of H2O to contain only a single node. This node is used to propagate // information about the client to the cluster. Once the nodes have the information about the client, then propagate // themselves via heartbeat to the client H2O.addNodeToFlatfile(h2o); } } // Never heard of this dude? See if we want to kill him off for being cloud-locked if( !PROPOSED.contains(h2o) && !h2o._heartbeat._client ) { if( _cloudLocked ) { Log.warn("Killing "+h2o+" because the cloud is no longer accepting new H2O nodes."); UDPRebooted.T.locked.send(h2o); return 0; } if( _commonKnowledge ) { _commonKnowledge = false; // No longer sure about things H2O.SELF._heartbeat._common_knowledge = false; Log.debug("Cloud voting in progress"); } // Add to proposed set, update cloud hash. Do not add clients H2ONode res = PROPOSED.putIfAbsent(h2o._key,h2o); assert res==null; H2O.SELF._heartbeat._cloud_hash += h2o.hashCode(); } else if( _commonKnowledge ) { return 0; // Already know about you, nothing more to do } int chash = H2O.SELF._heartbeat._cloud_hash; assert chash == doHash() : "mismatched hash4, HB="+chash+" full="+doHash(); assert !_commonKnowledge; // Do we have consensus now? H2ONode h2os[] = PROPOSED.values().toArray(new H2ONode[PROPOSED.size()]); if( H2O.ARGS.client && h2os.length == 0 ) return 0; // Client stalls until it finds *some* cloud for( H2ONode h2o2 : h2os ) if( chash != h2o2._heartbeat._cloud_hash ) return print("Heartbeat hashes differ, self=0x"+Integer.toHexString(chash)+" "+h2o2+"=0x"+Integer.toHexString(h2o2._heartbeat._cloud_hash)+" ",PROPOSED); // Hashes are same, so accept the new larger cloud-size H2O.CLOUD.set_next_Cloud(h2os,chash); // Demand everybody has rolled forward to same size before consensus boolean same_size=true; for( H2ONode h2o2 : h2os ) same_size &= (h2o2._heartbeat._cloud_size == H2O.CLOUD.size()); if( !same_size ) return 0; H2O.SELF._heartbeat._common_knowledge = true; for( H2ONode h2o2 : h2os ) if( !h2o2._heartbeat._common_knowledge ) return print("Missing common knowledge from all nodes!" ,PROPOSED); _commonKnowledge = true; // Yup! Have global consensus Paxos.class.notifyAll(); // Also, wake up a worker thread stuck in DKV.put Paxos.print("Announcing new Cloud Membership: ", H2O.CLOUD._memary); Log.info("Cloud of size ", H2O.CLOUD.size(), " formed ", H2O.CLOUD.toString()); H2Okey leader = H2O.CLOUD.leader()._key; H2O.notifyAboutCloudSize(H2O.SELF_ADDRESS, H2O.API_PORT, leader.getAddress(), leader.htm_port(), H2O.CLOUD.size()); return 0; } static private int doHash() { int hash = 0; for( H2ONode h2o : PROPOSED.values() ) hash += h2o.hashCode(); assert hash != 0 || H2O.ARGS.client; return hash; } // Before we start doing distributed writes... block until the cloud // stabilizes. After we start doing distributed writes, it is an error to // change cloud shape - the distributed writes will be in the wrong place. static void lockCloud(Object reason) { if( _cloudLocked ) return; // Fast-path cutout lockCloud_impl(reason); } static private void lockCloud_impl(Object reason) { // Any fast-path cutouts must happen en route to here. Log.info("Locking cloud to new members, because "+reason.toString()); synchronized(Paxos.class) { while( !_commonKnowledge ) try { Paxos.class.wait(); } catch( InterruptedException ignore ) { } _cloudLocked = true; // remove nodes which are not in the cluster (e.g. nodes from flat-file which are not actually used) if(H2O.isFlatfileEnabled()){ for(H2ONode n: H2O.getFlatfile()){ if(!n._heartbeat._client && !PROPOSED.containsKey(n._key)){ Log.warn("Flatfile entry ignored: Node " + n._key.getIpPortString() + " not active in this cloud. Removing it from the list."); n.removeFromCloud(); } } } } } static int print( String msg, NonBlockingHashMap<H2Okey,H2ONode> p ) { return print(msg,p.values().toArray(new H2ONode[p.size()])); } static int print( String msg, H2ONode h2os[] ) { return print(msg,h2os,""); } static int print( String msg, H2ONode h2os[], String msg2 ) { Log.debug(msg,Arrays.toString(h2os),msg2); return 0; // handy flow-coding return } }
package algorithms.imageProcessing; import algorithms.compGeometry.PointInPolygon; import algorithms.imageProcessing.SkylineExtractor.RemovedSets; import algorithms.misc.MiscMath; import algorithms.util.ArrayPair; import algorithms.util.PairInt; import algorithms.util.PolynomialFitter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; /** * class with methods to find a rainbow within an image and to create a hull * to encapsulate it for various methods. * * TODO: Note, it may be necessary to build a hull from a spine of more than 10 points for complex images w/ rainbow intersecting multiple times with structured foreground and sky (see the end of method createRainbowHull). * @author nichole */ public class RainbowFinder { private Logger log = Logger.getLogger(this.getClass().getName()); static class Hull { float[] xHull; float[] yHull; } private Set<PairInt> outputRainbowPoints = new HashSet<PairInt>(); private Set<PairInt> excludePointsInRainbowHull = new HashSet<PairInt>(); private Hull rainbowHull = null; private float[] rainbowCoeff = null; private float[] rainbowSkeletonX = null; private float[] rainbowSkeletonY = null; private float hullHalfWidth = 0; /** * search for a rainbow within the image, and if found, create a hull of * points around that encapsulates image points that are part of the * expanded rainbow. The results are kept in member variables * rainbowCoeff, rainbowHull, outputRainbowPoints, and * excludePointsInRainbowHull. * * @param skyPoints * @param reflectedSunRemoved * @param colorImg * @param xOffset * @param yOffset * @param imageWidth * @param imageHeight * @param skyIsDarkGrey * @param removedSets */ public void findRainbowInImage(Set<PairInt> skyPoints, Set<PairInt> reflectedSunRemoved, ImageExt colorImg, int xOffset, int yOffset, int imageWidth, int imageHeight, boolean skyIsDarkGrey, RemovedSets removedSets) { rainbowCoeff = findRainbowPoints(skyPoints, removedSets.getReflectedSunRemoved(), colorImg, xOffset, yOffset, skyIsDarkGrey, outputRainbowPoints); if (outputRainbowPoints.size() < 10) { outputRainbowPoints.clear(); rainbowCoeff = null; } if (rainbowCoeff != null) { rainbowHull = createRainbowHull(rainbowCoeff, outputRainbowPoints, colorImg, xOffset, yOffset); if (rainbowHull != null) { //TODO: may need adjustment for a boundary being an image boundary int minXHull = (int)MiscMath.findMin(rainbowHull.xHull); int maxXHull = (int)Math.ceil(MiscMath.findMax(rainbowHull.xHull)); int minYHull = (int)MiscMath.findMin(rainbowHull.yHull); int maxYHull = (int)Math.ceil(MiscMath.findMax(rainbowHull.yHull)); PointInPolygon p = new PointInPolygon(); for (int col = minXHull; col <= maxXHull; col++) { for (int row = minYHull; row <= maxYHull; row++) { boolean in = p.isInSimpleCurve(col, row, rainbowHull.xHull, rainbowHull.yHull, rainbowHull.yHull.length); if (in) { excludePointsInRainbowHull.add(new PairInt(col, row)); } } } if (!excludePointsInRainbowHull.isEmpty()) { // addRainbow to Hull, but only if there are sky points adjacent to hull addRainbowToPoints(skyPoints, imageWidth - 1, imageHeight - 1); } } } } public Set<PairInt> getPointsToExcludeInHull() { return excludePointsInRainbowHull; } public Set<PairInt> getRainbowPoints() { return outputRainbowPoints; } public float[] getRainbowCoeff() { return rainbowCoeff; } public void addRainbowToSkyPoints(Set<PairInt> skyPoints, int lastImgCol, int lastImgRow) { addRainbowToPoints(skyPoints, lastImgCol, lastImgRow); } private void addRainbowToPoints(Set<PairInt> skyPoints, int lastImgCol, int lastImgRow) { /* n=21 0,20 1 2 3 4 5 6 7 8 9 19 18 17 16 15 14 13 12 11 10 Points 0 and 19 are opposite points on the hull, so are 1 and 18, etc. So can do quick check that for each segment such as 0->1->18->19->0 that there are skyPoints surrounding them. If not, and if the coverage is partial, will reduce the segment polygon size and only add points to skypoints within the segment polygon. */ int nHull = rainbowHull.xHull.length; int nHalf = nHull >> 1; for (int c = 0; c < nHalf; c++) { int count0 = c; int count1 = nHull - 2 - c; double dy0 = rainbowHull.yHull[count0 + 1] - rainbowHull.yHull[count0]; double dx0 = rainbowHull.xHull[count0 + 1] - rainbowHull.xHull[count0]; int dist0 = (int)Math.sqrt(dx0*dx0 + dy0*dy0); double dy1 = rainbowHull.yHull[count1 - 1] - rainbowHull.yHull[count1]; double dx1 = rainbowHull.xHull[count1 - 1] - rainbowHull.xHull[count1]; int dist1 = (int)Math.sqrt(dx1*dx1 + dy1*dy1); boolean removeSection = false; int dist = (dist0 < dist1) ? dist0 : dist1; for (int i = 0; i < dist; i++) { int x0 = (int)(rainbowHull.xHull[count0] + i*dx0); int y0 = (int)(rainbowHull.yHull[count0] + i*dy0); int x1 = (int)(rainbowHull.xHull[count1] + i*dx1); int y1 = (int)(rainbowHull.yHull[count1] + i*dy1); int n0Sky = 0; int n0SkyPossible = 0; int n1Sky = 0; int n1SkyPossible = 0; for (int type = 0; type < 2; type++) { int x = (type == 0) ? x0 : x1; int y = (type == 0) ? y0 : y1; int n = 0; int nPossible = 0; for (int col = (x - 1); col <= (x + 1); col++) { if ((col < 0) || (col > lastImgCol)) { continue; } for (int row = (y - 1); row <= (y + 1); row++) { if ((row < 0) || (row > lastImgRow)) { continue; } PairInt p = new PairInt(col, row); if (!excludePointsInRainbowHull.contains(p)) { nPossible++; if (skyPoints.contains(p)) { n++; } } } } if (type == 0) { n0Sky = n; n0SkyPossible = nPossible; } else { n1Sky = n; n1SkyPossible = nPossible; } } // evaluate the n's and shorten rainbowHull values for count0 and count1 if needed float n0Div = (float)n0Sky/(float)n0SkyPossible; float n1Div = (float)n1Sky/(float)n1SkyPossible; if ((n0Div < 0.5) || (n1Div < 0.5)) { removeSection = true; break; } } // end for i if (removeSection) { // remove points from rainbowHull float[] xh = new float[]{ rainbowHull.xHull[count0], rainbowHull.xHull[count0 + 1], rainbowHull.xHull[count1 - 1], rainbowHull.xHull[count1], rainbowHull.xHull[count0]}; float[] yh = new float[]{ rainbowHull.yHull[count0], rainbowHull.yHull[count0 + 1], rainbowHull.yHull[count1 - 1], rainbowHull.yHull[count1], rainbowHull.yHull[count0]}; int minXHull = (int)MiscMath.findMin(xh); int maxXHull = (int)Math.ceil(MiscMath.findMax(xh)); int minYHull = (int)MiscMath.findMin(yh); int maxYHull = (int)Math.ceil(MiscMath.findMax(yh)); PointInPolygon p = new PointInPolygon(); for (int col = minXHull; col <= maxXHull; col++) { for (int row = minYHull; row <= maxYHull; row++) { boolean in = p.isInSimpleCurve(col, row, xh, yh, xh.length); if (in) { excludePointsInRainbowHull.remove(new PairInt(col, row)); } } } } } skyPoints.addAll(excludePointsInRainbowHull); } /** * search for rainbow colored points over the entire image, fit an * ellipse to them, and assert that the points have certain colors in * them. If the original fit to an ellipse is not good, the * method divides the rainbow points by contiguous subsets to find best * and similar fits. The last step of color requirement helps to rule * out half ellipse patterns in rocks for instance that have only rock * colors in them. * The return polynomial coefficients are float[]{c0, c1, c2} * where y[i] = c0 + c1 * x[i] + c2 * x[i] * x[i]. * when c2 is negative, the parabola peak is upward (higher y). c2 also indicates the magnitude of the points in powers of 1/10. * @param skyPoints * @param reflectedSunRemoved * @param colorImg * @param xRelativeOffset * @param yRelativeOffset * @param outputRainbowPoints output variable to return found rainbow * points if any * @return polynomial fit coefficients to * y[i] = c0*1 + c1*x[i] + c2*x[i]*x[i]. this may be null if a fit wasn't * possible. */ float[] findRainbowPoints(Set<PairInt> skyPoints, Set<PairInt> reflectedSunRemoved, ImageExt colorImg, int xOffset, int yOffset, boolean skyIsDarkGrey, Set<PairInt> outputRainbowPoints) { Set<PairInt> rainbowPoints = findRainbowColoredPoints(colorImg, reflectedSunRemoved, xOffset, yOffset, skyIsDarkGrey); if (rainbowPoints.isEmpty()) { return null; } if (rainbowPoints.size() < 12) { return null; } // fit a polynomial to rainbow points. // would prefer a circle, but the optical depth of the dispersers and the // orientation of groups of them is not always a slab perpendicular to // the camera int[] minMaxXY = MiscMath.findMinMaxXY(rainbowPoints); log.info("rainbow range in x: " + minMaxXY[0] + " to " + minMaxXY[1]); PolynomialFitter polyFitter = new PolynomialFitter(); //y = c0*1 + c1*x[i] + c2*x[i]*x[i] float[] coef = polyFitter.solveAfterRandomSampling(rainbowPoints); if (coef == null) { return null; } log.info("rainbow polynomial coefficients = " + Arrays.toString(coef)); log.info("image dimensions are " + colorImg.getWidth() + " X " + colorImg.getHeight() + " pixels^2"); polyFitter.plotFit(coef, rainbowPoints, colorImg.getWidth(), colorImg.getHeight(), 23, "rainbow points"); double resid = polyFitter.calcResiduals(coef, rainbowPoints); //TODO: determine this more accurately: if (resid > 5) { Set<PairInt> bestFittingPoints = new HashSet<PairInt>(); coef = polyFitter.solveForBestFittingContiguousSubSets( rainbowPoints, bestFittingPoints, colorImg.getWidth(), colorImg.getHeight()); if (coef == null) { return null; } int w = colorImg.getWidth() - xOffset; int h = colorImg.getHeight() - yOffset; if (bestFittingPoints.size() > (0.3f * (float)(w*h))) { return null; } // assert that colors are as expected, that is, that we don't // have only green and blue from rocks // filter to keep only those with a significant fraction with // cieX > 0.4 and cieY < 0.3 // filter to keep only those with red int nGTX = 0; int nLTY = 0; int nPurpRed = 0; int nOranRed = 0; int nYellow = 0; int nGreen = 0; int nRed = 0; int nWhite = 0; CIEChromaticity cieC = new CIEChromaticity(); ArrayPair cPurpRed = cieC.getRedThroughPurplishRedPolynomial(); ArrayPair cOranRed = cieC.getOrangePolynomial(); ArrayPair cYellow = cieC.getGreenishYellowThroughOrangePolynomial(); ArrayPair cGreen = cieC.getGreenPolynomial(); ArrayPair cRed = cieC.getRedPolynomial(); PointInPolygon pInPoly = new PointInPolygon(); float minCIEX = Float.MAX_VALUE; float maxCIEX = Float.MIN_VALUE; float minCIEY = Float.MAX_VALUE; float maxCIEY = Float.MIN_VALUE; for (PairInt p : bestFittingPoints) { int x = p.getX(); int y = p.getY(); int idx = colorImg.getInternalIndex(x + xOffset, y + yOffset); int r = colorImg.getR(idx); int g = colorImg.getG(idx); int b = colorImg.getB(idx); float rDivB = (float)r/(float)b; float cieX = colorImg.getCIEX(idx); float cieY = colorImg.getCIEY(idx); log.fine(String.format( "(%d,%d) r=%d, g=%d, b=%d rDivB=%f cieX=%f cieY=%f", x, y, r, g, b, rDivB, cieX, cieY)); boolean isWhite = cieC.isCentralWhite(cieX, cieY); if (cieX >= 0.35) { nGTX++; } if ((cieY <= 0.3) || (rDivB < 0.89f)) { nLTY++; } if (cieX < minCIEX) { minCIEX = cieX; } if (cieX > maxCIEX) { maxCIEX = cieX; } if (cieY < minCIEY) { minCIEY = cieY; } if (cieY > maxCIEY) { maxCIEY = cieY; } if (!isWhite) { if (pInPoly.isInSimpleCurve(cieX,cieY, cPurpRed.getX(), cPurpRed.getY(), cPurpRed.getX().length)) { nPurpRed++; } if (pInPoly.isInSimpleCurve(cieX, cieY, cOranRed.getX(), cOranRed.getY(), cOranRed.getX().length)) { nOranRed++; } if (pInPoly.isInSimpleCurve(cieX, cieY, cYellow.getX(), cYellow.getY(), cYellow.getX().length)) { nYellow++; } if (pInPoly.isInSimpleCurve(cieX, cieY, cGreen.getX(), cGreen.getY(), cGreen.getX().length)) { nGreen++; } if (pInPoly.isInSimpleCurve(cieX, cieY, cRed.getX(), cRed.getY(), cRed.getX().length)) { nRed++; } } } float cieXRange = maxCIEX - minCIEX; float cieYRange = maxCIEY - minCIEY; log.info("nGTX=" + nGTX + " nLTY=" + nLTY + " n=" + bestFittingPoints.size() + " " + " CIE: minCIEX=" + minCIEX + " maxCIEX=" + maxCIEX + " minCIEY=" + minCIEY + " maxCIEY=" + maxCIEY + " range=(" + cieXRange + "," + cieYRange + ")" + "\n nPurpRed=" + nPurpRed + " nOranRed=" + nOranRed + " nYellow=" + nYellow + " nGreen=" + nGreen + " nRed=" + nRed + " nOrange/nPurpRed=" + ((float)nOranRed/(float)nPurpRed) + " nOrange/nTot=" + ((float)nOranRed/(float)bestFittingPoints.size()) + " nPurpRed/nTot=" + ((float)nPurpRed/(float)bestFittingPoints.size()) ); rainbowPoints.clear(); debugPlot(bestFittingPoints, colorImg, xOffset, yOffset, "rainbow_before_clr_filter"); float greenFraction = (float)nGreen/(float)bestFittingPoints.size(); if ( (greenFraction < 0.01) || ( (((float)nPurpRed/(float)bestFittingPoints.size()) < 0.05) && (greenFraction < 0.03) ) ) { return null; }/* else if ((cieXRange < 0.08) && (cieYRange < 0.08)) { return null; }*/ if ((nGTX > 10) && ((nLTY > 10) || (!skyIsDarkGrey && ( (((float)nOranRed/(float)nPurpRed) > 1.5) && (nGreen > nPurpRed)) ) || (skyIsDarkGrey && (((float)nOranRed/(float)nPurpRed) > 1.5)) ) ) { float frac = (float)(nGTX + nLTY)/(float)bestFittingPoints.size(); if (frac > 0.002) { rainbowPoints.addAll(bestFittingPoints); } } } outputRainbowPoints.addAll(rainbowPoints); if (!rainbowPoints.isEmpty()) { polyFitter.plotFit(coef, outputRainbowPoints, colorImg.getWidth(), colorImg.getHeight(), 234, "rainbow points"); } log.info("rainbow points size=" + outputRainbowPoints.size()); return coef; } /** * search over the entire image for pixels that are rainbow colored. * * @param colorImg * @param reflectedSunRemoved * @param xOffset * @param yOffset * @param skyIsDarkGrey * @return rainbowPoints pixels from the entire image containing rainbow * colors. */ Set<PairInt> findRainbowColoredPoints(ImageExt colorImg, Set<PairInt> reflectedSunRemoved, int xOffset, int yOffset, boolean skyIsDarkGrey) { AbstractSkyRainbowColors colors = skyIsDarkGrey ? new DarkSkyRainbowColors() : new BrightSkyRainbowColors(); Set<PairInt> set = new HashSet<PairInt>(); for (int col = 0; col < colorImg.getWidth(); col++) { for (int row = 0; row < colorImg.getHeight(); row++) { PairInt p = new PairInt(col - xOffset, row - yOffset); if (reflectedSunRemoved.contains(p)) { continue; } int idx = colorImg.getInternalIndex(col, row); if (col==295 && row>= 173 && row <= 175) { int z = 1; } float cieX = colorImg.getCIEX(idx); float cieY = colorImg.getCIEY(idx); int r = colorImg.getR(idx); int g = colorImg.getG(idx); int b = colorImg.getB(idx); float saturation = colorImg.getSaturation(idx); float brightness = colorImg.getBrightness(idx); if (colors.isInRedThroughPurplishRed(r, g, b, cieX, cieY, saturation, brightness)) { set.add(p); } else if (colors.isInOrangeRed(r, g, b, cieX, cieY, saturation, brightness)) { set.add(p); } else if (colors.isInGreenishYellowOrange(r, g, b, cieX, cieY, saturation, brightness)) { set.add(p); } /*else if (colors.isInYellowishYellowGreen(r, g, b, cieX, cieY, saturation, brightness)) { // finds grass and trees set.add(p); }*/ } } //debugPlot(set, colorImg, xOffset, yOffset, "rainbow_colored_points"); return set; } /** * a method to roughly fit a hull around the rainbow polynomial described * by rainbowCoeff and populated by rainbowPoints. * * @param skyPoints * @param rainbowCoeff coefficients for a 2nd order polynomial * @param rainbowPoints rainbow colored points in the image that fit a polynomial. * there should be 10 or more points at least. * @param originalColorImage * @param xOffset * @param yOffset * @return */ private Hull createRainbowHull(float[] rainbowCoeff, Set<PairInt> rainbowPoints, ImageExt originalColorImage, int xOffset, int yOffset) { int width = originalColorImage.getWidth() - xOffset; int height = originalColorImage.getHeight() - yOffset; rainbowSkeletonX = new float[10]; rainbowSkeletonY = new float[10]; generatePolynomialPoints(rainbowPoints, rainbowCoeff, rainbowSkeletonX, rainbowSkeletonY); float maxOfPointMinDistances = maxOfPointMinDistances(rainbowPoints, rainbowSkeletonX, rainbowSkeletonY); float high = 2 * maxOfPointMinDistances; float low = maxOfPointMinDistances / 2; int nMatched = 0; /* n=21 0,20 1 2 3 4 5 6 7 8 9 19 18 17 16 15 14 13 12 11 10 */ float[] xPoly = new float[2 * rainbowSkeletonX.length + 1]; float[] yPoly = new float[xPoly.length]; int nMaxIter = 5; int nIter = 0; int eps = (int)(0.15f * rainbowPoints.size()); while ((low < high) && (nIter < nMaxIter)) { float mid = (high + low)/2.f; hullHalfWidth = mid; populatePolygon(rainbowSkeletonX, rainbowSkeletonY, mid, xPoly, yPoly, rainbowCoeff, width, height); nMatched = nPointsInPolygon(rainbowPoints, xPoly, yPoly); log.info("low=" + low + " high=" + high + " mid=" + mid + " nMatched=" + nMatched + " out of " + rainbowPoints.size()); if (Math.abs(nMatched - rainbowPoints.size()) < eps) { if (low < mid) { // decrease high so next mid is lower high = mid; } else { break; } } else { // nMatched < rainbowPoints.size() // increase low so next mid is higher low = mid; } nIter++; } //TODO: once a reasonable hullHalfWidth has been determined, // may want to regenerate the hull with higher resolution, // that is 5 or 10 times the number of skeleton points on // each side Hull hull = new Hull(); hull.xHull = xPoly; hull.yHull = yPoly; return hull; } protected void generatePolynomialPoints(Set<PairInt> points, float[] polyCoeff, float[] outputX, float[] outputY) { PolynomialFitter fitter = new PolynomialFitter(); float[] minXYMaxXY = fitter.determineGoodEndPoints(polyCoeff, points); // find the furthest points that have the smallest residuals on each side int minX = (int)minXYMaxXY[0]; int yForMinX = (int)minXYMaxXY[1]; int maxX = (int)minXYMaxXY[2]; int yForMaxX = (int)minXYMaxXY[3]; log.info("polyCoeff=" + Arrays.toString(polyCoeff) + " endpoints=(" + minX + "," + yForMinX + ") (" + maxX + "," + yForMaxX + ")"); int n = outputX.length; // max-min divided by 9 gives 8 more points float deltaX = (maxX - minX)/(float)(n - 1); outputX[0] = minX; outputY[0] = yForMinX; for (int i = 1; i < (n - 1); i++) { outputX[i] = outputX[i - 1] + deltaX; outputY[i] = polyCoeff[0] + polyCoeff[1] * outputX[i] + polyCoeff[2] * outputX[i] * outputX[i]; } outputX[n - 1] = maxX; outputY[n - 1] = yForMaxX; } protected float maxOfPointMinDistances(Set<PairInt> rainbowPoints, float[] xc, float[] yc) { double maxDistSq = Double.MIN_VALUE; for (PairInt p : rainbowPoints) { int x = p.getX(); int y = p.getY(); double minDistSq = Double.MAX_VALUE; int minIdx = -1; for (int i = 0; i < xc.length; i++) { float diffX = xc[i] - x; float diffY = yc[i] - y; float dist = (diffX * diffX) + (diffY * diffY); if (dist < minDistSq) { minDistSq = dist; minIdx = i; } } if (minDistSq > maxDistSq) { maxDistSq = minDistSq; } /*log.info(String.format( "(%d,%d) is closest to poly point (%f,%f) dist=%f", x, y, xc[minIdx], yc[minIdx], (float)Math.sqrt(minDistSq))); */ } return (float)Math.sqrt(maxDistSq); } /** populate outputXPoly and outputYPoly with points perpendicular to x and y * at distances dist. note that the lengths of outputXPoly and outputYPoly * should be 2*x.length+1. * Also note that one wants the separation between points in x and y * to be larger than dist (else, the concave portion of writing the hull * has a retrograde order and appearance). */ protected void populatePolygon(float[] x, float[] y, float dist, float[] outputXPoly, float[] outputYPoly, float[] polynomialCoeff, int imgWidth, int imgHeight) { if (x == null || y == null) { throw new IllegalArgumentException("neither x nor y can be null"); } if (x.length != y.length) { throw new IllegalArgumentException("x and y must be the same length"); } if (outputXPoly == null || outputYPoly == null) { throw new IllegalArgumentException( "neither outputXPoly nor outputYPoly can be null"); } if (outputXPoly.length != outputYPoly.length) { throw new IllegalArgumentException( "outputXPoly and outputYPoly must be the same length"); } if (polynomialCoeff == null) { throw new IllegalArgumentException( "polynomialCoeff cannot be null"); } if (polynomialCoeff.length != 3) { throw new IllegalArgumentException( "polynomialCoeff.length has to be 3"); } if (outputXPoly.length != (2*x.length + 1)) { throw new IllegalArgumentException("outputXPoly.length must be " + " (2 * x.length) + 1"); } /* y = c0*1 + c1*x[i] + c2*x[i]*x[i] dy/dx = c1 + 2*c2*x[i] = tan theta */ int n = outputXPoly.length; /* want them in order so using count0 and count1 n=21 0,20 1 2 3 4 5 6 7 8 9 19 18 17 16 15 14 13 12 11 10 */ int count0 = 0; int count1 = n - 2; for (int i = 0; i < x.length; i++) { double dydx = polynomialCoeff[1] + (2. * polynomialCoeff[2] * x[i]); if (dydx == 0) { // same x, y's are +- dist outputXPoly[count0] = x[i]; outputYPoly[count0] = y[i] + dist; count0++; outputXPoly[count1] = x[i]; outputYPoly[count1] = y[i] - dist; count1 continue; } double tangentSlope = -1./dydx; double theta = Math.atan(tangentSlope); double dy = dist * Math.sin(theta); double dx = dist * Math.cos(theta); if ((count0 == 0) && (x[i] == 0)) { dy = dist; dx = 0; } else if ( ((count0 == ((x.length/2) - 1) || (count0 == (x.length/2)))) && (x[i] == (imgWidth - 1))) { dy = dist; dx = 0; } //System.out.println("i=" + i + " theta=" + theta // + " x[i]=" + x[i] + " dx=" + dx + " dy=" + dy); float xHigh = (float)(x[i] + dx); float yHigh = (float)(y[i] + dy); float xLow = (float)(x[i] - dx); float yLow = (float)(y[i] - dy); if (theta < 0) { float tx = xHigh; float ty = yHigh; xHigh = xLow; yHigh = yLow; xLow = tx; yLow = ty; } if (xHigh < 0) { xHigh = 0; } if (yHigh < 0) { yHigh = 0; } if (xLow < 0) { xLow = 0; } if (yLow < 0) { yLow = 0; } if (xLow > (imgWidth - 1)) { xLow = (imgWidth - 1); } if (xHigh > (imgWidth - 1)) { xHigh = (imgWidth - 1); } if (yLow > (imgHeight - 1)) { yLow = (imgHeight - 1); } if (yHigh > (imgHeight - 1)) { yHigh = (imgHeight - 1); } outputXPoly[count0] = xHigh; outputYPoly[count0] = yHigh; count0++; outputXPoly[count1] = xLow; outputYPoly[count1] = yLow; count1 } outputXPoly[outputXPoly.length - 1] = outputXPoly[0]; outputYPoly[outputXPoly.length - 1] = outputYPoly[0]; } protected int nPointsInPolygon(Set<PairInt> rainbowPoints, float[] xPoly, float[] yPoly) { PointInPolygon pIn = new PointInPolygon(); int nInside = 0; for (PairInt p : rainbowPoints) { float x = p.getX(); float y = p.getY(); boolean ans = pIn.isInSimpleCurve(x, y, xPoly, yPoly, xPoly.length); if (ans) { nInside++; } } return nInside; } void debugPlot(Set<PairInt> extSkyPoints, Image originalColorImage, int xOffset, int yOffset, String outputPrefixForFileName) { //plot is made in aspects } }
package algorithms.imageProcessing.features; import algorithms.imageProcessing.GreyscaleImage; import algorithms.imageProcessing.ImageProcessor; import algorithms.misc.MiscMath; import algorithms.util.OneDIntArray; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** CAVEAT: small amount of testing done, not yet throughly tested. An implementation of Histograms of Oriented Gradients constructed from reading the following papers: <pre> "Histograms of Oriented Gradients for Human Detection" by Dalal and Triggs, 2010 and "Distinctive Image Features from Scale-Invariant Keypoints" by Lowe, 2004 </pre> The histograms of oriented gradients are constructed to compare the 2 part data of gradient angle and gradient magnitude between regions within different images as a feature descriptor. The feature is defined over several pixels surrounding the central keypoint in a pattern to improve the measurement. The GradientIntegralHistogram is used to store histograms of values that that are counts defined by gradient magnitudes in bins of orientation. As recommended by Dalal & Triggs, 9 bins are used for 180 degrees of gradient angle range. The building of the integral image has a runtime complexity of O(N_pixels) for the gradient and O(N_pixels) for the histogram integral image. Extraction of histogram data is 4 steps, just as in summed area tables, but there is additionally the copy which is nBins steps. The extraction of data is at the "cell" level, which is recommended to be 6 X 6 pixels^2 by Dalal and Triggs. a block of cells is gathered for a point and that is an addition of the N_cells X N_cells histograms. Before the addition, block level normalization is calculated for each cell. The block level normalization uses L2NormHys. They found best results using normalization of each cell histogram by the total over the block. The total number of values is summed over all cells within the block and a normalization factor for each cell is then computed using that block total. The individually normalized cells are then added over the block to create the block histogram. for each cell calculate cell_total_count. total_block_count = sum over cells ( cell_total_count ) for each cell, normalization is 1/total_block_count then the block histogram is added over the same bins in each cell. To keep the block histogram as integer but normalized to same max value could apply a further factor of max possible value for a block being, for example (2X2)*(6X6)*(255) = 36720. Note that a shift is needed for identifying the bin that is the canonical angle 0, that is a shift specific to a dominant angle correction for the histogram. That shift will be applied during the intersection stage to produce a canonicalized feature in a rotation corrected reference frame. (Note that for the use case here, the reference frame orientation will be supplied to the method. it's learned from the mser ellipse in one use case for example. so the application of a dominant orientation will be the same, but the calculation will not be performed for it. though that could be added as a method later...not necessary for current requirements). Comparison of block feature is then a histogram intersection, where normally 0 is no intersection, hence maximally different, and an intersection equal to the max value is maximally similar. (see the method ColorHistogram.intersection, but here, the normalization will already have been applied instead of determined in the method). Other details are in converting the intersection to a cost or score and specialized methods for that specific to this project will be present in this class. @author nichole */ public class HOGs { // 9 is default private final int nAngleBins; // 6 x 6 is recommended private final int N_PIX_PER_CELL_DIM; // 2x2 or 3x3 is recommended private final int N_CELLS_PER_BLOCK_DIM; // histogrm integral images with a sindowed sum of N_PIX_PER_CELL_DIM private final int[][] gHists; private final int w; private final int h; private boolean debug = false; //TODO: calculate the limits in nPixels this can handle due to // using integers instead of long for storage. // 8.4 million pix, roughly 2900 X 2900 public HOGs(GreyscaleImage rgb) { nAngleBins = 9; N_PIX_PER_CELL_DIM = 4; N_CELLS_PER_BLOCK_DIM = 2; w = rgb.getWidth(); h = rgb.getHeight(); gHists = init(rgb); } public HOGs(GreyscaleImage rgb, int nCellsPerDim, int nPixPerCellDim) { nAngleBins = 9; N_PIX_PER_CELL_DIM = nPixPerCellDim; N_CELLS_PER_BLOCK_DIM = nCellsPerDim; w = rgb.getWidth(); h = rgb.getHeight(); gHists = init(rgb); } public HOGs(GreyscaleImage gradientXY, GreyscaleImage theta) { nAngleBins = 9; N_PIX_PER_CELL_DIM = 4; N_CELLS_PER_BLOCK_DIM = 2; w = gradientXY.getWidth(); h = gradientXY.getHeight(); gHists = init(gradientXY, theta); } public void setToDebug() { debug = true; } private int[][] init(GreyscaleImage rgb) { ImageProcessor imageProcessor = new ImageProcessor(); GreyscaleImage[] gXgY = imageProcessor.createSobelGradients(rgb); GreyscaleImage theta = imageProcessor.computeTheta180(gXgY[0], gXgY[1]); GreyscaleImage gXY = imageProcessor.combineConvolvedImages(gXgY[0], gXgY[1]); if (debug) { algorithms.misc.MiscDebug.writeImage(gXgY[0], "_gX_"); algorithms.misc.MiscDebug.writeImage(gXgY[1], "_gY_"); algorithms.misc.MiscDebug.writeImage(gXY, "_gXY_"); algorithms.misc.MiscDebug.writeImage(theta, "_theta_"); } return init(gXY, theta); } private int[][] init(GreyscaleImage gradientXY, GreyscaleImage theta) { if (w != gradientXY.getWidth() || h != gradientXY.getHeight()) { throw new IllegalArgumentException("gradient and theta must be same size"); } if (w != theta.getWidth() || h != theta.getHeight()) { throw new IllegalArgumentException("gradient and theta must be same size"); } if (debug) { algorithms.misc.MiscDebug.writeImage(gradientXY, "_gXY_"); algorithms.misc.MiscDebug.writeImage(theta, "_theta_"); } GradientIntegralHistograms gh = new GradientIntegralHistograms(); int[][] histograms = gh.createHistograms(gradientXY, theta, nAngleBins); //apply a windowed sum across the integral image gh.applyWindowedSum(histograms, w, h, N_PIX_PER_CELL_DIM); return histograms; } /** * CAVEAT: small amount of testing done, not yet throughly tested. * * extract the block surrounding the feature. * the number of pixels in a cell and the number of cells in block were set during * construction. * * @param x * @param y * @param outHist */ public void extractFeature(int x, int y, int[] outHist) { if (outHist.length != nAngleBins) { throw new IllegalArgumentException("outHist.length != nAngleBins"); } if (x < 0 || y < 0 || x >= w || y >= h) { throw new IllegalArgumentException("x or y is out of bounds of " + "original image"); } // uses the block normalization recomended by Dalal & Triggs, // the summary of histogram counts over all cells // is used to normaliza each cell by that sum. int nH = N_CELLS_PER_BLOCK_DIM * N_CELLS_PER_BLOCK_DIM; double blockTotal = 0; List<OneDIntArray> cells = new ArrayList<OneDIntArray>(nH); for (int cX = 0; cX < N_CELLS_PER_BLOCK_DIM; ++cX) { int cXOff = -(N_CELLS_PER_BLOCK_DIM/2) + cX; int x2 = x + (cXOff * N_PIX_PER_CELL_DIM); if ((x2 + N_PIX_PER_CELL_DIM - 1) < 0) { break; } else if (x2 < 0) { x2 = 0; } else if (x2 >= w) { break; } for (int cY = 0; cY < N_CELLS_PER_BLOCK_DIM; ++cY) { int cYOff = -(N_CELLS_PER_BLOCK_DIM/2) + cY; int y2 = y + (cYOff * N_PIX_PER_CELL_DIM); if ((y2 + N_PIX_PER_CELL_DIM - 1) < 0) { break; } else if (y2 < 0) { y2 = 0; } else if (y2 >= h) { break; } int pixIdx = (y2 * w) + x2; int[] out = Arrays.copyOf(gHists[pixIdx], gHists[pixIdx].length); cells.add(new OneDIntArray(out)); int t = sumCounts(out); blockTotal += (t * t); } } blockTotal /= (double)cells.size(); double norm = 1./Math.sqrt(blockTotal + 0.0001); float maxBlock = (N_CELLS_PER_BLOCK_DIM * N_CELLS_PER_BLOCK_DIM) * (N_PIX_PER_CELL_DIM * N_PIX_PER_CELL_DIM) * 255,f; norm *= maxBlock; Arrays.fill(outHist, 0, outHist.length, 0); for (int i = 0; i < cells.size(); ++i) { int[] a = cells.get(i).a; for (int j = 0; j < a.length; ++j) { //v /= Math.sqrt(blockTotal + 0.0001); a[j] = (int)Math.round(norm * a[j]); } add(outHist, a); } /* part of a block of 3 X 3 cells 2 2 2 2 1 1 1 1 0 0 0 0 -9 -8 -7 -6 -5 -4 -3 -2 -1 * 1 2 3 4 5 6 7 9 * */ } /** * CAVEAT: small amount of testing done, not yet throughly tested. * * calculate the intersection of histA and histB which have already * been normalized to the same scale. * A result of 0 is maximally dissimilar and a result of 1 is maximally similar. * * The orientations are needed to compare the correct rotated bins to one another. * Internally, orientation of 90 leads to no shift for rotation, * and orientation near 0 results in rotation of nBins/2, etc... * * Note that an orientation of 90 is a unit vector from x,y=0,0 to * x,y=0,1. * * @param histA * @param orientationA * @param histB * @param orientationB * @return */ public float intersection(int[] histA, int orientationA, int[] histB, int orientationB) { if ((histA.length != histB.length)) { throw new IllegalArgumentException( "histA and histB must be same dimensions"); } if (orientationA < 0 || orientationA > 180 || orientationB < 0 || orientationB > 180) { throw new IllegalArgumentException("orientations must be in range 0 to 180," + " inclusixe"); } if (orientationA == 180) { orientationA = 0; } if (orientationB == 180) { orientationB = 0; } int nBins = histA.length; int binWidth = 180/nBins; int shiftA = (orientationA - 90)/binWidth; int shiftB = (orientationB - 90)/binWidth; /* histograms are already normalized K(a,b) = (summation_over_i_from_1_to_n( min(a_i, b_i)) / (min(summation_over_i(a_i), summation_over_i(b_i)) */ float sum = 0; float sumA = 0; float sumB = 0; for (int j = 0; j < nBins; ++j) { int idxA = j + shiftA; if (idxA < 0) { idxA += nBins; } else if (idxA > (nBins - 1 )) { idxA -= nBins; } int idxB = j + shiftB; if (idxB < 0) { idxB += nBins; } else if (idxB > (nBins - 1 )) { idxB -= nBins; } float yA = histA[idxA]; float yB = histB[idxB]; sum += Math.min(yA, yB); sumA += yA; sumB += yB; //System.out.println(" " + yA + " -- " + yB + " sum="+sum + ", " + sumA + "," + sumB); } float sim = sum / ((float)Math.min(sumA, sumB)); return sim; } /** * CAVEAT: small amount of testing done, not yet throughly tested. * * calculate the intersection of histA and histB which have already * been normalized to the same scale. * A result of 0 is maximally dissimilar and a result of 1 is maximally similar. * * The orientations are needed to compare the correct rotated bins to one another. * Internally, orientation of 90 leads to no shift for rotation, * and orientation near 0 results in rotation of nBins/2, etc... * * Note that an orientation of 90 is a unit vector from x,y=0,0 to * x,y=0,1. * * @param histA * @param orientationA * @param histB * @param orientationB * @return */ public float ssd(int[] histA, int orientationA, int[] histB, int orientationB) { if ((histA.length != histB.length)) { throw new IllegalArgumentException( "histA and histB must be same dimensions"); } if (orientationA < 0 || orientationA > 180 || orientationB < 0 || orientationB > 180) { throw new IllegalArgumentException("orientations must be in range 0 to 180," + " inclusixe"); } if (orientationA == 180) { orientationA = 0; } if (orientationB == 180) { orientationB = 0; } double sumDiff = 0; int nBins = histA.length; int binWidth = 180/nBins; int shiftA = (orientationA - 90)/binWidth; int shiftB = (orientationB - 90)/binWidth; for (int j = 0; j < nBins; ++j) { int idxA = j + shiftA; if (idxA < 0) { idxA += nBins; } else if (idxA > (nBins - 1 )) { idxA -= nBins; } int idxB = j + shiftB; if (idxB < 0) { idxB += nBins; } else if (idxB > (nBins - 1 )) { idxB -= nBins; } float yA = histA[idxA]; float yB = histB[idxB]; float diff = yA - yB; sumDiff += (diff * diff); } sumDiff /= (double)nBins; float maxValue = Math.max(MiscMath.findMax(histA), MiscMath.findMax(histB)); sumDiff = Math.sqrt(sumDiff)/maxValue; return (float)sumDiff; } private int sumCounts(int[] hist) { int sum = 0; for (int v : hist) { sum += v; } return sum; } private void add(int[] addTo, int[] addFrom) { for (int i = 0; i < addTo.length; ++i) { addTo[i] += addFrom[i]; } } }
package eu.bcvsolutions.idm.core.eav.service.impl; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.UUID; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.transaction.annotation.Transactional; import org.testng.collections.Lists; import com.fasterxml.jackson.databind.ObjectMapper; import eu.bcvsolutions.idm.core.api.config.domain.EventConfiguration; import eu.bcvsolutions.idm.core.api.domain.ConfigurationMap; import eu.bcvsolutions.idm.core.api.domain.PriorityType; import eu.bcvsolutions.idm.core.api.domain.RoleRequestState; import eu.bcvsolutions.idm.core.api.dto.IdmContractPositionDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto; import eu.bcvsolutions.idm.core.api.dto.IdmRoleDto; import eu.bcvsolutions.idm.core.api.dto.IdmRoleRequestDto; import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleRequestFilter; import eu.bcvsolutions.idm.core.api.dto.projection.IdmIdentityProjectionDto; import eu.bcvsolutions.idm.core.api.exception.ForbiddenEntityException; import eu.bcvsolutions.idm.core.api.rest.BaseController; import eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService; import eu.bcvsolutions.idm.core.api.service.IdmIdentityService; import eu.bcvsolutions.idm.core.api.service.IdmRoleRequestService; import eu.bcvsolutions.idm.core.api.service.LookupService; import eu.bcvsolutions.idm.core.eav.api.domain.PersistentType; import eu.bcvsolutions.idm.core.eav.api.dto.FormDefinitionAttributes; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormProjectionDto; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto; import eu.bcvsolutions.idm.core.eav.api.event.IdentityProjectionEvent; import eu.bcvsolutions.idm.core.eav.api.event.IdentityProjectionEvent.IdentityProjectionEventType; import eu.bcvsolutions.idm.core.eav.api.service.FormService; import eu.bcvsolutions.idm.core.eav.api.service.IdmFormProjectionService; import eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission; import eu.bcvsolutions.idm.core.model.entity.IdmIdentity; import eu.bcvsolutions.idm.core.model.entity.eav.IdmIdentityFormValue; import eu.bcvsolutions.idm.core.security.api.domain.GuardedString; import eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission; import eu.bcvsolutions.idm.core.security.evaluator.eav.IdentityFormValueEvaluator; import eu.bcvsolutions.idm.core.security.evaluator.identity.SelfIdentityEvaluator; import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowHistoricProcessInstanceDto; import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowProcessInstanceDto; import eu.bcvsolutions.idm.test.api.AbstractRestTest; import eu.bcvsolutions.idm.test.api.TestHelper; @Transactional public class DefaultIdentityProjectionManagerIntegrationTest extends AbstractRestTest { @Autowired private ApplicationContext context; @Autowired private FormService formService; @Autowired private ObjectMapper mapper; @Autowired private IdmFormProjectionService projectionService; @Autowired private LookupService lookupService; @Autowired private IdmIdentityService identityService; @Autowired private IdmIdentityRoleService identityRoleService; @Autowired private IdmRoleRequestService roleRequestService; @Autowired private EventConfiguration eventConfiguration; private DefaultIdentityProjectionManager manager; // FIXME: move to api (workflow config constant) private static final String APPROVE_BY_SECURITY_ENABLE = "idm.sec.core.wf.approval.security.enabled"; private static final String APPROVE_BY_MANAGER_ENABLE = "idm.sec.core.wf.approval.manager.enabled"; private static final String APPROVE_BY_USERMANAGER_ENABLE = "idm.sec.core.wf.approval.usermanager.enabled"; private static final String APPROVE_BY_HELPDESK_ENABLE = "idm.sec.core.wf.approval.helpdesk.enabled"; @Before public void init() { manager = context.getAutowireCapableBeanFactory().createBean(DefaultIdentityProjectionManager.class); getHelper().setConfigurationValue(APPROVE_BY_SECURITY_ENABLE, false); getHelper().setConfigurationValue(APPROVE_BY_MANAGER_ENABLE, false); getHelper().setConfigurationValue(APPROVE_BY_HELPDESK_ENABLE, false); getHelper().setConfigurationValue(APPROVE_BY_USERMANAGER_ENABLE, false); } @Test public void testSaveAndGetSimpleIdentity() { IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); IdmIdentityProjectionDto projection = new IdmIdentityProjectionDto(identity); IdmIdentityProjectionDto createdProjection = manager .publish(new IdentityProjectionEvent(IdentityProjectionEventType.CREATE, projection)) .getContent(); Assert.assertNotNull(createdProjection); Assert.assertNotNull(createdProjection.getId()); Assert.assertEquals(createdProjection.getId(), createdProjection.getIdentity().getId()); Assert.assertEquals(identity.getUsername(), createdProjection.getIdentity().getUsername()); Assert.assertNull(createdProjection.getContract()); Assert.assertTrue(createdProjection.getOtherContracts().isEmpty()); Assert.assertTrue(createdProjection.getOtherPositions().isEmpty()); Assert.assertTrue(createdProjection.getIdentityRoles().isEmpty()); } @Test public void testSaveAndGetFullProjectionGreenLine() { loginAsAdmin(); // role request implementer is needed Assert.assertFalse(eventConfiguration.isAsynchronous()); try { // prepare eav definition IdmFormAttributeDto attributeOne = new IdmFormAttributeDto(getHelper().createName()); attributeOne.setPersistentType(PersistentType.SHORTTEXT); IdmFormAttributeDto attributeTwo = new IdmFormAttributeDto(getHelper().createName()); attributeTwo.setPersistentType(PersistentType.SHORTTEXT); IdmFormDefinitionDto formDefinitionOne = formService.createDefinition(IdmIdentityDto.class, getHelper().createName(), Lists.newArrayList(attributeOne, attributeTwo)); attributeOne = formDefinitionOne.getMappedAttributeByCode(attributeOne.getCode()); attributeTwo = formDefinitionOne.getMappedAttributeByCode(attributeTwo.getCode()); IdmFormAttributeDto attributeThree = new IdmFormAttributeDto(getHelper().createName()); attributeThree.setPersistentType(PersistentType.SHORTTEXT); IdmFormDefinitionDto formDefinitionTwo = formService.createDefinition(IdmIdentityDto.class, getHelper().createName(), Lists.newArrayList(attributeThree)); attributeThree = formDefinitionTwo.getMappedAttributeByCode(attributeThree.getCode()); IdmFormAttributeDto attributeContract = new IdmFormAttributeDto(getHelper().createName()); attributeContract.setPersistentType(PersistentType.SHORTTEXT); IdmFormDefinitionDto formDefinitionContract = formService.createDefinition( IdmIdentityContractDto.class, getHelper().createName(), Lists.newArrayList(attributeContract)); attributeContract = formDefinitionContract.getMappedAttributeByCode(attributeContract.getCode()); IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); IdmIdentityProjectionDto projection = new IdmIdentityProjectionDto(identity); // set eav IdmFormInstanceDto instanceOne = new IdmFormInstanceDto(); instanceOne.setFormDefinition(formDefinitionOne); IdmFormValueDto valueOne = new IdmFormValueDto(attributeOne); valueOne.setValue(getHelper().createName()); IdmFormValueDto valueTwo = new IdmFormValueDto(attributeTwo); valueTwo.setValue(getHelper().createName()); instanceOne.setValues(Lists.newArrayList(valueOne, valueTwo)); IdmFormInstanceDto instanceTwo = new IdmFormInstanceDto(); instanceTwo.setFormDefinition(formDefinitionTwo); IdmFormValueDto valueThree = new IdmFormValueDto(attributeThree); valueThree.setValue(getHelper().createName()); instanceTwo.setValues(Lists.newArrayList(valueThree)); identity.setEavs(Lists.newArrayList(instanceOne, instanceTwo)); // set contract IdmIdentityContractDto primeContract = new IdmIdentityContractDto(); primeContract.setMain(true); primeContract.setWorkPosition(getHelper().createTreeNode().getId()); primeContract.setPosition(getHelper().createName()); primeContract.setValidFrom(LocalDate.now().minus(1l, ChronoUnit.DAYS)); primeContract.setValidFrom(LocalDate.now().plus(1l, ChronoUnit.DAYS)); projection.setContract(primeContract); IdmFormInstanceDto instanceContract = new IdmFormInstanceDto(); instanceContract.setFormDefinition(formDefinitionContract); IdmFormValueDto valueContract = new IdmFormValueDto(attributeContract); valueContract.setValue(getHelper().createName()); instanceContract.setValues(Lists.newArrayList(valueContract)); primeContract.setEavs(Lists.newArrayList(instanceContract)); // set other contract IdmIdentityContractDto otherContractOne = new IdmIdentityContractDto(); otherContractOne.setWorkPosition(getHelper().createTreeNode().getId()); otherContractOne.setPosition(getHelper().createName()); IdmIdentityContractDto otherContractTwo = new IdmIdentityContractDto(UUID.randomUUID()); // preset uuid otherContractTwo.setWorkPosition(getHelper().createTreeNode().getId()); otherContractTwo.setPosition(getHelper().createName()); projection.setOtherContracts(Lists.newArrayList(otherContractOne, otherContractTwo)); // set other contract position IdmContractPositionDto positionOne = new IdmContractPositionDto(); positionOne.setWorkPosition(getHelper().createTreeNode().getId()); positionOne.setPosition(getHelper().createName()); IdmContractPositionDto positionTwo = new IdmContractPositionDto(); positionTwo.setWorkPosition(getHelper().createTreeNode().getId()); positionTwo.setPosition(getHelper().createName()); positionTwo.setIdentityContract(otherContractTwo.getId()); projection.setOtherPositions(Lists.newArrayList(positionOne, positionTwo)); // set assigned roles IdmRoleDto roleOne = getHelper().createRole(); IdmRoleDto roleTwo = getHelper().createRole(); IdmIdentityRoleDto identityRoleOne = new IdmIdentityRoleDto(); identityRoleOne.setRole(roleOne.getId()); identityRoleOne.setValidFrom(LocalDate.now().plus(2l, ChronoUnit.DAYS)); IdmIdentityRoleDto identityRoleTwo = new IdmIdentityRoleDto(); identityRoleTwo.setRole(roleTwo.getId()); identityRoleTwo.setIdentityContract(otherContractTwo.getId()); projection.setIdentityRoles(Lists.newArrayList(identityRoleOne, identityRoleTwo)); IdentityProjectionEvent identityProjectionEvent = new IdentityProjectionEvent(IdentityProjectionEventType.CREATE, projection); identityProjectionEvent.setPriority(PriorityType.IMMEDIATE); projection = manager .publish(identityProjectionEvent) .getContent(); IdmIdentityProjectionDto createdProjection = manager.get(projection); Assert.assertNotNull(createdProjection); Assert.assertNotNull(createdProjection.getId()); Assert.assertEquals(createdProjection.getId(), createdProjection.getIdentity().getId()); // eavs Assert.assertEquals(valueOne.getValue(), createdProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionOne.getId())) .findFirst() .get() .toSinglePersistentValue(attributeOne.getCode())); Assert.assertEquals(valueTwo.getValue(), createdProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionOne.getId())) .findFirst() .get() .toSinglePersistentValue(attributeTwo.getCode())); Assert.assertEquals(valueThree.getValue(), createdProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionTwo.getId())) .findFirst() .get() .toSinglePersistentValue(attributeThree.getCode())); // prime contract IdmIdentityContractDto createdPrimeContract = createdProjection.getContract(); Assert.assertEquals(primeContract.getWorkPosition(), createdPrimeContract.getWorkPosition()); Assert.assertEquals(primeContract.getPosition(), createdPrimeContract.getPosition()); Assert.assertEquals(primeContract.getValidFrom(), createdPrimeContract.getValidFrom()); Assert.assertEquals(primeContract.getValidTill(), createdPrimeContract.getValidTill()); Assert.assertEquals(createdProjection.getIdentity().getId(), createdPrimeContract.getIdentity()); // eavs Assert.assertEquals(valueContract.getValue(), createdProjection .getContract() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionContract.getId())) .findFirst() .get() .toSinglePersistentValue(attributeContract.getCode())); // other contract Assert.assertEquals(2, createdProjection.getOtherContracts().size()); Assert.assertTrue(createdProjection.getOtherContracts().stream().anyMatch(c -> { return c.getWorkPosition().equals(otherContractOne.getWorkPosition()) && c.getPosition().equals(otherContractOne.getPosition()); })); Assert.assertTrue(createdProjection.getOtherContracts().stream().anyMatch(c -> { return c.getWorkPosition().equals(otherContractTwo.getWorkPosition()) && c.getPosition().equals(otherContractTwo.getPosition()) && c.getId().equals(otherContractTwo.getId()); // preserve id })); // other position Assert.assertEquals(2, createdProjection.getOtherPositions().size()); Assert.assertTrue(createdProjection.getOtherPositions().stream().anyMatch(p -> { return p.getWorkPosition().equals(positionOne.getWorkPosition()) && p.getPosition().equals(positionOne.getPosition()) && p.getIdentityContract().equals(createdPrimeContract.getId()); })); Assert.assertTrue(createdProjection.getOtherPositions().stream().anyMatch(p -> { return p.getWorkPosition().equals(positionTwo.getWorkPosition()) && p.getPosition().equals(positionTwo.getPosition()) && p.getIdentityContract().equals(positionTwo.getIdentityContract()); })); // assigned roles // check directly by service IdmRoleRequestFilter roleRequestFilter = new IdmRoleRequestFilter(); roleRequestFilter.setApplicantId(createdProjection.getIdentity().getId()); List<IdmRoleRequestDto> roleRequests = roleRequestService.find(roleRequestFilter, null).getContent(); Assert.assertFalse(roleRequests.isEmpty()); roleRequests.forEach(r -> { System.out.println(".... [" + r.getState() + "] ["+ r.getWfProcessId() +"] " + r.getLog()); if (r.getWfProcessId() != null) { Object p = r.getEmbedded().get(IdmRoleRequestDto.WF_PROCESS_FIELD); if (p != null) { if (p instanceof WorkflowProcessInstanceDto) { WorkflowProcessInstanceDto process = (WorkflowProcessInstanceDto) p; System.out.println(".... process [" + process.getName() + "] [" + process.getProcessDefinitionId() +"] [" + process.getProcessDefinitionKey() +"] [" + process.getProcessDefinitionName() +"]"); // task ... } if (p instanceof WorkflowHistoricProcessInstanceDto) { WorkflowHistoricProcessInstanceDto process = (WorkflowHistoricProcessInstanceDto) p; System.out.println(".... history [" + process.getName() + "] [" + process.getProcessDefinitionId() +"] [" + process.getProcessDefinitionKey() +"]"); } } else { System.out.println(".... process not found"); } } }); Assert.assertTrue(roleRequests.stream().allMatch(r -> r.getState() == RoleRequestState.EXECUTED)); List<IdmIdentityRoleDto> assignedRoles = identityRoleService.findAllByIdentity(createdProjection.getIdentity().getId()); Assert.assertEquals(2, assignedRoles.size()); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> { return ir.getRole().equals(roleOne.getId()) && ir.getValidFrom().equals(identityRoleOne.getValidFrom()) && ir.getIdentityContract().equals(createdPrimeContract.getId()); })); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> { return ir.getRole().equals(roleTwo.getId()) && ir.getIdentityContract().equals(otherContractTwo.getId()); })); // check by projection Assert.assertEquals(2, createdProjection.getIdentityRoles().size()); Assert.assertTrue(createdProjection.getIdentityRoles().stream().anyMatch(ir -> { return ir.getRole().equals(roleOne.getId()) && ir.getValidFrom().equals(identityRoleOne.getValidFrom()) && ir.getIdentityContract().equals(createdPrimeContract.getId()); })); Assert.assertTrue(createdProjection.getIdentityRoles().stream().anyMatch(ir -> { return ir.getRole().equals(roleTwo.getId()) && ir.getIdentityContract().equals(otherContractTwo.getId()); })); // simple update String newUsername = getHelper().createName(); createdProjection.getIdentity().setUsername(newUsername); IdmIdentityProjectionDto updatedProjection = manager .publish(new IdentityProjectionEvent(IdentityProjectionEventType.UPDATE, createdProjection)) .getContent(); // IdmIdentityProjectionDto updatedProjection = manager.get(projection); Assert.assertNotNull(updatedProjection); Assert.assertNotNull(updatedProjection.getId()); Assert.assertEquals(createdProjection.getId(), updatedProjection.getIdentity().getId()); Assert.assertEquals(newUsername, updatedProjection.getIdentity().getUsername()); // eavs Assert.assertEquals(valueOne.getValue(), updatedProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionOne.getId())) .findFirst() .get() .toSinglePersistentValue(attributeOne.getCode())); Assert.assertEquals(valueTwo.getValue(), updatedProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionOne.getId())) .findFirst() .get() .toSinglePersistentValue(attributeTwo.getCode())); Assert.assertEquals(valueThree.getValue(), updatedProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionTwo.getId())) .findFirst() .get() .toSinglePersistentValue(attributeThree.getCode())); // prime contract IdmIdentityContractDto updatedPrimeContract = updatedProjection.getContract(); Assert.assertEquals(primeContract.getWorkPosition(), updatedPrimeContract.getWorkPosition()); Assert.assertEquals(primeContract.getPosition(), updatedPrimeContract.getPosition()); Assert.assertEquals(primeContract.getValidFrom(), updatedPrimeContract.getValidFrom()); Assert.assertEquals(primeContract.getValidTill(), updatedPrimeContract.getValidTill()); Assert.assertEquals(updatedProjection.getIdentity().getId(), updatedPrimeContract.getIdentity()); // other contract Assert.assertEquals(2, updatedProjection.getOtherContracts().size()); Assert.assertTrue(updatedProjection.getOtherContracts().stream().anyMatch(c -> { return c.getWorkPosition().equals(otherContractOne.getWorkPosition()) && c.getPosition().equals(otherContractOne.getPosition()); })); Assert.assertTrue(updatedProjection.getOtherContracts().stream().anyMatch(c -> { return c.getWorkPosition().equals(otherContractTwo.getWorkPosition()) && c.getPosition().equals(otherContractTwo.getPosition()) && c.getId().equals(otherContractTwo.getId()); // preserve id })); // other position Assert.assertEquals(2, updatedProjection.getOtherPositions().size()); Assert.assertTrue(updatedProjection.getOtherPositions().stream().anyMatch(p -> { return p.getWorkPosition().equals(positionOne.getWorkPosition()) && p.getPosition().equals(positionOne.getPosition()) && p.getIdentityContract().equals(updatedPrimeContract.getId()); })); Assert.assertTrue(updatedProjection.getOtherPositions().stream().anyMatch(p -> { return p.getWorkPosition().equals(positionTwo.getWorkPosition()) && p.getPosition().equals(positionTwo.getPosition()) && p.getIdentityContract().equals(positionTwo.getIdentityContract()); })); // assigned roles Assert.assertEquals(2, updatedProjection.getIdentityRoles().size()); Assert.assertTrue(updatedProjection.getIdentityRoles().stream().anyMatch(ir -> { return ir.getRole().equals(roleOne.getId()) && ir.getValidFrom().equals(identityRoleOne.getValidFrom()) && ir.getIdentityContract().equals(updatedPrimeContract.getId()); })); Assert.assertTrue(updatedProjection.getIdentityRoles().stream().anyMatch(ir -> { return ir.getRole().equals(roleTwo.getId()) && ir.getIdentityContract().equals(otherContractTwo.getId()); })); } finally { logout(); } } @Test public void testSaveAndGetSimpleIdentityByRest() throws Exception { IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); IdmIdentityProjectionDto projection = new IdmIdentityProjectionDto(identity); projection.setContract(new IdmIdentityContractDto()); String response = getMockMvc().perform(post(BaseController.BASE_PATH + "/identity-projection") .with(authentication(getAdminAuthentication())) .content(getMapper().writeValueAsString(projection)) .contentType(TestHelper.HAL_CONTENT_TYPE)) .andExpect(status().is2xxSuccessful()) .andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)) .andReturn() .getResponse() .getContentAsString(); IdmIdentityProjectionDto createdProjection = getMapper().readValue(response, IdmIdentityProjectionDto.class); Assert.assertNotNull(createdProjection); Assert.assertNotNull(createdProjection.getId()); Assert.assertEquals(createdProjection.getId(), createdProjection.getIdentity().getId()); Assert.assertEquals(identity.getUsername(), createdProjection.getIdentity().getUsername()); Assert.assertNotNull(createdProjection.getContract()); Assert.assertNotNull(createdProjection.getContract().getId()); Assert.assertTrue(createdProjection.getOtherContracts().isEmpty()); Assert.assertTrue(createdProjection.getOtherPositions().isEmpty()); Assert.assertTrue(createdProjection.getIdentityRoles().isEmpty()); response = getMockMvc().perform(get(BaseController.BASE_PATH + "/identity-projection/" + createdProjection.getIdentity().getUsername()) .with(authentication(getAdminAuthentication())) .contentType(TestHelper.HAL_CONTENT_TYPE)) .andExpect(status().isOk()) .andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)) .andReturn() .getResponse() .getContentAsString(); createdProjection = getMapper().readValue(response, IdmIdentityProjectionDto.class); Assert.assertNotNull(createdProjection); Assert.assertNotNull(createdProjection.getId()); Assert.assertEquals(createdProjection.getId(), createdProjection.getIdentity().getId()); Assert.assertEquals(identity.getUsername(), createdProjection.getIdentity().getUsername()); Assert.assertNotNull(createdProjection.getContract()); Assert.assertNotNull(createdProjection.getContract().getId()); Assert.assertTrue(createdProjection.getOtherContracts().isEmpty()); Assert.assertTrue(createdProjection.getOtherPositions().isEmpty()); Assert.assertTrue(createdProjection.getIdentityRoles().isEmpty()); } @Test public void testDeleteOtherContractAndPosition() { IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); IdmIdentityProjectionDto projection = new IdmIdentityProjectionDto(identity); // set contract IdmIdentityContractDto primeContract = new IdmIdentityContractDto(); primeContract.setMain(true); primeContract.setWorkPosition(getHelper().createTreeNode().getId()); primeContract.setPosition(getHelper().createName()); primeContract.setValidFrom(LocalDate.now().minus(1l, ChronoUnit.DAYS)); primeContract.setValidFrom(LocalDate.now().plus(1l, ChronoUnit.DAYS)); projection.setContract(primeContract); // set other contract IdmIdentityContractDto otherContractOne = new IdmIdentityContractDto(); otherContractOne.setWorkPosition(getHelper().createTreeNode().getId()); otherContractOne.setPosition(getHelper().createName()); IdmIdentityContractDto otherContractTwo = new IdmIdentityContractDto(UUID.randomUUID()); // preset uuid otherContractTwo.setWorkPosition(getHelper().createTreeNode().getId()); otherContractTwo.setPosition(getHelper().createName()); projection.setOtherContracts(Lists.newArrayList(otherContractOne, otherContractTwo)); // set other contract position IdmContractPositionDto positionOne = new IdmContractPositionDto(); positionOne.setWorkPosition(getHelper().createTreeNode().getId()); positionOne.setPosition(getHelper().createName()); IdmContractPositionDto positionTwo = new IdmContractPositionDto(); positionTwo.setWorkPosition(getHelper().createTreeNode().getId()); positionTwo.setPosition(getHelper().createName()); positionTwo.setIdentityContract(otherContractTwo.getId()); projection.setOtherPositions(Lists.newArrayList(positionOne, positionTwo)); IdmIdentityProjectionDto createdProjection = manager .publish(new IdentityProjectionEvent(IdentityProjectionEventType.CREATE, projection)) .getContent(); // other contract Assert.assertEquals(2, createdProjection.getOtherContracts().size()); Assert.assertTrue(createdProjection.getOtherContracts().stream().anyMatch(c -> { return c.getWorkPosition().equals(otherContractOne.getWorkPosition()) && c.getPosition().equals(otherContractOne.getPosition()); })); Assert.assertTrue(createdProjection.getOtherContracts().stream().anyMatch(c -> { return c.getWorkPosition().equals(otherContractTwo.getWorkPosition()) && c.getPosition().equals(otherContractTwo.getPosition()) && c.getId().equals(otherContractTwo.getId()); // preserve id })); // other position Assert.assertEquals(2, createdProjection.getOtherPositions().size()); Assert.assertTrue(createdProjection.getOtherPositions().stream().anyMatch(p -> { return p.getWorkPosition().equals(positionOne.getWorkPosition()) && p.getPosition().equals(positionOne.getPosition()) && p.getIdentityContract().equals(createdProjection.getContract().getId()); })); Assert.assertTrue(createdProjection.getOtherPositions().stream().anyMatch(p -> { return p.getWorkPosition().equals(positionTwo.getWorkPosition()) && p.getPosition().equals(positionTwo.getPosition()) && p.getIdentityContract().equals(positionTwo.getIdentityContract()); })); // remove contract and position createdProjection.getOtherContracts().removeIf(c -> { return c.getWorkPosition().equals(otherContractOne.getWorkPosition()) && c.getPosition().equals(otherContractOne.getPosition()); }); createdProjection.getOtherPositions().removeIf(p -> { return p.getWorkPosition().equals(positionOne.getWorkPosition()) && p.getPosition().equals(positionOne.getPosition()) && p.getIdentityContract().equals(createdProjection.getContract().getId()); }); IdmIdentityProjectionDto updatedProjection = manager .publish(new IdentityProjectionEvent(IdentityProjectionEventType.UPDATE, createdProjection)) .getContent(); // other contract Assert.assertEquals(1, updatedProjection.getOtherContracts().size()); Assert.assertTrue(updatedProjection.getOtherContracts().stream().anyMatch(c -> { return c.getWorkPosition().equals(otherContractTwo.getWorkPosition()) && c.getPosition().equals(otherContractTwo.getPosition()) && c.getId().equals(otherContractTwo.getId()); // preserve id })); // other position Assert.assertEquals(1, updatedProjection.getOtherPositions().size()); Assert.assertTrue(updatedProjection.getOtherPositions().stream().anyMatch(p -> { return p.getWorkPosition().equals(positionTwo.getWorkPosition()) && p.getPosition().equals(positionTwo.getPosition()) && p.getIdentityContract().equals(positionTwo.getIdentityContract()); })); } @Test public void testGetProjectionEavReadOnly() { IdmIdentityDto identityLogged = getHelper().createIdentity(); // with password IdmRoleDto role = getHelper().createRole(); // read all getHelper().createBasePolicy( role.getId(), IdmBasePermission.AUTOCOMPLETE, // form definition autocomplete is required IdmBasePermission.READ); getHelper().createIdentityRole(identityLogged, role); // prepare eav definition IdmFormAttributeDto attributeOne = new IdmFormAttributeDto(getHelper().createName()); attributeOne.setPersistentType(PersistentType.SHORTTEXT); IdmFormAttributeDto attributeTwo = new IdmFormAttributeDto(getHelper().createName()); attributeTwo.setPersistentType(PersistentType.SHORTTEXT); IdmFormDefinitionDto formDefinitionOne = formService.createDefinition(IdmIdentityDto.class, getHelper().createName(), Lists.newArrayList(attributeOne, attributeTwo)); attributeOne = formDefinitionOne.getMappedAttributeByCode(attributeOne.getCode()); attributeTwo = formDefinitionOne.getMappedAttributeByCode(attributeTwo.getCode()); IdmFormAttributeDto attributeThree = new IdmFormAttributeDto(getHelper().createName()); attributeThree.setPersistentType(PersistentType.SHORTTEXT); IdmFormDefinitionDto formDefinitionTwo = formService.createDefinition(IdmIdentityDto.class, getHelper().createName(), Lists.newArrayList(attributeThree)); attributeThree = formDefinitionTwo.getMappedAttributeByCode(attributeThree.getCode()); IdmFormAttributeDto attributeContract = new IdmFormAttributeDto(getHelper().createName()); attributeContract.setPersistentType(PersistentType.SHORTTEXT); IdmFormDefinitionDto formDefinitionContract = formService.createDefinition( IdmIdentityContractDto.class, getHelper().createName(), Lists.newArrayList(attributeContract)); attributeContract = formDefinitionContract.getMappedAttributeByCode(attributeContract.getCode()); IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); IdmIdentityProjectionDto projection = new IdmIdentityProjectionDto(identity); // set eav IdmFormInstanceDto instanceOne = new IdmFormInstanceDto(); instanceOne.setFormDefinition(formDefinitionOne); IdmFormValueDto valueOne = new IdmFormValueDto(attributeOne); valueOne.setValue(getHelper().createName()); IdmFormValueDto valueTwo = new IdmFormValueDto(attributeTwo); valueTwo.setValue(getHelper().createName()); instanceOne.setValues(Lists.newArrayList(valueOne, valueTwo)); IdmFormInstanceDto instanceTwo = new IdmFormInstanceDto(); instanceTwo.setFormDefinition(formDefinitionTwo); IdmFormValueDto valueThree = new IdmFormValueDto(attributeThree); valueThree.setValue(getHelper().createName()); instanceTwo.setValues(Lists.newArrayList(valueThree)); identity.setEavs(Lists.newArrayList(instanceOne, instanceTwo)); // set contract IdmIdentityContractDto primeContract = new IdmIdentityContractDto(); primeContract.setMain(true); primeContract.setWorkPosition(getHelper().createTreeNode().getId()); primeContract.setPosition(getHelper().createName()); primeContract.setValidFrom(LocalDate.now().minus(1l, ChronoUnit.DAYS)); primeContract.setValidFrom(LocalDate.now().plus(1l, ChronoUnit.DAYS)); projection.setContract(primeContract); IdmFormInstanceDto instanceContract = new IdmFormInstanceDto(); instanceContract.setFormDefinition(formDefinitionContract); IdmFormValueDto valueContract = new IdmFormValueDto(attributeContract); valueContract.setValue(getHelper().createName()); instanceContract.setValues(Lists.newArrayList(valueContract)); primeContract.setEavs(Lists.newArrayList(instanceContract)); projection = manager .publish(new IdentityProjectionEvent(IdentityProjectionEventType.CREATE, projection)) .getContent(); getHelper().login(identityLogged); try { IdmIdentityProjectionDto createdProjection = manager.get(projection, IdmBasePermission.READ); Assert.assertNotNull(createdProjection); Assert.assertNotNull(createdProjection.getId()); Assert.assertEquals(createdProjection.getId(), createdProjection.getIdentity().getId()); Assert.assertTrue( createdProjection .getIdentity() .getEavs() .stream() .allMatch(i -> { return i.getFormDefinition().getFormAttributes().stream().allMatch(IdmFormAttributeDto::isReadonly); }) ); // eavs Assert.assertEquals(valueOne.getValue(), createdProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionOne.getId())) .findFirst() .get() .toSinglePersistentValue(attributeOne.getCode())); Assert.assertEquals(valueTwo.getValue(), createdProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionOne.getId())) .findFirst() .get() .toSinglePersistentValue(attributeTwo.getCode())); Assert.assertEquals(valueThree.getValue(), createdProjection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionTwo.getId())) .findFirst() .get() .toSinglePersistentValue(attributeThree.getCode())); // prime contract eavs Assert.assertTrue( createdProjection .getContract() .getEavs() .stream() .allMatch(i -> { return i.getFormDefinition().getFormAttributes().stream().allMatch(IdmFormAttributeDto::isReadonly); }) ); Assert.assertEquals(valueContract.getValue(), createdProjection .getContract() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinitionContract.getId())) .findFirst() .get() .toSinglePersistentValue(attributeContract.getCode())); } finally { logout(); } } @Test public void testGetProjectionWithoutContractAuthority() { IdmIdentityDto identityLogged = getHelper().createIdentity(); // with password IdmRoleDto role = getHelper().createRole(); // read all getHelper().createBasePolicy( role.getId(), CoreGroupPermission.IDENTITY, IdmIdentity.class, IdmBasePermission.READ, IdmBasePermission.UPDATE); getHelper().createIdentityRole(identityLogged, role); IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); IdmIdentityProjectionDto projection = new IdmIdentityProjectionDto(identity); // set contract IdmIdentityContractDto primeContract = new IdmIdentityContractDto(); primeContract.setMain(true); primeContract.setWorkPosition(getHelper().createTreeNode().getId()); primeContract.setPosition(getHelper().createName()); primeContract.setValidFrom(LocalDate.now().minus(1l, ChronoUnit.DAYS)); primeContract.setValidFrom(LocalDate.now().plus(1l, ChronoUnit.DAYS)); projection.setContract(primeContract); // set other contract IdmIdentityContractDto otherContractOne = new IdmIdentityContractDto(); otherContractOne.setWorkPosition(getHelper().createTreeNode().getId()); otherContractOne.setPosition(getHelper().createName()); IdmIdentityContractDto otherContractTwo = new IdmIdentityContractDto(UUID.randomUUID()); // preset uuid otherContractTwo.setWorkPosition(getHelper().createTreeNode().getId()); otherContractTwo.setPosition(getHelper().createName()); projection.setOtherContracts(Lists.newArrayList(otherContractOne, otherContractTwo)); // set other contract position IdmContractPositionDto positionOne = new IdmContractPositionDto(); positionOne.setWorkPosition(getHelper().createTreeNode().getId()); positionOne.setPosition(getHelper().createName()); IdmContractPositionDto positionTwo = new IdmContractPositionDto(); positionTwo.setWorkPosition(getHelper().createTreeNode().getId()); positionTwo.setPosition(getHelper().createName()); positionTwo.setIdentityContract(otherContractTwo.getId()); projection.setOtherPositions(Lists.newArrayList(positionOne, positionTwo)); projection = manager .publish(new IdentityProjectionEvent(IdentityProjectionEventType.CREATE, projection)) .getContent(); // assigned roles getHelper().createIdentityRole(projection.getIdentity(), role); getHelper().login(identityLogged); try { IdmIdentityProjectionDto createdProjection = manager.get(projection, IdmBasePermission.READ); Assert.assertNotNull(createdProjection); Assert.assertNull(createdProjection.getContract()); Assert.assertTrue(createdProjection.getOtherContracts().isEmpty()); Assert.assertTrue(createdProjection.getOtherPositions().isEmpty()); Assert.assertTrue(createdProjection.getIdentityRoles().isEmpty()); createdProjection = manager.get(projection); Assert.assertNotNull(createdProjection); Assert.assertNotNull(createdProjection.getContract()); Assert.assertFalse(createdProjection.getOtherContracts().isEmpty()); Assert.assertFalse(createdProjection.getOtherPositions().isEmpty()); Assert.assertFalse(createdProjection.getIdentityRoles().isEmpty()); } finally { logout(); } } @Test(expected = ForbiddenEntityException.class) public void testSaveProjectionWithoutContractAuthority() { IdmIdentityDto identityLogged = getHelper().createIdentity(); // with password IdmRoleDto role = getHelper().createRole(); // read all getHelper().createBasePolicy( role.getId(), CoreGroupPermission.IDENTITY, IdmIdentity.class, IdmBasePermission.READ, IdmBasePermission.CREATE, IdmBasePermission.UPDATE); getHelper().createIdentityRole(identityLogged, role); IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); IdmIdentityProjectionDto projection = new IdmIdentityProjectionDto(identity); projection.setContract(new IdmIdentityContractDto()); getHelper().login(identityLogged); try { manager .publish(new IdentityProjectionEvent(IdentityProjectionEventType.CREATE, projection), IdmBasePermission.CREATE) .getContent(); } finally { logout(); } } @Test public void testSaveProjectionEavSecuredException() { // create definition with two attributes IdmFormAttributeDto formAttributeOne = new IdmFormAttributeDto(getHelper().createName()); IdmFormAttributeDto formAttributeTwo = new IdmFormAttributeDto(getHelper().createName()); IdmFormDefinitionDto formDefinition = formService.createDefinition( IdmIdentityDto.class, getHelper().createName(), Lists.newArrayList(formAttributeOne, formAttributeTwo)); formAttributeOne = formDefinition.getMappedAttributeByCode(formAttributeOne.getCode()); formAttributeTwo = formDefinition.getMappedAttributeByCode(formAttributeTwo.getCode()); IdmIdentityDto identityOne = getHelper().createIdentity(); // password is needed IdmIdentityDto identityTwo = getHelper().createIdentity(); // password is needed IdmIdentityDto identityOther = getHelper().createIdentity((GuardedString) null); // assign self identity authorization policy - READ - to identityOne IdmRoleDto roleReadIdentity = getHelper().createRole(); getHelper().createAuthorizationPolicy( roleReadIdentity.getId(), CoreGroupPermission.IDENTITY, IdmIdentity.class, SelfIdentityEvaluator.class, IdmBasePermission.AUTOCOMPLETE, IdmBasePermission.READ); getHelper().createUuidPolicy( // and other roleReadIdentity.getId(), identityOther.getId(), IdmBasePermission.AUTOCOMPLETE, IdmBasePermission.READ); getHelper().createIdentityRole(identityOne, roleReadIdentity); // assign self identity authorization policy - UPDATE - to identityOne IdmRoleDto roleUpdateIdentity = getHelper().createRole(); getHelper().createAuthorizationPolicy( roleUpdateIdentity.getId(), CoreGroupPermission.IDENTITY, IdmIdentity.class, SelfIdentityEvaluator.class, // self IdmBasePermission.AUTOCOMPLETE, IdmBasePermission.READ, IdmBasePermission.UPDATE); getHelper().createUuidPolicy( // and other roleUpdateIdentity.getId(), identityOther.getId(), IdmBasePermission.AUTOCOMPLETE, IdmBasePermission.READ, IdmBasePermission.UPDATE); getHelper().createIdentityRole(identityTwo, roleUpdateIdentity); // assign autocomplete to form definition getHelper().createUuidPolicy( roleReadIdentity.getId(), formDefinition.getId(), IdmBasePermission.AUTOCOMPLETE, IdmBasePermission.READ); getHelper().createUuidPolicy( // and other roleUpdateIdentity.getId(), formDefinition.getId(), IdmBasePermission.AUTOCOMPLETE, IdmBasePermission.READ); // save some values as admin to identity one IdmFormValueDto formValueOne = new IdmFormValueDto(formAttributeOne); formValueOne.setValue(getHelper().createName()); IdmFormValueDto formValueTwo = new IdmFormValueDto(formAttributeTwo); formValueTwo.setValue(getHelper().createName()); List<IdmFormValueDto> formValues = Lists.newArrayList(formValueOne, formValueTwo); identityOne.setEavs(Lists.newArrayList(new IdmFormInstanceDto(identityOne, formDefinition, formValues))); manager.publish(new IdentityProjectionEvent(IdentityProjectionEventType.UPDATE, new IdmIdentityProjectionDto(identityOne))); // values cannot be read as identity one getHelper().login(identityOne); try { IdmIdentityProjectionDto projection = manager.get(identityOne.getId(), IdmBasePermission.READ); IdmFormInstanceDto formInstance = projection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinition.getId())) .findFirst() .get(); Assert.assertTrue(formInstance.getValues().isEmpty()); Assert.assertEquals(0, formInstance.getFormDefinition().getFormAttributes().size()); } finally { logout(); } getHelper().login(identityTwo); try { IdmIdentityProjectionDto projection = manager.get(identityOther.getId(), IdmBasePermission.READ); IdmFormInstanceDto formInstance = projection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinition.getId())) .findFirst() .get(); Assert.assertTrue(formInstance.getValues().isEmpty()); Assert.assertEquals(0, formInstance.getFormDefinition().getFormAttributes().size()); } finally { logout(); } // configure authorization policy to read attribute one and edit attribute two - for self ConfigurationMap properties = new ConfigurationMap(); properties.put(IdentityFormValueEvaluator.PARAMETER_FORM_DEFINITION, formDefinition.getId()); properties.put(IdentityFormValueEvaluator.PARAMETER_FORM_ATTRIBUTES, formAttributeOne.getCode()); properties.put(IdentityFormValueEvaluator.PARAMETER_SELF_ONLY, true); getHelper().createAuthorizationPolicy( roleReadIdentity.getId(), CoreGroupPermission.FORMVALUE, IdmIdentityFormValue.class, IdentityFormValueEvaluator.class, properties, IdmBasePermission.READ); // read self attribute one getHelper().login(identityOne); try { IdmIdentityProjectionDto projection = manager.get(identityOne.getId(), IdmBasePermission.READ); IdmFormInstanceDto formInstance = projection .getIdentity() .getEavs() .stream() .filter(i -> i.getFormDefinition().getId().equals(formDefinition.getId())) .findFirst() .get(); Assert.assertEquals(1, formInstance.getValues().size()); Assert.assertEquals(formValueOne.getShortTextValue(), formInstance.getValues().get(0).getShortTextValue()); Assert.assertEquals(1, formInstance.getFormDefinition().getFormAttributes().size()); Assert.assertEquals(formAttributeOne.getCode(), formInstance.getFormDefinition().getFormAttributes().get(0).getCode()); } finally { logout(); } // update is forbidden getHelper().login(identityOne); try { identityOne.setEavs(Lists.newArrayList(new IdmFormInstanceDto(identityOne, formDefinition, Lists.newArrayList(formValueOne)))); manager .publish( new IdentityProjectionEvent(IdentityProjectionEventType.UPDATE, new IdmIdentityProjectionDto(identityOne)), IdmBasePermission.UPDATE) .getContent(); } catch (ForbiddenEntityException ex) { } finally { logout(); } getHelper().login(identityOne); try { identityTwo.setEavs(Lists.newArrayList(new IdmFormInstanceDto(identityOne, formDefinition, Lists.newArrayList(formValueOne)))); manager .publish( new IdentityProjectionEvent(IdentityProjectionEventType.UPDATE, new IdmIdentityProjectionDto(identityTwo)), IdmBasePermission.UPDATE) .getContent(); } catch (ForbiddenEntityException ex) { } finally { logout(); } // add policy to edit attribute two for identity one properties = new ConfigurationMap(); properties.put(IdentityFormValueEvaluator.PARAMETER_FORM_DEFINITION, formDefinition.getId()); properties.put(IdentityFormValueEvaluator.PARAMETER_FORM_ATTRIBUTES, formAttributeTwo.getCode()); properties.put(IdentityFormValueEvaluator.PARAMETER_SELF_ONLY, true); getHelper().createAuthorizationPolicy( roleReadIdentity.getId(), CoreGroupPermission.FORMVALUE, IdmIdentityFormValue.class, IdentityFormValueEvaluator.class, properties, IdmBasePermission.READ, IdmBasePermission.UPDATE); String updatedValue = getHelper().createName(); formValueTwo.setValue(updatedValue); } @Test public void testLoadProjectionDefinedEavsOnly() throws Exception { // create definition with two attributes IdmFormAttributeDto formAttributeOne = new IdmFormAttributeDto(getHelper().createName()); IdmFormAttributeDto formAttributeTwo = new IdmFormAttributeDto(getHelper().createName()); IdmFormDefinitionDto formDefinition = formService.createDefinition( IdmIdentityDto.class, getHelper().createName(), Lists.newArrayList(formAttributeOne, formAttributeTwo)); formAttributeOne = formDefinition.getMappedAttributeByCode(formAttributeOne.getCode()); formAttributeTwo = formDefinition.getMappedAttributeByCode(formAttributeTwo.getCode()); // create projection with one attribute FormDefinitionAttributes attributes = new FormDefinitionAttributes(); attributes.setDefinition(formDefinition.getId()); attributes.getAttributes().add(formAttributeOne.getId()); IdmFormProjectionDto projection = new IdmFormProjectionDto(); projection.setCode(getHelper().createName()); projection.setOwnerType(lookupService.getOwnerType(IdmIdentityDto.class)); projection.setFormDefinitions(mapper.writeValueAsString(Lists.newArrayList(attributes))); projection = projectionService.save(projection); // create identity with projection is defined IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); identity.setFormProjection(projection.getId()); identity = identityService.save(identity); // save some values IdmFormValueDto formValueOne = new IdmFormValueDto(formAttributeOne); formValueOne.setValue(getHelper().createName()); IdmFormValueDto formValueTwo = new IdmFormValueDto(formAttributeTwo); formValueTwo.setValue(getHelper().createName()); List<IdmFormValueDto> formValues = Lists.newArrayList(formValueOne, formValueTwo); identity.setEavs(Lists.newArrayList(new IdmFormInstanceDto(identity, formDefinition, formValues))); manager.publish(new IdentityProjectionEvent(IdentityProjectionEventType.UPDATE, new IdmIdentityProjectionDto(identity))); IdmIdentityProjectionDto identityProjection = manager.get(identity.getId()); Assert.assertEquals(1, identityProjection.getIdentity().getEavs().size()); Assert.assertEquals(1, identityProjection.getIdentity().getEavs().get(0).getValues().size()); Assert.assertEquals(formValueOne.getValue(), identityProjection.getIdentity().getEavs().get(0).getValues().get(0).getValue()); } @Test public void testProjectionDontSaveOtherContractsAndPositions() { IdmFormProjectionDto formProjection = new IdmFormProjectionDto(); formProjection.setCode(getHelper().createName()); formProjection.setOwnerType(lookupService.getOwnerType(IdmIdentityDto.class)); formProjection = projectionService.save(formProjection); IdmIdentityDto identity = new IdmIdentityDto(getHelper().createName()); identity.setFormProjection(formProjection.getId()); IdmIdentityProjectionDto projection = new IdmIdentityProjectionDto(identity); // set contract IdmIdentityContractDto primeContract = new IdmIdentityContractDto(); primeContract.setMain(true); primeContract.setWorkPosition(getHelper().createTreeNode().getId()); primeContract.setPosition(getHelper().createName()); primeContract.setValidFrom(LocalDate.now().minus(1l, ChronoUnit.DAYS)); primeContract.setValidFrom(LocalDate.now().plus(1l, ChronoUnit.DAYS)); projection.setContract(primeContract); // set other contract IdmIdentityContractDto otherContractOne = new IdmIdentityContractDto(); otherContractOne.setWorkPosition(getHelper().createTreeNode().getId()); otherContractOne.setPosition(getHelper().createName()); IdmIdentityContractDto otherContractTwo = new IdmIdentityContractDto(UUID.randomUUID()); // preset uuid otherContractTwo.setWorkPosition(getHelper().createTreeNode().getId()); otherContractTwo.setPosition(getHelper().createName()); projection.setOtherContracts(Lists.newArrayList(otherContractOne, otherContractTwo)); // set other contract position IdmContractPositionDto positionOne = new IdmContractPositionDto(); positionOne.setWorkPosition(getHelper().createTreeNode().getId()); positionOne.setPosition(getHelper().createName()); IdmContractPositionDto positionTwo = new IdmContractPositionDto(); positionTwo.setWorkPosition(getHelper().createTreeNode().getId()); positionTwo.setPosition(getHelper().createName()); positionTwo.setIdentityContract(otherContractTwo.getId()); projection.setOtherPositions(Lists.newArrayList(positionOne, positionTwo)); IdmIdentityProjectionDto createdProjection = manager .publish(new IdentityProjectionEvent(IdentityProjectionEventType.CREATE, projection)) .getContent(); // other contract Assert.assertTrue(createdProjection.getOtherContracts().isEmpty()); // other position Assert.assertTrue(createdProjection.getOtherPositions().isEmpty()); } }
package org.opendaylight.protocol.bgp.openconfig.routing.policy.statement.conditions; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.opendaylight.protocol.bgp.openconfig.routing.policy.spi.RouteEntryBaseAttributes; import org.opendaylight.protocol.bgp.openconfig.routing.policy.spi.policy.condition.BgpConditionsAugmentationPolicy; import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryExportParameters; import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.AfiSafiType; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.attributes.ExtendedCommunities; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.RouteTarget; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.extended.community.ExtendedCommunity; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.extended.community.extended.community.As4RouteTargetExtendedCommunityCase; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.extended.community.extended.community.RouteTargetExtendedCommunityCase; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.extended.community.extended.community.RouteTargetIpv4Case; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.route.target.constrain._default.route.grouping.RouteTargetConstrainDefaultRoute; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.route.target.constrain._default.route.grouping.RouteTargetConstrainDefaultRouteBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.odl.bgp._default.policy.rev180329.VpnNonMemberCondition; /** * Returns true if Route Target extended communities attributes are not part of the VPN membership of destiny peer. * * @author Claudio D. Gasparini */ public final class VpnNonMemberHandler implements BgpConditionsAugmentationPolicy<VpnNonMemberCondition, List<ExtendedCommunities>> { private static final VpnNonMemberHandler INSTANCE = new VpnNonMemberHandler(); private static final RouteTargetConstrainDefaultRoute DEFAULT = new RouteTargetConstrainDefaultRouteBuilder() .build(); private VpnNonMemberHandler() { } public static VpnNonMemberHandler getInstance() { return INSTANCE; } @Override public boolean matchImportCondition( final Class<? extends AfiSafiType> afiSafiType, final RouteEntryBaseAttributes routeEntryInfo, final BGPRouteEntryImportParameters routeEntryImportParameters, final List<ExtendedCommunities> attributes, final VpnNonMemberCondition conditions) { return false; } @Override public boolean matchExportCondition( final Class<? extends AfiSafiType> afiSafiType, final RouteEntryBaseAttributes routeEntryInfo, final BGPRouteEntryExportParameters routeEntryExportParameters, final List<ExtendedCommunities> attributes, final VpnNonMemberCondition conditions) { final List<RouteTarget> allowedRouteTarget = routeEntryExportParameters.getMemberships(); if (allowedRouteTarget.contains(DEFAULT)) { return false; } final List<RouteTarget> toRT = attributes.stream() .map(ext -> ext.getExtendedCommunity()) .filter(Objects::nonNull) .filter(this::filterRTExtComm) .map(this::extendedCommunityToRouteTarget) .collect(Collectors.toList()); return Collections.disjoint(allowedRouteTarget, toRT); } private RouteTarget extendedCommunityToRouteTarget(final ExtendedCommunity rt) { if (rt instanceof RouteTargetExtendedCommunityCase) { return ((RouteTargetExtendedCommunityCase) rt).getRouteTargetExtendedCommunity(); } else if (rt instanceof As4RouteTargetExtendedCommunityCase) { return ((As4RouteTargetExtendedCommunityCase) rt).getAs4RouteTargetExtendedCommunity(); } return ((RouteTargetIpv4Case) rt).getRouteTargetIpv4(); } private boolean filterRTExtComm(final ExtendedCommunity rt) { return rt instanceof RouteTargetExtendedCommunityCase || rt instanceof As4RouteTargetExtendedCommunityCase || rt instanceof RouteTargetIpv4Case; } @Override public List<ExtendedCommunities> getConditionParameter(final Attributes attributes) { final List<ExtendedCommunities> ext = attributes.getExtendedCommunities(); return ext == null ? Collections.emptyList() : ext; } }
package org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import org.springframework.ide.vscode.commons.util.StringUtil; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * Provides existing Cloud Foundry client params, like target and credentials, * from the CLI config.json in the file system. * * */ public class CfCliParamsProvider implements ClientParamsProvider { public static final String TARGET = "Target"; public static final String REFRESH_TOKEN = "RefreshToken"; public static final String ORGANIZATION_FIELDS = "OrganizationFields"; public static final String SPACE_FIELDS = "SpaceFields"; public static final String NAME = "Name"; public static final String SSL_DISABLED = "SSLDisabled"; private CfCliProviderMessages cfCliProviderMessages = new CfCliProviderMessages(); private Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private static CfCliParamsProvider instance; public static final CfCliParamsProvider getInstance() { if (instance == null) { instance= new CfCliParamsProvider(); } return instance; } private CfCliParamsProvider() { } /* * (non-Javadoc) * * @see org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget. * ClientParamsProvider#getParams() */ @SuppressWarnings("unchecked") @Override public List<CFClientParams> getParams() throws NoTargetsException, ExecutionException { List<CFClientParams> params = new ArrayList<>(); try { File file = getConfigJsonFile(); if (file != null) { Map<String, Object> userData = gson.fromJson(new FileReader(file), Map.class); if (userData != null) { String refreshToken = (String) userData.get(REFRESH_TOKEN); // Only support connecting to CF via refresh token for now if (isRefreshTokenSet(refreshToken)) { CFCredentials credentials = CFCredentials.fromRefreshToken(refreshToken); boolean sslDisabled = (Boolean) userData.get(SSL_DISABLED); String target = (String) userData.get(TARGET); Map<String, Object> orgFields = (Map<String, Object>) userData.get(ORGANIZATION_FIELDS); Map<String, Object> spaceFields = (Map<String, Object>) userData.get(SPACE_FIELDS); if (target != null && orgFields != null && spaceFields != null) { String orgName = (String) orgFields.get(NAME); String spaceName = (String) spaceFields.get(NAME); if (!StringUtil.hasText(orgName) || !StringUtil.hasText(spaceName)) { throw new NoTargetsException(getMessages().noOrgSpace()); } params.add(new CFClientParams(target, null, credentials, orgName, spaceName, sslDisabled)); } } } } } catch (IOException | InterruptedException e) { throw new ExecutionException(e); } if (params.isEmpty()) { throw new NoTargetsException(getMessages().noTargetsFound()); } else { return params; } } private boolean isRefreshTokenSet(String token) { return StringUtil.hasText(token); } private File getConfigJsonFile() throws IOException, InterruptedException { String homeDir = getHomeDir(); if (homeDir != null) { if (!homeDir.endsWith("/")) { homeDir += '/'; } String filePath = homeDir + ".cf/config.json"; File file = new File(filePath); if (file.exists() && file.canRead()) { return file; } } return null; } private String getHomeDir() throws IOException, InterruptedException { return System.getProperty("user.home"); } @Override public CFParamsProviderMessages getMessages() { return cfCliProviderMessages; } }
package gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import model.Direction; import model.Game; /** * Announces the winner of each hand and allows the players to move on to the * next hand. * * @author Humaira Orchee * @version April 30, 2015 * */ public class NextHandGUI extends JPanel { private GameGUI gameGUI; private Game game; private JLabel winnerLabel; private JLabel tricksLabel; /** * * @param gameGUI * @param game */ public NextHandGUI(GameGUI gameGUI, Game game) { this.gameGUI = gameGUI; this.game = game; JPanel mainPanel = new JPanel(); BoxLayout boxLayout = new BoxLayout(mainPanel, BoxLayout.Y_AXIS); mainPanel.setLayout(boxLayout); // add the JLabel that shows who the winners of the last hand are winnerLabel = GUIUtilities.createTitleLabel(""); winnerLabel.setAlignmentX(Component.CENTER_ALIGNMENT); mainPanel.add(winnerLabel); // adds the JLabel that shows how many tricks the winning pair won tricksLabel = GUIUtilities.createTitleLabel(""); tricksLabel.setAlignmentX(Component.CENTER_ALIGNMENT); mainPanel.add(tricksLabel); // add vertical glue before the buttons mainPanel.add(Box.createRigidArea(new Dimension(500, 100))); mainPanel.add(Box.createVerticalGlue()); mainPanel.add(createNextHandButton()); add(mainPanel, BorderLayout.CENTER); } /** * Returns a String[] announcing the winners of the last hand and the tricks * they won in the last hand * * @return A String announcing the winners of the last hand and the tricks * they won in the last hand */ private String[] getWinnerText() { // ask game who the winners are String winnerText = "Hand is won by "; int tricksWon = game.determineHandWinner(); Direction winner = game.getLastHandWinner(); // TODO : add sound here // SoundManager soundManager = SoundManager.getInstance() ; // soundManager.addSound(filename); try { // figure out what the text should be if (winner.equals(Direction.NORTH) || winner.equals(Direction.SOUTH)) { winnerText += "North and South"; } else if (winner.equals(Direction.EAST) || winner.equals(Direction.WEST)) { winnerText = "East and West"; } } catch (NullPointerException e) { new AssertionError("String text is null"); System.out.println("There should be no null pointer Exception"); } String trickText = "They won " + tricksWon + " tricks in total."; return new String[] { winnerText, trickText }; } /** * * @return */ private JButton createNextHandButton() { JButton nextHandButton = GUIUtilities.createButton("Next Hand"); nextHandButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { gameGUI.changeFrame(); game.resetGame(); System.out.println("resetting game in Next Hand GUI"); } }); nextHandButton.setAlignmentX(Component.CENTER_ALIGNMENT); return nextHandButton; } /** * Refreshes the display after each hand */ public void refreshDisplay() { System.out.println("Refreshing display"); String[] text = getWinnerText(); winnerLabel.setText(text[0]); tricksLabel.setText(text[1]); } }
package com.ext.portlet.service.impl; import com.ext.portlet.Activity.ActivitySubscriptionNameGeneratorServiceUtil; import com.ext.portlet.Activity.SubscriptionType; import com.ext.portlet.NoSuchConfigurationAttributeException; import com.ext.portlet.messaging.MessageUtil; import com.ext.portlet.model.ActivitySubscription; import com.ext.portlet.model.Proposal; import com.ext.portlet.service.ActivitySubscriptionLocalServiceUtil; import com.ext.portlet.service.base.ActivitySubscriptionLocalServiceBaseImpl; import com.ext.portlet.service.persistence.ActivitySubscriptionUtil; import com.ext.utils.NotificationUnregisterUtils; import com.ext.utils.SocialActivityMessageLimitationHelper; import com.ext.utils.subscriptions.ActivitySubscriptionConstraint; import com.liferay.counter.service.CounterLocalServiceUtil; import com.liferay.portal.kernel.dao.orm.Criterion; import com.liferay.portal.kernel.dao.orm.DynamicQuery; import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil; import com.liferay.portal.kernel.dao.orm.OrderFactoryUtil; import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.transaction.Transactional; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.model.User; import com.liferay.portal.service.ClassNameLocalServiceUtil; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portal.util.PortalUtil; import com.liferay.portlet.social.model.SocialActivity; import com.liferay.portlet.social.model.SocialActivityFeedEntry; import com.liferay.portlet.social.service.SocialActivityInterpreterLocalServiceUtil; import com.liferay.portlet.social.service.SocialActivityLocalServiceUtil; import com.liferay.util.mail.MailEngine; import com.liferay.util.mail.MailEngineException; import org.apache.commons.collections.comparators.ComparatorChain; import org.xcolab.utils.HtmlUtil; import org.xcolab.utils.TemplateReplacementUtil; import javax.mail.internet.InternetAddress; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * The implementation of the activity subscription local service. * <p/> * <p> * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link com.ext.portlet.service.ActivitySubscriptionLocalService} interface. * <p/> * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM. * </p> * * @author Brian Wing Shun Chan * @see com.ext.portlet.service.base.ActivitySubscriptionLocalServiceBaseImpl * @see com.ext.portlet.service.ActivitySubscriptionLocalServiceUtil */ public class ActivitySubscriptionLocalServiceImpl extends ActivitySubscriptionLocalServiceBaseImpl { /* * NOTE FOR DEVELOPERS: * * Never reference this interface directly. Always use {@link com.ext.portlet.service.ActivitySubscriptionLocalServiceUtil} to access the activity subscription local service. */ private Date lastEmailNotification = new Date(); private final static String PROPERTY_CREATE_DATE = "createDate"; private final static Log _log = LogFactoryUtil.getLog(ActivitySubscriptionLocalServiceImpl.class); // 1 am private final static int DAILY_DIGEST_TRIGGER_HOUR = 1; private Date lastDailyEmailNotification = getLastDailyEmailNotificationDate(); private final static String MESSAGE_FOOTER_TEMPLATE = "<br /><br />\n<hr /><br />\n" + "To configure your notification preferences, visit your <a href=\"USER_PROFILE_LINK\">profile</a> page"; private final static String USER_PROFILE_LINK_PLACEHOLDER = "USER_PROFILE_LINK"; private final static String USER_PROFILE_LINK_TEMPLATE = "DOMAIN_PLACEHOLDER/web/guest/member/-/member/userId/USER_ID"; private final static String USER_ID_PLACEHOLDER = "USER_ID"; private final static String DOMAIN_PLACEHOLDER = "DOMAIN_PLACEHOLDER"; private static final String DAILY_DIGEST_NOTIFICATION_SUBJECT_TEMPLATE = "<colab-name/> Activities – Daily Digest DATE"; private static final String DAILY_DIGEST_NOTIFICATION_SUBJECT_DATE_PLACEHOLDER = "DATE"; private static final String DAILY_DIGEST_ENTRY_TEXT = "<colab-name/> Digest for DATE"; private static final String FAQ_DIGEST_URL_PATH = "/faqs#digest"; private static final String FAQ_DIGEST_LINK_PLACEHOLDER = "FAQ_DIGEST_LINK_PLACEHOLDER"; private static final String UNSUBSCRIBE_SUBSCRIPTION_LINK_PLACEHOLDER = "UNSUBSCRIBE_SUBSCRIPTION_LINK_PLACEHOLDER"; private static final String UNSUBSCRIBE_INSTANT_NOTIFICATION_TEXT = "You are receiving this message because you subscribed to a <contest/>, <proposal/> or discussion post on the <colab-name/>. " + "To receive all notifications in a daily digest, please click <a href='FAQ_DIGEST_LINK_PLACEHOLDER'>here</a> for instructions. " + "To stop receiving notifications from this <contest/>, <proposal/> or discussion post, please click <a href='UNSUBSCRIBE_SUBSCRIPTION_LINK_PLACEHOLDER'>here</a>."; private static final String UNSUBSCRIBE_DAILY_DIGEST_NOTIFICATION_TEXT = "You are receiving this message because you subscribed to receiving a daily digest of activities on the <colab-name/>. " + "To stop receiving these notifications, please click <a href='UNSUBSCRIBE_SUBSCRIPTION_LINK_PLACEHOLDER'>here</a>."; /** * This method is used to construct the last daily digest notification date after a restart of the application server */ private Date getLastDailyEmailNotificationDate() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, DAILY_DIGEST_TRIGGER_HOUR); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } @Override public List<ActivitySubscription> getActivitySubscriptions(Class clasz, Long classPK, Integer type, String extraData) throws PortalException, SystemException { return ActivitySubscriptionUtil.findByClassNameIdClassPKTypeExtraData(PortalUtil.getClassNameId(clasz), classPK, type, extraData); } @Override public List<ActivitySubscription> findByUser(Long userId) throws SystemException { return ActivitySubscriptionUtil.findByreceiverId(userId); } @Override public boolean isSubscribed(Long userId, Long classNameId, Long classPK, Integer type, String extraData) throws PortalException, SystemException { List<ActivitySubscription> ret = ActivitySubscriptionUtil.findByClassNameIdClassPKTypeExtraDataReceiverId(classNameId, classPK, type, extraData, userId); return ret != null && !ret.isEmpty(); } @Override public boolean isSubscribed(Long userId, Class clasz, Long classPK, Integer type, String extraData) throws PortalException, SystemException { return isSubscribed(userId, PortalUtil.getClassNameId(clasz), classPK, type, extraData); } @Override public void deleteSubscription(Long userId, Long classNameId, Long classPK, Integer type, String extraData) throws SystemException { deleteSubscription(userId, classNameId, classPK, type, extraData, false); } @Override @Transactional public void deleteSubscription(Long userId, Long classNameId, Long classPK, Integer type, String extraData, boolean automatic) throws SystemException { List<ActivitySubscription> subscriptions = ActivitySubscriptionUtil.findByClassNameIdClassPKTypeExtraDataReceiverId(classNameId, classPK, type, extraData, userId); for (ActivitySubscription subscription : subscriptions) { if (automatic) { // we are removing automatic subscriptions only if (subscription.getAutomaticSubscriptionCounter() == 1) { delete(subscription); } else if (subscription.getAutomaticSubscriptionCounter() > 1) { // decrement automatic subscription counter as this subscription can be still // valid (ie it has been added as a result of regional->global link and because // user is susbscribed to a contest) subscription.setAutomaticSubscriptionCounter(subscription.getAutomaticSubscriptionCounter() - 1); updateActivitySubscription(subscription); } } else { // remove subscription as it's probably requested directly by the user delete(subscription); } } } @Override public void deleteSubscription(Long userId, Class clasz, Long classPK, Integer type, String extraData, boolean automatic) throws SystemException { deleteSubscription(userId, PortalUtil.getClassNameId(clasz), classPK, type, extraData, automatic); } @Override public void deleteSubscription(Long userId, Class clasz, Long classPK, Integer type, String extraData) throws SystemException { deleteSubscription(userId, clasz, classPK, type, extraData, false); } @Override public void addSubscription(Long classNameId, Long classPK, Integer type, String extraData, Long userId) throws PortalException, SystemException { addSubscription(classNameId, classPK, type, extraData, userId, false); } @Override @Transactional public void addSubscription(Long classNameId, Long classPK, Integer type, String extraData, Long userId, boolean automatic) throws PortalException, SystemException { List<ActivitySubscription> subscriptions = ActivitySubscriptionUtil .findByClassNameIdClassPKTypeExtraDataReceiverId(classNameId, classPK, type, extraData, userId); if (!subscriptions.isEmpty()) { // subscription exists ActivitySubscription subscription = subscriptions.get(0); if (automatic && subscription.getAutomaticSubscriptionCounter() > 0) { // this is an automatic subscription, if existing subscription is also automatic then increment the counter, otherwise do nothing subscription.setAutomaticSubscriptionCounter(subscription.getAutomaticSubscriptionCounter() + 1); ActivitySubscriptionLocalServiceUtil.updateActivitySubscription(subscription); } return; } Long pk = CounterLocalServiceUtil.increment(ActivitySubscription.class.getName()); ActivitySubscription subscription = ActivitySubscriptionLocalServiceUtil.createActivitySubscription(pk); subscription.setClassNameId(classNameId); subscription.setClassPK(classPK); subscription.setType(type); subscription.setExtraData(extraData); subscription.setReceiverId(userId); subscription.setAutomaticSubscriptionCounter(automatic ? 1 : -1); subscription.setModifiedDate(new Date()); subscription.setCreateDate(new Date()); store(subscription); } @Override public void addSubscription(Class clasz, Long classPK, Integer type, String extraData, Long userId) throws PortalException, SystemException { addSubscription(clasz, classPK, type, extraData, userId, false); } @Override public void addSubscription(Class clasz, Long classPK, Integer type, String extraData, Long userId, boolean automatic) throws PortalException, SystemException { Long classNameId = ClassNameLocalServiceUtil.getClassNameId(clasz); addSubscription(classNameId, classPK, type, extraData, userId, automatic); } @Override public List<SocialActivity> getActivities(Long userId, int start, int count) throws SystemException { // for now no activity selection is made, TODO List<ActivitySubscription> subscriptions = ActivitySubscriptionUtil.findByreceiverId(userId); if (subscriptions.isEmpty()) { return new ArrayList<>(); } DynamicQuery query = DynamicQueryFactoryUtil.forClass(SocialActivity.class); Criterion crit = null; for (ActivitySubscription sub : subscriptions) { //Map<String, Number> criterion = new HashMap<String, Number>(); Criterion criterion = RestrictionsFactoryUtil.eq("classNameId", sub.getClassNameId()); if (sub.getClassPK() <= 0) { RestrictionsFactoryUtil.and(criterion, RestrictionsFactoryUtil.eq("classPk", sub.getClassPK())); } if (sub.getType() >= 0) { RestrictionsFactoryUtil.and(criterion, RestrictionsFactoryUtil.eq("type", sub.getType())); } if (sub.getExtraData() != null && !sub.getExtraData().isEmpty()) { criterion = RestrictionsFactoryUtil.and(criterion, RestrictionsFactoryUtil.ilike("extraData", sub.getExtraData() + "%")); } if (crit == null) { crit = criterion; } else { crit = RestrictionsFactoryUtil.or(crit, criterion); } } query.add(crit).addOrder(OrderFactoryUtil.desc("createDate")); List<SocialActivity> activities = new ArrayList<>(); List<Object> queryResults = SocialActivityLocalServiceUtil.dynamicQuery(query, start, start + count - 1); for (Object activity : queryResults) { activities.add((SocialActivity) activity); } return activities; } @Override public void store(ActivitySubscription activitySubscription) throws SystemException { if (activitySubscription.isNew()) { ActivitySubscriptionLocalServiceUtil.addActivitySubscription(activitySubscription); } else { ActivitySubscriptionLocalServiceUtil.updateActivitySubscription(activitySubscription); } } @Override public String getName(ActivitySubscription activitySubscription) { return ActivitySubscriptionNameGeneratorServiceUtil.getName(activitySubscription); } @Override public SubscriptionType getSubscriptionType(ActivitySubscription activitySubscription) { return SubscriptionType.getSubscriptionType(activitySubscription); } @Override public void delete(ActivitySubscription activitySubscription) throws SystemException { ActivitySubscriptionLocalServiceUtil.deleteActivitySubscription(activitySubscription); } @Override public void sendEmailNotifications(ServiceContext serviceContext) throws SystemException, PortalException { synchronized (lastEmailNotification) { List<SocialActivity> res = getActivitiesAfter(lastEmailNotification); for (SocialActivity activity : res) { try { sendInstantNotifications(activity, serviceContext); } catch (Throwable e) { _log.error(String.format("Can't process activity when sending notifications ( %s )", activity), e); } } lastEmailNotification = new Date(); } synchronized (lastDailyEmailNotification) { Date now = new Date(); // Send the daily digest at the predefined hour only if (now.getTime() - lastDailyEmailNotification.getTime() > 3600 * 1000 && Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == DAILY_DIGEST_TRIGGER_HOUR) { try { List<SocialActivity> res = getActivitiesAfter(lastDailyEmailNotification); sendDailyDigestNotifications(res, serviceContext); } catch (SystemException | PortalException t) { _log.error("Can't send daily email notification", t); } lastDailyEmailNotification = now; } } } @Override public List<User> getSubscribedUsers(Class clasz, long classPK) throws PortalException, SystemException { return getSubscribedUsers(ClassNameLocalServiceUtil.getClassNameId(clasz), classPK); } @Override public List<User> getSubscribedUsers(long classNameId, long classPK) throws PortalException, SystemException { List<User> users = new ArrayList<>(); for (ActivitySubscription subscription : activitySubscriptionPersistence.findByClassNameIdClassPK(classNameId, classPK)) { users.add(userLocalService.getUser(subscription.getReceiverId())); } return users; } private List<SocialActivity> getActivitiesAfter(Date minDate) throws SystemException { DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(SocialActivity.class); Criterion criterionCreateDate = RestrictionsFactoryUtil.gt(PROPERTY_CREATE_DATE, minDate.getTime()); dynamicQuery.add(criterionCreateDate); List<Object> activityObjects = SocialActivityLocalServiceUtil.dynamicQuery(dynamicQuery); //clean list of activities first in order not to send out activities concerning the same proposal multiple times SocialActivityMessageLimitationHelper h = new SocialActivityMessageLimitationHelper(Proposal.class); return h.process(activityObjects); } private void sendDailyDigestNotifications(List<SocialActivity> activities, ServiceContext serviceContext) throws SystemException, PortalException { Map<User, List<SocialActivity>> userActivitiesDigestMap = getUserToActivityDigestMap(activities); String subject = StringUtil.replace(DAILY_DIGEST_NOTIFICATION_SUBJECT_TEMPLATE, DAILY_DIGEST_NOTIFICATION_SUBJECT_DATE_PLACEHOLDER, dateToDateString(lastDailyEmailNotification)); // Send the digest to each user which is included in the set of subscriptions for (Map.Entry<User, List<SocialActivity>> entry : userActivitiesDigestMap.entrySet()) { final User recipient = entry.getKey(); final List<SocialActivity> userDigestActivities = entry.getValue(); String body = getDigestMessageBody(serviceContext, userDigestActivities); String unsubscribeFooter = getUnsubscribeDailyDigestFooter(NotificationUnregisterUtils.getActivityUnregisterLink(recipient, serviceContext)); sendEmailMessage(recipient, subject, body, unsubscribeFooter, serviceContext.getPortalURL()); } } private String getDigestMessageBody(ServiceContext serviceContext, List<SocialActivity> userDigestActivities) { Comparator<SocialActivity> socialActivityClassIdComparator = new Comparator<SocialActivity>() { @Override public int compare(SocialActivity o1, SocialActivity o2) { return (int)(o1.getClassNameId() - o2.getClassNameId()); } }; Comparator<SocialActivity> socialActivityCreateDateComparator = new Comparator<SocialActivity>() { @Override public int compare(SocialActivity o1, SocialActivity o2) { return (int)(o1.getCreateDate() - o2.getCreateDate()); } }; ComparatorChain comparatorChain = new ComparatorChain(); comparatorChain.addComparator(socialActivityClassIdComparator); comparatorChain.addComparator(socialActivityCreateDateComparator); Collections.sort(userDigestActivities, comparatorChain); StringBuilder body = new StringBuilder(); body.append(StringUtil.replace(DAILY_DIGEST_ENTRY_TEXT, DAILY_DIGEST_NOTIFICATION_SUBJECT_DATE_PLACEHOLDER, dateToDateString(lastDailyEmailNotification))); body.append("<br/><br/>"); for (SocialActivity socialActivity : userDigestActivities) { //prevent null pointer exceptions which might happen at this point if (socialActivity == null || serviceContext == null || serviceContext.getRequest() == null || serviceContext.getRequest().getAttribute(WebKeys.THEME_DISPLAY) == null) { continue; } SocialActivityFeedEntry entry = SocialActivityInterpreterLocalServiceUtil.interpret(StringPool.BLANK, socialActivity, serviceContext); if (entry == null) { continue; } body.append("<div style='margin-left: 10px'>").append(getMailBody(entry)).append("</div><br/><br/>"); } return body.toString(); } private Map<User, List<SocialActivity>> getUserToActivityDigestMap(List<SocialActivity> activities) throws SystemException, PortalException { Map<User, List<SocialActivity>> userDigestActivitiesMap = new HashMap<>(); for (SocialActivity activity : activities) { // Aggregate all activities for all users for (Object subscriptionObj : getActivitySubscribers(activity)) { ActivitySubscription subscription = (ActivitySubscription) subscriptionObj; User recipient = UserLocalServiceUtil.getUser(subscription.getReceiverId()); if (subscription.getReceiverId() == activity.getUserId()) { continue; } if (MessageUtil.getMessagingPreferences(recipient.getUserId()).getEmailOnActivity() && MessageUtil.getMessagingPreferences(recipient.getUserId()).getEmailActivityDailyDigest()) { List<SocialActivity> userDigestActivities = userDigestActivitiesMap.get(recipient); if (Validator.isNull(userDigestActivities)) { userDigestActivities = new ArrayList<>(); userDigestActivitiesMap.put(recipient, userDigestActivities); } userDigestActivities.add(activity); } } } return userDigestActivitiesMap; } private void sendInstantNotifications(SocialActivity activity, ServiceContext serviceContext) throws SystemException, PortalException { SocialActivityFeedEntry entry = SocialActivityInterpreterLocalServiceUtil.interpret(StringPool.BLANK, activity, serviceContext); if (entry == null) { return; } String subject = getMailSubject(entry); String messageTemplate = getMailBody(entry); Set<User> recipients = new HashSet<>(); Map<Long, ActivitySubscription> subscriptionsPerUser = new HashMap<>(); for (Object subscriptionObj : getActivitySubscribers(activity)) { ActivitySubscription subscription = (ActivitySubscription) subscriptionObj; if (subscription.getReceiverId() == activity.getUserId()) { continue; } User user = UserLocalServiceUtil.getUser(subscription.getReceiverId()); recipients.add(user); // map users to subscriptions for unregistration links subscriptionsPerUser.put(user.getUserId(), subscription); } for (User recipient : recipients) { if (MessageUtil.getMessagingPreferences(recipient.getUserId()).getEmailOnActivity() && !MessageUtil.getMessagingPreferences(recipient.getUserId()).getEmailActivityDailyDigest()) { String unsubscribeFooter = getUnsubscribeIndividualSubscriptionFooter(serviceContext.getPortalURL(), NotificationUnregisterUtils.getUnregisterLink(subscriptionsPerUser.get(recipient.getUserId()), serviceContext)); sendEmailMessage(recipient, subject, messageTemplate, unsubscribeFooter, serviceContext.getPortalURL()); } } } private List<ActivitySubscription> getActivitySubscribers(SocialActivity activity) throws SystemException { DynamicQuery query = DynamicQueryFactoryUtil.forClass(ActivitySubscription.class); Criterion criterionClassNameId = RestrictionsFactoryUtil.eq("classNameId", activity.getClassNameId()); Criterion criterionClassPK = RestrictionsFactoryUtil.eq("classPK", activity.getClassPK()); Criterion combinedCriterion = RestrictionsFactoryUtil.and(criterionClassNameId, criterionClassPK); // Check for constraints which users should receive notifications ActivitySubscriptionConstraint subscriptionConstraint = new ActivitySubscriptionConstraint(activity.getClassNameId(), activity.getType()); if (subscriptionConstraint.areSubscribersConstrained()) { Criterion contrainedUsers = RestrictionsFactoryUtil.in("receiverId", subscriptionConstraint.getWhitelist(activity.getClassPK())); query.add(RestrictionsFactoryUtil.and(combinedCriterion, contrainedUsers)); } else { query.add(combinedCriterion); } return ActivitySubscriptionLocalServiceUtil.dynamicQuery(query); } private void sendEmailMessage(User recipient, String subject, String body, String unregisterFooter, String portalBaseUrl) throws SystemException, NoSuchConfigurationAttributeException { try { InternetAddress fromEmail = TemplateReplacementUtil.getAdminFromEmailAddress(); InternetAddress toEmail = new InternetAddress(recipient.getEmailAddress(), recipient.getFullName()); body += MESSAGE_FOOTER_TEMPLATE; body = HtmlUtil.makeRelativeLinksAbsolute(body, portalBaseUrl); body = body.replaceAll("\n", "\n<br />"); String message = body.replace(USER_PROFILE_LINK_PLACEHOLDER, getUserLink(recipient, portalBaseUrl)); message = HtmlUtil.decodeHTMLEntitiesForEmail(message); // add link to unsubscribe message += "<br /><br />" + unregisterFooter; MailEngine.send(fromEmail, toEmail, TemplateReplacementUtil.replacePlatformConstants(subject), TemplateReplacementUtil.replacePlatformConstants(message), true); } catch (MailEngineException | UnsupportedEncodingException e) { _log.error("Can't send email notifications to users"); _log.debug("Can't send email message", e); } } private String getMailBody(SocialActivityFeedEntry entry) { try { return (String) entry.getClass().getMethod("getMailBody").invoke(entry); } catch (NoSuchMethodException e) { // ignore } catch (IllegalArgumentException | SecurityException | InvocationTargetException | IllegalAccessException e) { _log.error(e); } if (entry.getBody() != null) { return entry.getBody(); } return entry.getTitle(); } private String getMailSubject(SocialActivityFeedEntry entry) { try { return (String) entry.getClass().getMethod("getMailSubject").invoke(entry); } catch (NoSuchMethodException e) { // ignore } catch (IllegalArgumentException | SecurityException | InvocationTargetException | IllegalAccessException e) { _log.error(e); } if (entry.getTitle() != null) { return entry.getTitle(); } return entry.getBody(); } private String getUserLink(User user, String portalBaseUrl) { return USER_PROFILE_LINK_TEMPLATE.replaceAll(USER_ID_PLACEHOLDER, String.valueOf(user.getUserId())).replaceAll(DOMAIN_PLACEHOLDER, portalBaseUrl); } private String getUnsubscribeIndividualSubscriptionFooter(String portalBaseUrl, String unsubscribeUrl) throws PortalException, SystemException { String faqUrl = portalBaseUrl + FAQ_DIGEST_URL_PATH; String footer = TemplateReplacementUtil.replaceContestTypeStrings( StringUtil.replace(UNSUBSCRIBE_INSTANT_NOTIFICATION_TEXT, FAQ_DIGEST_LINK_PLACEHOLDER, faqUrl), null); //TODO: select contest type above? -> uses generic word! footer = StringUtil.replace(footer, UNSUBSCRIBE_SUBSCRIPTION_LINK_PLACEHOLDER, unsubscribeUrl); return footer; } private String getUnsubscribeDailyDigestFooter(String unsubscribeUrl) { return StringUtil.replace(UNSUBSCRIBE_DAILY_DIGEST_NOTIFICATION_TEXT, UNSUBSCRIBE_SUBSCRIPTION_LINK_PLACEHOLDER, unsubscribeUrl); } private String dateToDateString(Date date) { SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); return formatter.format(date); } }
package be.ibridge.kettle.core.database; import java.io.StringReader; import java.sql.BatchUpdateException; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Calendar; import java.util.Hashtable; import java.util.Properties; import org.eclipse.core.runtime.IProgressMonitor; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Counter; import be.ibridge.kettle.core.DBCache; import be.ibridge.kettle.core.DBCacheEntry; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.exception.KettleDatabaseBatchException; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.step.dimensionlookup.DimensionLookupMeta; /** * Database handles the process of connecting to, reading from, writing to and updating databases. * The database specific parameters are defined in DatabaseInfo. * * @author Matt * @since 05-04-2003 * */ public class Database { private DatabaseMeta databaseMeta; private int rowlimit; private int commitsize; private Connection connection; private Statement sel_stmt; private PreparedStatement pstmt; private PreparedStatement prepStatementLookup; private PreparedStatement prepStatementUpdate; private PreparedStatement prepStatementInsert; private PreparedStatement pstmt_pun; private PreparedStatement pstmt_dup; private PreparedStatement pstmt_seq; private CallableStatement cstmt; // private ResultSetMetaData rsmd; private DatabaseMetaData dbmd; private Row rowinfo; private int written; private LogWriter log; /** * Counts the number of rows written to a batch. */ private int batchCounter; /** * Construnct a new Database Connection * @param inf The Database Connection Info to construct the connection with. */ public Database(DatabaseMeta inf) { log=LogWriter.getInstance(); databaseMeta = inf; pstmt = null; // rsmd = null; rowinfo = null; dbmd = null; rowlimit=0; written=0; log.logDetailed(toString(), "New database connection defined"); } /** * @return Returns the connection. */ public Connection getConnection() { return connection; } /** * Set the maximum number of records to retrieve from a query. * @param rows */ public void setQueryLimit(int rows) { rowlimit = rows; } /** * @return Returns the prepStatementInsert. */ public PreparedStatement getPrepStatementInsert() { return prepStatementInsert; } /** * @return Returns the prepStatementLookup. */ public PreparedStatement getPrepStatementLookup() { return prepStatementLookup; } /** * @return Returns the prepStatementUpdate. */ public PreparedStatement getPrepStatementUpdate() { return prepStatementUpdate; } /** * Open the database connection. * @throws KettleDatabaseException if something went wrong. */ public void connect() throws KettleDatabaseException { try { if (databaseMeta!=null) { connect(databaseMeta.getDriverClass()); log.logDetailed(toString(), "Connected to database."); } else { throw new KettleDatabaseException("No valid database connection defined!"); } } catch(Exception e) { throw new KettleDatabaseException("Error occured while trying to connect to the database", e); } } /** * Connect using the correct classname * @param classname for example "org.gjt.mm.mysql.Driver" * @return true if the connect was succesfull, false if something went wrong. */ private void connect(String classname) throws KettleDatabaseException { // Install and load the jdbc Driver try { Class.forName(classname); } catch(NoClassDefFoundError e) { throw new KettleDatabaseException("Exception while loading class", e); } catch(ClassNotFoundException e) { throw new KettleDatabaseException("Exception while loading class", e); } catch(Exception e) { throw new KettleDatabaseException("Exception while loading class", e); } try { String url = StringUtil.environmentSubstitute(databaseMeta.getURL()); String userName = StringUtil.environmentSubstitute(databaseMeta.getUsername()); String password = StringUtil.environmentSubstitute(databaseMeta.getPassword()); if (databaseMeta.supportsOptionsInURL()) { if (!Const.isEmpty(userName)) { connection = DriverManager.getConnection(url, userName, password); } else { // Perhaps the username is in the URL or no username is required... connection = DriverManager.getConnection(url); } } else { Properties properties = databaseMeta.getConnectionProperties(); if (!Const.isEmpty(userName)) properties.put("user", userName); if (!Const.isEmpty(password)) properties.put("password", password); connection = DriverManager.getConnection(url, properties); } } catch(SQLException e) { throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e); } catch(Throwable e) { throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e); } } /** * Disconnect from the database and close all open prepared statements. */ public void disconnect() { try { if (connection==null) return ; // Nothing to do... if (connection.isClosed()) return ; // Nothing to do... if (!isAutoCommit()) commit(); if (pstmt !=null) { pstmt.close(); pstmt=null; } if (prepStatementLookup!=null) { prepStatementLookup.close(); prepStatementLookup=null; } if (prepStatementInsert!=null) { prepStatementInsert.close(); prepStatementInsert=null; } if (prepStatementUpdate!=null) { prepStatementUpdate.close(); prepStatementUpdate=null; } if (pstmt_seq!=null) { pstmt_seq.close(); pstmt_seq=null; } if (connection !=null) { connection.close(); connection=null; } log.logDetailed(toString(), "Connection to database closed!"); } catch(SQLException ex) { log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage()); } catch(KettleDatabaseException dbe) { log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage()); } } public void cancelQuery() throws KettleDatabaseException { try { if (pstmt !=null) { pstmt.cancel(); } if (sel_stmt !=null) { sel_stmt.cancel(); } log.logDetailed(toString(), "Open query canceled!"); } catch(SQLException ex) { throw new KettleDatabaseException("Error cancelling query", ex); } } /** * Specify after how many rows a commit needs to occur when inserting or updating values. * @param commsize The number of rows to wait before doing a commit on the connection. */ public void setCommit(int commsize) { commitsize=commsize; String onOff = (commitsize<=0?"on":"off"); try { connection.setAutoCommit(commitsize<=0); log.logDetailed(toString(), "Auto commit "+onOff); } catch(Exception e) { log.logError(toString(), "Can't turn auto commit "+onOff); } } /** * Perform a commit the connection if this is supported by the database */ public void commit() throws KettleDatabaseException { try { if (getDatabaseMetaData().supportsTransactions()) { connection.commit(); } else { log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]"); } } catch(Exception e) { if (databaseMeta.supportsEmptyTransactions()) throw new KettleDatabaseException("Error comitting connection", e); } } public void rollback() throws KettleDatabaseException { try { if (getDatabaseMetaData().supportsTransactions()) { connection.rollback(); } else { log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]"); } } catch(SQLException e) { throw new KettleDatabaseException("Error performing rollback on connection", e); } } /** * Prepare inserting values into a table, using the fields & values in a Row * @param r The row to determine which values need to be inserted * @param table The name of the table in which we want to insert rows * @throws KettleDatabaseException if something went wrong. */ public void prepareInsert(Row r, String table) throws KettleDatabaseException { if (r.size()==0) { throw new KettleDatabaseException("No fields in row, can't insert!"); } String ins = getInsertStatement(table, r); log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins); prepStatementInsert=prepareSQL(ins); } /** * Prepare a statement to be executed on the database. (does not return generated keys) * @param sql The SQL to be prepared * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql) throws KettleDatabaseException { return prepareSQL(sql, false); } /** * Prepare a statement to be executed on the database. * @param sql The SQL to be prepared * @param returnKeys set to true if you want to return generated keys from an insert statement * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException { try { if (returnKeys) { return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS); } else { return connection.prepareStatement(databaseMeta.stripCR(sql)); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex); } } public void closeLookup() throws KettleDatabaseException { closePreparedStatement(pstmt); } public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException { if (ps!=null) { try { ps.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing prepared statement", e); } } } public void closeInsert() throws KettleDatabaseException { if (prepStatementInsert!=null) { try { prepStatementInsert.close(); prepStatementInsert = null; } catch(SQLException e) { throw new KettleDatabaseException("Error closing insert prepared statement.", e); } } } public void closeUpdate() throws KettleDatabaseException { if (prepStatementUpdate!=null) { try { prepStatementUpdate.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing update prepared statement.", e); } } } public void setValues(Row r) throws KettleDatabaseException { setValues(r, pstmt); } public void setValuesInsert(Row r) throws KettleDatabaseException { setValues(r, prepStatementInsert); } public void setValuesUpdate(Row r) throws KettleDatabaseException { setValues(r, prepStatementUpdate); } public void setValuesLookup(Row r) throws KettleDatabaseException { setValues(r, prepStatementLookup); } public void setProcValues(Row r, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException { int pos; if (result) pos=2; else pos=1; for (int i=0;i<argnrs.length;i++) { if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT")) { Value v=r.getValue(argnrs[i]); setValue(cstmt, v, pos); pos++; } } } public void setValue(PreparedStatement ps, Value v, int pos) throws KettleDatabaseException { String debug = ""; try { switch(v.getType()) { case Value.VALUE_TYPE_NUMBER : debug="Number"; if (!v.isNull()) { debug="Number, not null, getting number from value"; double num = v.getNumber(); if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0) { debug="Number, rounding to precision ["+v.getPrecision()+"]"; num = Const.round(num, v.getPrecision()); } debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement"; ps.setDouble(pos, num); } else { ps.setNull(pos, java.sql.Types.DOUBLE); } break; case Value.VALUE_TYPE_INTEGER: debug="Integer"; if (!v.isNull()) { if (databaseMeta.supportsSetLong()) { ps.setLong(pos, v.getInteger() ); } else { if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0) { ps.setDouble(pos, v.getNumber() ); } else { ps.setDouble(pos, Const.round( v.getNumber(), v.getPrecision() ) ); } } } else { ps.setNull(pos, java.sql.Types.INTEGER); } break; case Value.VALUE_TYPE_STRING : debug="String"; if (v.getLength()<DatabaseMeta.CLOB_LENGTH) { if (!v.isNull() && v.getString()!=null) { ps.setString(pos, v.getString()); } else { ps.setNull(pos, java.sql.Types.VARCHAR); } } else { if (!v.isNull()) { int maxlen = databaseMeta.getMaxTextFieldLength(); int len = v.getStringLength(); // Take the last maxlen characters of the string... int begin = len - maxlen; if (begin<0) begin=0; // Get the substring! String logging = v.getString().substring(begin); if (databaseMeta.supportsSetCharacterStream()) { StringReader sr = new StringReader(logging); ps.setCharacterStream(pos, sr, logging.length()); } else { ps.setString(pos, logging); } } else { ps.setNull(pos, java.sql.Types.VARCHAR); } } break; case Value.VALUE_TYPE_DATE : debug="Date"; if (!v.isNull() && v.getDate()!=null) { long dat = v.getDate().getTime(); if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion()) { // Convert to DATE! java.sql.Date ddate = new java.sql.Date(dat); ps.setDate(pos, ddate); } else { java.sql.Timestamp sdate = new java.sql.Timestamp(dat); ps.setTimestamp(pos, sdate); } } else { if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion()) { ps.setNull(pos, java.sql.Types.DATE); } else { ps.setNull(pos, java.sql.Types.TIMESTAMP); } } break; case Value.VALUE_TYPE_BOOLEAN: debug="Boolean"; if (databaseMeta.supportsBooleanDataType()) { if (!v.isNull()) { ps.setBoolean(pos, v.getBoolean()); } else { ps.setNull(pos, java.sql.Types.BOOLEAN); } } else { if (!v.isNull()) { ps.setString(pos, v.getBoolean()?"Y":"N"); } else { ps.setNull(pos, java.sql.Types.CHAR); } } break; case Value.VALUE_TYPE_BIGNUMBER: debug="BigNumber"; if (!v.isNull()) { ps.setBigDecimal(pos, v.getBigNumber()); } else { ps.setNull(pos, java.sql.Types.DECIMAL); } break; case Value.VALUE_TYPE_BINARY: debug="Binary"; if (!v.isNull() && v.getBytes()!=null) { ps.setBytes(pos, v.getBytes()); } else { ps.setNull(pos, java.sql.Types.BINARY); } break; default: debug="default"; // placeholder ps.setNull(pos, java.sql.Types.VARCHAR); break; } } catch(SQLException ex) { throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex); } catch(Exception e) { throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e); } } // Sets the values of the preparedStatement pstmt. public void setValues(Row r, PreparedStatement ps) throws KettleDatabaseException { int i; Value v; // now set the values in the row! for (i=0;i<r.size();i++) { v=r.getValue(i); try { //System.out.println("Setting value ["+v+"] on preparedStatement, position="+i); setValue(ps, v, i+1); } catch(KettleDatabaseException e) { throw new KettleDatabaseException("offending row : "+r, e); } } } public void setDimValues(Row r, Value dateval) throws KettleDatabaseException { setDimValues(r, dateval, prepStatementLookup); } // Sets the values of the preparedStatement pstmt. public void setDimValues(Row r, Value dateval, PreparedStatement ps) throws KettleDatabaseException { int i; Value v; long dat; // now set the values in the row! for (i=0;i<r.size();i++) { v=r.getValue(i); try { setValue(ps, v, i+1); } catch(KettleDatabaseException e) { throw new KettleDatabaseException("Unable to set value #"+i+" on dimension using row :"+r, e); } } if (dateval!=null && dateval.getDate()!=null && !dateval.isNull()) { dat = dateval.getDate().getTime(); } else { Calendar cal=Calendar.getInstance(); // use system date! dat = cal.getTime().getTime(); } java.sql.Timestamp sdate = new java.sql.Timestamp(dat); try { ps.setTimestamp(r.size()+1, sdate); // ? > date_from ps.setTimestamp(r.size()+2, sdate); // ? <= date_to } catch(SQLException ex) { throw new KettleDatabaseException("Unable to set timestamp on fromdate or todate", ex); } } public void dimUpdate(Row row, String table, String fieldlookup[], int fieldnrs[], String returnkey, Value dimkey ) throws KettleDatabaseException { int i; if (pstmt_dup==null) // first time: construct prepared statement { // Construct the SQL statement... /* * UPDATE d_customer * SET fieldlookup[] = row.getValue(fieldnrs) * WHERE returnkey = dimkey * ; */ String sql="UPDATE "+table+Const.CR+"SET "; for (i=0;i<fieldlookup.length;i++) { if (i>0) sql+=", "; else sql+=" "; sql+=fieldlookup[i]+" = ?"+Const.CR; } sql+="WHERE "+returnkey+" = ?"; try { if (log.isDebug()) log.logDebug(toString(), "Preparing statement: ["+sql+"]"); pstmt_dup=connection.prepareStatement(databaseMeta.stripCR(sql)); } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't prepare statement :"+Const.CR+sql, ex); } } // Assemble information // New Row rupd=new Row(); for (i=0;i<fieldnrs.length;i++) { rupd.addValue( row.getValue(fieldnrs[i])); } rupd.addValue( dimkey ); setValues(rupd, pstmt_dup); insertRow(pstmt_dup); } // This inserts new record into dimension // Optionally, if the entry already exists, update date range from previous version // of the entry. public void dimInsert(Row row, String table, boolean newentry, String keyfield, boolean autoinc, Value technicalKey, String versionfield, Value val_version, String datefrom, Value val_datfrom, String dateto, Value val_datto, String fieldlookup[], int fieldnrs[], String key[], String keylookup[], int keynrs[] ) throws KettleDatabaseException { int i; if (prepStatementInsert==null && prepStatementUpdate==null) // first time: construct prepared statement { /* Construct the SQL statement... * * INSERT INTO * d_customer(keyfield, versionfield, datefrom, dateto, key[], fieldlookup[]) * VALUES (val_key ,val_version , val_datfrom, val_datto, keynrs[], fieldnrs[]) * ; */ String sql="INSERT INTO "+databaseMeta.quoteField(table)+"( "; if (!autoinc) sql+=databaseMeta.quoteField(keyfield)+", "; // NO AUTOINCREMENT else if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_INFORMIX) sql+="0, "; // placeholder on informix! sql+=databaseMeta.quoteField(versionfield)+", "+databaseMeta.quoteField(datefrom)+", "+databaseMeta.quoteField(dateto); for (i=0;i<keylookup.length;i++) { sql+=", "+databaseMeta.quoteField(keylookup[i]); } for (i=0;i<fieldlookup.length;i++) { sql+=", "+databaseMeta.quoteField(fieldlookup[i]); } sql+=") VALUES("; if (!autoinc) sql+="?, "; sql+="?, ?, ?"; for (i=0;i<keynrs.length;i++) { sql+=", ?"; } for (i=0;i<fieldnrs.length;i++) { sql+=", ?"; } sql+=" )"; try { if (keyfield==null) { log.logDetailed(toString(), "SQL w/ return keys=["+sql+"]"); prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS); } else { log.logDetailed(toString(), "SQL=["+sql+"]"); prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql)); } //pstmt=con.prepareStatement(sql, new String[] { "klant_tk" } ); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare dimension insert :"+Const.CR+sql, ex); } /* * UPDATE d_customer * SET dateto = val_datnow * WHERE keylookup[] = keynrs[] * AND versionfield = val_version - 1 * ; */ String sql_upd="UPDATE "+databaseMeta.quoteField(table)+Const.CR+"SET "+databaseMeta.quoteField(dateto)+" = ?"+Const.CR; sql_upd+="WHERE "; for (i=0;i<keylookup.length;i++) { if (i>0) sql_upd+="AND "; sql_upd+=databaseMeta.quoteField(keylookup[i])+" = ?"+Const.CR; } sql_upd+="AND "+databaseMeta.quoteField(versionfield)+" = ? "; try { log.logDetailed(toString(), "Preparing update: "+Const.CR+sql_upd+Const.CR); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql_upd)); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare dimension update :"+Const.CR+sql_upd, ex); } } Row rins=new Row(); if (!autoinc) rins.addValue(technicalKey); if (!newentry) { Value val_new_version = new Value(val_version); val_new_version.setValue( val_new_version.getNumber()+1 ); // determine next version rins.addValue(val_new_version); } else { rins.addValue(val_version); } rins.addValue(val_datfrom); rins.addValue(val_datto); for (i=0;i<keynrs.length;i++) { rins.addValue( row.getValue(keynrs[i])); } for (i=0;i<fieldnrs.length;i++) { Value val = row.getValue(fieldnrs[i]); rins.addValue( val ); } if (log.isDebug()) log.logDebug(toString(), "rins, size="+rins.size()+", values="+rins.toString()); // INSERT NEW VALUE! setValues(rins, prepStatementInsert); insertRow(prepStatementInsert); if (log.isDebug()) log.logDebug(toString(), "Row inserted!"); if (keyfield==null) { try { Row keys = getGeneratedKeys(prepStatementInsert); if (keys.size()>0) { technicalKey.setValue(keys.getValue(0).getInteger()); } else { throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : no value found!"); } } catch(Exception e) { throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : unexpected error: ", e); } } if (!newentry) // we have to update the previous version in the dimension! { /* * UPDATE d_customer * SET dateto = val_datfrom * WHERE keylookup[] = keynrs[] * AND versionfield = val_version - 1 * ; */ Row rupd = new Row(); rupd.addValue(val_datfrom); for (i=0;i<keynrs.length;i++) { rupd.addValue( row.getValue(keynrs[i])); } rupd.addValue(val_version); if (log.isRowLevel()) log.logRowlevel(toString(), "UPDATE using rupd="+rupd.toString()); // UPDATE VALUES setValues(rupd, prepStatementUpdate); // set values for update if (log.isDebug()) log.logDebug(toString(), "Values set for update ("+rupd.size()+")"); insertRow(prepStatementUpdate); // do the actual update if (log.isDebug()) log.logDebug(toString(), "Row updated!"); } } /** * @param ps The prepared insert statement to use * @return The generated keys in auto-increment fields * @throws KettleDatabaseException in case something goes wrong retrieving the keys. */ public Row getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException { ResultSet keys = null; try { keys=ps.getGeneratedKeys(); // 1 row of keys ResultSetMetaData resultSetMetaData = keys.getMetaData(); Row rowInfo = getRowInfo(resultSetMetaData); return getRow(keys, resultSetMetaData, rowInfo); } catch(Exception ex) { throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex); } finally { if (keys!=null) { try { keys.close(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e); } } } } // This updates all versions of a dimension entry. public void dimPunchThrough(Row row, String table, int fieldupdate[], String fieldlookup[], int fieldnrs[], String key[], String keylookup[], int keynrs[] ) throws KettleDatabaseException { int i; boolean first; if (pstmt_pun==null) // first time: construct prepared statement { /* * UPDATE table * SET punchv1 = fieldx, ... * WHERE keylookup[] = keynrs[] * ; */ String sql_upd="UPDATE "+table+Const.CR; sql_upd+="SET "; first=true; for (i=0;i<fieldlookup.length;i++) { if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH) { if (!first) sql_upd+=", "; else sql_upd+=" "; first=false; sql_upd+=fieldlookup[i]+" = ?"+Const.CR; } } sql_upd+="WHERE "; for (i=0;i<keylookup.length;i++) { if (i>0) sql_upd+="AND "; sql_upd+=keylookup[i]+" = ?"+Const.CR; } try { pstmt_pun=connection.prepareStatement(databaseMeta.stripCR(sql_upd)); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare dimension punchThrough update statement : "+Const.CR+sql_upd, ex); } } Row rupd=new Row(); for (i=0;i<fieldlookup.length;i++) { if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH) { rupd.addValue( row.getValue(fieldnrs[i])); } } for (i=0;i<keynrs.length;i++) { rupd.addValue( row.getValue(keynrs[i])); } // UPDATE VALUES setValues(rupd, pstmt_pun); // set values for update insertRow(pstmt_pun); // do the actual update } /** * This inserts new record into a junk dimension */ public void combiInsert( Row row, String table, String keyfield, boolean autoinc, Value val_key, String keylookup[], int keynrs[], boolean crc, String crcfield, Value val_crc ) throws KettleDatabaseException { String debug="Combination insert"; try { boolean comma; if (prepStatementInsert==null) // first time: construct prepared statement { debug="First: construct prepared statement"; /* Construct the SQL statement... * * INSERT INTO * d_test(keyfield, [crcfield,] keylookup[]) * VALUES(val_key, [val_crc], row values with keynrs[]) * ; */ StringBuffer sql = new StringBuffer(100); sql.append("INSERT INTO ").append(databaseMeta.quoteField(table)).append("( "); comma=false; if (!autoinc) // NO AUTOINCREMENT { sql.append(databaseMeta.quoteField(keyfield)); comma=true; } else if (databaseMeta.needsPlaceHolder()) { sql.append('0'); // placeholder on informix! Will be replaced in table by real autoinc value. comma=true; } if (crc) { if (comma) sql.append(", "); sql.append(databaseMeta.quoteField(crcfield)); comma=true; } for (int i=0;i<keylookup.length;i++) { if (comma) sql.append(", "); sql.append(databaseMeta.quoteField(keylookup[i])); comma=true; } sql.append(") VALUES ("); comma=false; if (keyfield!=null) { sql.append('?'); comma=true; } if (crc) { if (comma) sql.append(','); sql.append('?'); comma=true; } for (int i=0;i<keylookup.length;i++) { if (comma) sql.append(','); else comma=true; sql.append('?'); } sql.append(" )"); String sqlStatement = sql.toString(); try { debug="First: prepare statement"; if (keyfield==null) { log.logDetailed(toString(), "SQL with return keys: "+sqlStatement); prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sqlStatement), Statement.RETURN_GENERATED_KEYS); } else { log.logDetailed(toString(), "SQL without return keys: "+sqlStatement); prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sqlStatement)); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sqlStatement, ex); } catch(Exception ex) { throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sqlStatement, ex); } } debug="Create new insert row rins"; Row rins=new Row(); if (!autoinc) rins.addValue(val_key); if (crc) { rins.addValue(val_crc); } for (int i=0;i<keynrs.length;i++) { rins.addValue( row.getValue(keynrs[i])); } if (log.isRowLevel()) log.logRowlevel(toString(), "rins="+rins.toString()); debug="Set values on insert"; // INSERT NEW VALUE! setValues(rins, prepStatementInsert); debug="Insert row"; insertRow(prepStatementInsert); debug="Retrieve key"; if (keyfield==null) { ResultSet keys = null; try { keys=prepStatementInsert.getGeneratedKeys(); // 1 key if (keys.next()) val_key.setValue(keys.getDouble(1)); else { throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield+", no fields in resultset"); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex); } finally { try { if ( keys != null ) keys.close(); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex); } } } } catch(Exception e) { log.logError(toString(), Const.getStackTracker(e)); throw new KettleDatabaseException("Unexpected error in combination insert in part ["+debug+"] : "+e.toString(), e); } } public Value getNextSequenceValue(String seq, String keyfield) throws KettleDatabaseException { Value retval=null; try { if (pstmt_seq==null) { pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(seq))); } ResultSet rs=null; try { rs = pstmt_seq.executeQuery(); if (rs.next()) { long next = rs.getLong(1); retval=new Value(keyfield, next); retval.setLength(9,0); } } finally { if ( rs != null ) rs.close(); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to get next value for sequence : "+seq, ex); } return retval; } public void insertRow(String tableName, Row fields) throws KettleDatabaseException { prepareInsert(fields, tableName); setValuesInsert(fields); insertRow(); closeInsert(); } public String getInsertStatement(String tableName, Row fields) { StringBuffer ins=new StringBuffer(128); ins.append("INSERT INTO ").append(databaseMeta.quoteField(tableName)).append("("); // now add the names in the row: for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); String name = fields.getValue(i).getName(); ins.append(databaseMeta.quoteField(name)); } ins.append(") VALUES ("); // Add placeholders... for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); ins.append(" ?"); } ins.append(")"); return ins.toString(); } public void insertRow() throws KettleDatabaseException { insertRow(prepStatementInsert); } public void insertRow(boolean batch) throws KettleDatabaseException { insertRow(prepStatementInsert, batch); } public void updateRow() throws KettleDatabaseException { insertRow(prepStatementUpdate); } public void insertRow(PreparedStatement ps) throws KettleDatabaseException { insertRow(ps, false); } /** * @param batchCounter The batchCounter to set. */ public void setBatchCounter(int batchCounter) { this.batchCounter = batchCounter; } /** * @return Returns the batchCounter. */ public int getBatchCounter() { return batchCounter; } private long testCounter = 0; /** * Insert a row into the database using a prepared statement that has all values set. * @param ps The prepared statement * @param batch True if you want to use batch inserts (size = commitsize) * @throws KettleDatabaseException */ public void insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException { String debug="insertRow start"; try { boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates(); // Add support for batch inserts... if (!isAutoCommit()) { if (useBatchInsert) { debug="insertRow add batch"; batchCounter++; ps.addBatch(); // Add the batch, but don't forget to run the batch testCounter++; // System.out.println("testCounter is at "+testCounter); } else { debug="insertRow exec update"; ps.executeUpdate(); } } else { ps.executeUpdate(); } written++; if (!isAutoCommit() && (written%commitsize)==0) { if (useBatchInsert) { debug="insertRow executeBatch commit"; ps.executeBatch(); commit(); ps.clearBatch(); // System.out.println("EXECUTE BATCH, testcounter is at "+testCounter); batchCounter=0; } else { debug="insertRow normal commit"; commit(); } } } catch(BatchUpdateException ex) { //System.out.println("Batch update exception "+ex.getMessage()); KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); throw kdbe; } catch(SQLException ex) { log.logError(toString(), Const.getStackTracker(ex)); throw new KettleDatabaseException("Error inserting row", ex); } catch(Exception e) { // System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage()); throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e); } } /** * Clears batch of insert prepared statement * @deprecated * @throws KettleDatabaseException */ public void clearInsertBatch() throws KettleDatabaseException { clearBatch(prepStatementInsert); } public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException { try { preparedStatement.clearBatch(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to clear batch for prepared statement", e); } } public void insertFinished(boolean batch) throws KettleDatabaseException { insertFinished(prepStatementInsert, batch); prepStatementInsert = null; } public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException { try { if (ps!=null) { if (!isAutoCommit()) { if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0) { //System.out.println("Executing batch with "+batchCounter+" elements..."); ps.executeBatch(); commit(); } else { commit(); } } ps.close(); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex); } } /** * Execute an SQL statement on the database connection (has to be open) * @param sql The SQL to execute * @return a Result object indicating the number of lines read, deleted, inserted, updated, ... * @throws KettleDatabaseException in case anything goes wrong. */ public Result execStatement(String sql) throws KettleDatabaseException { return execStatement(sql, null); } public Result execStatement(String sql, Row params) throws KettleDatabaseException { Result result = new Result(); try { boolean resultSet; int count; if (params!=null) { PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql)); setValues(params, prep_stmt); // set the parameters! resultSet = prep_stmt.execute(); count = prep_stmt.getUpdateCount(); prep_stmt.close(); } else { String sqlStripped = databaseMeta.stripCR(sql); // log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]"); Statement stmt = connection.createStatement(); resultSet = stmt.execute(sqlStripped); count = stmt.getUpdateCount(); stmt.close(); } if (resultSet) { // the result is a resultset, but we don't do anything with it! // You should have called something else! // log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")"); } else { if (count > 0) { if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput((long) count); if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated((long) count); if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted((long) count); } } // See if a cache needs to be cleared... if (sql.toUpperCase().startsWith("ALTER TABLE")) { DBCache.getInstance().clear(databaseMeta.getName()); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex); } catch(Exception e) { throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e); } return result; } /** * Execute a series of SQL statements, separated by ; * * We are already connected... * Multiple statements have to be split into parts * We use the ";" to separate statements... * * We keep the results in Result object from Jobs * * @param script The SQL script to be execute * @throws KettleDatabaseException In case an error occurs * @return A result with counts of the number or records updates, inserted, deleted or read. */ public Result execStatements(String script) throws KettleDatabaseException { Result result = new Result(); String all = script; int from=0; int to=0; int length = all.length(); int nrstats = 0; while (to<length) { char c = all.charAt(to); if (c=='"') { to++; c=' '; while (to<length && c!='"') { c=all.charAt(to); to++; } } else if (c=='\'') // skip until next ' { to++; c=' '; while (to<length && c!='\'') { c=all.charAt(to); to++; } } else if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line... { to++; while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; } } if (c==';' || to>=length-1) // end of statement { if (to>=length-1) to++; // grab last char also! String stat; if (to<=length) stat = all.substring(from, to); else stat = all.substring(from); // If it ends with a ; remove that ; // Oracle for example can't stand it when this happens... if (stat.length()>0 && stat.charAt(stat.length()-1)==';') { stat = stat.substring(0,stat.length()-1); } if (!Const.onlySpaces(stat)) { String sql=Const.trim(stat); if (sql.toUpperCase().startsWith("SELECT")) { // A Query log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql); nrstats++; ResultSet rs = null; try { rs = openQuery(sql); if (rs!=null) { Row r = getRow(rs); while (r!=null) { result.setNrLinesRead(result.getNrLinesRead()+1); log.logDetailed(toString(), r.toString()); r=getRow(rs); } } else { if (log.isDebug()) log.logDebug(toString(), "Error executing query: "+Const.CR+sql); } } finally { try { if ( rs != null ) rs.close(); } catch (SQLException ex ) { if (log.isDebug()) log.logDebug(toString(), "Error closing query: "+Const.CR+sql); } } } else // any kind of statement { log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql); // A DDL statement nrstats++; Result res = execStatement(sql); result.add(res); } } to++; from=to; } else { to++; } } log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed"); return result; } public ResultSet openQuery(String sql) throws KettleDatabaseException { return openQuery(sql, null); } /** * Open a query on the database with a set of parameters stored in a Kettle Row * @param sql The SQL to launch with question marks (?) as placeholders for the parameters * @param params The parameters or null if no parameters are used. * @return A JDBC ResultSet * @throws KettleDatabaseException when something goes wrong with the query. */ public ResultSet openQuery(String sql, Row params) throws KettleDatabaseException { return openQuery(sql, params, ResultSet.FETCH_FORWARD); } public ResultSet openQuery(String sql, Row params, int fetch_mode) throws KettleDatabaseException { ResultSet res; String debug = "Start"; // Create a Statement try { if (params!=null) { debug = "P create prepared statement (con==null? "+(connection==null)+")"; pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); debug = "P Set values"; setValues(params); // set the dates etc! if (canWeSetFetchSize(pstmt) ) { debug = "P Set fetchsize"; int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE; // System.out.println("Setting pstmt fetchsize to : "+fs); { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { pstmt.setFetchSize(Integer.MIN_VALUE); } else pstmt.setFetchSize(fs); } debug = "P Set fetch direction"; pstmt.setFetchDirection(fetch_mode); } debug = "P Set max rows"; if (rowlimit>0) pstmt.setMaxRows(rowlimit); debug = "exec query"; res = pstmt.executeQuery(); } else { debug = "create statement"; sel_stmt = connection.createStatement(); if (canWeSetFetchSize(sel_stmt)) { debug = "Set fetchsize"; int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { sel_stmt.setFetchSize(Integer.MIN_VALUE); } else { sel_stmt.setFetchSize(fs); } debug = "Set fetch direction"; sel_stmt.setFetchDirection(fetch_mode); } debug = "Set max rows"; if (rowlimit>0) sel_stmt.setMaxRows(rowlimit); debug = "exec query"; res=sel_stmt.executeQuery(databaseMeta.stripCR(sql)); } debug = "openQuery : get rowinfo"; // MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened // to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows. rowinfo = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL); } catch(SQLException ex) { log.logError(toString(), "ERROR executing ["+sql+"]"); log.logError(toString(), "ERROR in part: ["+debug+"]"); printSQLException(ex); throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex); } catch(Exception e) { log.logError(toString(), "ERROR executing query: "+e.toString()); log.logError(toString(), "ERROR in part: "+debug); throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e); } return res; } private boolean canWeSetFetchSize(Statement statement) throws SQLException { return databaseMeta.isFetchSizeSupported() && ( statement.getMaxRows()>0 || databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES || databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL); } public ResultSet openQuery(PreparedStatement ps, Row params) throws KettleDatabaseException { ResultSet res; String debug = "Start"; // Create a Statement try { debug = "OQ Set values"; setValues(params, ps); // set the parameters! if (canWeSetFetchSize(ps)) { debug = "OQ Set fetchsize"; int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { ps.setFetchSize(Integer.MIN_VALUE); } else { ps.setFetchSize(fs); } debug = "OQ Set fetch direction"; ps.setFetchDirection(ResultSet.FETCH_FORWARD); } debug = "OQ Set max rows"; if (rowlimit>0) ps.setMaxRows(rowlimit); debug = "OQ exec query"; res = ps.executeQuery(); debug = "OQ getRowInfo()"; // rowinfo = getRowInfo(res.getMetaData()); // MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened // to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows. rowinfo = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL); } catch(SQLException ex) { throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex); } catch(Exception e) { throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e); } return res; } public Row getTableFields(String tablename) throws KettleDatabaseException { return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false); } public Row getQueryFields(String sql, boolean param) throws KettleDatabaseException { return getQueryFields(sql, param, null); } /** * See if the table specified exists by looking at the data dictionary! * @param tablename The name of the table to check. * @return true if the table exists, false if it doesn't. */ public boolean checkTableExists(String tablename) throws KettleDatabaseException { try { log.logDebug(toString(), "Checking if table ["+tablename+"] exists!"); if (getDatabaseMetaData()!=null) { ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } ); boolean found = false; if (alltables!=null) { while (alltables.next() && !found) { String schemaName = alltables.getString("TABLE_SCHEM"); String name = alltables.getString("TABLE_NAME"); if ( tablename.equalsIgnoreCase(name) || ( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) ) ) { log.logDebug(toString(), "table ["+tablename+"] was found!"); found=true; } } alltables.close(); return found; } else { throw new KettleDatabaseException("Unable to read table-names from the database meta-data."); } } else { throw new KettleDatabaseException("Unable to get database meta-data from the database."); } } catch(Exception e) { throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e); } } /** * Check whether the sequence exists, Oracle only! * @param sequenceName The name of the sequence * @return true if the sequence exists. */ public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException { boolean retval=false; if (!databaseMeta.supportsSequences()) return retval; try { // Get the info from the data dictionary... String sql = databaseMeta.getSQLSequenceExists(sequenceName); ResultSet res = openQuery(sql); if (res!=null) { Row row = getRow(res); if (row!=null) { retval=true; } closeQuery(res); } } catch(Exception e) { throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+sequenceName+"] exists", e); } return retval; } /** * Check if an index on certain fields in a table exists. * @param tablename The table on which the index is checked * @param idx_fields The fields on which the indexe is checked * @return True if the index exists */ public boolean checkIndexExists(String tablename, String idx_fields[]) throws KettleDatabaseException { if (!checkTableExists(tablename)) return false; log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc()); boolean exists[] = new boolean[idx_fields.length]; for (int i=0;i<exists.length;i++) exists[i]=false; try { switch(databaseMeta.getDatabaseType()) { case DatabaseMeta.TYPE_DATABASE_MSSQL: { // Get the info from the data dictionary... StringBuffer sql = new StringBuffer(128); sql.append("select i.name table_name, c.name column_name "); sql.append("from sysindexes i, sysindexkeys k, syscolumns c "); sql.append("where i.name = '"+tablename+"' "); sql.append("AND i.id = k.id "); sql.append("AND i.id = c.id "); sql.append("AND k.colid = c.colid "); ResultSet res = null; try { res = openQuery(sql.toString()); if (res!=null) { Row row = getRow(res); while (row!=null) { String column = row.getString("column_name", ""); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) exists[idx]=true; row = getRow(res); } } else { return false; } } finally { if ( res != null ) closeQuery(res); } } break; case DatabaseMeta.TYPE_DATABASE_ORACLE: { // Get the info from the data dictionary... String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tablename.toUpperCase()+"'"; ResultSet res = null; try { res = openQuery(sql); if (res!=null) { Row row = getRow(res); while (row!=null) { String column = row.getString("COLUMN_NAME", ""); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } row = getRow(res); } } else { return false; } } finally { if ( res != null ) closeQuery(res); } } break; case DatabaseMeta.TYPE_DATABASE_ACCESS: { // Get a list of all the indexes for this table ResultSet indexList = null; try { indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true); while (indexList.next()) { // String tablen = indexList.getString("TABLE_NAME"); // String indexn = indexList.getString("INDEX_NAME"); String column = indexList.getString("COLUMN_NAME"); // int pos = indexList.getShort("ORDINAL_POSITION"); // int type = indexList.getShort("TYPE"); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } } } finally { if ( indexList != null ) indexList.close(); } } break; default: { // Get a list of all the indexes for this table ResultSet indexList = null; try { indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true); while (indexList.next()) { // String tablen = indexList.getString("TABLE_NAME"); // String indexn = indexList.getString("INDEX_NAME"); String column = indexList.getString("COLUMN_NAME"); // int pos = indexList.getShort("ORDINAL_POSITION"); // int type = indexList.getShort("TYPE"); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } } } finally { if ( indexList != null ) indexList.close(); } } break; } // See if all the fields are indexed... boolean all=true; for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false; return all; } catch(Exception e) { e.printStackTrace(); throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e); } } public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon) { String cr_index=""; cr_index += "CREATE "; if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE)) cr_index += "UNIQUE "; if (bitmap && databaseMeta.supportsBitmapIndex()) cr_index += "BITMAP "; cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" "; cr_index += "ON "+databaseMeta.quoteField(tablename)+Const.CR; cr_index += "( "+Const.CR; for (int i=0;i<idx_fields.length;i++) { if (i>0) cr_index+=", "; else cr_index+=" "; cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR; } cr_index+=")"+Const.CR; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE && databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0) { cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace()); } if (semi_colon) { cr_index+=";"+Const.CR; } return cr_index; } public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon) { String cr_seq=""; if (sequence==null || sequence.length()==0) return cr_seq; if (databaseMeta.supportsSequences()) { cr_seq += "CREATE SEQUENCE "+databaseMeta.quoteField(sequence)+" "+Const.CR; // Works for both Oracle and PostgreSQL :-) cr_seq += "START WITH "+start_at+" "+Const.CR; cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR; if (max_value>0) cr_seq += "MAXVALUE "+max_value+Const.CR; if (semi_colon) cr_seq+=";"+Const.CR; } return cr_seq; } public Row getQueryFields(String sql, boolean param, Row inform) throws KettleDatabaseException { Row fields; DBCache dbcache = DBCache.getInstance(); DBCacheEntry entry=null; // Check the cache first! if (dbcache!=null) { entry = new DBCacheEntry(databaseMeta.getName(), sql); fields = dbcache.get(entry); if (fields!=null) { return fields; } } if (connection==null) return null; // Cache test without connect. // No cache entry found String debug=""; try { if (inform==null // Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214) && databaseMeta.getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_MSSQL ) { debug="inform==null"; sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); debug="isFetchSizeSupported()"; if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1) { debug = "Set fetchsize"; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { sel_stmt.setFetchSize(Integer.MIN_VALUE); } else { sel_stmt.setFetchSize(1); } } debug = "Set max rows to 1"; sel_stmt.setMaxRows(1); debug = "exec query"; ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql)); debug = "getQueryFields get row info"; fields = getRowInfo(r.getMetaData()); debug="close resultset"; r.close(); debug="close statement"; sel_stmt.close(); sel_stmt=null; } else { debug="prepareStatement"; PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql)); if (param) { Row par = inform; debug="getParameterMetaData()"; if (par==null) par = getParameterMetaData(ps); debug="getParameterMetaData()"; if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform); setValues(par, ps); } debug="executeQuery()"; ResultSet r = ps.executeQuery(); debug="getRowInfo"; fields=getRowInfo(ps.getMetaData()); debug="close resultset"; r.close(); debug="close preparedStatement"; ps.close(); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR+"Location: "+debug, ex); } catch(Exception e) { throw new KettleDatabaseException("Couldn't get field info in part ["+debug+"]", e); } // Store in cache!! if (dbcache!=null && entry!=null) { if (fields!=null) { dbcache.put(entry, fields); } } return fields; } public void closeQuery(ResultSet res) throws KettleDatabaseException { // close everything involved in the query! try { if (res!=null) res.close(); if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; } if (pstmt!=null) { pstmt.close(); pstmt=null;} } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex); } } private Row getRowInfo(ResultSetMetaData rm) throws KettleDatabaseException { return getRowInfo(rm, false); } // Build the row using ResultSetMetaData rsmd private Row getRowInfo(ResultSetMetaData rm, boolean ignoreLength) throws KettleDatabaseException { int nrcols; int i; Value v; String name; int type, valtype; int precision; int length; if (rm==null) return null; rowinfo = new Row(); try { nrcols=rm.getColumnCount(); for (i=1;i<=nrcols;i++) { name=new String(rm.getColumnName(i)); type=rm.getColumnType(i); valtype=Value.VALUE_TYPE_NONE; length=-1; precision=-1; switch(type) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: // Character Large Object valtype=Value.VALUE_TYPE_STRING; if (!ignoreLength) length=rm.getColumnDisplaySize(i); // System.out.println("Display of "+name+" = "+precision); // System.out.println("Precision of "+name+" = "+rm.getPrecision(i)); // System.out.println("Scale of "+name+" = "+rm.getScale(i)); break; case java.sql.Types.CLOB: valtype=Value.VALUE_TYPE_STRING; length=DatabaseMeta.CLOB_LENGTH; break; case java.sql.Types.BIGINT: valtype=Value.VALUE_TYPE_INTEGER; precision=0; // Max 9.223.372.036.854.775.807 length=15; break; case java.sql.Types.INTEGER: valtype=Value.VALUE_TYPE_INTEGER; precision=0; // Max 2.147.483.647 length=9; break; case java.sql.Types.SMALLINT: valtype=Value.VALUE_TYPE_INTEGER; precision=0; // Max 32.767 length=4; break; case java.sql.Types.TINYINT: valtype=Value.VALUE_TYPE_INTEGER; precision=0; // Max 127 length=2; break; case java.sql.Types.DECIMAL: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: case java.sql.Types.NUMERIC: valtype=Value.VALUE_TYPE_NUMBER; length=rm.getPrecision(i); precision=rm.getScale(i); if (length >=126) length=-1; if (precision >=126) precision=-1; if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL) { if (precision==0) { precision=-1; // precision is obviously incorrect if the type if Double/Float/Real } // If were dealing with Postgres and double precision types if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16) { precision=-1; length=-1; } } else { if (precision==0 && length<18 && length>0) // Among others Oracle is affected here. { valtype=Value.VALUE_TYPE_INTEGER; } } if (length>18 || precision>18) valtype=Value.VALUE_TYPE_BIGNUMBER; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE) { if (precision<=0 && length<=0) // undefined size: BIGNUMBER { valtype=Value.VALUE_TYPE_BIGNUMBER; length=-1; precision=-1; } } break; case java.sql.Types.DATE: case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: valtype=Value.VALUE_TYPE_DATE; break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: valtype=Value.VALUE_TYPE_BOOLEAN; break; case java.sql.Types.BINARY: case java.sql.Types.BLOB: case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: valtype=Value.VALUE_TYPE_BINARY; if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 && (2 * rm.getPrecision(i)) == rm.getColumnDisplaySize(i)) { // set the length for "CHAR(X) FOR BIT DATA" length = rm.getPrecision(i); } else { length=-1; } precision=-1; break; default: valtype=Value.VALUE_TYPE_STRING; if (!ignoreLength) length=rm.getPrecision(i); precision=rm.getScale(i); break; } // TODO: grab the comment as a description to the field, later // comment=rm.getColumnLabel(i); v=new Value(name, valtype); v.setLength(length, precision); rowinfo.addValue(v); } return rowinfo; } catch(SQLException ex) { throw new KettleDatabaseException("Error getting row information from database: ", ex); } } public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException { try { return rs.absolute(position); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to position "+position, e); } } public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException { try { return rs.relative(rows); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e); } } public void afterLast(ResultSet rs) throws KettleDatabaseException { try { rs.afterLast(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to after the last position", e); } } public void first(ResultSet rs) throws KettleDatabaseException { try { rs.first(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to the first position", e); } } /** * Get a row from the resultset. * @param rs The resultset to get the row from * @return one row or null if no row was found on the resultset or if an error occurred. */ public Row getRow(ResultSet rs) throws KettleDatabaseException { ResultSetMetaData rsmd = null; try { rsmd = rs.getMetaData(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e); } if (rowinfo==null) { rowinfo = getRowInfo(rsmd); } return getRow(rs, rsmd, rowinfo); } /** * Get a row from the resultset. * @param rs The resultset to get the row from * @return one row or null if no row was found on the resultset or if an error occurred. */ public Row getRow(ResultSet rs, ResultSetMetaData resultSetMetaData, Row rowInfo) throws KettleDatabaseException { Row row; int nrcols, i; Value val; try { nrcols=resultSetMetaData.getColumnCount(); if (rs.next()) { row=new Row(); for (i=0;i<nrcols;i++) { val=new Value(rowInfo.getValue(i)); // copy info from meta-data. switch(val.getType()) { case Value.VALUE_TYPE_BOOLEAN : val.setValue( rs.getBoolean(i+1) ); break; case Value.VALUE_TYPE_NUMBER : val.setValue( rs.getDouble(i+1) ); break; case Value.VALUE_TYPE_BIGNUMBER : val.setValue( rs.getBigDecimal(i+1) ); break; case Value.VALUE_TYPE_INTEGER : val.setValue( rs.getLong(i+1) ); break; case Value.VALUE_TYPE_STRING : val.setValue( rs.getString(i+1) ); break; case Value.VALUE_TYPE_BINARY : { if (databaseMeta.supportsGetBlob()) { Blob blob = rs.getBlob(i+1); val.setValue( blob.getBytes(1L, (int)blob.length()) ); } else { val.setValue( rs.getBytes(i+1) ); } } break; case Value.VALUE_TYPE_DATE : if (databaseMeta.supportsTimeStampToDateConversion()) { val.setValue( rs.getTimestamp(i+1) ); break; } else { val.setValue( rs.getDate(i+1) ); break; } default: break; } if (rs.wasNull()) val.setNull(); // null value! row.addValue(val); } } else { row=null; } return row; } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't get row from result set", ex); } } public void printSQLException(SQLException ex) { log.logError(toString(), "==> SQLException: "); while (ex != null) { log.logError(toString(), "Message: " + ex.getMessage ()); log.logError(toString(), "SQLState: " + ex.getSQLState ()); log.logError(toString(), "ErrorCode: " + ex.getErrorCode ()); ex = ex.getNextException(); log.logError(toString(), ""); } } public void setLookup(String table, String codes[], String condition[], String gets[], String rename[], String orderby ) throws KettleDatabaseException { setLookup(table, codes, condition, gets, rename, orderby, false); } // Lookup certain fields in a table public void setLookup(String table, String codes[], String condition[], String gets[], String rename[], String orderby, boolean checkForMultipleResults) throws KettleDatabaseException { String sql = "SELECT "; for (int i=0;i<gets.length;i++) { if (i!=0) sql += ", "; sql += databaseMeta.quoteField(gets[i]); if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i])) { sql+=" AS "+databaseMeta.quoteField(rename[i]); } } sql += " FROM "+databaseMeta.quoteField(table)+" WHERE "; for (int i=0;i<codes.length;i++) { if (i!=0) sql += " AND "; sql += databaseMeta.quoteField(codes[i]); if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql+=" BETWEEN ? AND ? "; } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql+=" "+condition[i]+" "; } else { sql+=" "+condition[i]+" ? "; } } if (orderby!=null && orderby.length()!=0) { sql += " ORDER BY "+orderby; } try { log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]"); prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql)); if (!checkForMultipleResults) { prepStatementLookup.setMaxRows(1); // alywas get only 1 line back! } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex); } } // Lookup certain fields in a table public boolean prepareUpdate(String table, String codes[], String condition[], String sets[]) { StringBuffer sql = new StringBuffer(128); int i; sql.append("UPDATE ").append(databaseMeta.quoteField(table)).append(Const.CR).append("SET "); for (i=0;i<sets.length;i++) { if (i!=0) sql.append(", "); sql.append(databaseMeta.quoteField(sets[i])); sql.append(" = ?").append(Const.CR); } sql.append("WHERE "); for (i=0;i<codes.length;i++) { if (i!=0) sql.append("AND "); sql.append(databaseMeta.quoteField(codes[i])); if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql.append(" BETWEEN ? AND ? "); } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql.append(" ").append(condition[i]).append(" "); } else { sql.append(" ").append(condition[i]).append(" ? "); } } try { String s = sql.toString(); log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]"); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s)); } catch(SQLException ex) { printSQLException(ex); return false; } return true; } /** * Prepare a delete statement by giving it the tablename, fields and conditions to work with. * @param table The table-name to delete in * @param codes * @param condition * @return */ public boolean prepareDelete(String table, String codes[], String condition[]) { String sql; int i; sql = "DELETE FROM "+table+Const.CR; sql+= "WHERE "; for (i=0;i<codes.length;i++) { if (i!=0) sql += "AND "; sql += codes[i]; if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql+=" BETWEEN ? AND ? "; } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql+=" "+condition[i]+" "; } else { sql+=" "+condition[i]+" ? "; } } try { log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]"); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql)); } catch(SQLException ex) { printSQLException(ex); return false; } return true; } public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype) throws KettleDatabaseException { String sql; int pos=0; int i; sql = "{ "; if (returnvalue!=null && returnvalue.length()!=0) { sql+="? = "; } sql+="call "+proc+" "; if (arg.length>0) sql+="("; for (i=0;i<arg.length;i++) { if (i!=0) sql += ", "; sql += " ?"; } if (arg.length>0) sql+=")"; sql+="}"; try { log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]"); cstmt=connection.prepareCall(sql); pos=1; if (!Const.isEmpty(returnvalue)) { switch(returntype) { case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break; case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break; case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break; case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break; case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break; case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break; default: break; } pos++; } for (i=0;i<arg.length;i++) { if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) { switch(argtype[i]) { case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break; case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break; case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break; case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break; case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break; case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break; default: break; } } } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare database procedure call", ex); } } /* * table: dimension table * keys[]: which dim-fields do we use to look up key? * retval: name of the key to return * datefield: do we have a datefield? * datefrom, dateto: date-range, if any. */ public boolean setDimLookup(String table, String keys[], String tk, String version, String extra[], String extraRename[], String datefrom, String dateto ) throws KettleDatabaseException { String sql; int i; /* * SELECT <tk>, <version>, ... * FROM <table> * WHERE key1=keys[1] * AND key2=keys[2] ... * AND <datefield> BETWEEN <datefrom> AND <dateto> * ; * */ sql = "SELECT "+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version); if (extra!=null) { for (i=0;i<extra.length;i++) { if (extra[i]!=null && extra[i].length()!=0) { sql+=", "+databaseMeta.quoteField(extra[i]); if (extraRename[i]!=null && extraRename[i].length()>0 && !extra[i].equals(extraRename[i])) { sql+=" AS "+databaseMeta.quoteField(extraRename[i]); } } } } sql+= " FROM "+databaseMeta.quoteField(table)+" WHERE "; for (i=0;i<keys.length;i++) { if (i!=0) sql += " AND "; sql += databaseMeta.quoteField(keys[i])+" = ? "; } sql += " AND ? >= "+databaseMeta.quoteField(datefrom)+" AND ? < "+databaseMeta.quoteField(dateto); try { log.logDetailed(toString(), "Dimension Lookup setting preparedStatement to ["+sql+"]"); prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql)); prepStatementLookup.setMaxRows(1); // alywas get only 1 line back! if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { prepStatementLookup.setFetchSize(0); // Make sure to DISABLE Streaming Result sets } log.logDetailed(toString(), "Finished preparing dimension lookup statement."); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare dimension lookup", ex); } return true; } /* CombinationLookup * table: dimension table * keys[]: which dim-fields do we use to look up key? * retval: name of the key to return */ public void setCombiLookup(String table, String keys[], String retval, boolean crc, String crcfield ) throws KettleDatabaseException { StringBuffer sql = new StringBuffer(100); int i; boolean comma; /* * SELECT <retval> * FROM <table> * WHERE ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) ) * AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) ) * ... * ; * * OR * * SELECT <retval> * FROM <table> * WHERE <crcfield> = ? * AND ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) ) * AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) ) * ... * ; * */ sql.append("SELECT ").append(databaseMeta.quoteField(retval)).append(Const.CR); sql.append("FROM ").append(databaseMeta.quoteField(table)).append(Const.CR); sql.append("WHERE "); comma=false; if (crc) { sql.append(databaseMeta.quoteField(crcfield)).append(" = ? ").append(Const.CR); comma=true; } else { sql.append("( ( "); } for (i=0;i<keys.length;i++) { if (comma) { sql.append(" AND ( ( "); } else { comma=true; } sql.append(databaseMeta.quoteField(keys[i])).append(" = ? ) OR ( ").append(databaseMeta.quoteField(keys[i])); sql.append(" IS NULL AND "); if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_DB2) { sql.append("CAST(? AS VARCHAR(256)) IS NULL"); } else { sql.append("? IS NULL"); } sql.append(" ) )"); sql.append(Const.CR); } try { String sqlStatement = sql.toString(); if (log.isDebug()) log.logDebug(toString(), "preparing combi-lookup statement:"+Const.CR+sqlStatement); prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sqlStatement)); prepStatementLookup.setMaxRows(1); // alywas get only 1 line back! } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare combi-lookup statement", ex); } } public Row callProcedure(String arg[], String argdir[], int argtype[], String resultname, int resulttype) throws KettleDatabaseException { Row ret; try { cstmt.execute(); ret=new Row(); int pos=1; if (resultname!=null && resultname.length()!=0) { Value v=new Value(resultname, Value.VALUE_TYPE_NONE); switch(resulttype) { case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos) ); break; case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos) ); break; case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos)); break; case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos) ); break; case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos) ); break; case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos) ); break; } ret.addValue(v); pos++; } for (int i=0;i<arg.length;i++) { if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) { Value v=new Value(arg[i], Value.VALUE_TYPE_NONE); switch(argtype[i]) { case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos+i) ); break; case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos+i) ); break; case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos+i)); break; case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos+i) ); break; case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos+i) ); break; case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos+i) ); break; } ret.addValue(v); } } return ret; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to call procedure", ex); } } public Row getLookup() throws KettleDatabaseException { return getLookup(prepStatementLookup); } public Row getLookup(boolean failOnMultipleResults) throws KettleDatabaseException { return getLookup(prepStatementLookup, failOnMultipleResults); } public Row getLookup(PreparedStatement ps) throws KettleDatabaseException { return getLookup(ps, false); } public Row getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException { String debug = "start"; Row ret; ResultSet res = null; try { debug = "pstmt.executeQuery()"; res = ps.executeQuery(); debug = "getRowInfo()"; rowinfo = getRowInfo(res.getMetaData()); debug = "getRow(res)"; ret=getRow(res); if (failOnMultipleResults) { if (res.next()) { throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!"); } } debug = "res.close()"; return ret; } catch(SQLException ex) { throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex); } finally { try { if (res!=null) res.close(); // close resultset! } catch(SQLException e) { throw new KettleDatabaseException("Unable to close resultset after looking up data", e); } } } public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException { try { if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once! } catch(Exception e) { throw new KettleDatabaseException("Unable to get database metadata from this database connection", e); } return dbmd; } public String getDDL(String tablename, Row fields) throws KettleDatabaseException { return getDDL(tablename, fields, null, false, null, true); } public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException { return getDDL(tablename, fields, tk, use_autoinc, pk, true); } public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException { String retval; // First, check for reserved SQL in the input row r... databaseMeta.quoteReservedWords(fields); String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null; if (checkTableExists(tablename)) { retval=getAlterTableStatement(tablename, fields, quotedTk, use_autoinc, pk, semicolon); } else { retval=getCreateTableStatement(tablename, fields, quotedTk, use_autoinc, pk, semicolon); } return retval; } public String getCreateTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon) { String retval; retval = "CREATE TABLE "+databaseMeta.quoteField(tablename)+Const.CR; retval+= "("+Const.CR; for (int i=0;i<fields.size();i++) { if (i>0) retval+=", "; else retval+=" "; Value v=fields.getValue(i); retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc); } // At the end, before the closing of the statement, we might need to add some constraints... // Technical keys if (tk!=null) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE) { retval+=", PRIMARY KEY ("+tk+")"+Const.CR; } } // Primary keys if (pk!=null) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE) { retval+=", PRIMARY KEY ("+pk+")"+Const.CR; } } retval+= ")"+Const.CR; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE && databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0) { retval+="TABLESPACE "+databaseMeta.getDataTablespace(); } if (semicolon) retval+=";"; retval+=Const.CR; return retval; } public String getAlterTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException { String retval=""; String tableName = databaseMeta.quoteField(tablename); // Get the fields that are in the table now: Row tabFields = getTableFields(tablename); // Don't forget to quote these as well... databaseMeta.quoteReservedWords(tabFields); // Find the missing fields Row missing = new Row(); for (int i=0;i<fields.size();i++) { Value v = fields.getValue(i); // Not found? if (tabFields.searchValue( v.getName() )==null ) { missing.addValue(v); // nope --> Missing! } } if (missing.size()!=0) { for (int i=0;i<missing.size();i++) { Value v=missing.getValue(i); retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } // Find the surplus fields Row surplus = new Row(); for (int i=0;i<tabFields.size();i++) { Value v = tabFields.getValue(i); // Found in table, not in input ? if (fields.searchValue( v.getName() )==null ) { surplus.addValue(v); // yes --> surplus! } } if (surplus.size()!=0) { for (int i=0;i<surplus.size();i++) { Value v=surplus.getValue(i); retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } // OK, see if there are fields for wich we need to modify the type... (length, precision) Row modify = new Row(); for (int i=0;i<fields.size();i++) { Value desiredField = fields.getValue(i); Value currentField = tabFields.searchValue( desiredField.getName()); if (currentField!=null) { boolean mod = false; mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0; mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0; // Numeric values... mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() ); if (mod) { // System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]"); modify.addValue(desiredField); } } } if (modify.size()>0) { for (int i=0;i<modify.size();i++) { Value v=modify.getValue(i); retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } return retval; } public void checkDimZero(String tablename, String tk, String version, boolean use_autoinc) throws KettleDatabaseException { int start_tk = databaseMeta.getNotFoundTK(use_autoinc); String sql = "SELECT count(*) FROM "+databaseMeta.quoteField(tablename)+" WHERE "+databaseMeta.quoteField(tk)+" = "+start_tk; Row r = getOneRow(sql); Value count = r.getValue(0); if (count.getNumber() == 0) { try { Statement st = connection.createStatement(); String isql; if (!databaseMeta.supportsAutoinc() || !use_autoinc) { isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)"; } else { switch(databaseMeta.getDatabaseType()) { case DatabaseMeta.TYPE_DATABASE_CACHE : case DatabaseMeta.TYPE_DATABASE_GUPTA : case DatabaseMeta.TYPE_DATABASE_ORACLE : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)"; break; case DatabaseMeta.TYPE_DATABASE_INFORMIX : case DatabaseMeta.TYPE_DATABASE_MYSQL : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (1, 1)"; break; case DatabaseMeta.TYPE_DATABASE_MSSQL : case DatabaseMeta.TYPE_DATABASE_DB2 : case DatabaseMeta.TYPE_DATABASE_DBASE : case DatabaseMeta.TYPE_DATABASE_GENERIC : case DatabaseMeta.TYPE_DATABASE_SYBASE : case DatabaseMeta.TYPE_DATABASE_ACCESS : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(version)+") values (1)"; break; default: isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)"; break; } } st.executeUpdate(databaseMeta.stripCR(isql)); } catch(SQLException e) { throw new KettleDatabaseException("Error inserting 'unknown' row in dimension ["+tablename+"] : "+sql, e); } } } public Value checkSequence(String seqname) throws KettleDatabaseException { String sql=null; if (databaseMeta.supportsSequences()) { sql = databaseMeta.getSQLCurrentSequenceValue(seqname); ResultSet rs = openQuery(sql, null); Row r = getRow(rs); // One value: a number; if (r!=null) { Value last = r.getValue(0); // errorstr="Sequence is at number: "+last.toString(); return last; } else { return null; } } else { throw new KettleDatabaseException("Sequences are only available for Oracle databases."); } } public void truncateTable(String tablename) throws KettleDatabaseException { execStatement(databaseMeta.getTruncateTableStatement(tablename)); } /** * Execute a query and return at most one row from the resultset * @param sql The SQL for the query * @return one Row with data or null if nothing was found. */ public Row getOneRow(String sql) throws KettleDatabaseException { ResultSet rs = openQuery(sql, null); if (rs!=null) { Row r = getRow(rs); // One row only; try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); } if (pstmt!=null) { try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); } pstmt=null; } if (sel_stmt!=null) { try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); } sel_stmt=null; } return r; } else { throw new KettleDatabaseException("error opening resultset for query: "+sql); } } public Row getOneRow(String sql, Row param) throws KettleDatabaseException { ResultSet rs = openQuery(sql, param); if (rs!=null) { Row r = getRow(rs); // One value: a number; try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); } if (pstmt!=null) { try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); } pstmt=null; } if (sel_stmt!=null) { try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); } sel_stmt=null; } rowinfo=null; return r; } else { return null; } } public Row getParameterMetaData(PreparedStatement ps) { Row par = new Row(); try { ParameterMetaData pmd = ps.getParameterMetaData(); for (int i=1;i<=pmd.getParameterCount();i++) { String name = "par"+i; int sqltype = pmd.getParameterType(i); int length = pmd.getPrecision(i); int precision = pmd.getScale(i); Value val; switch(sqltype) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: val=new Value(name, Value.VALUE_TYPE_STRING); break; case java.sql.Types.BIGINT: case java.sql.Types.INTEGER: case java.sql.Types.NUMERIC: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: val=new Value(name, Value.VALUE_TYPE_INTEGER); break; case java.sql.Types.DECIMAL: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: val=new Value(name, Value.VALUE_TYPE_NUMBER); break; case java.sql.Types.DATE: case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: val=new Value(name, Value.VALUE_TYPE_DATE); break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: val=new Value(name, Value.VALUE_TYPE_BOOLEAN); break; default: val=new Value(name, Value.VALUE_TYPE_NONE); break; } if (val.isNumeric() && ( length>18 || precision>18) ) { val = new Value(name, Value.VALUE_TYPE_BIGNUMBER); } val.setNull(); par.addValue(val); } } // Oops: probably the database or JDBC doesn't support it. catch(AbstractMethodError e) { return null; } catch(SQLException e) { return null; } catch(Exception e) { return null; } return par; } public int countParameters(String sql) { int q=0; boolean quote_opened=false; boolean dquote_opened=false; for (int x=0;x<sql.length();x++) { char c = sql.charAt(x); switch(c) { case '\'': quote_opened= !quote_opened; break; case '"' : dquote_opened=!dquote_opened; break; case '?' : if (!quote_opened && !dquote_opened) q++; break; } } return q; } // Get the fields back from an SQL query public Row getParameterMetaData(String sql, Row inform) { // The database couldn't handle it: try manually! int q=countParameters(sql); Row par=new Row(); if (inform!=null && q==inform.size()) { for (int i=0;i<q;i++) { Value inf=inform.getValue(i); Value v = new Value(inf); par.addValue(v); } } else { for (int i=0;i<q;i++) { Value v = new Value("name"+i, Value.VALUE_TYPE_NUMBER); v.setValue( 0.0 ); par.addValue(v); } } return par; } public static final Row getTransLogrecordFields(boolean use_batchid, boolean use_logfield) { Row r = new Row(); Value v; if (use_batchid) { v=new Value("ID_BATCH", Value.VALUE_TYPE_INTEGER); v.setLength(8,0); r.addValue(v); } v=new Value("TRANSNAME", Value.VALUE_TYPE_STRING ); v.setLength(50); r.addValue(v); v=new Value("STATUS", Value.VALUE_TYPE_STRING ); v.setLength(15); r.addValue(v); v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("REPLAYDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); if (use_logfield) { v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING); v.setLength(DatabaseMeta.CLOB_LENGTH,0); r.addValue(v); } return r; } public static final Row getJobLogrecordFields(boolean use_jobid, boolean use_logfield) { Row r = new Row(); Value v; if (use_jobid) { v=new Value("ID_JOB", Value.VALUE_TYPE_INTEGER); v.setLength(8,0); r.addValue(v); } v=new Value("JOBNAME", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v); v=new Value("STATUS", Value.VALUE_TYPE_STRING); v.setLength(15); r.addValue(v); v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("REPLAYDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); if (use_logfield) { v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING); v.setLength(DatabaseMeta.CLOB_LENGTH,0); r.addValue(v); } return r; } public void writeLogRecord( String logtable, boolean use_id, long id, boolean job, String name, String status, long read, long written, long updated, long input, long output, long errors, java.util.Date startdate, java.util.Date enddate, java.util.Date logdate, java.util.Date depdate, java.util.Date replayDate, String log_string ) throws KettleDatabaseException { if (use_id && log_string!=null && !status.equalsIgnoreCase("start")) { String sql = "UPDATE "+logtable+" SET STATUS=?, LINES_READ=?, LINES_WRITTEN=?, LINES_INPUT=?," + " LINES_OUTPUT=?, LINES_UPDATED=?, ERRORS=?, STARTDATE=?, ENDDATE=?, LOGDATE=?, DEPDATE=?, REPLAYDATE=?, LOG_FIELD=? " + "WHERE "; if (job) sql+="ID_JOB=?"; else sql+="ID_BATCH=?"; Row r = new Row(); r.addValue( new Value("STATUS", status )); r.addValue( new Value("LINES_READ", (long)read )); r.addValue( new Value("LINES_WRITTEN", (long)written)); r.addValue( new Value("LINES_INPUT", (long)input )); r.addValue( new Value("LINES_OUTPUT", (long)output )); r.addValue( new Value("LINES_UPDATED", (long)updated)); r.addValue( new Value("ERRORS", (long)errors )); r.addValue( new Value("STARTDATE", startdate )); r.addValue( new Value("ENDDATE", enddate )); r.addValue( new Value("LOGDATE", logdate )); r.addValue( new Value("DEPDATE", depdate )); r.addValue( new Value("REPLAYDATE", replayDate )); Value logfield = new Value("LOG_FIELD", log_string); logfield.setLength(DatabaseMeta.CLOB_LENGTH); r.addValue( logfield ); r.addValue( new Value("ID_BATCH", id )); execStatement(sql, r); } else { int parms; String sql = "INSERT INTO "+logtable+" ( "; if (job) { if (use_id) { sql+="ID_JOB, JOBNAME"; parms=14; } else { sql+="JOBNAME"; parms=13; } } else { if (use_id) { sql+="ID_BATCH, TRANSNAME"; parms=14; } else { sql+="TRANSNAME"; parms=13; } } sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE, REPLAYDATE"; if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB! sql+=") VALUES("; for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?"; if (log_string!=null && log_string.length()>0) sql+=", ?"; sql+=")"; try { pstmt = connection.prepareStatement(databaseMeta.stripCR(sql)); Row r = new Row(); if (job) { if (use_id) { r.addValue( new Value("ID_BATCH", id )); } r.addValue( new Value("TRANSNAME", name )); } else { if (use_id) { r.addValue( new Value("ID_JOB", id )); } r.addValue( new Value("JOBNAME", name )); } r.addValue( new Value("STATUS", status )); r.addValue( new Value("LINES_READ", (long)read )); r.addValue( new Value("LINES_WRITTEN", (long)written)); r.addValue( new Value("LINES_UPDATED", (long)updated)); r.addValue( new Value("LINES_INPUT", (long)input )); r.addValue( new Value("LINES_OUTPUT", (long)output )); r.addValue( new Value("ERRORS", (long)errors )); r.addValue( new Value("STARTDATE", startdate )); r.addValue( new Value("ENDDATE", enddate )); r.addValue( new Value("LOGDATE", logdate )); r.addValue( new Value("DEPDATE", depdate )); r.addValue( new Value("REPLAYDATE", replayDate )); if (log_string!=null && log_string.length()>0) { Value large = new Value("LOG_FIELD", log_string ); large.setLength(DatabaseMeta.CLOB_LENGTH); r.addValue( large ); } setValues(r); pstmt.executeUpdate(); pstmt.close(); pstmt=null; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex); } } } public Row getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException { Row row=null; String jobtrans = job?"JOBNAME":"TRANSNAME"; String sql = ""; sql+=" SELECT ENDDATE, DEPDATE, STARTDATE"; sql+=" FROM "+logtable; sql+=" WHERE ERRORS = 0"; sql+=" AND STATUS = 'end'"; sql+=" AND "+jobtrans+" = ?"; sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC"; try { pstmt = connection.prepareStatement(databaseMeta.stripCR(sql)); Row r = new Row(); r.addValue( new Value("TRANSNAME", name )); setValues(r); ResultSet res = pstmt.executeQuery(); if (res!=null) { rowinfo = getRowInfo(res.getMetaData()); row = getRow(res); res.close(); } pstmt.close(); pstmt=null; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex); } return row; } public synchronized void getNextValue(Hashtable counters, String table, Value val_key) throws KettleDatabaseException { String lookup = databaseMeta.quoteField(table)+"."+databaseMeta.quoteField(val_key.getName()); // Try to find the previous sequence value... Counter counter = null; if (counters!=null) counter=(Counter)counters.get(lookup); if (counter==null) { Row r = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key.getName())+") FROM "+databaseMeta.quoteField(table)); if (r!=null) { counter = new Counter(r.getValue(0).getInteger()+1, 1); val_key.setValue(counter.next()); if (counters!=null) counters.put(lookup, counter); } else { throw new KettleDatabaseException("Couldn't find maximum key value from table "+table); } } else { val_key.setValue(counter.next()); } } public String toString() { if (databaseMeta!=null) return databaseMeta.getName(); else return "-"; } public boolean isSystemTable(String table_name) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL) { if ( table_name.startsWith("sys")) return true; if ( table_name.equals("dtproperties")) return true; } else if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA) { if ( table_name.startsWith("SYS")) return true; } return false; } /** Reads the result of an SQL query into an ArrayList * * @param sql The SQL to launch * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public ArrayList getRows(String sql, int limit) throws KettleDatabaseException { return getRows(sql, limit, null); } /** Reads the result of an SQL query into an ArrayList * * @param sql The SQL to launch * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public ArrayList getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException { if (monitor!=null) monitor.setTaskName("Opening query..."); ResultSet rset = openQuery(sql); return getRows(rset, limit, monitor); } /** Reads the result of a ResultSet into an ArrayList * * @param rset the ResultSet to read out * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public ArrayList getRows(ResultSet rset, int limit, IProgressMonitor monitor) throws KettleDatabaseException { try { ArrayList result = new ArrayList(); boolean stop=false; int i=0; if (rset!=null) { if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit); while ((limit<=0 || i<limit) && !stop) { Row row = getRow(rset); if (row!=null) { result.add(row); i++; } else { stop=true; } if (monitor!=null && limit>0) monitor.worked(1); } closeQuery(rset); if (monitor!=null) monitor.done(); } return result; } catch(Exception e) { throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e); } } public ArrayList getFirstRows(String table_name, int limit) throws KettleDatabaseException { return getFirstRows(table_name, limit, null); } public ArrayList getFirstRows(String table_name, int limit, IProgressMonitor monitor) throws KettleDatabaseException { String sql = "SELECT * FROM "+databaseMeta.quoteField(table_name); if (limit>0) { sql+=databaseMeta.getLimitClause(limit); } return getRows(sql, limit, monitor); } public Row getReturnRow() { return rowinfo; } public String[] getTableTypes() throws KettleDatabaseException { try { ArrayList types = new ArrayList(); ResultSet rstt = getDatabaseMetaData().getTableTypes(); while(rstt.next()) { String ttype = rstt.getString("TABLE_TYPE"); types.add(ttype); } return (String[])types.toArray(new String[types.size()]); } catch(SQLException e) { throw new KettleDatabaseException("Unable to get table types from database!", e); } } public String[] getTablenames() throws KettleDatabaseException { String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase(); ArrayList names = new ArrayList(); ResultSet alltables=null; try { alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+table); names.add(table); } } catch(SQLException e) { log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]"); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data."); return (String[])names.toArray(new String[names.size()]); } public String[] getViews() throws KettleDatabaseException { if (!databaseMeta.supportsViews()) return new String[] {}; String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase(); ArrayList names = new ArrayList(); ResultSet alltables=null; try { alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+table); names.add(table); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data."); return (String[])names.toArray(new String[names.size()]); } public String[] getSynonyms() throws KettleDatabaseException { if (!databaseMeta.supportsSynonyms()) return new String[] {}; String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase(); ArrayList names = new ArrayList(); ResultSet alltables=null; try { alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+table); names.add(table); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data."); return (String[])names.toArray(new String[names.size()]); } public String[] getProcedures() throws KettleDatabaseException { String sql = databaseMeta.getSQLListOfProcedures(); if (sql!=null) { //System.out.println("SQL= "+sql); ArrayList procs = getRows(sql, 1000); //System.out.println("Found "+procs.size()+" rows"); String[] str = new String[procs.size()]; for (int i=0;i<procs.size();i++) { str[i] = ((Row)procs.get(i)).getValue(0).getString(); } return str; } else { ResultSet rs = null; try { DatabaseMetaData dbmd = getDatabaseMetaData(); rs = dbmd.getProcedures(null, null, null); ArrayList rows = getRows(rs, 0, null); String result[] = new String[rows.size()]; for (int i=0;i<rows.size();i++) { Row row = (Row)rows.get(i); String procCatalog = row.getString("PROCEDURE_CAT", null); String procSchema = row.getString("PROCEDURE_SCHEMA", null); String procName = row.getString("PROCEDURE_NAME", ""); String name = ""; if (procCatalog!=null) name+=procCatalog+"."; else if (procSchema!=null) name+=procSchema+"."; name+=procName; result[i] = name; } return result; } catch(Exception e) { throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e); } finally { if (rs!=null) try { rs.close(); } catch(Exception e) {} } } } public boolean isAutoCommit() { return commitsize<=0; } /** * @return Returns the databaseMeta. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * Lock a tables in the database for write operations * @param tableNames The tables to lock * @throws KettleDatabaseException */ public void lockTables(String tableNames[]) throws KettleDatabaseException { String sql = databaseMeta.getSQLLockTables(tableNames); if (sql!=null) { execStatements(sql); } } /** * Unlock certain tables in the database for write operations * @param tableNames The tables to unlock * @throws KettleDatabaseException */ public void unlockTables(String tableNames[]) throws KettleDatabaseException { String sql = databaseMeta.getSQLUnlockTables(tableNames); if (sql!=null) { execStatement(sql); } } }
package org.xcolab.service.contents.domain.contentarticleversion; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SelectQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.xcolab.model.tables.pojos.ContentArticleVersion; import org.xcolab.model.tables.records.ContentArticleVersionRecord; import org.xcolab.service.contents.exceptions.NotFoundException; import org.xcolab.service.utils.PaginationHelper; import org.xcolab.service.utils.PaginationHelper.SortColumn; import java.util.List; import static org.xcolab.model.Tables.CONTENT_ARTICLE; import static org.xcolab.model.Tables.CONTENT_ARTICLE_VERSION; @Repository public class ContentArticleVersionDaoImpl implements ContentArticleVersionDao { @Autowired private DSLContext dslContext; @Override public ContentArticleVersion create(ContentArticleVersion contentArticleVersion) { ContentArticleVersionRecord ret = this.dslContext.insertInto(CONTENT_ARTICLE_VERSION) .set(CONTENT_ARTICLE_VERSION.AUTHOR_ID, contentArticleVersion.getAuthorId()) .set(CONTENT_ARTICLE_VERSION.CREATE_DATE, contentArticleVersion.getCreateDate()) .set(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_ID, contentArticleVersion.getContentArticleId()) .set(CONTENT_ARTICLE_VERSION.FOLDER_ID, contentArticleVersion.getFolderId()) .set(CONTENT_ARTICLE_VERSION.CONTENT, contentArticleVersion.getContent()) .set(CONTENT_ARTICLE_VERSION.TITLE, contentArticleVersion.getTitle()) .returning(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID) .fetchOne(); if (ret != null) { contentArticleVersion.setContentArticleVersionId(ret.getValue(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID)); return contentArticleVersion; } else { return null; } } @Override public int deleteByArticleId(long contentArticleId) { return dslContext.deleteFrom(CONTENT_ARTICLE_VERSION) .where(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_ID.eq(contentArticleId)) .execute(); } @Override public boolean update(ContentArticleVersion contentArticleVersion) { return dslContext.update(CONTENT_ARTICLE_VERSION) .set(CONTENT_ARTICLE_VERSION.AUTHOR_ID, contentArticleVersion.getAuthorId()) .set(CONTENT_ARTICLE_VERSION.CREATE_DATE, contentArticleVersion.getCreateDate()) .set(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_ID, contentArticleVersion.getContentArticleId()) .set(CONTENT_ARTICLE_VERSION.FOLDER_ID, contentArticleVersion.getFolderId()) .set(CONTENT_ARTICLE_VERSION.CONTENT, contentArticleVersion.getContent()) .set(CONTENT_ARTICLE_VERSION.TITLE, contentArticleVersion.getTitle()) .where(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID.eq(contentArticleVersion.getContentArticleVersionId())) .execute() > 0; } @Override public ContentArticleVersion get(Long contentArticleId) throws NotFoundException { final Record record = this.dslContext.select() .from(CONTENT_ARTICLE_VERSION) .where(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID.eq(contentArticleId)) .fetchOne(); if (record == null) { throw new NotFoundException(); } return record.into(ContentArticleVersion.class); } @Override public List<ContentArticleVersion> getByFolderId(Long contentFolderId) { if (contentFolderId == null) { return this.dslContext.select() .from(CONTENT_ARTICLE_VERSION) .join(CONTENT_ARTICLE).on(CONTENT_ARTICLE.CONTENT_ARTICLE_ID.eq(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_ID)) .where(CONTENT_ARTICLE_VERSION.FOLDER_ID.isNull()) .and(CONTENT_ARTICLE.MAX_VERSION_ID.eq(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID)) .fetch() .into(ContentArticleVersion.class); } else { return this.dslContext.select() .from(CONTENT_ARTICLE_VERSION) .join(CONTENT_ARTICLE).on(CONTENT_ARTICLE.CONTENT_ARTICLE_ID.eq(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_ID)) .where(CONTENT_ARTICLE_VERSION.FOLDER_ID.eq(contentFolderId)) .and(CONTENT_ARTICLE.MAX_VERSION_ID.eq(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID)) .fetch() .into(ContentArticleVersion.class); } } @Override public List<ContentArticleVersion> findByGiven(PaginationHelper paginationHelper, Long contentArticleId, Long contentArticleVersion, Long folderId, String title) { final SelectQuery<Record> query = dslContext.select() .from(CONTENT_ARTICLE_VERSION) .getQuery(); if (contentArticleId != null) { query.addConditions(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_ID.eq(contentArticleId)); } if (contentArticleVersion != null) { query.addConditions(CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID.eq(contentArticleVersion)); } if (folderId != null) { query.addConditions(CONTENT_ARTICLE_VERSION.FOLDER_ID.eq(folderId)); } if (title != null) { query.addConditions(CONTENT_ARTICLE_VERSION.TITLE.eq(title)); } for (SortColumn sortColumn : paginationHelper.getSortColumns()) { switch (sortColumn.getColumnName()) { case "contentArticleId": query.addOrderBy(sortColumn.isAscending() ? CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_ID.asc() : CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_ID.desc()); break; case "folderId": query.addOrderBy(sortColumn.isAscending() ? CONTENT_ARTICLE_VERSION.FOLDER_ID.asc() : CONTENT_ARTICLE_VERSION.FOLDER_ID.desc()); break; case "title": query.addOrderBy(sortColumn.isAscending() ? CONTENT_ARTICLE_VERSION.TITLE.asc() : CONTENT_ARTICLE_VERSION.TITLE.desc()); break; default: case "contentArticleVersion": query.addOrderBy(sortColumn.isAscending() ? CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID.asc() : CONTENT_ARTICLE_VERSION.CONTENT_ARTICLE_VERSION_ID.desc()); break; } } query.addLimit(paginationHelper.getStartRecord(), paginationHelper.getLimitRecord()); return query.fetchInto(ContentArticleVersion.class); } }
package edu.rit.se.wifibuddy; import android.net.wifi.p2p.WifiP2pDevice; /** * A class for storing Bonjour service information that is advertised over a Wi-Fi P2P connection. */ public class DnsSdService{ private String instanceName; private String registrationType; private WifiP2pDevice srcDevice; public DnsSdService(String instanceName, String registrationType, WifiP2pDevice srcDevice) { this.instanceName = instanceName; this.registrationType = registrationType; this.srcDevice = srcDevice; } public String getInstanceName() { return instanceName; } public WifiP2pDevice getSrcDevice() { return srcDevice; } @Override public boolean equals(Object o) { if (o == null || !(o instanceof DnsSdService)) { return false; } else { DnsSdService other = (DnsSdService) o; return other.srcDevice.deviceName.equals(this.srcDevice.deviceName) && other.instanceName.equals(this.instanceName) && other.srcDevice.deviceAddress.equals(this.srcDevice.deviceAddress); } } }
package org.lunifera.runtime.web.ecview.presentation.vaadin.internal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecp.ecview.common.editpart.IElementEditpart; import org.eclipse.emf.ecp.ecview.common.editpart.IEmbeddableEditpart; import org.eclipse.emf.ecp.ecview.common.editpart.ILayoutEditpart; import org.eclipse.emf.ecp.ecview.common.model.core.YEmbeddable; import org.eclipse.emf.ecp.ecview.common.presentation.IWidgetPresentation; import org.eclipse.emf.ecp.ecview.extension.model.extension.YAlignment; import org.eclipse.emf.ecp.ecview.extension.model.extension.YGridLayout; import org.eclipse.emf.ecp.ecview.extension.model.extension.YGridLayoutCellStyle; import org.eclipse.emf.ecp.ecview.extension.model.extension.YSpanInfo; import org.lunifera.runtime.web.ecview.presentation.vaadin.IConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.vaadin.ui.Alignment; import com.vaadin.ui.Component; import com.vaadin.ui.ComponentContainer; import com.vaadin.ui.CssLayout; import com.vaadin.ui.GridLayout; import com.vaadin.ui.GridLayout.Area; /** * This presenter is responsible to render a text field on the given layout. */ public class GridLayoutPresentation extends AbstractLayoutPresenter<ComponentContainer> { private static final Logger logger = LoggerFactory .getLogger(GridLayoutPresentation.class); private CssLayout componentBase; private GridLayout gridlayout; private ModelAccess modelAccess; /** * The constructor. * * @param editpart * The editpart of that presentation. */ public GridLayoutPresentation(IElementEditpart editpart) { super((ILayoutEditpart) editpart); this.modelAccess = new ModelAccess((YGridLayout) editpart.getModel()); } @Override public void add(IWidgetPresentation<?> presentation) { super.add(presentation); refreshUI(); } @Override public void remove(IWidgetPresentation<?> presentation) { super.remove(presentation); presentation.unrender(); refreshUI(); } @Override public void insert(IWidgetPresentation<?> presentation, int index) { super.insert(presentation, index); refreshUI(); } @Override public void move(IWidgetPresentation<?> presentation, int index) { super.move(presentation, index); refreshUI(); } /** * Is called to refresh the UI. The element will be removed from the grid * layout and added to it again afterwards. */ protected void refreshUI() { gridlayout.removeAllComponents(); // create a map containing the style for the embeddable Map<YEmbeddable, YGridLayoutCellStyle> yStyles = new HashMap<YEmbeddable, YGridLayoutCellStyle>(); for (YGridLayoutCellStyle style : modelAccess.getCellStyles()) { if (yStyles.containsKey(style.getTarget())) { logger.warn("Multiple style for element {}", style.getTarget()); } yStyles.put(style.getTarget(), style); } // iterate all elements and build the child element List<Cell> cells = new ArrayList<Cell>(); for (IEmbeddableEditpart editPart : getEditpart().getElements()) { IWidgetPresentation<?> childPresentation = editPart .getPresentation(); YEmbeddable yChild = (YEmbeddable) childPresentation.getModel(); Cell cell = addChild(childPresentation, yStyles.get(yChild)); cells.add(cell); } // Build a model of rows and columns. // Each coordinate (row/column) has an assigned cell. If a cell is // spanned, // it will be assigned to many coordinates. List<Row> rows = new ArrayList<Row>(); for (int i = 0; i < gridlayout.getRows(); i++) { rows.add(new Row(i, gridlayout.getColumns())); } List<Column> columns = new ArrayList<Column>(); for (int i = 0; i < gridlayout.getColumns(); i++) { columns.add(new Column(i, gridlayout.getRows())); } for (Cell cell : cells) { for (int r = cell.area.getRow1(); r <= cell.area.getRow2(); r++) { for (int c = cell.area.getColumn1(); c <= cell.area .getColumn2(); c++) { Row row = rows.get(r); row.addCell(c, cell); Column col = columns.get(c); col.addCell(r, cell); } } } boolean expandVerticalFound = false; for (Row row : rows) { if (row.isShouldExpandVertical()) { expandVerticalFound = true; gridlayout.setRowExpandRatio(row.getRowindex(), 1.0f); } } boolean expandHorizontalFound = false; for (Column col : columns) { if (col.isShouldExpandHorizontal()) { expandHorizontalFound = true; gridlayout.setColumnExpandRatio(col.getColumnindex(), 1.0f); } } // handle packaging - therefore a new row / column is added and set to // expandRatio = 1.0f. This will cause the // last row / column to grab excess space. // If there is already a row / column that is expanded, we do not need // to add a helper row if (!expandVerticalFound && !modelAccess.isFillVertical()) { int packingHelperRowIndex = gridlayout.getRows(); gridlayout.setRows(packingHelperRowIndex + 1); gridlayout.setRowExpandRatio(packingHelperRowIndex, 1.0f); } if (!expandHorizontalFound && !modelAccess.isFillHorizontal()) { int packingHelperColumnIndex = gridlayout.getColumns(); gridlayout.setColumns(packingHelperColumnIndex + 1); gridlayout.setColumnExpandRatio(packingHelperColumnIndex, 1.0f); } } /** * Is called to create the child component and apply layouting defaults to * it. * * @param presentation * @param yStyle * @return */ protected Cell addChild(IWidgetPresentation<?> presentation, YGridLayoutCellStyle yStyle) { Component child = (Component) presentation.createWidget(gridlayout); // calculate the spanning of the element // and adds the child to the grid layout int col1 = -1; int row1 = -1; int col2 = -1; int row2 = -1; if (yStyle != null) { YSpanInfo ySpanInfo = yStyle.getSpanInfo(); if (ySpanInfo != null) { col1 = ySpanInfo.getColumnFrom(); row1 = ySpanInfo.getRowFrom(); col2 = ySpanInfo.getColumnTo(); row2 = ySpanInfo.getRowTo(); } } // calculate and apply the alignment to be used YAlignment yAlignment = yStyle != null && yStyle.getAlignment() != null ? yStyle .getAlignment() : null; if (yAlignment == null) { // use default yAlignment = YAlignment.TOP_LEFT; if (modelAccess.isFillVertical()) { // ensure that vertical alignment is FILL yAlignment = mapToVerticalFill(yAlignment); } if (modelAccess.isFillHorizontal()) { // ensure that horizontal alignment is FILL yAlignment = mapToHorizontalFill(yAlignment); } } // add the element to the grid layout if (col1 >= 0 && row1 >= 0 && (col1 < col2 || row1 < row2)) { if(gridlayout.getRows() < row2 +1){ gridlayout.setRows(row2 + 1); } gridlayout.addComponent(child, col1, row1, col2, row2); } else if (col1 < 0 || row1 < 0) { gridlayout.addComponent(child); } else { gridlayout.addComponent(child); logger.warn("Invalid span: col1 {}, row1 {}, col2 {}, row2{}", new Object[] { col1, row1, col2, row2 }); } applyAlignment(child, yAlignment); GridLayout.Area area = gridlayout.getComponentArea(child); return new Cell(child, yAlignment, area); } /** * Sets the alignment to the component. * * @param child * @param yAlignment */ protected void applyAlignment(Component child, YAlignment yAlignment) { if (yAlignment != null) { child.setWidth("-1%"); child.setHeight("-1%"); switch (yAlignment) { case BOTTOM_CENTER: gridlayout .setComponentAlignment(child, Alignment.BOTTOM_CENTER); break; case BOTTOM_FILL: gridlayout.setComponentAlignment(child, Alignment.BOTTOM_LEFT); child.setWidth("100%"); break; case BOTTOM_LEFT: gridlayout.setComponentAlignment(child, Alignment.BOTTOM_LEFT); break; case BOTTOM_RIGHT: gridlayout.setComponentAlignment(child, Alignment.BOTTOM_RIGHT); break; case MIDDLE_CENTER: gridlayout .setComponentAlignment(child, Alignment.MIDDLE_CENTER); break; case MIDDLE_FILL: gridlayout.setComponentAlignment(child, Alignment.MIDDLE_LEFT); child.setWidth("100%"); break; case MIDDLE_LEFT: gridlayout.setComponentAlignment(child, Alignment.MIDDLE_LEFT); break; case MIDDLE_RIGHT: gridlayout.setComponentAlignment(child, Alignment.MIDDLE_RIGHT); break; case TOP_CENTER: gridlayout.setComponentAlignment(child, Alignment.TOP_CENTER); break; case TOP_FILL: gridlayout.setComponentAlignment(child, Alignment.TOP_LEFT); child.setWidth("100%"); break; case TOP_LEFT: gridlayout.setComponentAlignment(child, Alignment.TOP_LEFT); break; case TOP_RIGHT: gridlayout.setComponentAlignment(child, Alignment.TOP_RIGHT); break; case FILL_CENTER: gridlayout.setComponentAlignment(child, Alignment.TOP_CENTER); child.setHeight("100%"); break; case FILL_FILL: gridlayout.setComponentAlignment(child, Alignment.TOP_LEFT); child.setWidth("100%"); child.setHeight("100%"); break; case FILL_LEFT: gridlayout.setComponentAlignment(child, Alignment.TOP_LEFT); child.setHeight("100%"); break; case FILL_RIGHT: gridlayout.setComponentAlignment(child, Alignment.TOP_RIGHT); child.setHeight("100%"); break; default: break; } } } /** * Maps the vertical part of the alignment to FILL. * * @param yAlignment * the alignment * @return alignment the mapped alignment */ // BEGIN SUPRESS CATCH EXCEPTION protected YAlignment mapToVerticalFill(YAlignment yAlignment) { // END SUPRESS CATCH EXCEPTION if (yAlignment != null) { switch (yAlignment) { case BOTTOM_CENTER: case MIDDLE_CENTER: case TOP_CENTER: return YAlignment.FILL_CENTER; case BOTTOM_FILL: case MIDDLE_FILL: case TOP_FILL: return YAlignment.FILL_FILL; case BOTTOM_LEFT: case MIDDLE_LEFT: case TOP_LEFT: return YAlignment.FILL_LEFT; case BOTTOM_RIGHT: case MIDDLE_RIGHT: case TOP_RIGHT: return YAlignment.FILL_RIGHT; case FILL_FILL: case FILL_LEFT: case FILL_RIGHT: case FILL_CENTER: return YAlignment.FILL_FILL; default: break; } } return YAlignment.FILL_FILL; } /** * Maps the horizontal part of the alignment to FILL. * * @param yAlignment * the alignment * @return alignment the mapped alignment */ // BEGIN SUPRESS CATCH EXCEPTION protected YAlignment mapToHorizontalFill(YAlignment yAlignment) { // END SUPRESS CATCH EXCEPTION if (yAlignment != null) { switch (yAlignment) { case BOTTOM_CENTER: case BOTTOM_FILL: case BOTTOM_LEFT: case BOTTOM_RIGHT: return YAlignment.BOTTOM_FILL; case MIDDLE_CENTER: case MIDDLE_FILL: case MIDDLE_LEFT: case MIDDLE_RIGHT: return YAlignment.MIDDLE_FILL; case TOP_CENTER: case TOP_FILL: case TOP_LEFT: case TOP_RIGHT: return YAlignment.TOP_FILL; case FILL_FILL: case FILL_LEFT: case FILL_RIGHT: case FILL_CENTER: return YAlignment.FILL_FILL; default: break; } } return YAlignment.FILL_FILL; } @Override public ComponentContainer createWidget(Object parent) { if (componentBase == null) { componentBase = new CssLayout(); componentBase.setSizeFull(); componentBase.addStyleName(CSS_CLASS__CONTROL_BASE); if (modelAccess.isCssIdValid()) { componentBase.setId(modelAccess.getCssID()); } else { componentBase.setId(getEditpart().getId()); } gridlayout = new GridLayout(modelAccess.getColumns(), 1); gridlayout.setSizeFull(); gridlayout.setSpacing(false); componentBase.addComponent(gridlayout); if (modelAccess.isMargin()) { gridlayout.addStyleName(IConstants.CSS_CLASS__MARGIN); gridlayout.setMargin(true); } if (modelAccess.isSpacing()) { gridlayout.setData(IConstants.CSS_CLASS__SPACING); gridlayout.setSpacing(true); } if (modelAccess.isCssClassValid()) { gridlayout.addStyleName(modelAccess.getCssClass()); } else { gridlayout.addStyleName(CSS_CLASS__CONTROL); } renderChildren(false); } return componentBase; } @Override public ComponentContainer getWidget() { return componentBase; } @Override public boolean isRendered() { return componentBase != null; } @Override protected void internalDispose() { unrender(); } @Override public void unrender() { if (componentBase != null) { ComponentContainer parent = ((ComponentContainer) componentBase .getParent()); if (parent != null) { parent.removeComponent(componentBase); } componentBase = null; gridlayout = null; // unrender the childs for (IWidgetPresentation<?> child : getChildren()) { child.unrender(); } } } @Override public void renderChildren(boolean force) { if (force) { unrenderChildren(); } refreshUI(); } /** * Will unrender all children. */ protected void unrenderChildren() { for (IWidgetPresentation<?> presentation : getChildren()) { if (presentation.isRendered()) { presentation.unrender(); } } } /** * An internal helper class. */ private static class ModelAccess { private final YGridLayout yLayout; public ModelAccess(YGridLayout yLayout) { super(); this.yLayout = yLayout; } /** * @return * @see org.eclipse.emf.ecp.ecview.ui.core.model.core.YCssAble#getCssClass() */ public String getCssClass() { return yLayout.getCssClass(); } /** * Returns true, if the css class is not null and not empty. * * @return */ public boolean isCssClassValid() { return getCssClass() != null && !getCssClass().equals(""); } /** * @return * @see org.eclipse.emf.ecp.ecview.ui.core.model.extension.YGridLayout#isSpacing() */ public boolean isSpacing() { return yLayout.isSpacing(); } /** * @return * @see org.eclipse.emf.ecp.ecview.ui.core.model.core.YCssAble#getCssID() */ public String getCssID() { return yLayout.getCssID(); } /** * Returns true, if the css id is not null and not empty. * * @return */ public boolean isCssIdValid() { return getCssID() != null && !getCssID().equals(""); } /** * @return * @see org.eclipse.emf.ecp.ecview.ui.core.model.extension.YGridLayout#isMargin() */ public boolean isMargin() { return yLayout.isMargin(); } /** * @return * @see org.eclipse.emf.ecp.ecview.ui.core.model.extension.YGridLayout#getColumns() */ public int getColumns() { int columns = yLayout.getColumns(); return columns <= 0 ? 2 : columns; } /** * @return * @see org.eclipse.emf.ecp.ecview.ui.core.model.extension.YGridLayout#getCellStyles() */ public EList<YGridLayoutCellStyle> getCellStyles() { return yLayout.getCellStyles(); } /** * @return * @see org.eclipse.emf.ecp.ecview.ui.core.model.extension.YGridLayout#isFillHorizontal() */ public boolean isFillHorizontal() { return yLayout.isFillHorizontal(); } /** * @return * @see org.eclipse.emf.ecp.ecview.ui.core.model.extension.YGridLayout#isFillVertical() */ public boolean isFillVertical() { return yLayout.isFillVertical(); } } private static class Row { private int rowindex; private List<Cell> cells; private boolean shouldExpandVertical; private Row(int rowindex, int columns) { this.rowindex = rowindex; cells = new ArrayList<Cell>(columns); } public void addCell(int column, Cell cell) { cells.add(column, cell); YAlignment alignment = cell.getAlignment(); // if not already sure, that it should expand // try to find out if (!shouldExpandVertical) { // If the cell should FILL-vertical, then we test if the cell is // spanned. // --> If not spanned, then "shouldExpandVertical" is true. // --> Otherwise we test, if the cell is the most bottom cell. switch (alignment) { case FILL_LEFT: case FILL_CENTER: case FILL_RIGHT: case FILL_FILL: if (!cell.isSpanned()) { // if the cell is not spanned, then // "shouldExpandHorizontal" is true shouldExpandVertical = true; } else { if (cell.getArea().getRow2() == rowindex) { // if the cell is the most right one, then // "shouldExpandHorizontal" is true shouldExpandVertical = true; } } break; default: // nothing to do break; } } } /** * @return the rowindex */ protected int getRowindex() { return rowindex; } /** * @return the shouldExpandVertical */ protected boolean isShouldExpandVertical() { return shouldExpandVertical; } } private static class Column { private final int columnindex; private List<Cell> cells; private boolean shouldExpandHorizontal; private Column(int columnindex, int rows) { this.columnindex = columnindex; cells = new ArrayList<Cell>(rows); } public void addCell(int row, Cell cell) { try { cells.add(row, cell); } catch (Exception e) { System.out.println(e); } YAlignment alignment = cell.getAlignment(); // if not already sure, that it should expand // try to find out if (!shouldExpandHorizontal) { // If the cell should FILL-horizontal, then we test if the cell // is spanned. // --> If not spanned, then "shouldExpandHorizontal" is true. // --> Otherwise we test, if the cell is the most right cell. switch (alignment) { case BOTTOM_FILL: case MIDDLE_FILL: case TOP_FILL: case FILL_FILL: if (!cell.isSpanned()) { // if the cell is not spanned, then // "shouldExpandHorizontal" is true shouldExpandHorizontal = true; } else { if (cell.getArea().getColumn2() == cells.size() - 1) { // if the cell is the most right one, then // "shouldExpandHorizontal" is true shouldExpandHorizontal = true; } } break; default: // nothing to do break; } } } /** * @return the columnindex */ protected int getColumnindex() { return columnindex; } /** * @return the shouldExpandHorizontal */ protected boolean isShouldExpandHorizontal() { return shouldExpandHorizontal; } } public static class Cell { private final Component component; private final YAlignment alignment; private final Area area; public Cell(Component component, YAlignment alignment, GridLayout.Area area) { super(); this.component = component; this.alignment = alignment; this.area = area; } /** * @return the component */ protected Component getComponent() { return component; } /** * @return the alignment */ protected YAlignment getAlignment() { return alignment; } /** * @return the area */ protected Area getArea() { return area; } /** * Returns true, if the cell is spanned. * * @return */ public boolean isSpanned() { return area.getRow1() != area.getRow2() || area.getColumn1() != area.getColumn2(); } } }
package cc.hughes.droidchatty; import java.util.ArrayList; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Parcelable; import android.preference.PreferenceManager; import android.support.v4.app.ListFragment; import android.text.ClipboardManager; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; public class ThreadViewFragment extends ListFragment { PostLoadingAdapter _adapter; int _rootPostId; int _currentPostId; boolean _postDisplayed = false; boolean _initialPostSelected = false; ProgressDialog _progressDialog; // list view saved state while rotating private Parcelable _listState = null; private int _listPosition = 0; private int _itemPosition = 0; private int _itemChecked = ListView.INVALID_POSITION; public int getPostId() { return _rootPostId; } @Override public void onCreate(Bundle savedInstanceBundle) { super.onCreate(savedInstanceBundle); this.setRetainInstance(true); if (getArguments() != null) _rootPostId = getArguments().getInt("postId"); _currentPostId = _rootPostId; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.thread_view, null); } public void loadPost(Post post) { _currentPostId = post.getPostId(); _rootPostId = _currentPostId; displayPost(post); _postDisplayed = false; // reset the adapter _adapter.clear(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // makes links actually clickable getView().findViewById(R.id.textPostedTime).setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { copyPostUrl(); Toast.makeText(getActivity(), "Copied post URL to clipboard.", Toast.LENGTH_SHORT).show(); return true; } }); TextView content = (TextView)getView().findViewById(R.id.textContent); content.setMovementMethod(new LinkMovementMethod()); setHasOptionsMenu(true); registerForContextMenu(content); if (_adapter == null) { // first launch, try to set everything up Bundle args = getArguments(); String action = getActivity().getIntent().getAction(); Uri uri = getActivity().getIntent().getData(); // only load this junk if the arguments isn't null if (args != null) { if (args.containsKey("content")) { String userName = args.getString("userName"); String postContent = args.getString("content"); String posted = args.getString("posted"); String moderation = args.containsKey("moderation") ? args.getString("moderation") : ""; Post post = new Post(_rootPostId, userName, postContent, posted, 0, moderation); displayPost(post); } else if (action != null && action.equals(Intent.ACTION_VIEW) && uri != null) { String id = uri.getQueryParameter("id"); if (id == null) { ErrorDialog.display(getActivity(), "Error", "Invalid URL Found"); return; } _currentPostId = Integer.parseInt(id); _rootPostId = _currentPostId; } } _adapter = new PostLoadingAdapter(getActivity(), new ArrayList<Post>()); setListAdapter(_adapter); } else { // user rotated the screen, try to go back to where they where if (_listState != null) getListView().onRestoreInstanceState(_listState); getListView().setSelectionFromTop(_listPosition, _itemPosition); if (_itemChecked != ListView.INVALID_POSITION) displayPost(_itemChecked); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // we should put this info into the outState, but the compatibility framework // seems to swallow it somewhere ListView listView = getListView(); _listState = listView.onSaveInstanceState(); _listPosition = listView.getFirstVisiblePosition(); _itemChecked = listView.getCheckedItemPosition(); View itemView = listView.getChildAt(0); _itemPosition = itemView == null ? 0 : itemView.getTop(); } void ensurePostSelectedAndDisplayed() { int length = _adapter.getCount(); for (int i = 0; i < length; i++) { Post post = _adapter.getItem(i); if (post != null && post.getPostId() == _currentPostId) { if (!_postDisplayed) displayPost(i); if (!_initialPostSelected) { getListView().setItemChecked(i, true); getListView().setSelection(i); _initialPostSelected = true; } break; } } } @Override public void onListItemClick(ListView l, View v, int position, long id) { displayPost(position); } void copyPostUrl() { String url = "http: ClipboardManager clipboard = (ClipboardManager)getActivity().getSystemService(Activity.CLIPBOARD_SERVICE); clipboard.setText(url); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.thread_menu, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean enabled = (_rootPostId != 0); setMenuItemEnabled(menu, R.id.refreshThread, enabled); setMenuItemEnabled(menu, R.id.reply, enabled); setMenuItemEnabled(menu, R.id.tagMenu, enabled); setMenuItemEnabled(menu, R.id.modToolsMenu, enabled); // show the mod tools if enabled in settings Activity activity = getActivity(); if (activity != null) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); boolean showModTools = prefs.getBoolean("showModTools", false); if(showModTools) { MenuItem modMenu = menu.findItem(R.id.modToolsMenu); modMenu.setVisible(true); } } } void setMenuItemEnabled(Menu menu, int id, boolean enabled) { MenuItem item = menu.findItem(id); item.setEnabled(enabled); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.refreshThread: _initialPostSelected = false; _adapter.clear(); return true; case R.id.reply: postReply(); return true; case R.id.lol: case R.id.inf: case R.id.unf: case R.id.tag: case R.id.wtf: lolPost((String)item.getTitle()); return true; case R.id.mod_interesting: case R.id.mod_nuked: case R.id.mod_nws: case R.id.mod_tangent: case R.id.mod_ontopic: case R.id.mod_political: case R.id.mod_stupid: modPost((String)item.getTitle()); return true; default: return super.onOptionsItemSelected(item); } } private static final int POST_REPLY = 0; private void postReply() { boolean isNewsItem = _adapter.getItem(0).getUserName().equalsIgnoreCase("shacknews"); Intent i = new Intent(getActivity(), ComposePostView.class); i.putExtra(SingleThreadView.THREAD_ID, _currentPostId); i.putExtra(SingleThreadView.IS_NEWS_ITEM, isNewsItem); startActivityForResult(i, POST_REPLY); } private void lolPost(String tag) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ThreadViewFragment.this.getActivity()); String userName = prefs.getString("userName", ""); if (userName.length() == 0) { ErrorDialog.display(getActivity(), "Error", "You must set your username before you can lol."); return; } new LolTask().execute(userName, tag); _progressDialog = ProgressDialog.show(getActivity(), "Please wait", "Tagging post as " + tag); } private void modPost(String moderation) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ThreadViewFragment.this.getActivity()); String userName = prefs.getString("userName", ""); String password = prefs.getString("password", ""); if (userName.length() == 0) { ErrorDialog.display(getActivity(), "Error", "You must set your username before you can mod stuff."); return; } new ModTask().execute(userName, password, moderation); _progressDialog = ProgressDialog.show(getActivity(), "Please wait", "Laying down the ban hammer..."); } class LolTask extends AsyncTask<String, Void, Void> { Exception _exception; @Override protected Void doInBackground(String... params) { String userName = params[0]; String tag = params[1]; try { ShackApi.tagPost(_currentPostId, tag, userName); } catch (Exception ex) { Log.e("DroidChatty", "Error tagging post", ex); _exception = ex; } return null; } @Override protected void onPostExecute(Void result) { _progressDialog.dismiss(); if (_exception != null) ErrorDialog.display(getActivity(), "Error", "Error tagging post:\n" + _exception.getMessage()); } } class ModTask extends AsyncTask<String, Void, String> { Exception _exception; @Override protected String doInBackground(String... params) { String userName = params[0]; String password = params[1]; String moderation = params[2]; try { int rootPost = _adapter.getItem(0).getPostId(); String result = ShackApi.modPost(userName, password, rootPost, _currentPostId, moderation); return result; } catch (Exception e) { _exception = e; Log.e("DroidChatty", "Error modding post", e); } return null; } @Override protected void onPostExecute(String result) { _progressDialog.dismiss(); if (_exception != null) ErrorDialog.display(getActivity(), "Error", "Error occured modding post."); else if (result != null) ErrorDialog.display(getActivity(), "Moderation", result); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case POST_REPLY: if (resultCode == Activity.RESULT_OK) { // read the resulting thread id from the post int postId = data.getExtras().getInt("postId"); _rootPostId = postId; _currentPostId = postId; _adapter.clear(); } break; default: break; } } private void displayPost(int position) { Post post = _adapter.getItem(position); // user clicked "Loading..." if (post == null) return; getListView().setItemChecked(position, true); if (!_postDisplayed) getListView().setSelection(position); displayPost(post); } private void displayPost(Post post) { View view = getView(); TextView userName = (TextView)view.findViewById(R.id.textUserName); TextView posted = (TextView)view.findViewById(R.id.textPostedTime); TextView content = (TextView)view.findViewById(R.id.textContent); ScrollView scroll = (ScrollView)view.findViewById(R.id.scroll); View moderation = (View)view.findViewById(R.id.threadModeration); userName.setText(post.getUserName()); posted.setText(post.getPosted()); content.setText(PostFormatter.formatContent(post, content, true)); if (post.getModeration().equalsIgnoreCase("nws")) moderation.setBackgroundColor(Color.RED); else moderation.setBackgroundColor(Color.TRANSPARENT); scroll.scrollTo(0, 0); _currentPostId = post.getPostId(); _postDisplayed = true; } private class PostLoadingAdapter extends LoadingAdapter<Post> { private boolean _loaded = false; private String _userName = ""; public PostLoadingAdapter(Context context, ArrayList<Post> items) { super(context, R.layout.thread_row, R.layout.row_loading, items); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ThreadViewFragment.this.getActivity()); _userName = prefs.getString("userName", ""); } @Override public void clear() { _loaded = false; super.clear(); } @Override protected boolean getMoreToLoad() { if (_rootPostId == 0) return false; return !_loaded; } @Override protected View createView(int position, View convertView, ViewGroup parent) { ViewHolder holder = (ViewHolder)convertView.getTag(); if (holder == null) { holder = new ViewHolder(); holder.content = (TextView)convertView.findViewById(R.id.textPreview); holder.moderation = (View)convertView.findViewById(R.id.postModeration); convertView.setTag(holder); } // get the thread to display and populate all the data into the layout Post t = getItem(position); holder.content.setPadding(15 * t.getLevel(), 0, 0, 0); holder.content.setText(t.getPreview()); if (t.getModeration().equalsIgnoreCase("nws")) holder.moderation.setBackgroundColor(Color.RED); else holder.moderation.setBackgroundColor(Color.TRANSPARENT); if (t.getUserName().equalsIgnoreCase(_userName)) { // highlight your own posts holder.content.setTextColor(getResources().getColor(R.color.user_paricipated)); } else { // highlight newer posts int color = 255 - (12 * Math.min(t.getOrder(), 10)); holder.content.setTextColor(Color.argb(255, color, color, color)); } return convertView; } @Override protected ArrayList<Post> loadData() throws Exception { ArrayList<Post> posts = ShackApi.getPosts(_rootPostId); _loaded = true; return posts; } @Override protected void afterDisplay() { try { ensurePostSelectedAndDisplayed(); } catch (Exception e) { Log.w("DroidChatty", "Error selecting root post", e); } } private class ViewHolder { TextView content; View moderation; } } public void adjustSelected(int movement) { int index = getListView().getCheckedItemPosition() + movement; if (index >= 0 && index < getListView().getCount()) { displayPost(index); ensureVisible(index); } } void ensureVisible(int position) { ListView view = getListView(); if (position < 0 || position >= view.getCount()) return; int first = view.getFirstVisiblePosition(); int last = view.getLastVisiblePosition(); if (position < first) view.setSelection(position); else if (position >= last) view.setSelection(1 + position - (last - first)); } }
package wint.lang.utils; import wint.help.mvc.security.csrf.CsrfTokenUtil; import wint.mvc.template.filters.CvsFilterRender; import wint.mvc.template.filters.HtmlFilterRender; import wint.mvc.template.filters.JavaScriptFilterRender; import wint.mvc.template.filters.RawContentFilterRender; import wint.mvc.template.filters.XmlFilterRender; import wint.mvc.view.Render; public class SecurityUtil { public static Render rawContent(Object o) { return new RawContentFilterRender(o); } public static Render rawText(Object o) { return rawContent(o); } public static Render raw(Object o) { return rawContent(o); } public static Render escapeHtml(Object o) { return new HtmlFilterRender(o); } public static Render escapeJavaScript(Object o) { return new JavaScriptFilterRender(o); } public static Render escapeJs(Object o) { return escapeJavaScript(o); } public static Render escapeXml(Object o) { return new XmlFilterRender(o); } public static Render escapeCvs(Object o) { return new CvsFilterRender(o); } public static String csrfToken() { return getCsrfToken(); } public static String xToken() { return getCsrfToken(); } public static String getCsrfToken() { return CsrfTokenUtil.token(); } public static Render tokenHtml() { return rawContent(CsrfTokenUtil.tokenHtml()); } }
package net.winroad.Models; import java.util.List; import org.hibernate.validator.constraints.NotEmpty; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * * @author AdamsLi * @version 0.1 * @memo init create */ public class Person { private String name; private int age; @SuppressWarnings("unused") private double weight; private Gender gender; private double h; private boolean isAdult; private String LOGOURL; private int xIndex; private Address address; private List<String> friendNames; public final static String PET_PHRASE = "MY GOD!"; @SuppressFBWarnings(value="SS_SHOULD_BE_STATIC", justification = "just for demo") public final String hobby = "hot girl"; public static String favStar = "Jackie Chen"; public boolean isAdult() { return isAdult; } public void setAdult(boolean isAdult) { this.isAdult = isAdult; } public String getTEast() { return this.name; } public void setTest(String test) { this.name = test; } @NotEmpty(message = "name should not be empty") public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @SuppressWarnings("unused") @SuppressFBWarnings(value="URF_UNREAD_FIELD", justification = "just for demo") private void setW(double weight) { this.weight = weight; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public String saySomething() { return PET_PHRASE; } public void setHeight(double height) { this.h = height; } public double getHeight() { return h; } public String getHobbies() { return this.hobby; } public String getLOGOURL() { return LOGOURL; } public void setLOGOURL(String lOGOURL) { LOGOURL = lOGOURL; } public int getxIndex() { return xIndex; } public void setxIndex(int xIndex) { this.xIndex = xIndex; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public List<String> getFriendNames() { return friendNames; } public void setFriendNames(List<String> friendNames) { this.friendNames = friendNames; } }
package scal.io.liger; import timber.log.Timber; import android.app.Activity; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.storage.StorageManager; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import java.io.IOException; import java.lang.reflect.Method; import java.nio.CharBuffer; import info.guardianproject.cacheword.CacheWordHandler; import info.guardianproject.cacheword.ICacheWordSubscriber; import info.guardianproject.iocipher.File; import info.guardianproject.iocipher.VirtualFileSystem; public class LockableActivity extends Activity implements ICacheWordSubscriber { protected CacheWordHandler mCacheWordHandler; public static final String CACHEWORD_UNSET = "unset"; public static final String CACHEWORD_FIRST_LOCK = "first_lock"; public static final String CACHEWORD_SET = "set"; public static final String CACHEWORD_TIMEOUT = "300"; // protected VirtualFileSystem vfs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); int timeout = Integer.parseInt(settings.getString("pcachewordtimeout", CACHEWORD_TIMEOUT)); mCacheWordHandler = new CacheWordHandler(this, timeout); // TEST /* String path = StorageHelper.getActualStorageDirectory(this).getPath() + "/" + "FOO" + ".db"; java.io.File db = new java.io.File(path); if (db.exists()) { Timber.d("delete existing file " + db.getAbsolutePath()); db.delete(); } else { Timber.d("no existing file " + db.getAbsolutePath()); } vfs = VirtualFileSystem.get(); vfs.setContainerPath(path); vfs.mount("PASSWORD"); if (vfs.isMounted()) { Timber.d("vfs is mounted"); } else { Timber.d("vfs is NOT mounted"); } vfs.unmount(); */ //TEST /* File checkFile = new File(getDir("vfs", MODE_PRIVATE).getAbsolutePath() + File.separator + "liger.db"); if (checkFile.exists()) { Timber.d("found iocipher file"); } else { try { checkFile.createNewFile(); Timber.d("created iocipher file"); } catch (IOException ioe) { ioe.printStackTrace(); Timber.d("could not create iocipher file"); } } */ } @Override protected void onPause() { super.onPause(); mCacheWordHandler.disconnectFromService(); } @Override protected void onResume() { super.onResume(); // only display notification if the user has set a pin SharedPreferences sp = getSharedPreferences("appPrefs", MODE_PRIVATE); String cachewordStatus = sp.getString("cacheword_status", "default"); if (cachewordStatus.equals(CACHEWORD_SET)) { Timber.d("pin set, so display notification (lockable)"); mCacheWordHandler.setNotification(buildNotification(this)); } else { Timber.d("no pin set, so no notification (lockable)"); } mCacheWordHandler.connectToService(); } @Override protected void onDestroy() { super.onDestroy(); /* if (vfs.isMounted()) { vfs.unmount(); Timber.d("onDestroy - vfs un-mounted"); } else { Timber.d("onDestroy - vfs not mounted"); } */ } protected Notification buildNotification(Context c) { Timber.d("buildNotification (lockable)"); NotificationCompat.Builder b = new NotificationCompat.Builder(c); b.setSmallIcon(android.R.drawable.ic_menu_info_details); b.setContentTitle(c.getText(R.string.cacheword_notification_cached_title)); b.setContentText(c.getText(R.string.cacheword_notification_cached_message)); b.setTicker(c.getText(R.string.cacheword_notification_cached)); b.setWhen(System.currentTimeMillis()); b.setOngoing(true); b.setContentIntent(CacheWordHandler.getPasswordLockPendingIntent(c)); return b.build(); } @Override public void onCacheWordUninitialized() { // if we're uninitialized, default behavior should be to stop Timber.d("cacheword uninitialized, activity will not continue"); finish(); } @Override public void onCacheWordLocked() { // unmount vfs file /* if (vfs.isMounted()) { vfs.unmount(); Timber.d("onCacheWordLocked - vfs un-mounted"); } else { Timber.d("onCacheWordLocked - vfs not mounted"); } */ // if we're locked, default behavior should be to stop Timber.d("cacheword locked, activity will not continue"); finish(); } @Override public void onCacheWordOpened() { // mount vfs file (if a pin has been set) // NEW ATTEMPT, USES MANAGER SharedPreferences sp = getSharedPreferences("appPrefs", MODE_PRIVATE); String cachewordStatus = sp.getString("cacheword_status", "default"); if (cachewordStatus.equals(CACHEWORD_SET)) { if (mCacheWordHandler.isLocked()) { Timber.d("onCacheWordOpened - pin set but cacheword locked, cannot mount vfs"); } else { Timber.d("onCacheWordOpened - pin set and cacheword unlocked, mounting vfs"); StorageHelper.mountStorage(this, null, mCacheWordHandler.getEncryptionKey()); } } else { Timber.d("onCacheWordOpened - no pin set, cannot mount vfs"); } /* SharedPreferences sp = getSharedPreferences("appPrefs", MODE_PRIVATE); String cachewordStatus = sp.getString("cacheword_status", "default"); if (cachewordStatus.equals(CACHEWORD_SET)) { if (mCacheWordHandler.isLocked()) { Timber.d("onResume - pin set but cacheword locked, cannot mount vfs"); } else { Timber.d("onResume - pin set and cacheword unlocked, mounting vfs"); if (vfs.isMounted()) { Timber.d("onResume - vfs already mounted?"); } else { Timber.d("onResume - vfs not mounted"); // create file? String vfsPath = getDir("vfs", MODE_PRIVATE).getAbsolutePath() + File.separator + "liger.db"; File checkFile = new File(vfsPath); if (checkFile.exists()) { Timber.d("onResume - iocipher file found, setting path to " + vfsPath); vfs.setContainerPath(vfsPath); Timber.d("onResume - done"); // this was the same "password" used for getWritableDatabase() in StoryMakerDBWrapper vfs.mount(encodeRawKey(mCacheWordHandler.getEncryptionKey())); Timber.d("onResume - vfs mounted"); } else { //checkFile.createNewFile(); Timber.d("onResume - iocipher file not found, creating new file at " + vfsPath); vfs.unmount(); // this was the same "password" used for getWritableDatabase() in StoryMakerDBWrapper vfs.createNewContainer(vfsPath, mCacheWordHandler.getEncryptionKey()); Timber.d("onResume - done"); // createNewContainer also seems to mount the file? Timber.d("onResume - vfs mounted (?)"); } // this was the same "password" used for getWritableDatabase() in StoryMakerDBWrapper // vfs.mount(encodeRawKey(mCacheWordHandler.getEncryptionKey())); // Timber.d("onResume - vfs mounted"); } } } else { Timber.d("onResume - no pin set, cannot mount vfs"); } */ // if we're opened, check db and update menu status Timber.d("cacheword opened (liger), activity will continue"); } // copied from StoryMakerDBWrapper, may not be necessary but trying to be consistent public static String encodeRawKey(byte[] raw_key) { if (raw_key.length != 32) throw new IllegalArgumentException("provided key not 32 bytes (256 bits) wide"); final String kPrefix; final String kSuffix; if (check_sqlcipher_uses_native_key()) { Timber.d("sqlcipher uses native method to set key"); kPrefix = "x'"; kSuffix = "'"; } else { Timber.d("sqlcipher uses PRAGMA to set key - SPECIAL HACK IN PROGRESS"); kPrefix = "x''"; kSuffix = "''"; } final char[] key_chars = encodeHex(raw_key, HEX_DIGITS_LOWER); if (key_chars.length != 64) throw new IllegalStateException("encoded key is not 64 bytes wide"); char[] kPrefix_c = kPrefix.toCharArray(); char[] kSuffix_c = kSuffix.toCharArray(); CharBuffer cb = CharBuffer.allocate(kPrefix_c.length + kSuffix_c.length + key_chars.length); cb.put(kPrefix_c); cb.put(key_chars); cb.put(kSuffix_c); return cb.toString(); } private static final char[] HEX_DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private static boolean check_sqlcipher_uses_native_key() { for (Method method : SQLiteDatabase.class.getDeclaredMethods()) { if (method.getName().equals("native_key")) return true; } return false; } private static char[] encodeHex(final byte[] data, final char[] toDigits) { final int l = data.length; final char[] out = new char[l << 1]; // two characters form the hex value. for (int i = 0, j = 0; i < l; i++) { out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; out[j++] = toDigits[0x0F & data[i]]; } return out; } }
package com.facebook.yoga; import com.facebook.soloader.SoLoader; public class YogaJNI { // Known constants. 1-3 used in previous experiments. Do not reuse. public static int JNI_FAST_CALLS = 4; // set before loading any other Yoga code public static boolean useFastCall = false; private static native void jni_bindNativeMethods(boolean useFastCall); static boolean init() { if (SoLoader.loadLibrary("yoga")) { jni_bindNativeMethods(useFastCall); return true; } return false; } }
package org.eclipse.birt.report.designer.ui.editor.pages.xml; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.util.mediator.IColleague; import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest; import org.eclipse.birt.report.designer.internal.ui.command.WrapperCommandStack; import org.eclipse.birt.report.designer.internal.ui.editors.parts.event.ModelEventManager; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.Policy; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.internal.ui.views.outline.DesignerOutlinePage; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.editors.IPageStaleType; import org.eclipse.birt.report.designer.ui.editors.IReportEditorContants; import org.eclipse.birt.report.designer.ui.editors.IReportEditorPage; import org.eclipse.birt.report.designer.ui.editors.IReportProvider; import org.eclipse.birt.report.designer.ui.editors.MultiPageReportEditor; import org.eclipse.birt.report.designer.ui.editors.pages.ReportFormPage; import org.eclipse.birt.report.model.api.DesignFileException; import org.eclipse.birt.report.model.api.ErrorDetail; import org.eclipse.birt.report.model.api.LibraryHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.activity.ActivityStackEvent; import org.eclipse.birt.report.model.api.activity.ActivityStackListener; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.gef.ui.actions.ActionRegistry; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IPathEditorInput; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel; import org.eclipse.ui.texteditor.MarkerUtilities; import org.eclipse.ui.views.contentoutline.ContentOutlinePage; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.wst.sse.ui.StructuredTextEditor; /** * XML editor for report source file. */ public class ReportXMLSourceEditorFormPage extends ReportFormPage implements IColleague { private ModelEventManager manager; public static final String ID = "org.eclipse.birt.report.designer.ui.editors.xmlsource"; //$NON-NLS-1$ private static final String switchAction_ID = "switch"; private ActionRegistry registry; private static final String SWITCH_REPORT_OUTLINE = Messages.getString( "ContentOutlinePage.action.text.reportOutline" ); private static final String SWITCH_REPORT_XML_OUTLINE = Messages.getString( "ContentOutlinePage.action.text.reportXMLSourceOutline" ); // Leverage from WST private StructuredTextEditor reportXMLEditor; private Control control; private int staleType; private boolean isModified = false; private boolean isLeaving = false; private boolean registered = false; private ActivityStackListener commandStackListener; private OutlineSwitchAction outlineSwitchAction; /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.editor.pages.xml.ReportFormPage#init(org.eclipse.ui.IEditorSite, * org.eclipse.ui.IEditorInput) */ public void init( IEditorSite site, IEditorInput input ) throws PartInitException { super.init( site, input ); try { reportXMLEditor = new StructuredTextEditor( ); reportXMLEditor.init( site, input ); } catch ( Exception e ) { } } private int getErrorLIine( boolean checkReport ) { IEditorInput input = getEditorInput( ); if ( !( input instanceof IPathEditorInput ) ) { return 0; } IPath path = ( (IPathEditorInput) input ).getPath( ); try { if ( path.toOSString( ) .endsWith( IReportEditorContants.LIBRARY_FILE_EXTENTION ) ) { LibraryHandle library = null; try { library = SessionHandleAdapter.getInstance( ) .getSessionHandle( ) .openLibrary( path.toOSString( ) ); if ( checkReport ) { return getErrorLineFromModuleHandle( library ); } } catch ( DesignFileException e ) { return getExpetionErrorLine( e ); } finally { if ( library != null ) { library.close( ); } } } else { ReportDesignHandle report = null; try { report = SessionHandleAdapter.getInstance( ) .getSessionHandle( ) .openDesign( path.toOSString( ), new FileInputStream( path.toFile( ) ) ); if ( checkReport ) { return getErrorLineFromModuleHandle( report ); } } catch ( DesignFileException e ) { return getExpetionErrorLine( e ); } finally { if ( report != null ) { report.close( ); } } } } catch ( FileNotFoundException e ) { return 0; } return -1; } private int getExpetionErrorLine( DesignFileException e ) { List errorList = e.getErrorList( ); for ( Iterator iter = errorList.iterator( ); iter.hasNext( ); ) { Object element = iter.next( ); if ( element instanceof ErrorDetail ) { return ( (ErrorDetail) element ).getLineNo( ); } } return 0; } private int getErrorLineFromModuleHandle( ModuleHandle handle ) { handle.checkReport( ); List list = handle.getErrorList( ); if ( list != null ) for ( int i = 0, m = list.size( ); i < m; i++ ) { Object obj = list.get( i ); if ( obj instanceof ErrorDetail ) { ErrorDetail errorDetail = (ErrorDetail) list.get( i ); return errorDetail.getLineNo( ); } } return 0; } /* * (non-Javadoc) * * @see org.eclipse.ui.forms.editor.IFormPage#canLeaveThePage() */ public boolean canLeaveThePage( ) { if ( isDirty( ) ) { MessageDialog prefDialog = new MessageDialog( UIUtil.getDefaultShell( ), Messages.getString( "XMLSourcePage.Error.Dialog.title" ),//$NON-NLS-1$ null, Messages.getString( "XMLSourcePage.Error.Dialog.Message.PromptMsg" ),//$NON-NLS-1$ MessageDialog.INFORMATION, new String[]{ Messages.getString( "XMLSourcePage.Error.Dialog.Message.Yes" ),//$NON-NLS-1$ Messages.getString( "XMLSourcePage.Error.Dialog.Message.No" ),//$NON-NLS-1$ Messages.getString( "XMLSourcePage.Error.Dialog.Message.Cancel" )}, 0 );//$NON-NLS-1$ int ret = prefDialog.open( ); switch ( ret ) { case 0 : isLeaving = true; getReportEditor( ).doSave( null ); break; case 1 : if ( getEditorInput( ) != null ) { this.setInput( getEditorInput( ) ); } break; case 2 : if ( getEditorInput( ) != null ) { this.setInput( getEditorInput( ) ); } return false; } } int errorLine = getErrorLIine( false ); if ( errorLine > -1 ) { // Display.getCurrent( ).beep( ); MessageDialog.openError( Display.getCurrent( ).getActiveShell( ), Messages.getString( "XMLSourcePage.Error.Dialog.title" ), //$NON-NLS-1$ Messages.getString( "XMLSourcePage.Error.Dialog.Message.InvalidFile" ) ); //$NON-NLS-1$ setFocus( ); setHighlightLine( errorLine ); return false; } return true; } private void setHighlightLine( int line ) { try { IRegion region = reportXMLEditor.getDocumentProvider( ) .getDocument( getEditorInput( ) ) .getLineInformation( --line ); reportXMLEditor.setHighlightRange( region.getOffset( ), region.getLength( ), true ); } catch ( BadLocationException e ) { } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.editor.pages.xml.ReportFormPage#selectReveal(java.lang.Object) */ public boolean selectReveal( Object marker ) { int start = MarkerUtilities.getCharStart( (IMarker) marker ); int end = MarkerUtilities.getCharEnd( (IMarker) marker ); boolean selectLine = start < 0 || end < 0; // look up the current range of the marker when the document has been // edited IAnnotationModel model = reportXMLEditor.getDocumentProvider( ) .getAnnotationModel( reportXMLEditor.getEditorInput( ) ); if ( model instanceof AbstractMarkerAnnotationModel ) { AbstractMarkerAnnotationModel markerModel = (AbstractMarkerAnnotationModel) model; Position pos = markerModel.getMarkerPosition( (IMarker) marker ); if ( pos != null ) { if ( !pos.isDeleted( ) ) { // use position instead of marker values start = pos.getOffset( ); end = pos.getOffset( ) + pos.getLength( ); } else { return false; } } } IDocument document = reportXMLEditor.getDocumentProvider( ) .getDocument( reportXMLEditor.getEditorInput( ) ); if ( selectLine ) { int line; try { if ( start >= 0 ) line = document.getLineOfOffset( start ); else { line = MarkerUtilities.getLineNumber( (IMarker) marker ); // Marker line numbers are 1-based if ( line >= 1 ) { line } start = document.getLineOffset( line ); } end = start + document.getLineLength( line ) - 1; } catch ( BadLocationException e ) { return false; } } int length = document.getLength( ); if ( end - 1 < length && start < length ) reportXMLEditor.selectAndReveal( start, end - start ); return true; } /* * (non-Javadoc) * * @see org.eclipse.ui.forms.editor.IFormPage#getPartControl() */ public Control getPartControl( ) { return control; } /* * (non-Javadoc) * * @see org.eclipse.ui.forms.editor.IFormPage#getId() */ public String getId( ) { return ID; } private ActivityStackListener getCommandStackListener( ) { if ( commandStackListener == null ) { commandStackListener = new ActivityStackListener( ) { public void stackChanged( ActivityStackEvent event ) { if ( isActive( ) && event.getAction( ) != ActivityStackEvent.ROLL_BACK ) { reloadEditorInput( ); } } }; } return commandStackListener; } /* * (non-Javadoc) * * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ public void createPartControl( Composite parent ) { reportXMLEditor.createPartControl( parent ); Control[] children = parent.getChildren( ); control = children[children.length - 1]; // suport the mediator SessionHandleAdapter.getInstance( ).getMediator( ).addColleague( this ); // Add Command Stack Listener if ( SessionHandleAdapter.getInstance( ).getCommandStack( ) != null ) { getCommandStack( ).addCommandStackListener( getCommandStackListener( ) ); hookModelEventManager( getModel( ) ); } reportXMLEditor.getTextViewer( ).addTextListener( new ITextListener( ) { public void textChanged( TextEvent event ) { if ( !isTextModified( ) && event.getOffset( ) != 0 ) { markDirty( ); } } } ); reportXMLEditor.getTextViewer( ) .getTextWidget( ) .addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { markDirty( ); } } ); } private void registerOutlineSwitchAction( ) { if ( registered == true ) return; // Register the switch action onto outline page Page reportMultiBookPage = (Page) ( (MultiPageReportEditor) getEditor( ) ).getOutlinePage( ); if ( reportMultiBookPage.getSite( ) != null ) { reportMultiBookPage.getSite( ) .getActionBars( ) .getMenuManager( ) .add( getOutlineSwitchAction( ) ); registered = true; } } private void removeOutlineSwitchAction( ) { Page reportMultiBookPage = (Page) ( (MultiPageReportEditor) getEditor( ) ).getOutlinePage( ); if ( reportMultiBookPage.getSite( ) != null ) { reportMultiBookPage.getSite( ) .getActionBars( ) .getMenuManager( ) .remove( switchAction_ID ); registered = false; } } public void setIsModified( boolean modified ) { isModified = modified; } private boolean isTextModified( ) { return isModified; } protected void markDirty( ) { setIsModified( true ); getEditor( ).editorDirtyStateChanged( ); } private WrapperCommandStack getCommandStack( ) { return new WrapperCommandStack( ); } private void reloadEditorInput( ) { ByteArrayOutputStream out = new ByteArrayOutputStream( ); try { getModel( ).serialize( out ); String newInput = out.toString( ); reportXMLEditor.getDocumentProvider( ) .getDocument( getEditorInput( ) ) .set( newInput ); markDirty( ); } catch ( IOException e ) { ExceptionHandler.handle( e ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.core.util.mediator.IColleague#performRequest(org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest) */ public void performRequest( ReportRequest request ) { if ( ReportRequest.SELECTION.equals( request.getType( ) ) && !( request.getSource( ) instanceof ReportXMLSourceEditorFormPage ) && isActive( ) && request.getSource( ) instanceof DesignerOutlinePage ) { handleSelectionChange( request ); } } private void handleSelectionChange( ReportRequest request ) { List selectedObjects = request.getSelectionObject( ); ModuleHandle model = ( (DesignerOutlinePage) request.getSource( ) ).getRoot( ); if ( !selectedObjects.isEmpty( ) ) { if ( selectedObjects.get( 0 ) instanceof ReportElementHandle ) { setHighlightLine( model.getLineNoByID( ( (ReportElementHandle) selectedObjects.get( 0 ) ).getID( ) ) ); } if ( selectedObjects.get( 0 ) instanceof LibraryHandle ) { setHighlightLine( model.getLineNoByID( ( (LibraryHandle) selectedObjects.get( 0 ) ).getID( ) ) ); } } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.editors.IReportEditorPage#onBroughtToTop(org.eclipse.birt.report.designer.ui.editors.IReportEditorPage) */ public boolean onBroughtToTop( IReportEditorPage prePage ) { if ( getEditorInput( ) != prePage.getEditorInput( ) ) { setInput( prePage.getEditorInput( ) ); } if ( prePage != this && ( prePage.isDirty( ) || prePage.getStaleType( ) != IPageStaleType.NONE ) ) { prePage.doSave( null ); prePage.markPageStale( IPageStaleType.NONE ); refreshDocument( ); markPageStale( IPageStaleType.NONE ); } hookModelEventManager( getModel( ) ); // ser the attribute view disedit. ReportRequest request = new ReportRequest( ReportXMLSourceEditorFormPage.this ); List list = new ArrayList( ); request.setSelectionObject( list ); request.setType( ReportRequest.SELECTION ); // SessionHandleAdapter.getInstance().getMediator().pushState(); SessionHandleAdapter.getInstance( ) .getMediator( ) .notifyRequest( request ); registerOutlineSwitchAction( ); return true; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.editors.IReportEditorPage#markPageStale(int) */ public void markPageStale( int type ) { staleType = type; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.editors.IReportEditorPage#getStaleType() */ public int getStaleType( ) { return staleType; } /* * (non-Javadoc) * * @see org.eclipse.ui.texteditor.AbstractTextEditor#getAdapter(java.lang.Class) */ public Object getAdapter( Class required ) { if ( required.equals( ActionRegistry.class ) ) { if ( registry == null ) { registry = new ActionRegistry( ); } return registry; } else if ( IContentOutlinePage.class.equals( required ) ) { if ( getModel( ) != null ) { DesignerOutlinePage outlinePage = new DesignerOutlinePage( getModel( ) ); getModelEventManager( ).addModelEventProcessor( outlinePage.getModelProcessor( ) ); registerOutlineSwitchAction( ); return outlinePage; } } else if ( ContentOutlinePage.class.equals( required ) ) { return reportXMLEditor.getAdapter( IContentOutlinePage.class ); } return super.getAdapter( required ); } private ModelEventManager getModelEventManager( ) { if ( manager == null ) { return manager = new ModelEventManager( ); } return manager; } protected void hookModelEventManager( Object model ) { getModelEventManager( ).hookRoot( model ); getModelEventManager( ).hookCommandStack( getCommandStack( ) ); } protected void unhookModelEventManager( Object model ) { getModelEventManager( ).unhookRoot( model ); // getModelEventManager( ).unhookCommandStack( getCommandStack( ) ); } protected void finalize( ) throws Throwable { if ( Policy.TRACING_PAGE_CLOSE ) { System.out.println( "Report source page finalized" ); //$NON-NLS-1$ } super.finalize( ); } public void refreshDocument( ) { setInput( getEditorInput( ) ); } private IReportProvider getProvider( ) { return (IReportProvider) getEditor( ).getAdapter( IReportProvider.class ); } /* * (non-Javadoc) * * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSave(org.eclipse.core.runtime.IProgressMonitor) */ public void doSave( IProgressMonitor progressMonitor ) { reportXMLEditor.doSave( progressMonitor ); IReportProvider provider = getProvider( ); if ( provider != null && getErrorLIine( false ) == -1 ) { unhookModelEventManager( getModel( ) ); getCommandStack( ).removeCommandStackListener( getCommandStackListener( ) ); ModuleHandle model = provider.getReportModuleHandle( getEditorInput( ), true ); SessionHandleAdapter.getInstance( ).setReportDesignHandle( model ); SessionHandleAdapter.getInstance( ) .getMediator( ) .addColleague( this ); hookModelEventManager( getModel( ) ); getCommandStack( ).addCommandStackListener( getCommandStackListener( ) ); setIsModified( false ); getEditor( ).editorDirtyStateChanged( ); if ( isActive( ) && !isLeaving ) { getReportEditor( ).reloadOutlinePage( ); } } } /* * (non-Javadoc) * * @see org.eclipse.ui.part.EditorPart#doSaveAs() */ public void doSaveAs( ) { // Do nothing, SavaAs is not allowed by default } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.editor.pages.xml.ReportFormPage#isSaveAsAllowed() */ public boolean isSaveAsAllowed( ) { return false; } /* * (non-Javadoc) * * @see org.eclipse.ui.part.EditorPart#isDirty() */ public boolean isDirty( ) { return reportXMLEditor.isDirty( ); } /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#dispose() */ public void dispose( ) { super.dispose( ); reportXMLEditor.dispose( ); reportXMLEditor = null; unhookModelEventManager( getModel( ) ); } private OutlineSwitchAction getOutlineSwitchAction( ) { if ( outlineSwitchAction == null ) { outlineSwitchAction = new OutlineSwitchAction( ); } return outlineSwitchAction; } protected class OutlineSwitchAction extends Action { public OutlineSwitchAction( ) { setText( SWITCH_REPORT_OUTLINE ); setEnabled( true ); setId( switchAction_ID ); } public void run( ) { getReportEditor( ).outlineSwitch( ); if ( getText( ).equals( SWITCH_REPORT_OUTLINE ) ) { setText( SWITCH_REPORT_XML_OUTLINE ); } else { setText( SWITCH_REPORT_OUTLINE ); } } } /* * (non-Javadoc) * * @see org.eclipse.ui.forms.editor.IFormPage#setActive(boolean) */ public void setActive( boolean active ) { super.setActive( active ); if ( active == false ) { removeOutlineSwitchAction( ); } } }
package android.support.v4.app; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.Rect; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.support.v7.app.ActionBarActivity; import android.support.v7.internal.view.menu.ContextMenuCallbackGetter; import android.support.v7.internal.view.menu.ContextMenuDecorView.ContextMenuListenersProvider; import android.support.v7.internal.view.menu.ContextMenuListener; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import org.holoeverywhere.HoloEverywhere; import org.holoeverywhere.HoloEverywhere.PreferenceImpl; import org.holoeverywhere.LayoutInflater; import org.holoeverywhere.R; import org.holoeverywhere.SystemServiceManager; import org.holoeverywhere.SystemServiceManager.SuperSystemService; import org.holoeverywhere.ThemeManager; import org.holoeverywhere.ThemeManager.SuperStartActivity; import org.holoeverywhere.addon.IAddonActivity; import org.holoeverywhere.addon.IAddonAttacher; import org.holoeverywhere.app.Activity; import org.holoeverywhere.app.Application; import org.holoeverywhere.app.ContextThemeWrapperPlus; import org.holoeverywhere.internal.WindowDecorView; import org.holoeverywhere.preference.PreferenceManagerHelper; import org.holoeverywhere.preference.SharedPreferences; import org.holoeverywhere.util.SparseIntArray; import org.holoeverywhere.util.WeaklyMap; import java.util.Map; public abstract class _HoloActivity extends ActionBarActivity implements SuperStartActivity, SuperSystemService, ContextMenuListener, ContextMenuListenersProvider, IAddonAttacher<IAddonActivity> { private static final String CONFIG_KEY = "holo:config:activity"; private Context mActionBarContext; private Holo mConfig; private Map<View, ContextMenuListener> mContextMenuListeners; private WindowDecorView mDecorView; private boolean mInited = false; private int mLastThemeResourceId = 0; private Handler mUserHandler; @Override public void addContentView(View view, LayoutParams params) { if (requestDecorView(view, params, -1)) { mDecorView.addView(view, params); } onSupportContentChanged(); } protected Holo createConfig(Bundle savedInstanceState) { if (mConfig == null) { mConfig = onCreateConfig(savedInstanceState); } if (mConfig == null) { mConfig = Holo.defaultConfig(); } return mConfig; } protected void forceInit(Bundle savedInstanceState) { if (mInited) { return; } if (mConfig == null && savedInstanceState != null && savedInstanceState.containsKey(CONFIG_KEY)) { mConfig = savedInstanceState.getParcelable(CONFIG_KEY); } onInit(mConfig, savedInstanceState); } public Holo getConfig() { return mConfig; } @Override public ContextMenuListener getContextMenuListener(View view) { if (mContextMenuListeners == null) { return null; } return mContextMenuListeners.get(view); } public SharedPreferences getDefaultSharedPreferences() { return PreferenceManagerHelper.getDefaultSharedPreferences(this); } public SharedPreferences getDefaultSharedPreferences(PreferenceImpl impl) { return PreferenceManagerHelper.getDefaultSharedPreferences(this, impl); } public int getLastThemeResourceId() { return mLastThemeResourceId; } @Override public LayoutInflater getLayoutInflater() { return LayoutInflater.from(this); } public SharedPreferences getSharedPreferences(PreferenceImpl impl, String name, int mode) { return PreferenceManagerHelper.wrap(this, impl, name, mode); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { return PreferenceManagerHelper.wrap(this, name, mode); } /** * @return Themed context for using in action bar */ public Context getSupportActionBarContext() { if (mActionBarContext == null) { int theme = ThemeManager.getThemeType(this); if (theme != ThemeManager.LIGHT) { theme = ThemeManager.DARK; } theme = ThemeManager.getThemeResource(theme, false); if (mLastThemeResourceId == theme) { mActionBarContext = this; } else { mActionBarContext = new ContextThemeWrapperPlus(this, theme); } } return mActionBarContext; } public Application getSupportApplication() { return Application.getLastInstance(); } @Override public Object getSystemService(String name) { return SystemServiceManager.getSystemService(this, name); } @Override public Theme getTheme() { if (mLastThemeResourceId == 0) { setTheme(ThemeManager.getDefaultTheme()); } return super.getTheme(); } @Override public void setTheme(int resid) { setTheme(resid, true); } public LayoutInflater getThemedLayoutInflater() { return getLayoutInflater(); } public Handler getUserHandler() { if (mUserHandler == null) { mUserHandler = new Handler(getMainLooper()); } return mUserHandler; } protected final WindowDecorView getWindowDecorView() { return mDecorView; } public boolean isDecorViewInited() { return mDecorView != null; } public boolean isInited() { return mInited; } @Override @SuppressLint("NewApi") public void onBackPressed() { if (!getSupportFragmentManager().popBackStackImmediate()) { finish(); } } @Override protected void onCreate(Bundle savedInstanceState) { forceInit(savedInstanceState); super.onCreate(savedInstanceState); } protected Holo onCreateConfig(Bundle savedInstanceState) { if (savedInstanceState != null && savedInstanceState.containsKey(CONFIG_KEY)) { final Holo config = savedInstanceState.getParcelable(CONFIG_KEY); if (config != null) { return config; } } return Holo.defaultConfig(); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); if (view instanceof ContextMenuCallbackGetter) { final OnCreateContextMenuListener l = ((ContextMenuCallbackGetter) view) .getOnCreateContextMenuListener(); if (l != null) { l.onCreateContextMenu(menu, view, menuInfo); } } } @Override protected void onDestroy() { super.onDestroy(); LayoutInflater.removeInstance(this); } public boolean onHomePressed() { return false; } /** * Do not override this method. Use {@link #onPreInit(Holo, Bundle)} and * {@link #onPostInit(Holo, Bundle)} */ protected void onInit(Holo config, Bundle savedInstanceState) { if (mInited) { throw new IllegalStateException("This instance was already inited"); } mInited = true; if (config == null) { config = createConfig(savedInstanceState); } if (config == null) { config = Holo.defaultConfig(); } onPreInit(config, savedInstanceState); if (!config.ignoreApplicationInstanceCheck && !(getApplication() instanceof Application)) { String text = "Application instance isn't HoloEverywhere.\n"; if (getApplication().getClass() == android.app.Application.class) { text += "Put attr 'android:name=\"org.holoeverywhere.app.Application\"'" + " in <application> tag of AndroidManifest.xml"; } else { text += "Please sure that you extend " + getApplication().getClass() + " from a org.holoeverywhere.app.Application"; } throw new IllegalStateException(text); } getLayoutInflater().setFragmentActivity(this); if (this instanceof Activity) { Activity activity = (Activity) this; if (config.requireRoboguice) { activity.addon(Activity.ADDON_ROBOGUICE); } if (config.requireSlider) { activity.addon(Activity.ADDON_SLIDER); } final SparseIntArray windowFeatures = config.windowFeatures; if (windowFeatures != null) { for (int i = 0; i < windowFeatures.size(); i++) { if (windowFeatures.valueAt(i) > 0) { requestWindowFeature((long) windowFeatures.keyAt(i)); } } } ThemeManager.applyTheme(activity, mLastThemeResourceId == 0); if (!config.ignoreThemeCheck && ThemeManager.getThemeType(this) == ThemeManager.INVALID) { throw new HoloThemeException(activity); } TypedArray a = obtainStyledAttributes(new int[]{ android.R.attr.windowActionBarOverlay, R.attr.windowActionBarOverlay }); if (a.getBoolean(0, false) || a.getBoolean(1, false)) { requestWindowFeature((long) Window.FEATURE_ACTION_BAR_OVERLAY); } a.recycle(); } onPostInit(config, savedInstanceState); lockAttaching(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home && onHomePressed()) { return true; } return false; } @Override protected void onPostCreate(Bundle savedInstanceState) { requestDecorView(null, null, -1); super.onPostCreate(savedInstanceState); } protected void onPostInit(Holo config, Bundle savedInstanceState) { } protected void onPreInit(Holo config, Bundle savedInstanceState) { } @Override public boolean onPrepareOptionsMenu(Menu menu) { return true; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mConfig != null) { outState.putParcelable(CONFIG_KEY, mConfig); } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (mDecorView != null) { rOnWindowFocusChanged(mDecorView, hasFocus); } } private void rOnWindowFocusChanged(View view, boolean hasFocus) { if (view instanceof OnWindowFocusChangeListener) { ((OnWindowFocusChangeListener) view).onWindowFocusChanged(hasFocus); } if (view instanceof ViewGroup) { final ViewGroup vg = (ViewGroup) view; final int childCount = vg.getChildCount(); for (int i = 0; i < childCount; i++) { rOnWindowFocusChanged(vg.getChildAt(i), hasFocus); } } } @Override public void registerForContextMenu(View view) { registerForContextMenu(view, this); } public void registerForContextMenu(View view, ContextMenuListener listener) { if (mContextMenuListeners == null) { mContextMenuListeners = new WeaklyMap<View, ContextMenuListener>(); } mContextMenuListeners.put(view, listener); view.setLongClickable(true); } protected final void requestDecorView() { if (mDecorView == null) { requestDecorView(null, null, -1); } } private boolean requestDecorView(View view, LayoutParams params, int layoutRes) { if (mDecorView != null) { return true; } mDecorView = new ActivityDecorView(); mDecorView.setId(android.R.id.content); mDecorView.setProvider(this); if (view != null) { mDecorView.addView(view, params); } else if (layoutRes > 0) { getThemedLayoutInflater().inflate(layoutRes, mDecorView, true); } final LayoutParams p = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); performAddonAction(new AddonCallback<IAddonActivity>() { @Override public boolean action(IAddonActivity addon) { return addon.installDecorView(mDecorView, p); } @Override public void justPost() { _HoloActivity.super.setContentView(mDecorView, p); } }); return false; } public void requestWindowFeature(long featureId) { createConfig(null).requestWindowFeature((int) featureId); } @Override public void setContentView(int layoutResID) { if (requestDecorView(null, null, layoutResID)) { mDecorView.removeAllViewsInLayout(); getThemedLayoutInflater().inflate(layoutResID, mDecorView, true); } onSupportContentChanged(); } public void onSupportContentChanged() { } @Override public void setContentView(View view) { setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } @Override public void setContentView(View view, LayoutParams params) { if (requestDecorView(view, params, -1)) { mDecorView.removeAllViewsInLayout(); mDecorView.addView(view, params); } onSupportContentChanged(); } public synchronized void setTheme(int resid, boolean modifyGlobal) { if (resid > ThemeManager._START_RESOURCES_ID) { if (mLastThemeResourceId != resid) { mActionBarContext = null; super.setTheme(mLastThemeResourceId = resid); } } else { if ((resid & ThemeManager.COLOR_SCHEME_MASK) == 0) { int theme = ThemeManager.getTheme(getIntent(), false); if (theme == 0) { final android.app.Activity activity = getParent(); if (activity != null) { theme = ThemeManager.getTheme(activity.getIntent(), false); } } theme &= ThemeManager.COLOR_SCHEME_MASK; if (theme != 0) { resid |= theme; } } setTheme(ThemeManager.getThemeResource(resid, modifyGlobal)); } } @SuppressLint("NewApi") @Override public void startActivities(Intent[] intents) { startActivities(intents, null); } @SuppressLint("NewApi") @Override public void startActivities(Intent[] intents, Bundle options) { for (Intent intent : intents) { startActivity(intent, options); } } @SuppressLint("NewApi") @Override public void startActivity(Intent intent) { startActivity(intent, null); } @SuppressLint("NewApi") @Override public void startActivity(Intent intent, Bundle options) { startActivityForResult(intent, -1, options); } @SuppressLint("NewApi") @Override public void startActivityForResult(Intent intent, int requestCode) { startActivityForResult(intent, requestCode, null); } @Override public void startActivityForResult(Intent intent, int requestCode, Bundle options) { if (HoloEverywhere.ALWAYS_USE_PARENT_THEME) { ThemeManager.startActivity(this, intent, requestCode, options); } else { superStartActivity(intent, requestCode, options); } } public android.content.SharedPreferences superGetSharedPreferences( String name, int mode) { return super.getSharedPreferences(name, mode); } @Override public Object superGetSystemService(String name) { return super.getSystemService(name); } @Override @SuppressLint("NewApi") public void superStartActivity(Intent intent, int requestCode, Bundle options) { if (VERSION.SDK_INT >= 16) { super.startActivityForResult(intent, requestCode, options); } else { super.startActivityForResult(intent, requestCode); } } @Override public void onContextMenuClosed(ContextMenu menu) { } @Override public void unregisterForContextMenu(View view) { if (mContextMenuListeners != null) { mContextMenuListeners.remove(view); } view.setLongClickable(false); } public static interface OnWindowFocusChangeListener { public void onWindowFocusChanged(boolean hasFocus); } public static final class Holo implements Parcelable { public static final Parcelable.Creator<Holo> CREATOR = new Creator<Holo>() { @Override public Holo createFromParcel(Parcel source) { return new Holo(source); } @Override public Holo[] newArray(int size) { return new Holo[size]; } }; public boolean ignoreApplicationInstanceCheck = false; public boolean ignoreThemeCheck = false; public boolean requireRoboguice = false; public boolean requireSlider = false; public boolean requireTabber = false; private SparseIntArray windowFeatures; public Holo() { } private Holo(Parcel source) { ignoreThemeCheck = source.readInt() == 1; ignoreApplicationInstanceCheck = source.readInt() == 1; requireSlider = source.readInt() == 1; requireRoboguice = source.readInt() == 1; requireTabber = source.readInt() == 1; windowFeatures = source.readParcelable(SparseIntArray.class.getClassLoader()); } public static Holo defaultConfig() { return new Holo(); } @Override public int describeContents() { return 0; } public void requestWindowFeature(int feature) { if (windowFeatures == null) { windowFeatures = new SparseIntArray(); } windowFeatures.put(feature, feature); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(ignoreThemeCheck ? 1 : 0); dest.writeInt(ignoreApplicationInstanceCheck ? 1 : 0); dest.writeInt(requireSlider ? 1 : 0); dest.writeInt(requireRoboguice ? 1 : 0); dest.writeInt(requireTabber ? 1 : 0); dest.writeParcelable(windowFeatures, flags); } } private static final class HoloThemeException extends RuntimeException { private static final long serialVersionUID = -2346897999325868420L; public HoloThemeException(_HoloActivity activity) { super("You must apply Holo.Theme, Holo.Theme.Light or " + "Holo.Theme.Light.DarkActionBar theme on the activity (" + activity.getClass().getSimpleName() + ") for using HoloEverywhere"); } } private final class ActivityDecorView extends WindowDecorView { public ActivityDecorView() { super(_HoloActivity.this); } @Override protected boolean fitSystemWindows(Rect insets) { final SparseIntArray windowFeatures = createConfig(null).windowFeatures; if (windowFeatures != null && windowFeatures.get(Window.FEATURE_ACTION_BAR_OVERLAY, 0) != 0) { return false; } return super.fitSystemWindows(insets); } } }
package de.mrapp.android.view; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.AttrRes; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.annotation.StyleRes; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.util.LinkedHashSet; import java.util.Set; import de.mrapp.android.util.ViewUtil; import static de.mrapp.android.util.BitmapUtil.clipCircle; import static de.mrapp.android.util.BitmapUtil.drawableToBitmap; import static de.mrapp.android.util.Condition.ensureNotNull; public class Chip extends FrameLayout { /** * Defines the interface, a class, which should be notified, when a chip has been closed, must * implement. */ public interface CloseListener { /** * The method, which is invoked, when a chip has been closed. * * @param chip * The chip, which has been closed, as an instance of the class {@link Chip} */ void onChipClosed(@NonNull Chip chip); } /** * The image view, which is used to show the chip's icon. */ private ImageView imageView; /** * The text view, which is used to show the chip's text. */ private TextView textView; /** * The image button, which allows to close the chip. */ private ImageButton closeButton; /** * The chip's color. */ private int color; /** * True, if the chip is closable, false otherwise. */ private boolean closable; /** * A set, which contains the listeners, which should be notified, when the chip has been * closed. */ private Set<CloseListener> listeners; /** * Initializes the view. * * @param attributeSet * The attribute set, the view's attributes should be obtained from, as an instance of * the type {@link AttributeSet} or null, if no attributes should be obtained */ private void initialize(@Nullable final AttributeSet attributeSet) { listeners = new LinkedHashSet<>(); inflateLayout(); Drawable background = ContextCompat.getDrawable(getContext(), R.drawable.chip_background); ViewUtil.setBackground(this, background); obtainStyledAttributes(attributeSet); } /** * Inflates the view's layout. */ private void inflateLayout() { View view = View.inflate(getContext(), R.layout.chip, null); imageView = (ImageView) view.findViewById(android.R.id.icon); textView = (TextView) view.findViewById(android.R.id.text1); closeButton = (ImageButton) view.findViewById(android.R.id.closeButton); closeButton.setOnClickListener(createCloseButtonListener()); int height = getResources().getDimensionPixelSize(R.dimen.chip_height); addView(view, LayoutParams.WRAP_CONTENT, height); } /** * Creates and returns a listener, which allows to observe, when the button, which allows to * close the chip, has been clicked. * * @return The listener, which has been created, as an instance of the type {@link * OnClickListener} */ private OnClickListener createCloseButtonListener() { return new OnClickListener() { @Override public void onClick(final View v) { notifyOnChipClosed(); } }; } /** * Obtains the view's attributes from a specific attribute set. * * @param attributeSet * The attribute set, the view's attributes should be obtained from, as an instance of * the type {@link AttributeSet} or null, if no attributes should be obtained */ private void obtainStyledAttributes(@Nullable final AttributeSet attributeSet) { TypedArray typedArray = getContext().obtainStyledAttributes(attributeSet, R.styleable.Chip); try { obtainText(typedArray); obtainTextColor(typedArray); obtainColor(typedArray); obtainIcon(typedArray); obtainClosable(typedArray); obtainCloseIcon(typedArray); } finally { typedArray.recycle(); } } /** * Obtains the chip's text from a specific typed array. * * @param typedArray * The typed array, the text should be obtained from, as an instance of the class {@link * TypedArray}. The typed array may not be null */ private void obtainText(@NonNull final TypedArray typedArray) { setText(typedArray.getText(R.styleable.Chip_android_text)); } /** * Obtains the chip's text color from a specific typed array. * * @param typedArray * The typed array, the text color should be obtained from, as an instance of the class * {@link TypedArray}. The typed array may not be null */ private void obtainTextColor(@NonNull final TypedArray typedArray) { int defaultColor = ContextCompat.getColor(getContext(), R.color.chip_text_color_light); setTextColor(typedArray.getColor(R.styleable.Chip_android_textColor, defaultColor)); } /** * Obtains the chip's color from a specific typed array. * * @param typedArray * The typed array, the color should be obtained from, as an instance of the class * {@link TypedArray}. The typed array may not be null */ private void obtainColor(@NonNull final TypedArray typedArray) { int defaultColor = ContextCompat.getColor(getContext(), R.color.chip_color_light); setColor(typedArray.getColor(R.styleable.Chip_android_color, defaultColor)); } /** * Obtains the chip's icon from a specific typed array. * * @param typedArray * The typed array, the icon should be obtained from, as an instance of the class {@link * TypedArray}. The typed array may not be null */ private void obtainIcon(@NonNull final TypedArray typedArray) { setIcon(typedArray.getDrawable(R.styleable.Chip_android_icon)); } /** * Obtains, whether the chip should be closable, or not, from a specific typed array. * * @param typedArray * The typed array, which should be used to obtain, whether the chip should be closable, * or not, as an instance of the class {@link TypedArray}. The typed array may not be * null */ private void obtainClosable(@NonNull final TypedArray typedArray) { setClosable(typedArray.getBoolean(R.styleable.Chip_closable, false)); } /** * Obtains the icon of the button, which allows to close the chip, from a specific typed array. * * @param typedArray * The typed array, which should be used to obtain the icon of the button, which allows * to close the chip, as an instance of the class {@link TypedArray}. The typed array * may not be null */ private void obtainCloseIcon(@NonNull final TypedArray typedArray) { Drawable icon = typedArray.getDrawable(R.styleable.Chip_closeButtonIcon); if (icon != null) { setCloseButtonIcon(icon); } } /** * Notifies all listeners, which have been registered to be notified, when the chip has been * closed, about the chip being closed. */ private void notifyOnChipClosed() { for (CloseListener listener : listeners) { listener.onChipClosed(this); } } /** * Creates a new chip, which has been designed according to the Material design guidelines. * * @param context * The context, the view should belong to, as an instance of the class {@link Context}. * The context may not be null */ public Chip(@NonNull final Context context) { this(context, null); } /** * Creates a chip, which has been designed according to the Material design guidelines. * * @param context * The context, the view should belong to, as an instance of the class {@link Context}. * The context may not be null * @param attributeSet * The attribute set, the view's attributes should be obtained from, as an instance of * the type {@link AttributeSet} or null, if no attributes should be obtained */ public Chip(@NonNull final Context context, @Nullable final AttributeSet attributeSet) { super(context, attributeSet); initialize(attributeSet); } /** * Creates a new chip, which has been designed according to the Material design guidelines. * * @param context * The context, the view should belong to, as an instance of the class {@link Context}. * The context may not be null * @param attributeSet * The attribute set, the view's attributes should be obtained from, as an instance of * the type {@link AttributeSet} or null, if no attributes should be obtained * @param defaultStyle * The default style to apply to this view. If 0, no style will be applied (beyond what * is included in the theme). This may either be an attribute resource, whose value will * be retrieved from the current theme, or an explicit style resource */ public Chip(final Context context, @Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle) { super(context, attributeSet, defaultStyle); initialize(attributeSet); } /** * Creates a new chip, which has been designed according to the Material design guidelines. * * @param context * The context, which should be used by the view, as an instance of the class {@link * Context}. The context may not be null * @param attributeSet * The attribute set, the view's attributes should be obtained from, as an instance of * the type {@link AttributeSet} or null, if no attributes should be obtained * @param defaultStyle * The default style to apply to this view. If 0, no style will be applied (beyond what * is included in the theme). This may either be an attribute resource, whose value will * be retrieved from the current theme, or an explicit style resource * @param defaultStyleResource * A resource identifier of a style resource that supplies default values for the view, * used only if the default style is 0 or can not be found in the theme. Can be 0 to not * look for defaults */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public Chip(@NonNull final Context context, @Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { super(context, attributeSet, defaultStyle, defaultStyleResource); initialize(attributeSet); } /** * Adds a new listener, which should be notified, when the chip has been closed. * * @param listener * The listener, which should be added, as an instance of the type {@link * CloseListener}. The listener may not be null */ public final void addCloseListener(@NonNull final CloseListener listener) { ensureNotNull(listener, "The listener may not be null"); listeners.add(listener); } /** * Removes a specific listener, which should not be notified, when the chip has been closed, * anymore. * * @param listener * The listener, which should be removed, as an instance of the type {@link * CloseListener}. The listener may not be null */ public final void removeCloseListener(@NonNull final CloseListener listener) { ensureNotNull(listener, "The listener may not be null"); listeners.remove(listener); } /** * Returns the chip's text. * * @return The chip's text as an instance of the type {@link CharSequence} or null, if no text * has been set */ public final CharSequence getText() { return textView.getText(); } /** * Sets the chip's text. * * @param resourceId * The resource id of the text, which should be set, as an {@link Integer} value. The * resource id must correspond to a valid string resource */ public final void setText(@StringRes final int resourceId) { setText(getContext().getText(resourceId)); } /** * Sets the chip's text. * * @param text * The text, which should be set, as an instance of the type {@link CharSequence} or * null, if no text should be set */ public final void setText(@Nullable final CharSequence text) { textView.setText(text); } /** * Sets the chip's text color. * * @param color * The text color, which should be set, as an {@link Integer} value */ public final void setTextColor(@ColorInt final int color) { textView.setTextColor(color); } /** * Sets the chip's text color. * * @param resourceId * The resource id of the text color, which should be set, as an {@link Integer} value. * The resource id must correspond to a valid color resource */ public final void setTextColorResource(@ColorRes final int resourceId) { setTextColor(ContextCompat.getColor(getContext(), resourceId)); } /** * Returns the chip's text color. * * @return The chip's text color as an {@link Integer} value */ public final int getTextColor() { return textView.getCurrentTextColor(); } /** * Sets the chip's color. * * @param color * The color, which should be set, as an {@link Integer} value */ public final void setColor(@ColorInt final int color) { this.color = color; getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN); } /** * Sets the chip's color. * * @param resourceId * The resource id of the color, which should be set, as an {@link Integer} value. The * resource id must correspond to a valid color resource */ public final void setColorResource(@ColorRes final int resourceId) { setColor(ContextCompat.getColor(getContext(), resourceId)); } /** * Returns the chip's color. * * @return The chip's color as an {@link Integer} value */ public final int getColor() { return color; } /** * Sets the chip's icon. * * @param icon * The icon, which should be set, as an instance of the class {@link Drawable} or null, * if no icon should be set */ public final void setIcon(@Nullable final Drawable icon) { setIcon(icon != null ? drawableToBitmap(icon) : null); } /** * Sets the chip's icon. * * @param icon * The icon, which should be set, as an instance of the class {@link Bitmap} or null, if * no icon should be set */ public final void setIcon(@Nullable final Bitmap icon) { if (icon != null) { int size = getResources().getDimensionPixelSize(R.dimen.chip_height); imageView.setImageBitmap(clipCircle(icon, size)); imageView.setVisibility(View.VISIBLE); textView.setPadding(0, textView.getPaddingTop(), textView.getPaddingRight(), textView.getPaddingBottom()); } else { imageView.setImageBitmap(null); imageView.setVisibility(View.GONE); textView.setPadding( getResources().getDimensionPixelSize(R.dimen.chip_horizontal_padding), textView.getPaddingTop(), textView.getPaddingRight(), textView.getPaddingBottom()); } } /** * Returns the chip's icon. * * @return The chip's icon as an instance of the class {@link Drawable} or null, if no icon has * been set */ public final Drawable getIcon() { return imageView.getDrawable(); } /** * Returns, whether the chip is closable, or not. * * @return True, if the chip is closable, false otherwise. */ public final boolean isClosable() { return closable; } /** * Sets, whether the chip is closable, or not. * * @param closable * True, if the chip should be closable, false otherwise */ public final void setClosable(final boolean closable) { this.closable = closable; if (closable) { closeButton.setVisibility(View.VISIBLE); textView.setPadding(textView.getPaddingLeft(), textView.getPaddingTop(), 0, textView.getPaddingBottom()); } else { closeButton.setVisibility(View.GONE); textView.setPadding(textView.getPaddingLeft(), textView.getPaddingTop(), getResources().getDimensionPixelSize(R.dimen.chip_horizontal_padding), textView.getPaddingBottom()); } } /** * Returns the icon of the button, which allows to close the chip. * * @return The icon of the button, which allows to close the chip, as an instance of the class * {@link Drawable} or null, if the chip is not closable */ public final Drawable getCloseButtonIcon() { return closable ? closeButton.getDrawable() : null; } /** * Sets the icon of the button, which allows to close the chip. * * @param icon * The icon, which should be set, as an instance of the class {@link Drawable}. The icon * may not be null */ public final void setCloseButtonIcon(@NonNull final Drawable icon) { ensureNotNull(icon, "The icon may not be null"); closeButton.setImageDrawable(icon); } /** * Sets the icon of the button, which allows to close the chip. * * @param icon * The icon, which should be set, as an instance of the class {@link Bitmap}. The icon * may not be null */ public final void setCloseButtonIcon(@NonNull final Bitmap icon) { ensureNotNull(icon, "The icon may not be null"); closeButton.setImageBitmap(icon); } }
package com.txmcu.activity; import java.io.IOException; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import org.apache.http.conn.ConnectTimeoutException; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import com.sina.weibo.sdk.auth.Oauth2AccessToken; import com.sina.weibo.sdk.auth.WeiboAuth; import com.sina.weibo.sdk.auth.WeiboAuthListener; import com.sina.weibo.sdk.auth.sso.SsoHandler; import com.sina.weibo.sdk.demo.openapi.AccessTokenKeeper; import com.sina.weibo.sdk.exception.WeiboException; import com.tencent.open.HttpStatusException; import com.tencent.open.NetworkUnavailableException; import com.tencent.tauth.Constants; import com.tencent.tauth.IRequestListener; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import com.txmcu.common.Util; import com.txmcu.iair.R; public class LoginActivity extends Activity implements OnClickListener { public WeiboAuth mWeiboAuth; public static Oauth2AccessToken accessToken; // token public SsoHandler mSsoHandler; public Tencent mTencent; public static String mAppid; public Button loginQQ; public Button loginSina; // public View loginTenWb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); this.loginQQ = ((Button) findViewById(R.id.loginQQRL)); this.loginSina = ((Button) findViewById(R.id.loginSinaRL)); this.loginQQ.setOnClickListener(this); this.loginSina.setOnClickListener(this); mWeiboAuth = new WeiboAuth(this, com.sina.weibo.sdk.demo.openapi.Constants.APP_KEY, com.sina.weibo.sdk.demo.openapi.Constants.REDIRECT_URL, com.sina.weibo.sdk.demo.openapi.Constants.SCOPE); accessToken = AccessTokenKeeper.readAccessToken(this); mAppid = "101017203"; mTencent = Tencent.createInstance(mAppid, this.getApplicationContext()); updateLoginButton(); updateUserInfo(); // this.loginQQ = ((Button)findViewById(R.id.button_login)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.main, menu); return true; } public void onClick(View paramAnonymousView) { if (paramAnonymousView.getId() == R.id.loginQQRL) { if (!mTencent.isSessionValid()) { IUiListener listener = new BaseUiListener() { @Override protected void doComplete(JSONObject values) { updateUserInfo(); updateLoginButton(); } }; mTencent.login(this, "all", listener); } else { mTencent.logout(this); updateUserInfo(); updateLoginButton(); } } else if (paramAnonymousView.getId() == R.id.loginSinaRL) { // mWeiboAuth.anthorize(new AuthListener()); mSsoHandler = new SsoHandler(LoginActivity.this, mWeiboAuth); mSsoHandler.authorize(new AuthListener()); } } /** * SSO Activity , * * * @see {@link Activity#onActivityResult} */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // SSO // : SSO Activity onActivityResult if (mSsoHandler != null) { mSsoHandler.authorizeCallBack(requestCode, resultCode, data); } } class AuthListener implements WeiboAuthListener { @Override public void onCancel() { // Oauth2.0 Toast.makeText(getApplicationContext(), "Auth cancel", Toast.LENGTH_LONG).show(); updateLoginButton(); } @Override public void onWeiboException(WeiboException e) { // WeiboException Toast.makeText(getApplicationContext(), "Auth exception:" + e.getMessage(), Toast.LENGTH_LONG) .show(); } @Override public void onComplete(Bundle values) { // Bundle Token accessToken = Oauth2AccessToken.parseAccessToken(values); if (accessToken.isSessionValid()) { // Token //mWeiboAuth.getAuthInfo() // updateTokenView(false); // Token SharedPreferences AccessTokenKeeper.writeAccessToken(LoginActivity.this, accessToken); updateLoginButton(); } else { // , Code, // String code = values.getString("code", ""); ......... updateLoginButton(); } } } private void updateLoginButton() { if (mTencent != null && mTencent.isSessionValid()) { loginQQ.setTextColor(Color.RED); loginQQ.setText("QQ"); } else { loginQQ.setTextColor(Color.BLUE); loginQQ.setText("QQ"); } if(accessToken!= null && accessToken.isSessionValid()){ loginSina.setTextColor(Color.RED); loginSina.setText("SINA"); } else { loginSina.setTextColor(Color.BLUE); loginSina.setText("SINA"); } } private void updateUserInfo() { if (mTencent != null && mTencent.isSessionValid()) { IRequestListener requestListener = new IRequestListener() { @Override public void onUnknowException(Exception e, Object state) { // TODO Auto-generated method stub } @Override public void onSocketTimeoutException(SocketTimeoutException e, Object state) { // TODO Auto-generated method stub } @Override public void onNetworkUnavailableException( NetworkUnavailableException e, Object state) { // TODO Auto-generated method stub } @Override public void onMalformedURLException(MalformedURLException e, Object state) { // TODO Auto-generated method stub } @Override public void onJSONException(JSONException e, Object state) { // TODO Auto-generated method stub } @Override public void onIOException(IOException e, Object state) { // TODO Auto-generated method stub } @Override public void onHttpStatusException(HttpStatusException e, Object state) { // TODO Auto-generated method stub } @Override public void onConnectTimeoutException( ConnectTimeoutException e, Object state) { // TODO Auto-generated method stub } @Override public void onComplete(final JSONObject response, Object state) { // TODO Auto-generated method stub // Message msg = new Message(); // msg.obj = response; // msg.what = 0; // mHandler.sendMessage(msg); JSONObject res = (JSONObject) response; if (res.has("nickname")) { try { String userName = res.getString("nickname"); Log.i("iair", "nickname" + userName); // mUserInfo.setVisibility(android.view.View.VISIBLE); // mUserInfo.setText(response.getString("nickname")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; mTencent.requestAsync(Constants.GRAPH_SIMPLE_USER_INFO, null, Constants.HTTP_GET, requestListener, null); } else { // mUserInfo.setText(""); // mUserInfo.setVisibility(android.view.View.GONE); // mUserLogo.setVisibility(android.view.View.GONE); } } private class BaseUiListener implements IUiListener { @Override public void onComplete(JSONObject response) { //Util.showResultDialog(LoginActivity.this, response.toString(), doComplete(response); } protected void doComplete(JSONObject values) { } @Override public void onError(UiError e) { Util.toastMessage(LoginActivity.this, "onError: " + e.errorDetail); Util.dismissDialog(); } @Override public void onCancel() { Util.toastMessage(LoginActivity.this, "onCancel: "); Util.dismissDialog(); } } }
package eu.bcvsolutions.idm.core.model.service.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.time.LocalDate; import java.util.List; import java.util.Set; import java.util.UUID; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.data.domain.Page; import org.springframework.transaction.annotation.Transactional; import org.testng.collections.Lists; import eu.bcvsolutions.idm.core.api.config.domain.EventConfiguration; import eu.bcvsolutions.idm.core.api.config.domain.IdentityConfiguration; import eu.bcvsolutions.idm.core.api.domain.AutomaticRoleAttributeRuleComparison; import eu.bcvsolutions.idm.core.api.domain.AutomaticRoleAttributeRuleType; import eu.bcvsolutions.idm.core.api.domain.ContractState; import eu.bcvsolutions.idm.core.api.domain.CoreResultCode; import eu.bcvsolutions.idm.core.api.domain.OperationState; import eu.bcvsolutions.idm.core.api.domain.RecursionType; import eu.bcvsolutions.idm.core.api.domain.TransactionContextHolder; import eu.bcvsolutions.idm.core.api.dto.DefaultResultModel; import eu.bcvsolutions.idm.core.api.dto.IdmAutomaticRoleAttributeDto; import eu.bcvsolutions.idm.core.api.dto.IdmContractGuaranteeDto; import eu.bcvsolutions.idm.core.api.dto.IdmContractPositionDto; import eu.bcvsolutions.idm.core.api.dto.IdmEntityEventDto; import eu.bcvsolutions.idm.core.api.dto.IdmEntityStateDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto; import eu.bcvsolutions.idm.core.api.dto.IdmRoleDto; import eu.bcvsolutions.idm.core.api.dto.IdmRoleTreeNodeDto; import eu.bcvsolutions.idm.core.api.dto.IdmTreeNodeDto; import eu.bcvsolutions.idm.core.api.dto.IdmTreeTypeDto; import eu.bcvsolutions.idm.core.api.dto.OperationResultDto; import eu.bcvsolutions.idm.core.api.dto.filter.IdmContractGuaranteeFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmContractPositionFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmEntityEventFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmEntityStateFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityContractFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter; import eu.bcvsolutions.idm.core.api.event.EntityEvent; import eu.bcvsolutions.idm.core.api.exception.AcceptedException; import eu.bcvsolutions.idm.core.api.exception.ResultCodeException; import eu.bcvsolutions.idm.core.api.service.AutomaticRoleManager; import eu.bcvsolutions.idm.core.api.service.ConfigurationService; import eu.bcvsolutions.idm.core.api.service.EntityEventManager; import eu.bcvsolutions.idm.core.api.service.EntityStateManager; import eu.bcvsolutions.idm.core.api.service.IdmContractGuaranteeService; import eu.bcvsolutions.idm.core.api.service.IdmContractPositionService; import eu.bcvsolutions.idm.core.api.service.IdmIdentityContractService; import eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService; import eu.bcvsolutions.idm.core.api.service.IdmRoleTreeNodeService; import eu.bcvsolutions.idm.core.api.service.IdmTreeNodeService; import eu.bcvsolutions.idm.core.api.service.LookupService; import eu.bcvsolutions.idm.core.api.utils.AutowireHelper; import eu.bcvsolutions.idm.core.model.entity.IdmIdentityContract; import eu.bcvsolutions.idm.core.model.entity.IdmIdentityContract_; import eu.bcvsolutions.idm.core.model.event.ContractPositionEvent; import eu.bcvsolutions.idm.core.model.event.ContractPositionEvent.ContractPositionEventType; import eu.bcvsolutions.idm.core.model.event.IdentityContractEvent; import eu.bcvsolutions.idm.core.model.event.IdentityContractEvent.IdentityContractEventType; import eu.bcvsolutions.idm.core.scheduler.api.config.SchedulerConfiguration; import eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto; import eu.bcvsolutions.idm.core.scheduler.api.dto.LongRunningFutureTask; import eu.bcvsolutions.idm.core.scheduler.api.dto.filter.IdmLongRunningTaskFilter; import eu.bcvsolutions.idm.core.scheduler.api.event.LongRunningTaskEvent.LongRunningTaskEventType; import eu.bcvsolutions.idm.core.scheduler.api.service.IdmLongRunningTaskService; import eu.bcvsolutions.idm.core.scheduler.api.service.LongRunningTaskManager; import eu.bcvsolutions.idm.core.scheduler.task.impl.ProcessAutomaticRoleByTreeTaskExecutor; import eu.bcvsolutions.idm.core.scheduler.task.impl.ProcessSkippedAutomaticRoleByTreeForContractTaskExecutor; import eu.bcvsolutions.idm.core.scheduler.task.impl.RemoveAutomaticRoleTaskExecutor; import eu.bcvsolutions.idm.core.security.api.domain.GuardedString; import eu.bcvsolutions.idm.test.api.AbstractIntegrationTest; public class DefaultIdmIdentityContractServiceIntegrationTest extends AbstractIntegrationTest { @Autowired private ApplicationContext context; @Autowired private IdmIdentityRoleService identityRoleService; @Autowired private IdmRoleTreeNodeService roleTreeNodeService; @Autowired private LongRunningTaskManager taskManager; @Autowired private IdmContractGuaranteeService contractGuaranteeService; @Autowired private IdmContractPositionService contractPositionService; @Autowired private ConfigurationService configurationService; @Autowired private IdmTreeNodeService treeNodeService; @Autowired private LookupService lookupService; @Autowired private EntityEventManager entityEventManager; @Autowired private EntityStateManager entityStateManager; @Autowired private LongRunningTaskManager longRunningTaskManager; @Autowired private IdmLongRunningTaskService longRunningTaskService; private DefaultIdmIdentityContractService service; private IdmTreeTypeDto treeType = null; private IdmTreeNodeDto nodeA = null; private IdmTreeNodeDto nodeB = null; private IdmTreeNodeDto nodeC = null; private IdmTreeNodeDto nodeD = null; private IdmTreeNodeDto nodeE = null; private IdmTreeNodeDto nodeF = null; private IdmRoleDto roleA = null; private IdmRoleDto roleB = null; private IdmRoleDto roleC = null; private IdmRoleDto roleD = null; private IdmRoleTreeNodeDto automaticRoleA = null; private IdmRoleTreeNodeDto automaticRoleD = null; private IdmRoleTreeNodeDto automaticRoleE = null; private IdmRoleTreeNodeDto automaticRoleF = null; @Before public void init() { service = context.getAutowireCapableBeanFactory().createBean(DefaultIdmIdentityContractService.class); prepareTreeStructureAndRoles(); } @After public void after() { // delete this test automatic roles only if(automaticRoleA != null) try { deleteAutomaticRole(automaticRoleA); } catch (EmptyResultDataAccessException ex) {} ; if(automaticRoleD != null) try { deleteAutomaticRole(automaticRoleD); } catch (EmptyResultDataAccessException ex) {} ; if(automaticRoleE != null) try { deleteAutomaticRole(automaticRoleE); } catch (EmptyResultDataAccessException ex) {} ; if(automaticRoleF != null) try { deleteAutomaticRole(automaticRoleF); } catch (EmptyResultDataAccessException ex) {} ; } private void prepareTreeStructureAndRoles() { // tree type treeType = getHelper().createTreeType(); // four levels // https://proj.bcvsolutions.eu/ngidm/doku.php?id=roztridit:standardni_procesy#role_pridelovane_na_zaklade_zarazeni_v_organizacni_strukture nodeA = getHelper().createTreeNode(treeType, null); nodeB = getHelper().createTreeNode(treeType, nodeA); nodeC = getHelper().createTreeNode(treeType, nodeB); nodeD = getHelper().createTreeNode(treeType, nodeB); nodeE = getHelper().createTreeNode(treeType, nodeD); nodeF = getHelper().createTreeNode(treeType, nodeD); // create roles roleA = getHelper().createRole(); roleB = getHelper().createRole(); roleC = getHelper().createRole(); roleD = getHelper().createRole(); } /** * Save automatic role with repository and manual create and wait for task * @param automaticRole * @return */ private IdmRoleTreeNodeDto saveAutomaticRole(IdmRoleTreeNodeDto automaticRole, boolean withLongRunningTask) { automaticRole.setName("default"); // default name IdmRoleTreeNodeDto roleTreeNode = roleTreeNodeService.saveInternal(automaticRole); if (withLongRunningTask) { ProcessAutomaticRoleByTreeTaskExecutor task = new ProcessAutomaticRoleByTreeTaskExecutor(); task.setAutomaticRoles(Lists.newArrayList(roleTreeNode.getId())); taskManager.executeSync(task); } return roleTreeNodeService.get(roleTreeNode.getId()); } private void deleteAutomaticRole(IdmRoleTreeNodeDto automaticRole) { RemoveAutomaticRoleTaskExecutor task = new RemoveAutomaticRoleTaskExecutor(); task.setAutomaticRoleId(automaticRole.getId()); task.setContinueOnException(true); task.setRequireNewTransaction(true); taskManager.executeSync(task); } private void prepareAutomaticRoles() { // prepare automatic roles automaticRoleA = new IdmRoleTreeNodeDto(); automaticRoleA.setRecursionType(RecursionType.DOWN); automaticRoleA.setRole(roleA.getId()); automaticRoleA.setTreeNode(nodeA.getId()); automaticRoleA = saveAutomaticRole(automaticRoleA, false); automaticRoleD = new IdmRoleTreeNodeDto(); automaticRoleD.setRecursionType(RecursionType.DOWN); automaticRoleD.setRole(roleB.getId()); automaticRoleD.setTreeNode(nodeD.getId()); automaticRoleD = saveAutomaticRole(automaticRoleD, false); automaticRoleF = new IdmRoleTreeNodeDto(); automaticRoleF.setRecursionType(RecursionType.UP); automaticRoleF.setRole(roleC.getId()); automaticRoleF.setTreeNode(nodeF.getId()); automaticRoleF = saveAutomaticRole(automaticRoleF, false); automaticRoleE = new IdmRoleTreeNodeDto(); automaticRoleE.setRecursionType(RecursionType.NO); automaticRoleE.setRole(roleD.getId()); automaticRoleE.setTreeNode(nodeE.getId()); automaticRoleE = saveAutomaticRole(automaticRoleE, false); } @Test public void testFindAutomaticRoleWithoutRecursion() { // prepare automaticRoleA = new IdmRoleTreeNodeDto(); automaticRoleA.setRecursionType(RecursionType.NO); automaticRoleA.setRole(roleA.getId()); automaticRoleA.setTreeNode(nodeD.getId()); automaticRoleA = saveAutomaticRole(automaticRoleA, false); // test Set<IdmRoleTreeNodeDto> automaticRoles = roleTreeNodeService.getAutomaticRolesByTreeNode(nodeD.getId()); assertEquals(1, automaticRoles.size()); assertEquals(roleA.getId(), automaticRoles.iterator().next().getRole()); assertTrue(roleTreeNodeService.getAutomaticRolesByTreeNode(nodeB.getId()).isEmpty()); assertTrue(roleTreeNodeService.getAutomaticRolesByTreeNode(nodeF.getId()).isEmpty()); } @Test public void testFindAutomaticRoleWithRecursionDown() { // prepare automaticRoleA = new IdmRoleTreeNodeDto(); automaticRoleA.setRecursionType(RecursionType.DOWN); automaticRoleA.setRole(roleA.getId()); automaticRoleA.setTreeNode(nodeD.getId()); automaticRoleA = saveAutomaticRole(automaticRoleA, false); // test Set<IdmRoleTreeNodeDto> automaticRoles = roleTreeNodeService.getAutomaticRolesByTreeNode(nodeD.getId()); assertEquals(1, automaticRoles.size()); assertEquals(roleA.getId(), automaticRoles.iterator().next().getRole()); assertTrue(roleTreeNodeService.getAutomaticRolesByTreeNode(nodeB.getId()).isEmpty()); automaticRoles = roleTreeNodeService.getAutomaticRolesByTreeNode(nodeF.getId()); assertEquals(1, automaticRoles.size()); assertEquals(roleA.getId(), automaticRoles.iterator().next().getRole()); } @Test public void testFindAutomaticRoleWithRecursionUp() { // prepare automaticRoleA = new IdmRoleTreeNodeDto(); automaticRoleA.setRecursionType(RecursionType.UP); automaticRoleA.setRole(roleA.getId()); automaticRoleA.setTreeNode(nodeD.getId()); automaticRoleA = saveAutomaticRole(automaticRoleA, false); // test Set<IdmRoleTreeNodeDto> automaticRoles = roleTreeNodeService.getAutomaticRolesByTreeNode(nodeD.getId()); assertEquals(1, automaticRoles.size()); assertEquals(roleA.getId(), automaticRoles.iterator().next().getRole()); assertTrue(roleTreeNodeService.getAutomaticRolesByTreeNode(nodeF.getId()).isEmpty()); automaticRoles = roleTreeNodeService.getAutomaticRolesByTreeNode(nodeB.getId()); assertEquals(1, automaticRoles.size()); assertEquals(roleA.getId(), automaticRoles.iterator().next().getRole()); } @Test public void testCRUDContractWithAutomaticRoles() { prepareAutomaticRoles(); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contractToCreate = service.getPrimeContract(identity.getId()); contractToCreate.setIdentity(identity.getId()); contractToCreate.setValidFrom(LocalDate.now().minusDays(1)); contractToCreate.setValidTill(LocalDate.now().plusMonths(1)); contractToCreate.setWorkPosition(nodeD.getId()); contractToCreate.setMain(true); contractToCreate.setDescription("test-node-d"); service.save(contractToCreate); IdmIdentityContractDto contract = service.getPrimeContract(identity.getId()); // test after create Assert.assertEquals(nodeD.getId(), contract.getWorkPosition()); Assert.assertEquals("test-node-d", contract.getDescription()); List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); Assert.assertEquals(3, identityRoles.size()); Assert.assertTrue(identityRoles.stream().allMatch(ir -> contract.getValidFrom().equals(ir.getValidFrom()))); Assert.assertTrue(identityRoles.stream().allMatch(ir -> contract.getValidTill().equals(ir.getValidTill()))); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleA.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleB.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleC.getId().equals(ir.getRole()); })); identityRoles = identityRoleService.findAllByIdentity(identity.getId()); assertEquals(3, identityRoles.size()); // test after delete service.delete(contract); assertTrue(identityRoleService.findAllByIdentity(identity.getId()).isEmpty()); } @Test public void testCRUDContractWithAutomaticRolesAsync() { prepareAutomaticRoles(); try { getHelper().setConfigurationValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED, true); TransactionContextHolder.setContext(TransactionContextHolder.createEmptyContext()); UUID transactionId = TransactionContextHolder.getContext().getTransactionId(); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contractToCreate = service.getPrimeContract(identity.getId()); contractToCreate.setIdentity(identity.getId()); contractToCreate.setValidFrom(LocalDate.now().minusDays(1)); contractToCreate.setValidTill(LocalDate.now().plusMonths(1)); contractToCreate.setWorkPosition(nodeD.getId()); contractToCreate.setMain(true); contractToCreate.setDescription("test-node-d"); service.save(contractToCreate); IdmIdentityContractDto contract = service.getPrimeContract(identity.getId()); // test after create Assert.assertEquals(nodeD.getId(), contract.getWorkPosition()); Assert.assertEquals("test-node-d", contract.getDescription()); Assert.assertEquals(transactionId, contract.getTransactionId()); getHelper().waitForResult(res -> { return identityRoleService.findAllByContract(contract.getId()).isEmpty(); }, 500, Integer.MAX_VALUE); getHelper().waitForResult(res -> { IdmLongRunningTaskFilter filter = new IdmLongRunningTaskFilter(); filter.setRunning(Boolean.TRUE); return taskManager.findLongRunningTasks(filter, null).getTotalElements() != 0; }); List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); Assert.assertEquals(3, identityRoles.size()); Assert.assertTrue(identityRoles.stream().allMatch(ir -> contract.getValidFrom().equals(ir.getValidFrom()))); Assert.assertTrue(identityRoles.stream().allMatch(ir -> contract.getValidTill().equals(ir.getValidTill()))); Assert.assertTrue(identityRoles.stream().allMatch(ir -> ir.getTransactionId().equals(transactionId))); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleA.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleB.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleC.getId().equals(ir.getRole()); })); // find by transactionId IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter(); filter.setTransactionId(transactionId); identityRoles = identityRoleService.find(filter, null).getContent(); Assert.assertEquals(3, identityRoles.size()); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleA.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleB.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleC.getId().equals(ir.getRole()); })); service.delete(contract); } finally { getHelper().setConfigurationValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED, false); } } @Test public void testChangeContractValidityWithAssignedRoles() { prepareAutomaticRoles(); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setValidFrom(LocalDate.now().minusDays(1)); contract.setValidTill(LocalDate.now().plusMonths(1)); contract.setWorkPosition(nodeD.getId()); contract = service.save(contract); // test after create List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); assertEquals(3, identityRoles.size()); for(IdmIdentityRoleDto identityRole : identityRoles) { assertEquals(contract.getValidFrom(), identityRole.getValidFrom()); assertEquals(contract.getValidTill(), identityRole.getValidTill()); }; // test after change contract.setValidFrom(LocalDate.now().minusDays(2)); contract.setValidTill(LocalDate.now().plusMonths(4)); contract = service.save(contract); identityRoles = identityRoleService.findAllByContract(contract.getId()); assertEquals(3, identityRoles.size()); for(IdmIdentityRoleDto identityRole : identityRoles) { assertEquals(contract.getValidFrom(), identityRole.getValidFrom()); assertEquals(contract.getValidTill(), identityRole.getValidTill()); } } @Test public void testChangeContractPositionWithAutomaticRolesAssigned() { prepareAutomaticRoles(); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setWorkPosition(nodeD.getId()); contract = service.save(contract); // test after create List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); assertEquals(3, identityRoles.size()); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleA.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleB.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleC.getId().equals(ir.getRole()); })); contract.setWorkPosition(nodeE.getId()); contract = service.save(contract); // test after change identityRoles = identityRoleService.findAllByContract(contract.getId()); assertEquals(3, identityRoles.size()); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleA.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleB.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleD.getId().equals(ir.getRole()); })); } @Test public void testChangeContractPositionAndValidityWithAutomaticRolesAssigned() { prepareAutomaticRoles(); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setWorkPosition(nodeD.getId()); LocalDate validTill = LocalDate.now().plusDays(1); contract.setValidTill(validTill); contract = service.save(contract); // test after create List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); IdmIdentityRoleDto automaticRole = identityRoles .stream() .filter(ir -> { return roleA.getId().equals(ir.getRole()); }) .findFirst() .orElse(null); Assert.assertNotNull(automaticRole); Assert.assertEquals(validTill, automaticRole.getValidTill()); contract.setWorkPosition(nodeB.getId()); // => role A is the same => down recursion LocalDate newValidTill = LocalDate.now().plusDays(3); contract.setValidTill(newValidTill); contract = service.save(contract); // test after change identityRoles = identityRoleService.findAllByContract(contract.getId()); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleA.getId().equals(ir.getRole()) && ir.getId().equals(automaticRole.getId()) // prevent drop and create && newValidTill.equals(ir.getValidTill()); // validity is changed })); } @Test public void testChangeInvalidContractPositionAndValidityWithAutomaticRolesAssigned() { prepareAutomaticRoles(); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setWorkPosition(nodeD.getId()); LocalDate validTill = LocalDate.now().plusDays(1); contract.setValidTill(validTill); contract = service.save(contract); // test after create List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); IdmIdentityRoleDto automaticRole = identityRoles .stream() .filter(ir -> { return roleA.getId().equals(ir.getRole()); }) .findFirst() .orElse(null); Assert.assertNotNull(automaticRole); Assert.assertEquals(validTill, automaticRole.getValidTill()); UUID automaticRoleId = automaticRole.getId(); // change validity of contract to past => LOOKOUT: internal method is used to test only LocalDate minusDays = LocalDate.now().minusDays(1); contract.setValidTill(minusDays); contract = service.saveInternal(contract); Assert.assertEquals(minusDays, contract.getValidTill()); // assigned roles is still unchanged identityRoles = identityRoleService.findAllByContract(contract.getId()); automaticRole = identityRoles .stream() .filter(ir -> { return roleA.getId().equals(ir.getRole()); }) .findFirst() .orElse(null); Assert.assertNotNull(automaticRole); Assert.assertEquals(validTill, automaticRole.getValidTill()); LocalDate newValidTill = LocalDate.now().plusDays(3); contract.setValidTill(newValidTill); contract = service.save(contract); // test after change identityRoles = identityRoleService.findAllByContract(contract.getId()); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleA.getId().equals(ir.getRole()) && ir.getId().equals(automaticRoleId) // prevent drop and create && newValidTill.equals(ir.getValidTill()); // validity is changed })); } @Test public void testAssignAutomaticRoleToExistIdentitySync() { IdmIdentityDto identityOne = getHelper().createIdentityOnly(); IdmIdentityDto identityTwo = getHelper().createIdentityOnly(); IdmIdentityDto identityThree = getHelper().createIdentityOnly(); IdmTreeNodeDto treeNode = getHelper().createTreeNode(); IdmIdentityContractDto contractOne = getHelper().createContract(identityOne, treeNode); IdmIdentityContractDto contractTwo = getHelper().createContract(identityTwo, treeNode); IdmIdentityContractDto contractThree = getHelper().createContract(identityThree, treeNode); IdmRoleDto role = getHelper().createRole(); IdmRoleTreeNodeDto automaticRole = getHelper().createAutomaticRole(role, treeNode); List<IdmIdentityRoleDto> assignedRoles = identityRoleService.findByAutomaticRole(automaticRole.getId(), null).getContent(); Assert.assertEquals(3, assignedRoles.size()); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getIdentityContract().equals(contractOne.getId()))); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getIdentityContract().equals(contractTwo.getId()))); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getIdentityContract().equals(contractThree.getId()))); } @Test public void testAssignAutomaticRoleToExistIdentityAsync() { IdmIdentityDto identityOne = getHelper().createIdentityOnly(); IdmIdentityDto identityTwo = getHelper().createIdentityOnly(); IdmIdentityDto identityThree = getHelper().createIdentityOnly(); IdmTreeNodeDto treeNode = getHelper().createTreeNode(); IdmIdentityContractDto contractOne = getHelper().createContract(identityOne, treeNode); IdmIdentityContractDto contractTwo = getHelper().createContract(identityTwo, treeNode); IdmIdentityContractDto contractThree = getHelper().createContract(identityThree, treeNode); IdmRoleDto role = getHelper().createRole(); List<IdmLongRunningTaskDto> lrts = null; getHelper().setConfigurationValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED, true); getHelper().setConfigurationValue(SchedulerConfiguration.PROPERTY_TASK_ASYNCHRONOUS_ENABLED, true); try { IdmRoleTreeNodeDto automaticRole = getHelper().createAutomaticRole(role, treeNode); getHelper().waitForResult(res -> { return identityRoleService.findByAutomaticRole(automaticRole.getId(), null).getTotalElements() != 3; }, 500, 30); getHelper().waitForResult(res -> { IdmLongRunningTaskFilter filter = new IdmLongRunningTaskFilter(); filter.setRunning(Boolean.TRUE); return taskManager.findLongRunningTasks(filter, null).getTotalElements() != 0; }); List<IdmIdentityRoleDto> assignedRoles = identityRoleService.findByAutomaticRole(automaticRole.getId(), null).getContent(); Assert.assertEquals(3, assignedRoles.size()); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getIdentityContract().equals(contractOne.getId()))); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getIdentityContract().equals(contractTwo.getId()))); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getIdentityContract().equals(contractThree.getId()))); // check asynchronous LRT IdmLongRunningTaskFilter filter = new IdmLongRunningTaskFilter(); filter.setTransactionId(assignedRoles.get(0).getTransactionId()); lrts = taskManager.findLongRunningTasks(filter, null).getContent(); Assert.assertFalse(lrts.isEmpty()); Assert.assertTrue(lrts.stream().allMatch(lrt -> lrt.getResultState() == OperationState.EXECUTED)); // and check lrt start event is properly created and ended IdmEntityEventFilter eventFilter = new IdmEntityEventFilter(); eventFilter.setOwnerType(entityEventManager.getOwnerType(IdmLongRunningTaskDto.class)); eventFilter.setTransactionId(assignedRoles.get(0).getTransactionId()); List<IdmEntityEventDto> events = entityEventManager.findEvents(eventFilter, null).getContent(); Assert.assertFalse(events.isEmpty()); Assert.assertTrue(events.stream().allMatch(event -> event.getResult().getState() == OperationState.EXECUTED)); Assert.assertTrue(events.stream().allMatch(event -> event.getEventStarted() != null)); Assert.assertTrue(events.stream().allMatch(event -> event.getEventEnded() != null)); Assert.assertTrue(events.stream().anyMatch(event -> event.getEventType().equals(LongRunningTaskEventType.START.name()))); } finally { getHelper().setConfigurationValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED, false); getHelper().setConfigurationValue(SchedulerConfiguration.PROPERTY_TASK_ASYNCHRONOUS_ENABLED, false); if (lrts != null) { lrts.forEach(lrt -> { if (lrt.isRunning() || lrt.getResultState() == OperationState.RUNNING) { taskManager.cancel(lrt.getId()); } }); } } } @Test public void testDeleteAutomaticRoleWithContractAlreadyExists() { prepareAutomaticRoles(); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setWorkPosition(nodeC.getId()); contract = service.save(contract); assertEquals(1, identityRoleService.findAllByContract(contract.getId()).size()); deleteAutomaticRole(automaticRoleD); automaticRoleD = null; assertEquals(1, identityRoleService.findAllByContract(contract.getId()).size()); deleteAutomaticRole(automaticRoleA); automaticRoleA = null; assertTrue(identityRoleService.findAllByContract(contract.getId()).isEmpty()); } @Test public void testDontRemoveSameRole() { automaticRoleF = new IdmRoleTreeNodeDto(); automaticRoleF.setRecursionType(RecursionType.UP); automaticRoleF.setRole(roleA.getId()); automaticRoleF.setTreeNode(nodeF.getId()); automaticRoleF = saveAutomaticRole(automaticRoleF, false); automaticRoleE = new IdmRoleTreeNodeDto(); automaticRoleE.setRecursionType(RecursionType.NO); automaticRoleE.setRole(roleA.getId()); automaticRoleE.setTreeNode(nodeE.getId()); automaticRoleE = saveAutomaticRole(automaticRoleE, false); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setWorkPosition(nodeF.getId()); contract = service.save(contract); // check assigned role after creation List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); assertEquals(1, identityRoles.size()); assertEquals(roleA.getId(), identityRoles.get(0).getRole()); assertEquals(automaticRoleF.getId(), identityRoles.get(0).getAutomaticRole()); UUID id = identityRoles.get(0).getId(); // change contract.setWorkPosition(nodeE.getId()); contract = service.save(contract); // check assigned role after creation identityRoles = identityRoleService.findAllByContract(contract.getId()); assertEquals(1, identityRoles.size()); assertEquals(roleA.getId(), identityRoles.get(0).getRole()); assertEquals(automaticRoleE.getId(), identityRoles.get(0).getAutomaticRole()); assertEquals(id, identityRoles.get(0).getId()); } @Test public void testAssingRoleByNewAutomaticRoleForExistingContracts() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setPosition("new position"); contract = service.save(contract); IdmIdentityContractDto contractF = new IdmIdentityContractDto(); contractF.setIdentity(identity.getId()); contractF.setWorkPosition(nodeF.getId()); contractF = service.save(contractF); IdmIdentityContractDto contractD = new IdmIdentityContractDto(); contractD.setIdentity(identity.getId()); contractD.setWorkPosition(nodeD.getId()); contractD = service.save(contractD); IdmIdentityContractDto contractB = new IdmIdentityContractDto(); contractB.setIdentity(identity.getId()); contractB.setWorkPosition(nodeB.getId()); contractB = service.save(contractB); // create new automatic role automaticRoleD = new IdmRoleTreeNodeDto(); automaticRoleD.setRecursionType(RecursionType.DOWN); automaticRoleD.setRole(roleA.getId()); automaticRoleD.setTreeNode(nodeD.getId()); automaticRoleD = saveAutomaticRole(automaticRoleD, true); // check List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contractB.getId()); assertTrue(identityRoles.isEmpty()); identityRoles = identityRoleService.findAllByContract(contractD.getId()); assertEquals(1, identityRoles.size()); assertEquals(automaticRoleD.getId(), identityRoles.get(0).getAutomaticRole()); identityRoles = identityRoleService.findAllByContract(contractF.getId()); assertEquals(1, identityRoles.size()); assertEquals(automaticRoleD.getId(), identityRoles.get(0).getAutomaticRole()); } @Test public void testAssingRoleForContractValidInTheFuture() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contractD = new IdmIdentityContractDto(); contractD.setIdentity(identity.getId()); contractD.setWorkPosition(nodeD.getId()); contractD.setValidFrom(LocalDate.now().plusDays(1)); contractD = service.save(contractD); // create new automatic role automaticRoleD = new IdmRoleTreeNodeDto(); automaticRoleD.setRecursionType(RecursionType.NO); automaticRoleD.setRole(roleA.getId()); automaticRoleD.setTreeNode(nodeD.getId()); automaticRoleD = saveAutomaticRole(automaticRoleD, true); // check List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contractD.getId()); assertEquals(1, identityRoles.size()); assertEquals(automaticRoleD.getId(), identityRoles.get(0).getAutomaticRole()); } @Test public void testDontAssingRoleForContractValidInThePast() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contractD = new IdmIdentityContractDto(); contractD.setIdentity(identity.getId()); contractD.setWorkPosition(nodeD.getId()); contractD.setValidTill(LocalDate.now().minusDays(1)); contractD = service.save(contractD); // create new automatic role automaticRoleD = new IdmRoleTreeNodeDto(); automaticRoleD.setRecursionType(RecursionType.NO); automaticRoleD.setRole(roleA.getId()); automaticRoleD.setTreeNode(nodeD.getId()); automaticRoleD = saveAutomaticRole(automaticRoleD, true); // check List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contractD.getId()); assertEquals(0, identityRoles.size()); } @Test public void testDontAssingRoleForDisabledContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contractD = new IdmIdentityContractDto(); contractD.setIdentity(identity.getId()); contractD.setWorkPosition(nodeD.getId()); contractD.setState(ContractState.DISABLED); contractD = service.save(contractD); // create new automatic role automaticRoleD = new IdmRoleTreeNodeDto(); automaticRoleD.setRecursionType(RecursionType.NO); automaticRoleD.setRole(roleA.getId()); automaticRoleD.setTreeNode(nodeD.getId()); automaticRoleD = saveAutomaticRole(automaticRoleD, true); // check List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contractD.getId()); assertEquals(0, identityRoles.size()); } @Test public void testDisableContractWithAssignedRoles() { prepareAutomaticRoles(); // prepare identity and contract IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setValidFrom(LocalDate.now().minusDays(1)); contract.setValidTill(LocalDate.now().plusMonths(1)); contract.setWorkPosition(nodeD.getId()); contract = service.save(contract); // test after create List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); assertEquals(3, identityRoles.size()); for(IdmIdentityRoleDto identityRole : identityRoles) { assertEquals(contract.getValidFrom(), identityRole.getValidFrom()); assertEquals(contract.getValidTill(), identityRole.getValidTill()); }; // test after change contract.setState(ContractState.DISABLED); contract = service.save(contract); identityRoles = identityRoleService.findAllByContract(contract.getId()); assertTrue(identityRoles.isEmpty()); // enable again contract.setState(null); contract = service.save(contract); identityRoles = identityRoleService.findAllByContract(contract.getId()); assertEquals(3, identityRoles.size()); } @Test(expected = ResultCodeException.class) public void testReferentialIntegrityOnRole() { // prepare data IdmRoleDto role = getHelper().createRole(); IdmTreeNodeDto treeNode = getHelper().createTreeNode(); // automatic role IdmRoleTreeNodeDto roleTreeNode = getHelper().createRoleTreeNode(role, treeNode, false); assertNotNull(roleTreeNode.getId()); assertEquals(roleTreeNode.getId(), roleTreeNodeService.get(roleTreeNode.getId()).getId()); getHelper().deleteRole(role.getId()); } @Test(expected = ResultCodeException.class) public void testReferentialIntegrityOnTreeNode() { // prepare data IdmRoleDto role = getHelper().createRole(); IdmTreeNodeDto treeNode = getHelper().createTreeNode(); // automatic role IdmRoleTreeNodeDto roleTreeNode = getHelper().createRoleTreeNode(role, treeNode, false); assertNotNull(roleTreeNode.getId()); assertEquals(roleTreeNode.getId(), roleTreeNodeService.get(roleTreeNode.getId()).getId()); getHelper().deleteTreeNode(treeNode.getId()); } @Test public void testReferentialIntegrityOnIdentityDelete() { // prepare data IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identityWithContract = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().createContract(identityWithContract); getHelper().createContractGuarantee(contract.getId(), identity.getId()); IdmContractGuaranteeFilter filter = new IdmContractGuaranteeFilter(); filter.setIdentityContractId(contract.getId()); List<IdmContractGuaranteeDto> guarantees = contractGuaranteeService.find(filter, null).getContent(); assertEquals(1, guarantees.size()); getHelper().deleteIdentity(identity.getId()); guarantees = contractGuaranteeService.find(filter, null).getContent(); assertEquals(0, guarantees.size()); } @Test public void testReferentialIntegrityOnContractDelete() { // prepare data IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identityWithContract = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().createContract(identityWithContract); getHelper().createContractGuarantee(contract.getId(), identity.getId()); getHelper().createContractPosition(contract); IdmContractGuaranteeFilter filter = new IdmContractGuaranteeFilter(); filter.setGuaranteeId(identity.getId()); List<IdmContractGuaranteeDto> guarantees = contractGuaranteeService.find(filter, null).getContent(); assertEquals(1, guarantees.size()); IdmContractPositionFilter positionFilter = new IdmContractPositionFilter(); positionFilter.setIdentityContractId(contract.getId()); List<IdmContractPositionDto> positions = contractPositionService.find(positionFilter, null).getContent(); assertEquals(1, positions.size()); getHelper().deleteContract(contract.getId()); guarantees = contractGuaranteeService.find(filter, null).getContent(); Assert.assertTrue(guarantees.isEmpty()); positions = contractPositionService.find(positionFilter, null).getContent(); Assert.assertTrue(positions.isEmpty()); } @Test public void testDontCreateContractByConfiguration() { configurationService.setBooleanValue(IdentityConfiguration.PROPERTY_IDENTITY_CREATE_DEFAULT_CONTRACT, false); try { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); assertNull(service.getPrimeContract(identity.getId())); } finally { configurationService.setBooleanValue(IdentityConfiguration.PROPERTY_IDENTITY_CREATE_DEFAULT_CONTRACT, true); } } @Test public void testSetStateByDateValidInFuture() { IdmIdentityContractDto contract = getHelper().createContract(getHelper().createIdentity((GuardedString) null), null, LocalDate.now().plusDays(1), null); Assert.assertNull(contract.getState()); Assert.assertFalse(((IdmIdentityContract) lookupService.lookupEntity(IdmIdentityContractDto.class, contract.getId())).isDisabled()); } @Test public void testSetStateByDateValidInPast() { IdmIdentityContractDto contract = getHelper().createContract(getHelper().createIdentity((GuardedString) null), null, LocalDate.now().plusDays(1), LocalDate.now().minusDays(1)); Assert.assertNull(contract.getState()); Assert.assertFalse(((IdmIdentityContract) lookupService.lookupEntity(IdmIdentityContractDto.class, contract.getId())).isDisabled()); } @Test public void textFilterTest(){ IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identity2 = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identity3 = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identity4 = getHelper().createIdentity((GuardedString) null); IdmTreeNodeDto node = getHelper().createTreeNode(); node.setName("Position105"); treeNodeService.save(node); IdmTreeNodeDto node2 = getHelper().createTreeNode(); node2.setName("Position006"); treeNodeService.save(node2); IdmTreeNodeDto node3 = getHelper().createTreeNode(); node3.setCode("Position007"); treeNodeService.save(node3); IdmTreeNodeDto node4 = getHelper().createTreeNode(); node4.setCode("Position108"); treeNodeService.save(node4); IdmIdentityContractDto contract = getHelper().createContract(identity,node); IdmIdentityContractDto contract2 = getHelper().createContract(identity2,node2); IdmIdentityContractDto contract3 = getHelper().createContract(identity3,node3); IdmIdentityContractDto contract4 = getHelper().createContract(identity4,node4); contract.setPosition("Position001"); contract = service.save(contract); contract2.setPosition("Position102"); service.save(contract2); contract3.setPosition("Position103"); service.save(contract3); contract4.setPosition("Position104"); service.save(contract4); IdmIdentityContractFilter filter = new IdmIdentityContractFilter(); filter.setText("Position00"); Page<IdmIdentityContractDto> result = service.find(filter,null); assertEquals("Wrong Text",3,result.getTotalElements()); assertTrue(result.getContent().contains(contract)); assertTrue(result.getContent().contains(contract2)); assertTrue(result.getContent().contains(contract3)); } @Test public void identityFilterTest(){ IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmTreeNodeDto node = getHelper().createTreeNode(); IdmTreeNodeDto node2 = getHelper().createTreeNode(); IdmIdentityContractDto contract = getHelper().createContract(identity,node); IdmIdentityContractDto contract2 = getHelper().createContract(identity,node2); IdmIdentityContractFilter filter = new IdmIdentityContractFilter(); filter.setIdentity(identity.getId()); Page<IdmIdentityContractDto> result = service.find(filter,null); assertEquals("Wrong Identity",3,result.getTotalElements()); assertTrue(result.getContent().contains(service.getPrimeContract(identity.getId()))); assertTrue(result.getContent().contains(contract)); assertTrue(result.getContent().contains(contract2)); } @Test public void datesValidFilterTest(){ IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identity2 = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identity3 = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identity4 = getHelper().createIdentity((GuardedString) null); IdmTreeNodeDto node = getHelper().createTreeNode(); IdmTreeNodeDto node2 = getHelper().createTreeNode(); IdmTreeNodeDto node3 = getHelper().createTreeNode(); IdmTreeNodeDto node4 = getHelper().createTreeNode(); IdmIdentityContractDto contract = getHelper().createContract(identity,node, LocalDate.now(), LocalDate.now().plusDays(2)); IdmIdentityContractDto contract2 = getHelper().createContract(identity2,node2, LocalDate.now(), LocalDate.now().plusDays(2)); IdmIdentityContractDto contract3 = getHelper().createContract(identity3,node3, LocalDate.now().minusDays(10), LocalDate.now().minusDays(2)); IdmIdentityContractDto contract4 = getHelper().createContract(identity4,node4, LocalDate.now().minusDays(2), LocalDate.now().plusDays(2)); IdmIdentityContractFilter filter = new IdmIdentityContractFilter(); filter.setValidFrom(contract.getValidFrom()); Page<IdmIdentityContractDto> result = service.find(filter,null); assertTrue(result.getContent().contains(contract)); filter.setValidFrom(null); filter.setValidTill(contract2.getValidTill()); result = service.find(filter,null); assertTrue(result.getContent().contains(contract2)); filter.setValidTill(null); filter.setValid(true); result = service.find(filter,null); assertTrue(result.getContent().contains(contract)); assertTrue(result.getContent().contains(contract2)); assertFalse(result.getContent().contains(contract3)); filter.setValid(null); filter.setValidNowOrInFuture(true); result = service.find(filter,null); assertTrue(result.getContent().contains(contract4)); filter.setValidNowOrInFuture(false); result = service.find(filter,null); assertTrue(result.getContent().contains(contract3)); } @Test public void externeFilterTest(){ IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identity2 = getHelper().createIdentity((GuardedString) null); IdmTreeNodeDto node = getHelper().createTreeNode(); IdmTreeNodeDto node2 = getHelper().createTreeNode(); IdmIdentityContractDto contract = getHelper().createContract(identity,node); IdmIdentityContractDto contract2 = getHelper().createContract(identity2,node2); contract.setExterne(true); service.save(contract); contract2.setExterne(false); service.save(contract2); IdmIdentityContractFilter filter = new IdmIdentityContractFilter(); filter.setExterne(true); Page<IdmIdentityContractDto> result = service.find(filter,null); assertTrue(result.getContent().contains(contract)); assertFalse(result.getContent().contains(contract2)); filter.setExterne(false); result = service.find(filter,null); assertTrue(result.getContent().contains(contract2)); assertFalse(result.getContent().contains(contract)); } @Test public void mainFilterTest() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityDto identity2 = getHelper().createIdentity((GuardedString) null); IdmTreeNodeDto node = getHelper().createTreeNode(); IdmTreeNodeDto node2 = getHelper().createTreeNode(); IdmIdentityContractDto contract = getHelper().createContract(identity,node); IdmIdentityContractDto contract2 = getHelper().createContract(identity2,node2); contract.setMain(true); service.save(contract); contract2.setMain(false); service.save(contract2); IdmIdentityContractFilter filter = new IdmIdentityContractFilter(); filter.setMain(true); Page<IdmIdentityContractDto> result = service.find(filter,null); assertTrue(result.getContent().contains(contract)); assertFalse(result.getContent().contains(contract2)); filter.setMain(false); result = service.find(filter,null); assertTrue(result.getContent().contains(contract2)); assertFalse(result.getContent().contains(contract)); } @Test public void positionFilterTest() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setPosition(getHelper().createName()); contract = getHelper().getService(IdmIdentityContractService.class).save(contract); IdmIdentityContractFilter filter = new IdmIdentityContractFilter(); filter.setPosition(contract.getPosition()); Page<IdmIdentityContractDto> results = service.find(filter, null); Assert.assertTrue(results.getContent().contains(contract)); Assert.assertEquals(1, results.getTotalElements()); } @Test public void workPositionFilterTest() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmTreeNodeDto treeNode = getHelper().createTreeNode(); IdmIdentityContractDto contract = new IdmIdentityContractDto(); contract.setIdentity(identity.getId()); contract.setWorkPosition(treeNode.getId()); contract = getHelper().getService(IdmIdentityContractService.class).save(contract); IdmIdentityContractFilter filter = new IdmIdentityContractFilter(); filter.setWorkPosition(treeNode.getId()); Page<IdmIdentityContractDto> results = service.find(filter, null); Assert.assertTrue(results.getContent().contains(contract)); Assert.assertEquals(1, results.getTotalElements()); } @Test public void testFindAllValidContracts() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); List<IdmIdentityContractDto> contracts = service.findAllValidForDate(identity.getId(), LocalDate.now(), false); Assert.assertEquals(1, contracts.size()); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setState(ContractState.DISABLED); contract = service.save(contract); contracts = service.findAllValidForDate(identity.getId(), LocalDate.now(), false); Assert.assertEquals(0, contracts.size()); // invalid getHelper().createContract(identity, null, LocalDate.now().plusDays(1), null); contracts = service.findAllValidForDate(identity.getId(), LocalDate.now(), false); Assert.assertEquals(0, contracts.size()); contracts = service.findAllValidForDate(identity.getId(), LocalDate.now().plusDays(1), false); Assert.assertEquals(1, contracts.size()); // externe contracts = service.findAllValidForDate(identity.getId(), LocalDate.now(), true); Assert.assertEquals(0, contracts.size()); contract.setExterne(true); contract.setState(ContractState.EXCLUDED); contract = service.save(contract); contracts = service.findAllValidForDate(identity.getId(), LocalDate.now(), true); Assert.assertEquals(1, contracts.size()); } @Test public void testFindExcludedContracts() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setState(ContractState.EXCLUDED); contract = service.save(contract); IdmIdentityContractDto disabled = getHelper().createContract(identity); disabled.setState(ContractState.DISABLED); contract = service.save(contract); IdmIdentityContractDto valid = getHelper().createContract(identity); IdmIdentityContractFilter filter = new IdmIdentityContractFilter(); filter.setIdentity(identity.getId()); filter.setExcluded(Boolean.TRUE); List<IdmIdentityContractDto> contracts = service.find(filter, null).getContent(); Assert.assertEquals(1, contracts.size()); Assert.assertEquals(contract.getId(), contracts.get(0).getId()); filter.setExcluded(Boolean.FALSE); contracts = service.find(filter, null).getContent(); Assert.assertEquals(2, contracts.size()); Assert.assertTrue(contracts.stream().anyMatch(c -> c.getId().equals(disabled.getId()))); Assert.assertTrue(contracts.stream().anyMatch(c -> c.getId().equals(valid.getId()))); } @Test public void testDisableIdentityAfterExcludeContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); Assert.assertFalse(identity.isDisabled()); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setState(ContractState.EXCLUDED); service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); } @Test public void testEnableIdentityMoreContracts() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); getHelper().createContract(identity); Assert.assertFalse(identity.isDisabled()); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setState(ContractState.EXCLUDED); service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertFalse(identity.isDisabled()); } @Test public void testEnableIdentityAfterIncludeContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setState(ContractState.EXCLUDED); contract = service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); contract.setState(null); contract = service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertFalse(identity.isDisabled()); } @Test public void testEnableIdentityAfterEnableContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setState(ContractState.DISABLED); contract = service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); contract.setState(null); contract = service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertFalse(identity.isDisabled()); } @Test public void testDisableIdentityAfterDisableContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setState(ContractState.DISABLED); contract = service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); } @Test public void testDisableIdentityAfterInvalidateContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setValidFrom(LocalDate.now().plusDays(1)); contract = service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); } @Test public void testEnableIdentityAfterValidateContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); contract.setValidFrom(LocalDate.now().plusDays(1)); contract = service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); contract.setValidFrom(LocalDate.now()); service.save(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertFalse(identity.isDisabled()); } @Test public void testDisableIdentityAfterDeleteContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); service.delete(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); } @Test public void testEnableIdentityAfterCreateValidContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); service.delete(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); getHelper().createContract(identity); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertFalse(identity.isDisabled()); } @Test public void testDisableIdentityAfterCreateInvalidContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); service.delete(contract); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); getHelper().createContract(identity, null, LocalDate.now().plusDays(1), null); identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, identity.getId()); Assert.assertTrue(identity.isDisabled()); } @Test public void testDontAssingRoleForDisabledContractWhenPositionIsChanged() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contractD = new IdmIdentityContractDto(); contractD.setIdentity(identity.getId()); contractD.setState(ContractState.DISABLED); contractD = service.save(contractD); // create new automatic role automaticRoleD = new IdmRoleTreeNodeDto(); automaticRoleD.setRecursionType(RecursionType.NO); automaticRoleD.setRole(roleA.getId()); automaticRoleD.setTreeNode(nodeD.getId()); automaticRoleD = saveAutomaticRole(automaticRoleD, true); contractD.setWorkPosition(nodeD.getId()); contractD = service.save(contractD); // check List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contractD.getId()); assertEquals(0, identityRoles.size()); } @Test public void testDontAssingRoleForInvalidContractWhenPositionIsChanged() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contractD = new IdmIdentityContractDto(); contractD.setIdentity(identity.getId()); contractD.setValidTill(LocalDate.now().minusDays(1)); contractD = service.save(contractD); // create new automatic role automaticRoleD = new IdmRoleTreeNodeDto(); automaticRoleD.setRecursionType(RecursionType.NO); automaticRoleD.setRole(roleA.getId()); automaticRoleD.setTreeNode(nodeD.getId()); automaticRoleD = saveAutomaticRole(automaticRoleD, true); contractD.setWorkPosition(nodeD.getId()); contractD = service.save(contractD); // check List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contractD.getId()); assertEquals(0, identityRoles.size()); } @Test public void testFindLastExpiredContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto last = service.findLastExpiredContract(identity.getId(), null); Assert.assertNull(last); IdmIdentityContractDto contractOne = new IdmIdentityContractDto(); contractOne.setIdentity(identity.getId()); contractOne.setValidTill(LocalDate.now().minusDays(1)); contractOne = service.save(contractOne); IdmIdentityContractDto contractTwo = new IdmIdentityContractDto(); contractTwo.setIdentity(identity.getId()); contractTwo.setValidTill(LocalDate.now().minusDays(2)); contractTwo = service.save(contractTwo); last = service.findLastExpiredContract(identity.getId(), contractTwo.getValidTill()); Assert.assertNull(last); last = service.findLastExpiredContract(identity.getId(), null); Assert.assertEquals(contractOne, last); last = service.findLastExpiredContract(identity.getId(), contractOne.getValidTill()); Assert.assertEquals(contractTwo, last); } @Test public void testCheckExpiredContract() { IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); List<IdmIdentityContractDto> contracts = service.findAllByIdentity(identity.getId()); assertEquals(1, contracts.size()); IdmIdentityContractDto last = service.findLastExpiredContract(identity.getId(), null); Assert.assertNull(last); IdmIdentityContractDto identityContractTwo = getHelper().createContract(identity); last = service.findLastExpiredContract(identity.getId(), null); Assert.assertNull(last); contracts = service.findAllByIdentity(identity.getId()); assertEquals(2, contracts.size()); identityContractTwo.setValidTill(LocalDate.now().minusDays(5)); identityContractTwo = service.save(identityContractTwo); contracts = service.findAllByIdentity(identity.getId()); assertEquals(2, contracts.size()); last = service.findLastExpiredContract(identity.getId(), null); Assert.assertNotNull(last); assertEquals(identityContractTwo.getId(), last.getId()); IdmIdentityDto identityTwo = getHelper().createIdentity((GuardedString) null); contracts = service.findAllByIdentity(identityTwo.getId()); assertEquals(1, contracts.size()); last = service.findLastExpiredContract(identityTwo.getId(), null); Assert.assertNull(last); } @Test @Transactional public void testOtherMainContractByValidFrom() { IdmIdentityDto identity = getHelper().createIdentity(); IdmIdentityContractDto contractOne = getHelper().getPrimeContract(identity); contractOne.setWorkPosition(null); contractOne.setMain(false); contractOne.setValidFrom(LocalDate.now().minusDays(2)); service.save(contractOne); IdmIdentityContractDto contractTwo = getHelper().createContract(identity, null, LocalDate.now().minusDays(1), null); Assert.assertEquals(contractOne.getId(), getHelper().getPrimeContract(identity).getId()); contractTwo.setValidFrom(LocalDate.now().minusDays(3)); service.save(contractTwo); Assert.assertEquals(contractTwo.getId(), getHelper().getPrimeContract(identity).getId()); } @Test public void testAutomaticRolesRemovalAfterContractEnds() { // automatic roles by tree structure prepareAutomaticRoles(); // automatic role by attribute on contract String autoPosition = getHelper().createName(); IdmRoleDto autoAttributeRole = getHelper().createRole(); IdmAutomaticRoleAttributeDto automaticRole = getHelper().createAutomaticRole(autoAttributeRole.getId()); getHelper().createAutomaticRoleRule(automaticRole.getId(), AutomaticRoleAttributeRuleComparison.EQUALS, AutomaticRoleAttributeRuleType.CONTRACT, IdmIdentityContract_.position.getName(), null, autoPosition); // prepare identity, contract, direct roles and automatic roles IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = service.getPrimeContract(identity.getId()); contract.setIdentity(identity.getId()); contract.setValidFrom(LocalDate.now().minusDays(1)); contract.setValidTill(LocalDate.now().plusMonths(1)); contract.setWorkPosition(nodeD.getId()); contract.setMain(true); contract.setDescription("test-node-d"); contract.setPosition(autoPosition); contract = service.save(contract); UUID contractId = contract.getId(); IdmRoleDto directRole = getHelper().createRole(); getHelper().createIdentityRole(contract, directRole); List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByContract(contract.getId()); Assert.assertEquals(5, identityRoles.size()); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleA.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleB.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return roleC.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return directRole.getId().equals(ir.getRole()); })); Assert.assertTrue(identityRoles.stream().anyMatch(ir -> { return autoAttributeRole.getId().equals(ir.getRole()); })); try { getHelper().setConfigurationValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED, true); // end contract - all roles should be removed, after asynchronous role request ends contract.setValidTill(LocalDate.now().minusDays(1)); contract = service.save(contract); Assert.assertFalse(contract.isValidNowOrInFuture()); getHelper().waitForResult(res -> { return !identityRoleService.findAllByContract(contractId).isEmpty(); }, 300, Integer.MAX_VALUE); getHelper().waitForResult(res -> { IdmLongRunningTaskFilter filter = new IdmLongRunningTaskFilter(); filter.setRunning(Boolean.TRUE); return taskManager.findLongRunningTasks(filter, null).getTotalElements() != 0; }); identityRoles = identityRoleService.findAllByContract(contract.getId()); Assert.assertTrue(identityRoles.isEmpty()); service.delete(contract); } finally { getHelper().setConfigurationValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED, false); } } @Test @Transactional public void testRecountAutomaticRoleWithMissingContent() { // create state with missing content IdmEntityStateDto state = new IdmEntityStateDto(); UUID stateId = UUID.randomUUID(); state.setOwnerId(stateId); state.setOwnerType(entityStateManager.getOwnerType(IdmIdentityContractDto.class)); state.setResult( new OperationResultDto .Builder(OperationState.BLOCKED) .setModel(new DefaultResultModel(CoreResultCode.AUTOMATIC_ROLE_SKIPPED)) .build()); entityStateManager.saveState(null, state); state = new IdmEntityStateDto(); state.setOwnerId(stateId); state.setOwnerType(entityStateManager.getOwnerType(IdmIdentityContractDto.class)); state.setResult( new OperationResultDto .Builder(OperationState.BLOCKED) .setModel(new DefaultResultModel(CoreResultCode.AUTOMATIC_ROLE_SKIPPED)) .build()); entityStateManager.saveState(null, state); state = new IdmEntityStateDto(); state.setOwnerId(UUID.randomUUID()); state.setOwnerType(entityStateManager.getOwnerType(IdmContractPositionDto.class)); state.setResult( new OperationResultDto .Builder(OperationState.BLOCKED) .setModel(new DefaultResultModel(CoreResultCode.AUTOMATIC_ROLE_SKIPPED)) .build()); entityStateManager.saveState(null, state); // recount skipped automatic roles LongRunningFutureTask<Boolean> executor = longRunningTaskManager.execute(new ProcessSkippedAutomaticRoleByTreeForContractTaskExecutor()); IdmLongRunningTaskDto longRunningTask = longRunningTaskManager.getLongRunningTask(executor); Assert.assertTrue(longRunningTask.getWarningItemCount() > 1); } @Test public void testSkipAndAssignAutomaticRoleOnContractAfterChange() { IdmTreeNodeDto otherNode = getHelper().createTreeNode(); IdmTreeNodeDto node = getHelper().createTreeNode(); // define automatic role for parent IdmRoleDto role = getHelper().createRole(); IdmRoleTreeNodeDto automaticRole = getHelper().createRoleTreeNode(role, node, RecursionType.NO, true); // create identity with contract on node IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().createContract(identity, otherNode); // no role should be assigned now List<IdmIdentityRoleDto> assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertTrue(assignedRoles.isEmpty()); contract.setWorkPosition(node.getId()); EntityEvent<IdmIdentityContractDto> event = new IdentityContractEvent(IdentityContractEventType.UPDATE, contract); event.getProperties().put(AutomaticRoleManager.SKIP_RECALCULATION, Boolean.TRUE); contract = service.publish(event).getContent(); UUID contractId = contract.getId(); IdmEntityStateFilter filter = new IdmEntityStateFilter(); filter.setStates(Lists.newArrayList(OperationState.BLOCKED)); filter.setResultCode(CoreResultCode.AUTOMATIC_ROLE_SKIPPED.getCode()); filter.setOwnerType(entityStateManager.getOwnerType(IdmIdentityContractDto.class)); List<IdmEntityStateDto> skippedStates = entityStateManager.findStates(filter, null).getContent(); Assert.assertTrue(skippedStates.stream().anyMatch(s -> s.getOwnerId().equals(contractId))); assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertTrue(assignedRoles.isEmpty()); // recount skipped automatic roles longRunningTaskManager.execute(new ProcessSkippedAutomaticRoleByTreeForContractTaskExecutor()); skippedStates = entityStateManager.findStates(filter, null).getContent(); Assert.assertFalse(skippedStates.stream().anyMatch(s -> s.getOwnerId().equals(automaticRole.getId()))); assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertEquals(1, assignedRoles.size()); Assert.assertEquals(automaticRole.getId(), assignedRoles.get(0).getAutomaticRole()); } @Test public void testSkipAndAssignAutomaticRoleOnPositionAfterChange() { IdmTreeNodeDto otherNode = getHelper().createTreeNode(); IdmTreeNodeDto node = getHelper().createTreeNode(); // define automatic role for parent IdmRoleDto role = getHelper().createRole(); IdmRoleTreeNodeDto automaticRole = getHelper().createRoleTreeNode(role, node, RecursionType.NO, true); // create identity with contract on node IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmContractPositionDto position = getHelper().createContractPosition(getHelper().getPrimeContract(identity), otherNode); // no role should be assigned now List<IdmIdentityRoleDto> assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertTrue(assignedRoles.isEmpty()); position.setWorkPosition(node.getId()); EntityEvent<IdmContractPositionDto> event = new ContractPositionEvent(ContractPositionEventType.UPDATE, position); event.getProperties().put(AutomaticRoleManager.SKIP_RECALCULATION, Boolean.TRUE); position = contractPositionService.publish(event).getContent(); UUID positionId = position.getId(); IdmEntityStateFilter filter = new IdmEntityStateFilter(); filter.setStates(Lists.newArrayList(OperationState.BLOCKED)); filter.setResultCode(CoreResultCode.AUTOMATIC_ROLE_SKIPPED.getCode()); filter.setOwnerType(entityStateManager.getOwnerType(IdmContractPositionDto.class)); List<IdmEntityStateDto> skippedStates = entityStateManager.findStates(filter, null).getContent(); Assert.assertTrue(skippedStates.stream().anyMatch(s -> s.getOwnerId().equals(positionId))); assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertTrue(assignedRoles.isEmpty()); // recount skipped automatic roles longRunningTaskManager.execute(new ProcessSkippedAutomaticRoleByTreeForContractTaskExecutor()); skippedStates = entityStateManager.findStates(filter, null).getContent(); Assert.assertFalse(skippedStates.stream().anyMatch(s -> s.getOwnerId().equals(automaticRole.getId()))); assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertEquals(1, assignedRoles.size()); Assert.assertEquals(automaticRole.getId(), assignedRoles.get(0).getAutomaticRole()); } @Test public void testSkipAndRemoveAutomaticRoleOnInvalidContract() { IdmTreeNodeDto node = getHelper().createTreeNode(); // define automatic role for parent IdmRoleDto role = getHelper().createRole(); IdmRoleDto subRole = getHelper().createRole(); getHelper().createRoleComposition(role, subRole); IdmRoleTreeNodeDto automaticRole = getHelper().createRoleTreeNode(role, node, RecursionType.NO, true); // create identity with contract on node IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null); IdmIdentityContractDto contract = getHelper().createContract(identity, node); // role should be assigned now List<IdmIdentityRoleDto> assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertEquals(2, assignedRoles.size()); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> automaticRole.getId().equals(ir.getAutomaticRole()))); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getDirectRole() != null)); contract.setValidTill(LocalDate.now().minusDays(2)); EntityEvent<IdmIdentityContractDto> event = new IdentityContractEvent(IdentityContractEventType.UPDATE, contract); event.getProperties().put(AutomaticRoleManager.SKIP_RECALCULATION, Boolean.TRUE); contract = service.publish(event).getContent(); UUID contractId = contract.getId(); IdmEntityStateFilter filter = new IdmEntityStateFilter(); filter.setStates(Lists.newArrayList(OperationState.BLOCKED)); filter.setResultCode(CoreResultCode.AUTOMATIC_ROLE_SKIPPED_INVALID_CONTRACT.getCode()); filter.setOwnerType(entityStateManager.getOwnerType(IdmIdentityContractDto.class)); List<IdmEntityStateDto> skippedStates = entityStateManager.findStates(filter, null).getContent(); Assert.assertTrue(skippedStates.stream().anyMatch(s -> s.getOwnerId().equals(contractId))); assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertEquals(2, assignedRoles.size()); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> automaticRole.getId().equals(ir.getAutomaticRole()))); Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getDirectRole() != null)); // recount skipped automatic roles longRunningTaskManager.execute(new ProcessSkippedAutomaticRoleByTreeForContractTaskExecutor()); skippedStates = entityStateManager.findStates(filter, null).getContent(); Assert.assertFalse(skippedStates.stream().anyMatch(s -> s.getOwnerId().equals(automaticRole.getId()))); assignedRoles = identityRoleService.findAllByIdentity(identity.getId()); Assert.assertTrue(assignedRoles.isEmpty()); } @Test(expected = AcceptedException.class) public void testPreventToDeleteCurrentlyDeletedRole() { IdmRoleTreeNodeDto automaticRole = getHelper().createRoleTreeNode(getHelper().createRole(), getHelper().createTreeNode(), true); RemoveAutomaticRoleTaskExecutor taskExecutor = AutowireHelper.createBean(RemoveAutomaticRoleTaskExecutor.class); taskExecutor.setAutomaticRoleId(automaticRole.getId()); IdmLongRunningTaskDto lrt = null; try { lrt = longRunningTaskManager.resolveLongRunningTask(taskExecutor, null, OperationState.RUNNING); lrt.setRunning(true); longRunningTaskService.save(lrt); taskExecutor = AutowireHelper.createBean(RemoveAutomaticRoleTaskExecutor.class); taskExecutor.setAutomaticRoleId(automaticRole.getId()); longRunningTaskManager.execute(taskExecutor); } finally { lrt.setRunning(false); lrt = longRunningTaskService.save(lrt); longRunningTaskService.delete(lrt); } } @Test(expected = AcceptedException.class) public void testAcceptSimultaneousAutomaticRoleTask() { IdmRoleTreeNodeDto automaticRole = getHelper().createRoleTreeNode(getHelper().createRole(), getHelper().createTreeNode(), true); ProcessAutomaticRoleByTreeTaskExecutor taskExecutor = AutowireHelper.createBean(ProcessAutomaticRoleByTreeTaskExecutor.class); taskExecutor.setAutomaticRoles(Lists.newArrayList(automaticRole.getId())); IdmLongRunningTaskDto lrt = null; try { lrt = longRunningTaskManager.resolveLongRunningTask(taskExecutor, null, OperationState.RUNNING); lrt.setRunning(true); longRunningTaskService.save(lrt); taskExecutor = AutowireHelper.createBean(ProcessAutomaticRoleByTreeTaskExecutor.class); taskExecutor.setAutomaticRoles(Lists.newArrayList(automaticRole.getId())); longRunningTaskManager.execute(taskExecutor); } finally { lrt.setRunning(false); lrt = longRunningTaskService.save(lrt); longRunningTaskService.delete(lrt); } } }
package org.openhab.binding.zwave.internal.protocol.commandclass; import org.openhab.binding.zwave.internal.protocol.SerialMessage; import org.openhab.binding.zwave.internal.protocol.ZWaveController; import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageClass; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessagePriority; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageType; import org.openhab.binding.zwave.internal.protocol.event.ZWaveConfigurationParameterEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * Handles the Association command class. This allows reading * and writing of node association parameters * @author Chris Jackson * @since 1.4.0 */ @XStreamAlias("associationCommandClass") public class ZWaveAssociationCommandClass extends ZWaveCommandClass { private static final Logger logger = LoggerFactory.getLogger(ZWaveAssociationCommandClass.class); private static final int ASSOCIATIONCMD_SET = 0x01; private static final int ASSOCIATIONCMD_GET = 0x02; private static final int ASSOCIATIONCMD_REPORT = 0x03; private static final int ASSOCIATIONCMD_REMOVE = 0x04; private static final int ASSOCIATIONCMD_GROUPINGSGET = 0x05; private static final int ASSOCIATIONCMD_GROUPINGSREPORT = 0x06; /** * Creates a new instance of the ZWaveAssociationCommandClass class. * @param node the node this command class belongs to * @param controller the controller to use * @param endpoint the endpoint this Command class belongs to */ public ZWaveAssociationCommandClass(ZWaveNode node, ZWaveController controller, ZWaveEndpoint endpoint) { super(node, controller, endpoint); } /** * {@inheritDoc} */ @Override public CommandClass getCommandClass() { return CommandClass.ASSOCIATION; } /** * {@inheritDoc} */ @Override public void handleApplicationCommandRequest(SerialMessage serialMessage, int offset, int endpoint) { logger.debug(String.format("Received Association Request for Node ID = %d", this.getNode().getNodeId())); int command = serialMessage.getMessagePayloadByte(offset); switch (command) { case ASSOCIATIONCMD_SET: logger.trace("Process Association Set"); processAssociationReport(serialMessage, offset); break; case ASSOCIATIONCMD_GET: logger.trace("Process Association Get"); return; case ASSOCIATIONCMD_REPORT: logger.trace("Process Association Report"); processAssociationReport(serialMessage, offset); break; case ASSOCIATIONCMD_REMOVE: logger.trace("Process Association Remove"); return; case ASSOCIATIONCMD_GROUPINGSGET: logger.trace("Process Association GroupingsGet"); return; case ASSOCIATIONCMD_GROUPINGSREPORT: logger.trace("Process Association GroupingsReport - number of groups " + serialMessage.getMessagePayloadByte(offset+1)); return; default: logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).", command, this.getCommandClass().getLabel(), this.getCommandClass().getKey())); } } /** * Processes a CONFIGURATIONCMD_REPORT / CONFIGURATIONCMD_SET message. * @param serialMessage the incoming message to process. * @param offset the offset position from which to start message processing. * @param endpoint the endpoint or instance number this message is meant for. */ protected void processAssociationReport(SerialMessage serialMessage, int offset) { // Extract the group index int group = serialMessage.getMessagePayloadByte(offset+1); // The max associations supported (0 if the requested group is not supported) int maxAssociations = serialMessage.getMessagePayloadByte(offset+2); // Number of outstanding requests (if the group is large, it may come in multiple frames) int following = serialMessage.getMessagePayloadByte(offset+3); if(maxAssociations == 0) { // Unsupported association group. Nothing to do! return; } if(serialMessage.getMessagePayload().length > 5) { logger.debug("Node {}, association group {} includes the following nodes:", this.getNode().getNodeId(), group); int numAssociations = serialMessage.getMessagePayload().length - 5; for(int cnt = 0; cnt < numAssociations; cnt++) { int node = serialMessage.getMessagePayloadByte(offset+3+cnt); logger.debug("Node {}", node); } } // Is this the end of the list if(following == 0) { } // ZWaveConfigurationParameterEvent zEvent = new ZWaveConfigurationParameterEvent(this.getNode().getNodeId(), parameter, value, size); // this.getController().notifyEventListeners(zEvent); } /** * Gets a SerialMessage with the ASSOCIATIONCMD_GET command * @param group the association group to read * @return the serial message */ public SerialMessage getAssociationMessage(int group) { logger.debug("Creating new message for application command ASSOCIATIONCMD_GET for node {}", this.getNode().getNodeId()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); byte[] newPayload = { (byte) this.getNode().getNodeId(), 3, (byte) getCommandClass().getKey(), (byte) ASSOCIATIONCMD_GET, (byte) (group & 0xff) }; result.setMessagePayload(newPayload); return result; } /** * Gets a SerialMessage with the ASSOCIATIONCMD_SET command * @param group the association group * @param node the node to add to the specified group * @return the serial message */ public SerialMessage setAssociationMessage(int group, int node) { logger.debug("Creating new message for application command ASSOCIATIONCMD_SET for node {}", this.getNode().getNodeId()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set); byte[] newPayload = { (byte) this.getNode().getNodeId(), 4, (byte) getCommandClass().getKey(), (byte) ASSOCIATIONCMD_SET, (byte) (group & 0xff), (byte) (node & 0xff) }; result.setMessagePayload(newPayload); return result; } /** * Gets a SerialMessage with the ASSOCIATIONCMD_REMOVE command * @param group the association group * @param node the node to add to the specified group * @return the serial message */ public SerialMessage removeAssociationMessage(int group, int node) { logger.debug("Creating new message for application command ASSOCIATIONCMD_REMOVE for node {}", this.getNode().getNodeId()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set); byte[] newPayload = { (byte) this.getNode().getNodeId(), 4, (byte) getCommandClass().getKey(), (byte) ASSOCIATIONCMD_REMOVE, (byte) (group & 0xff), (byte) (node & 0xff) }; result.setMessagePayload(newPayload); return result; } }
package bitmapbenchmarks.synth; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.Iterator; import java.util.Random; /** * This class will generate "uniform" lists of random integers. * * @author Daniel Lemire */ public class UniformDataGenerator { /** * construct generator of random arrays. */ public UniformDataGenerator() { this.rand = new Random(); } /** * @param seed random seed */ public UniformDataGenerator(final int seed) { this.rand = new Random(seed); } /** * generates randomly N distinct integers from 0 to Max. */ int[] generateUniformHash(int N, int Max) { if (N > Max) throw new RuntimeException("not possible"); int[] ans = new int[N]; HashSet<Integer> s = new HashSet<Integer>(); while (s.size() < N) s.add(new Integer(this.rand.nextInt(Max))); Iterator<Integer> i = s.iterator(); for (int k = 0; k < N; ++k) ans[k] = i.next().intValue(); Arrays.sort(ans); return ans; } /** * output all integers from the range [0,Max) that are not * in the array */ static int[] negate(int[] x, int Max) { int[] ans = new int[Max - x.length]; int i = 0; int c = 0; for (int j = 0; j < x.length; ++j) { int v = x[j]; for (; i < v; ++i) ans[c++] = i; ++i; } while (c < ans.length) ans[c++] = i++; return ans; } /** * generates randomly N distinct integers from 0 to Max. */ public int[] generateUniform(int N, int Max) { if(N * 2 > Max) { return negate( generateUniform(Max - N, Max), Max ); } if (2048 * N > Max) return generateUniformBitmap(N, Max); return generateUniformHash(N, Max); } /** * generates randomly N distinct integers from 0 to Max. */ int[] generateUniformBitmap(int N, int Max) { if (N > Max) throw new RuntimeException("not possible"); int[] ans = new int[N]; BitSet bs = new BitSet(Max); int cardinality = 0; while (cardinality < N) { int v = rand.nextInt(Max); if (!bs.get(v)) { bs.set(v); cardinality++; } } int pos = 0; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { ans[pos++] = i; } return ans; } Random rand = new Random(); }
package com.ceco.gm2.gravitybox; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import com.ceco.gm2.gravitybox.Utils.MethodState; import com.ceco.gm2.gravitybox.quicksettings.AQuickSettingsTile; import com.ceco.gm2.gravitybox.quicksettings.NetworkModeTile; import com.ceco.gm2.gravitybox.quicksettings.TorchTile; import com.ceco.gm2.gravitybox.quicksettings.GravityBoxTile; import com.ceco.gm2.gravitybox.quicksettings.SyncTile; import com.ceco.gm2.gravitybox.quicksettings.WifiApTile; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.os.IBinder; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; public class ModQuickSettings { private static final String TAG = "ModQuickSettings"; public static final String PACKAGE_NAME = "com.android.systemui"; private static final String CLASS_QUICK_SETTINGS = "com.android.systemui.statusbar.phone.QuickSettings"; private static final String CLASS_PHONE_STATUSBAR = "com.android.systemui.statusbar.phone.PhoneStatusBar"; private static final String CLASS_PANEL_BAR = "com.android.systemui.statusbar.phone.PanelBar"; private static final String CLASS_QS_TILEVIEW = "com.android.systemui.statusbar.phone.QuickSettingsTileView"; private static final String CLASS_NOTIF_PANELVIEW = "com.android.systemui.statusbar.phone.NotificationPanelView"; private static final boolean DEBUG = false; private static Context mContext; private static Context mGbContext; private static ViewGroup mContainerView; private static Object mPanelBar; private static Object mStatusBar; private static Set<String> mActiveTileKeys; private static Class<?> mQuickSettingsTileViewClass; private static Object mSimSwitchPanelView; private static ArrayList<AQuickSettingsTile> mTiles; private static List<String> mCustomSystemTileKeys = new ArrayList<String>(Arrays.asList( "user_textview", "airplane_mode_textview", "battery_textview", "wifi_textview", "bluetooth_textview", "gps_textview", "data_conn_textview", "rssi_textview", "audio_profile_textview", "brightness_textview", "timeout_textview", "auto_rotate_textview" )); private static List<String> mCustomGbTileKeys = new ArrayList<String>(Arrays.asList( "sync_tileview", "wifi_ap_tileview", "gravitybox_tileview", "torch_tileview", "network_mode_tileview" )); private static void log(String message) { XposedBridge.log(TAG + ": " + message); } private static BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { log("received broadcast: " + intent.toString()); if (intent.getAction().equals(GravityBoxSettings.ACTION_PREF_QUICKSETTINGS_CHANGED) && intent.hasExtra(GravityBoxSettings.EXTRA_QS_PREFS)) { String[] qsPrefs = intent.getStringArrayExtra(GravityBoxSettings.EXTRA_QS_PREFS); mActiveTileKeys = new HashSet<String>(Arrays.asList(qsPrefs)); updateTileVisibility(); } } }; // TODO: quickfix that needs some optimizations private static boolean isCustomizableTile(View view) { Resources res = mContext.getResources(); for (String key : mCustomSystemTileKeys) { int resId = res.getIdentifier(key, "id", PACKAGE_NAME); if (view.findViewById(resId) != null) { return true; } } res = mGbContext.getResources(); for (String key : mCustomGbTileKeys) { int resId = res.getIdentifier(key, "id", GravityBox.PACKAGE_NAME); if (view.findViewById(resId) != null) { return true; } } return false; } private static void updateTileVisibility() { if (mActiveTileKeys == null) { log("updateTileVisibility: mActiveTileKeys is null - skipping"); return; } int tileCount = mContainerView.getChildCount(); // hide all tiles first for(int i = 0; i < tileCount; i++) { View view = mContainerView.getChildAt(i); if (view != null && isCustomizableTile(view)) { view.setVisibility(View.GONE); } } // unhide only those tiles present in mActiveTileKeys set for(String tileKey : mActiveTileKeys) { // search within mContext resources (system specific tiles) View view = mContainerView.findViewById(mContext.getResources().getIdentifier( tileKey, "id", PACKAGE_NAME)); if (view == null) { // search within mGbContext (our additional GB specific tiles) view = mContainerView.findViewById(mGbContext.getResources().getIdentifier( tileKey, "id", GravityBox.PACKAGE_NAME)); } if (view != null) { if (DEBUG) { log("updateTileVisibility: unhiding tile for key: " + tileKey + "; " + "view=" + ((view == null) ? "null" : view.toString())); } // bubble up in view hierarchy to find QuickSettingsTileView parent view View rootView = view; do { rootView = (View) rootView.getParent(); } while (rootView != null && rootView.getClass() != mQuickSettingsTileViewClass); if (DEBUG) { log("updateTileVisibility: finished searching for root view; rootView=" + ((rootView == null) ? "null" : rootView.toString())); } if (rootView != null) { rootView.setVisibility(View.VISIBLE); } } } } public static void init(final XSharedPreferences prefs, final ClassLoader classLoader) { log("init"); try { final ThreadLocal<MethodState> removeNotificationState = new ThreadLocal<MethodState>(); removeNotificationState.set(MethodState.UNKNOWN); prefs.reload(); mActiveTileKeys = prefs.getStringSet(GravityBoxSettings.PREF_KEY_QUICK_SETTINGS, null); log("got tile prefs: mActiveTileKeys = " + (mActiveTileKeys == null ? "null" : mActiveTileKeys.toString())); final Class<?> quickSettingsClass = XposedHelpers.findClass(CLASS_QUICK_SETTINGS, classLoader); final Class<?> phoneStatusBarClass = XposedHelpers.findClass(CLASS_PHONE_STATUSBAR, classLoader); final Class<?> panelBarClass = XposedHelpers.findClass(CLASS_PANEL_BAR, classLoader); mQuickSettingsTileViewClass = XposedHelpers.findClass(CLASS_QS_TILEVIEW, classLoader); final Class<?> notifPanelViewClass = XposedHelpers.findClass(CLASS_NOTIF_PANELVIEW, classLoader); XposedBridge.hookAllConstructors(quickSettingsClass, quickSettingsConstructHook); XposedHelpers.findAndHookMethod(quickSettingsClass, "setBar", panelBarClass, quickSettingsSetBarHook); XposedHelpers.findAndHookMethod(quickSettingsClass, "setService", phoneStatusBarClass, quickSettingsSetServiceHook); XposedHelpers.findAndHookMethod(quickSettingsClass, "addSystemTiles", ViewGroup.class, LayoutInflater.class, quickSettingsAddSystemTilesHook); XposedHelpers.findAndHookMethod(quickSettingsClass, "updateResources", quickSettingsUpdateResourcesHook); XposedHelpers.findAndHookMethod(notifPanelViewClass, "onTouchEvent", MotionEvent.class, notificationPanelViewOnTouchEvent); XposedHelpers.findAndHookMethod(phoneStatusBarClass, "makeStatusBarView", makeStatusBarViewHook); XposedHelpers.findAndHookMethod(phoneStatusBarClass, "removeNotification", IBinder.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { if (DEBUG) { log("removeNotification method ENTER"); } removeNotificationState.set(MethodState.METHOD_ENTERED); } @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { if (DEBUG) { log("removeNotification method EXIT"); } removeNotificationState.set(MethodState.METHOD_EXITED); } }); XposedHelpers.findAndHookMethod(phoneStatusBarClass, "animateCollapsePanels", new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { if (removeNotificationState.get().equals(MethodState.METHOD_ENTERED)) { log("animateCollapsePanels called from removeNotification method"); boolean hasFlipSettings = XposedHelpers.getBooleanField(param.thisObject, "mHasFlipSettings"); boolean animating = XposedHelpers.getBooleanField(param.thisObject, "mAnimating"); View flipSettingsView = (View) XposedHelpers.getObjectField(param.thisObject, "mFlipSettingsView"); Object notificationData = XposedHelpers.getObjectField(mStatusBar, "mNotificationData"); int ndSize = (Integer) XposedHelpers.callMethod(notificationData, "size"); boolean isShowingSettings = hasFlipSettings && flipSettingsView.getVisibility() == View.VISIBLE; if (ndSize == 0 && !animating && !isShowingSettings) { // let the original method finish its work } else { log("animateCollapsePanels: all notifications removed but showing QuickSettings - do nothing"); param.setResult(null); } } } }); } catch (Exception e) { XposedBridge.log(e); } } private static XC_MethodHook quickSettingsConstructHook = new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { log("QuickSettings constructed - initializing local members"); mContext = (Context) XposedHelpers.getObjectField(param.thisObject, "mContext"); mGbContext = mContext.createPackageContext(GravityBox.PACKAGE_NAME, Context.CONTEXT_IGNORE_SECURITY); mContainerView = (ViewGroup) XposedHelpers.getObjectField(param.thisObject, "mContainerView"); IntentFilter intentFilter = new IntentFilter(GravityBoxSettings.ACTION_PREF_QUICKSETTINGS_CHANGED); mContext.registerReceiver(mBroadcastReceiver, intentFilter); } }; private static XC_MethodHook quickSettingsSetBarHook = new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { mPanelBar = param.args[0]; log("mPanelBar set"); } }; private static XC_MethodHook quickSettingsSetServiceHook = new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { mStatusBar = param.args[0]; log("mStatusBar set"); } }; private static XC_MethodHook quickSettingsAddSystemTilesHook = new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { log("about to add tiles"); LayoutInflater inflater = (LayoutInflater) param.args[1]; mTiles = new ArrayList<AQuickSettingsTile>(); NetworkModeTile nmTile = new NetworkModeTile(mContext, mGbContext, mStatusBar, mPanelBar); nmTile.setupQuickSettingsTile(mContainerView, inflater); mTiles.add(nmTile); SyncTile syncTile = new SyncTile(mContext, mGbContext, mStatusBar, mPanelBar); syncTile.setupQuickSettingsTile(mContainerView, inflater); mTiles.add(syncTile); WifiApTile wifiApTile = new WifiApTile(mContext, mGbContext, mStatusBar, mPanelBar); wifiApTile.setupQuickSettingsTile(mContainerView, inflater); mTiles.add(wifiApTile); TorchTile torchTile = new TorchTile(mContext, mGbContext, mStatusBar, mPanelBar); torchTile.setupQuickSettingsTile(mContainerView, inflater); mTiles.add(torchTile); GravityBoxTile gbTile = new GravityBoxTile(mContext, mGbContext, mStatusBar, mPanelBar); gbTile.setupQuickSettingsTile(mContainerView, inflater); mTiles.add(gbTile); updateTileVisibility(); } }; private static XC_MethodHook quickSettingsUpdateResourcesHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { if (DEBUG) { log("updateResources - updating all tiles"); } for (AQuickSettingsTile t : mTiles) { t.updateResources(); } } }; private static XC_MethodReplacement notificationPanelViewOnTouchEvent = new XC_MethodReplacement() { @Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { MotionEvent event = (MotionEvent) param.args[0]; if (mStatusBar != null && XposedHelpers.getBooleanField(mStatusBar, "mHasFlipSettings")) { boolean shouldFlip = false; boolean okToFlip = XposedHelpers.getBooleanField(param.thisObject, "mOkToFlip"); Object notificationData = XposedHelpers.getObjectField(mStatusBar, "mNotificationData"); float handleBarHeight = XposedHelpers.getFloatField(param.thisObject, "mHandleBarHeight"); Method getExpandedHeight = param.thisObject.getClass().getSuperclass().getMethod("getExpandedHeight"); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: okToFlip = ((Float) getExpandedHeight.invoke(param.thisObject)) == 0; XposedHelpers.setBooleanField(param.thisObject, "mOkToFlip", okToFlip); if ((Integer)XposedHelpers.callMethod(notificationData, "size") == 0 && !isSimSwitchPanelShowing()) { shouldFlip = true; } break; case MotionEvent.ACTION_POINTER_DOWN: if (okToFlip) { float miny = event.getY(0); float maxy = miny; for (int i = 1; i < event.getPointerCount(); i++) { final float y = event.getY(i); if (y < miny) miny = y; if (y > maxy) maxy = y; } if (maxy - miny < handleBarHeight) { shouldFlip = true; } } break; } if (okToFlip && shouldFlip) { if (((View)param.thisObject).getMeasuredHeight() < handleBarHeight) { XposedHelpers.callMethod(mStatusBar, "switchToSettings"); } else { XposedHelpers.callMethod(mStatusBar, "flipToSettings"); } okToFlip = false; } } View handleView = (View) XposedHelpers.getObjectField(param.thisObject, "mHandleView"); return handleView.dispatchTouchEvent(event); } }; private static XC_MethodHook makeStatusBarViewHook = new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { try { Object toolbarView = XposedHelpers.getObjectField(param.thisObject, "mToolBarView"); if (toolbarView != null) { mSimSwitchPanelView = XposedHelpers.getObjectField(toolbarView, "mSimSwitchPanelView"); log("makeStatusBarView: SimSwitchPanelView found"); } } catch (Exception e) { } } }; private static boolean isSimSwitchPanelShowing() { if (mSimSwitchPanelView == null) return false; return (Boolean) XposedHelpers.callMethod(mSimSwitchPanelView, "isPanelShowing"); } }
package bitronix.tm.resource.jdbc; import java.io.PrintWriter; import java.lang.reflect.*; import java.sql.*; import javax.naming.*; import javax.sql.*; import javax.transaction.xa.XAResource; import org.slf4j.*; import bitronix.tm.internal.XAResourceHolderState; import bitronix.tm.recovery.RecoveryException; import bitronix.tm.resource.*; import bitronix.tm.resource.common.*; public class PoolingDataSource extends ResourceBean implements DataSource, XAResourceProducer { private final static Logger log = LoggerFactory.getLogger(PoolingDataSource.class); private transient XAPool pool; private transient XADataSource xaDataSource; private transient RecoveryXAResourceHolder recoveryXAResourceHolder; private transient JdbcConnectionHandle recoveryConnectionHandle; private String testQuery; private boolean enableJdbc4ConnectionTest; private int preparedStatementCacheSize = 0; private String isolationLevel; private String cursorHoldability; private String localAutoCommit; public PoolingDataSource() { } /** * Initializes the pool by creating the initial amount of connections. */ public synchronized void init() { try { buildXAPool(); } catch (Exception ex) { throw new ResourceConfigurationException("cannot create JDBC datasource named " + getUniqueName(), ex); } } private void buildXAPool() throws Exception { if (this.pool != null) return; if (log.isDebugEnabled()) log.debug("building XA pool for " + getUniqueName() + " with " + getMinPoolSize() + " connection(s)"); this.pool = new XAPool(this, this); this.xaDataSource = (XADataSource) pool.getXAFactory(); ResourceRegistrar.register(this); } /** * @return the query that will be used to test connections. */ public String getTestQuery() { return testQuery; } /** * When set, the specified query will be executed on the connection acquired from the pool before being handed to * the caller. The connections won't be tested when not set. Default value is null. * @param testQuery the query that will be used to test connections. */ public void setTestQuery(String testQuery) { this.testQuery = testQuery; } /** * @param enableJdbc4ConnectionTest the enableJdbc4ConnectionTest to set */ public void setEnableJdbc4ConnectionTest(boolean enableJdbc4ConnectionTest) { this.enableJdbc4ConnectionTest = enableJdbc4ConnectionTest; } /** * @return the enableJdbc4ConnectionTest */ public boolean isEnableJdbc4ConnectionTest() { return enableJdbc4ConnectionTest; } public int getPreparedStatementCacheSize() { return preparedStatementCacheSize; } /** * Set the target maximum size of the prepared statement cache. In * reality under certain unusual conditions the cache may temporarily * drift higher in size. * * @param preparedStatementCacheSize the target maximum size */ public void setPreparedStatementCacheSize(int preparedStatementCacheSize) { this.preparedStatementCacheSize = preparedStatementCacheSize; } public String getIsolationLevel() { return isolationLevel; } /** * Set the default isolation level for connections. * * @param isolationLevel the isolation level */ public void setIsolationLevel(String isolationLevel) { this.isolationLevel = isolationLevel; } public String getCursorHoldability() { return cursorHoldability; } /** * Set the default cursor holdability for connections. * * @param cursorHoldability the cursor holdability */ public void setCursorHoldability(String cursorHoldability) { this.cursorHoldability = cursorHoldability; } public String getLocalAutoCommit() { return localAutoCommit; } public void setLocalAutoCommit(String localAutoCommit) { this.localAutoCommit = localAutoCommit; } /* Implementation of DataSource interface */ public Connection getConnection() throws SQLException { init(); if (log.isDebugEnabled()) log.debug("acquiring connection from " + this); if (pool == null) { if (log.isDebugEnabled()) log.debug("pool is closed, returning null connection"); return null; } try { InvocationHandler connectionHandle = (InvocationHandler) pool.getConnectionHandle(); if (log.isDebugEnabled()) log.debug("acquired connection from " + this); return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { Connection.class }, connectionHandle); } catch (Exception ex) { throw (SQLException) new SQLException("unable to get a connection from pool of " + this).initCause(ex); } } public Connection getConnection(String username, String password) throws SQLException { if (log.isDebugEnabled()) log.debug("JDBC connections are pooled, username and password ignored"); return getConnection(); } public String toString() { return "a PoolingDataSource containing " + pool; } /* XAResourceProducer implementation */ public XAResourceHolderState startRecovery() throws RecoveryException { init(); if (recoveryConnectionHandle != null) throw new RecoveryException("recovery already in progress on " + this); try { recoveryConnectionHandle = (JdbcConnectionHandle) pool.getConnectionHandle(false); recoveryXAResourceHolder = recoveryConnectionHandle.getPooledConnection().createRecoveryXAResourceHolder(); return new XAResourceHolderState(recoveryConnectionHandle.getPooledConnection(), this); } catch (Exception ex) { throw new RecoveryException("cannot start recovery on " + this, ex); } } public void endRecovery() throws RecoveryException { if (recoveryConnectionHandle == null) return; try { recoveryXAResourceHolder.close(); recoveryXAResourceHolder = null; recoveryConnectionHandle = null; } catch (Exception ex) { throw new RecoveryException("error ending recovery on " + this, ex); } } public void setFailed(boolean failed) { pool.setFailed(failed); } public void close() { if (pool == null) { if (log.isDebugEnabled()) log.debug("trying to close already closed PoolingDataSource " + getUniqueName()); return; } ResourceRegistrar.unregister(this); if (log.isDebugEnabled()) log.debug("closing " + this); pool.close(); pool = null; } public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) throws Exception { if (!(xaFactory instanceof XADataSource)) throw new IllegalArgumentException("class '" + xaFactory.getClass().getName() + "' does not implement " + XADataSource.class.getName()); XADataSource xads = (XADataSource) xaFactory; return new JdbcPooledConnection(this, xads.getXAConnection()); } public XAResourceHolder findXAResourceHolder(XAResource xaResource) { return pool.findXAResourceHolder(xaResource); } /** * {@link PoolingDataSource} must alway have a unique name so this method builds a reference to this object using * the unique name as {@link javax.naming.RefAddr}. * @return a reference to this {@link PoolingDataSource}. */ public Reference getReference() throws NamingException { if (log.isDebugEnabled()) log.debug("creating new JNDI reference of " + this); return new Reference( PoolingDataSource.class.getName(), new StringRefAddr("uniqueName", getUniqueName()), ResourceObjectFactory.class.getName(), null); } /* DataSource implementation */ public int getLoginTimeout() throws SQLException { return xaDataSource.getLoginTimeout(); } public void setLoginTimeout(int seconds) throws SQLException { xaDataSource.setLoginTimeout(seconds); } public PrintWriter getLogWriter() throws SQLException { return xaDataSource.getLogWriter(); } public void setLogWriter(PrintWriter out) throws SQLException { xaDataSource.setLogWriter(out); } /* Java 6 JDBC4 methods. Compilable under source 1.4 restriction. * Original interface definition uses generics, but generics are * unwrapped at compile-time, so these should work. Under 1.4 they * are ignored as simple additional methods on this class. Under * 1.6 they will be invoked appropriately. */ public boolean isWrapperFor(Class iface) throws SQLException { return false; } public Object unwrap(Class iface) throws SQLException { throw new SQLException("bitronix.tm.resource.jdbc.PoolingDataSource is not a wrapper"); } }
package burlap.shell.command.env; import burlap.oomdp.singleagent.environment.Environment; import burlap.shell.BurlapShell; import burlap.shell.EnvironmentShell; import burlap.shell.command.ShellCommand; import joptsimple.OptionParser; import joptsimple.OptionSet; import java.io.PrintStream; import java.util.Scanner; /** * A {@link burlap.shell.command.ShellCommand} printing the current observation in the {@link burlap.oomdp.singleagent.environment.Environment} * Use the -h option for help information. * @author James MacGlashan. */ public class ObservationCommand implements ShellCommand { protected OptionParser parser = new OptionParser("h*"); @Override public String commandName() { return "obs"; } @Override public int call(BurlapShell shell, String argString, Scanner is, PrintStream os) { OptionSet oset = this.parser.parse(argString.split(" ")); if(oset.has("h")){ os.println("Prints the current observation from the environment."); return 0; } Environment env = ((EnvironmentShell)shell).getEnv(); os.println(env.getCurrentObservation().getCompleteStateDescriptionWithUnsetAttributesAsNull()); return 0; } }
package org.springframework.ide.vscode.boot.java.requestmapping; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.SingleMemberAnnotation; import org.eclipse.jdt.core.dom.StringLiteral; import org.eclipse.lsp4j.Hover; import org.eclipse.lsp4j.MarkedString; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.json.JSONObject; import org.springframework.ide.vscode.boot.java.handlers.HoverProvider; import org.springframework.ide.vscode.commons.boot.app.cli.SpringBootApp; import org.springframework.ide.vscode.commons.util.BadLocationException; import org.springframework.ide.vscode.commons.util.Log; import org.springframework.ide.vscode.commons.util.text.TextDocument; /** * @author Martin Lippert */ public class RequestMappingHoverProvider implements HoverProvider { @Override public CompletableFuture<Hover> provideHover(ASTNode node, Annotation annotation, ITypeBinding type, int offset, TextDocument doc, SpringBootApp[] runningApps) { return provideHover(annotation, doc, runningApps); } @Override public Range getLiveHoverHint(Annotation annotation, TextDocument doc, SpringBootApp[] runningApps) { try { if (runningApps.length > 0) { // TODO: this check is too simple, we need to do a lot more here // -> check if the running app has a matching request mapping for this annotation Range hoverRange = doc.toRange(annotation.getStartPosition(), annotation.getLength()); return hoverRange; } } catch (BadLocationException e) { e.printStackTrace(); } return null; } private CompletableFuture<Hover> provideHover(Annotation annotation, TextDocument doc, SpringBootApp[] runningApps) { try { Optional<AppMappings> val = getRequestMappingsForAnnotation(annotation, runningApps); List<Either<String, MarkedString>> hoverContent = new ArrayList<>(); if (val.isPresent()) { addHoverContent(val.get(), hoverContent, annotation); } Range hoverRange = doc.toRange(annotation.getStartPosition(), annotation.getLength()); Hover hover = new Hover(); hover.setContents(hoverContent); hover.setRange(hoverRange); return CompletableFuture.completedFuture(hover); } catch (Exception e) { e.printStackTrace(); } return null; } private Optional<AppMappings> getRequestMappingsForAnnotation(Annotation annotation, SpringBootApp[] runningApps) { try { SpringBootApp foundApp = null; JSONObject requestMappings = null; for (SpringBootApp app : runningApps) { String mappings = app.getRequestMappings(); if (doesMatch(annotation, mappings)) { requestMappings = new JSONObject(mappings); foundApp = app; break; } } if (foundApp != null && requestMappings != null) { return Optional.of(new AppMappings(requestMappings, foundApp)); } } catch (Exception e) { Log.log(e); } return Optional.empty(); } private void addHoverContent(AppMappings appMappings, List<Either<String, MarkedString>> hoverContent, Annotation annotation) throws Exception { Iterator<String> keys = appMappings.mappings.keys(); String processId = appMappings.app.getProcessID(); String processName = appMappings.app.getProcessName(); while (keys.hasNext()) { String key = keys.next(); if (doesMatch(annotation, key)) { String path = UrlUtil.extractPath(key); String port = appMappings.app.getPort(); String host = appMappings.app.getHost(); String url = UrlUtil.createUrl(host, port, path); StringBuilder builder = new StringBuilder(); if (url != null) { builder.append("Path: "); builder.append("["); builder.append(path); builder.append("]"); builder.append("("); builder.append(url); builder.append(")"); } else { builder.append("Unable to resolve URL for path: " + key); } hoverContent.add(Either.forLeft(builder.toString())); } } hoverContent.add(Either.forLeft("Process ID: " + processId)); hoverContent.add(Either.forLeft("Process Name: " + processName)); } private boolean doesMatch(Annotation annotation, String key) { String mappingPath = null; if (annotation instanceof SingleMemberAnnotation) { Expression valueContent = ((SingleMemberAnnotation) annotation).getValue(); if (valueContent instanceof StringLiteral) { mappingPath = ((StringLiteral)valueContent).getLiteralValue(); } } else if (annotation instanceof NormalAnnotation) { List<?> values = ((NormalAnnotation) annotation).values(); for (Object value : values) { if (value instanceof MemberValuePair) { String name = ((MemberValuePair)value).getName().toString(); if (name != null && name.equals("value")) { Expression valueContent = ((MemberValuePair)value).getValue(); if (valueContent instanceof StringLiteral) { mappingPath = ((StringLiteral)valueContent).getLiteralValue(); } } } } } return mappingPath != null ? key.contains(mappingPath) : false; } public JSONObject[] getRequestMappingsFromProcesses(SpringBootApp[] runningApps) { List<JSONObject> result = new ArrayList<>(); try { for (SpringBootApp app : runningApps) { String mappings = app.getRequestMappings(); if (mappings != null) { JSONObject requestMappings = new JSONObject(mappings); if (requestMappings != null) { result.add(requestMappings); } } } } catch (Exception e) { e.printStackTrace(); } return result.toArray(new JSONObject[result.size()]); } static class AppMappings { public final JSONObject mappings; public final SpringBootApp app; public AppMappings(JSONObject mapping, SpringBootApp app) { this.mappings = mapping; this.app = app; } } }
package com.jcwhatever.bukkit.v1_8_R1; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.v1_8_R1.scheduler.CraftScheduler; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryType.SlotType; import org.bukkit.inventory.InventoryView; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPluginLoader; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * Static utilities for testing Bukkit plugins. */ public class BukkitTest { public static final String NMS_TEST_VERSION = "v1_8_R1"; private static boolean _isInit; private static long _nextHeartBeat; private static int _currentTick = 0; private static MockServer _server; /** * Initialize the Bukkit server. This needs to be called * before running any tests that may potentially use Bukkit. * * @return True if initialized, false if already initialized. */ public static boolean init() { if (_isInit) { return false; } _isInit = true; if (_server == null) _server = new MockServer(); try { Bukkit.setServer(_server); } catch (UnsupportedOperationException ignore) { return false; } return true; } /** * Get the mock Bukkit server. */ public static MockServer getServer() { init(); return _server; } /** * Invoke from within loops to send a heart beat signal to the scheduler service. * * <p>Required when testing components that use the Bukkit scheduler.</p> */ public static void heartBeat() { if (!_isInit || System.currentTimeMillis() < _nextHeartBeat) return; ((CraftScheduler)Bukkit.getServer().getScheduler()).mainThreadHeartbeat(_currentTick); _currentTick++; _nextHeartBeat = System.currentTimeMillis() + 50; } /** * Invoke to pause for the specified number of ticks. * A heart beat is sent to the Bukkit scheduler during this time. */ public static void pause(int ticks) { long end = System.currentTimeMillis() + (ticks * 50); while (System.currentTimeMillis() < end) { heartBeat(); try { Thread.sleep(10); } catch (InterruptedException e) { return; } } } /** * Login a mock player and return the {@code MockPlayer} * instance. If the player is already logged in, the current * player is returned. * * @param playerName The name of the player. */ public static MockPlayer login(String playerName) { return getServer().login(playerName); } /** * Logout a player by name. * * @param playerName The name of the player to logout. * * @return True if the player was found and removed. */ public static boolean logout(String playerName) { return logout(playerName, "Disconnected"); } /** * Logout a player by name. * * @param playerName The name of the player to logout. * @param message The logout message. * * @return True if the player was found and removed. */ public static boolean logout(String playerName, String message) { return getServer().logout(playerName, message); } /** * Kick a player by name. * * @param playerName The name of the player to kick. * * @return True if the player was found and kicked. */ public static boolean kick(String playerName) { return getServer().kick(playerName, "test", "kicked."); } /** * Kick a player by name. * * @param playerName The name of the player to kick. * @param reason The reason the player is being kicked. * @param message The message to show the player. * * @return True if the player was found and kicked. */ public static boolean kick(String playerName, String reason, String message) { return getServer().kick(playerName, reason, message); } /** * Add a world to the server or get an existing one. * * @param name The name of the world. * * @return The world. */ public static MockWorld world(String name) { return getServer().world(name); } /** * Create a new instance of a mock plugin. The plugin * returned is already enabled. * * <p>The plugins version is "v0".</p> * * @param name The name of the plugin. * * @return The {@code MockPlugin} instance. */ public static MockPlugin mockPlugin(String name) { return new MockPlugin(name).enable(); } /** * Instantiate and init a non-mock Bukkit plugin. * * <p>The plugin is initialized without commands. The returned * instance is not yet enabled.</p> * * @param name The name to initialize the plugin with. * @param version The version to initialize the plugin with. * @param pluginClass The plugin class. * * @param <T> The plugin type. * * @return The plugin instance. */ public static <T extends JavaPlugin> T initPlugin(String name, String version, Class<T> pluginClass) { init(); PluginDescriptionFile descriptionFile = new PluginDescriptionFile(name, version, ""); Map<String, Object> descriptionMap = new HashMap<>(10); descriptionMap.put("version", version); descriptionMap.put("name", name); descriptionMap.put("main", pluginClass.getName()); descriptionMap.put("commands", new HashMap(0)); try { Method method = descriptionFile.getClass().getDeclaredMethod("loadMap", Map.class); method.setAccessible(true); method.invoke(descriptionFile, descriptionMap); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } T plugin; // instantiate plugin try { Constructor<T> constructor = pluginClass.getDeclaredConstructor( JavaPluginLoader.class, PluginDescriptionFile.class, File.class, File.class); constructor.setAccessible(true); plugin = constructor.newInstance(new JavaPluginLoader(Bukkit.getServer()), descriptionFile, new File(""), new File("")); try { plugin = pluginClass.newInstance(); } catch (IllegalStateException ignore) {} } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new RuntimeException(e); } return plugin; } /** * Enable a plugin instance. * * @param plugin The plugin to enable. */ public static void enablePlugin(Plugin plugin) { getServer().getPluginManager().enablePlugin(plugin); } /** * Disable a plugin instance. * * @param plugin The plugin to disable. */ public static void disablePlugin(Plugin plugin) { getServer().getPluginManager().disablePlugin(plugin); } /** * Simulate a click on a slot in the players current inventory view. * * @param player The player to simulate a click for. * @param type The slot type. * @param rawSlotIndex The raw slot index of the click. * @param clickType The click type. * @param action The inventory action. */ public static void viewClick(Player player, SlotType type, int rawSlotIndex, ClickType clickType, InventoryAction action) { InventoryView view = player.getOpenInventory(); if (view == null) throw new AssertionError("Cannot click inventory view because the player " + "does not have an open inventory view."); if (!(view instanceof MockInventoryView)) throw new AssertionError("Cannot click inventory view because its not an " + "instance of MockInventoryView."); MockInventoryView mockView = (MockInventoryView)view; mockView.click(type, rawSlotIndex, clickType, action); pause(1); } }
package ca.eandb.jdcp.worker; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.jnlp.UnavailableServiceException; import ca.eandb.jdcp.job.TaskDescription; import ca.eandb.jdcp.job.TaskWorker; import ca.eandb.jdcp.remote.AuthenticationService; import ca.eandb.jdcp.remote.JobService; import ca.eandb.util.UnexpectedException; import ca.eandb.util.classloader.ClassLoaderStrategy; import ca.eandb.util.classloader.StrategyClassLoader; import ca.eandb.util.jobs.Job; import ca.eandb.util.progress.PermanentProgressMonitor; import ca.eandb.util.progress.ProgressMonitor; import ca.eandb.util.rmi.Serialized; /** * A job that processes tasks for a parallelizable job from a remote * <code>JobServiceMaster<code>. This class may potentially use multiple * threads to process tasks. * @author bkimmel */ public final class ThreadServiceWorkerJob implements Job { /** * Initializes the address of the master and the amount of time to idle * when no task is available. * @param masterHost The URL of the master. * @param idleTime The time (in seconds) to idle when no task is * available. * @param maxConcurrentWorkers The maximum number of concurrent worker * threads to allow. * @param executor The <code>Executor</code> to use to process tasks. */ public ThreadServiceWorkerJob(String masterHost, int idleTime, int maxConcurrentWorkers, Executor executor) { assert(maxConcurrentWorkers > 0); this.masterHost = masterHost; this.idleTime = idleTime; this.executor = executor; this.maxConcurrentWorkers = maxConcurrentWorkers; } /* (non-Javadoc) * @see ca.eandb.util.jobs.Job#go(ca.eandb.util.progress.ProgressMonitor) */ public boolean go(ProgressMonitor monitor) { try { monitor.notifyIndeterminantProgress(); monitor.notifyStatusChanged("Looking up master..."); this.registry = LocateRegistry.getRegistry(this.masterHost); this.initializeService(); this.initializeWorkers(maxConcurrentWorkers, monitor); while (!monitor.isCancelPending()) { Worker worker = this.workerQueue.take(); monitor.notifyStatusChanged("Queueing worker process..."); this.executor.execute(worker); } monitor.notifyStatusChanged("Cancelled."); } catch (Exception e) { monitor.notifyStatusChanged("Exception: " + e.toString()); System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } finally { monitor.notifyCancelled(); } return false; } /** * Initializes the worker queue with the specified number of workers. * @param numWorkers The number of workers to create. * @param parentMonitor The <code>ProgressMonitor</code> to use to create * child <code>ProgressMonitor</code>s for each <code>Worker</code>. */ private void initializeWorkers(int numWorkers, ProgressMonitor parentMonitor) { for (int i = 0; i < numWorkers; i++) { String title = String.format("Worker (%d)", i + 1); ProgressMonitor monitor = new PermanentProgressMonitor(parentMonitor.createChildProgressMonitor(title)); workerQueue.add(new Worker(monitor)); } } /** * Attempt to initialize a connection to the master service. * @return A value indicating whether the operation succeeded. */ private boolean initializeService() { try { AuthenticationService authService = (AuthenticationService) this.registry.lookup("AuthenticationService"); this.service = authService.authenticate("guest", ""); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * An entry in the <code>TaskWorker</code> cache. * @author bkimmel */ private static class WorkerCacheEntry { /** * Initializes the cache entry. * @param jobId The <code>UUID</code> of the job that the * <code>TaskWorker</code> processes tasks for. */ public WorkerCacheEntry(UUID jobId) { this.jobId = jobId; this.workerGuard.writeLock().lock(); } /** * Returns a value indicating if this <code>WorkerCacheEntry</code> * is to be used for the job with the specified <code>UUID</code>. * @param jobId The job's <code>UUID</code> to test. * @return A value indicating if this <code>WorkerCacheEntry</code> * applies to the specified job. */ public boolean matches(UUID jobId) { return this.jobId.equals(jobId); } /** * Sets the <code>TaskWorker</code> to use. This method may only be * called once. * @param worker The <code>TaskWorker</code> to use for matching * jobs. */ public synchronized void setWorker(TaskWorker worker) { /* Set the worker. */ this.worker = worker; /* Release the lock. */ this.workerGuard.writeLock().unlock(); } /** * Gets the <code>TaskWorker</code> to use to process tasks for the * matching job. This method will wait for <code>setWorker</code> * to be called if it has not yet been called. * @return The <code>TaskWorker</code> to use to process tasks for * the matching job. * @see {@link #setWorker(TaskWorker)}. */ public TaskWorker getWorker() { this.workerGuard.readLock().lock(); TaskWorker worker = this.worker; this.workerGuard.readLock().unlock(); return worker; } /** * The <code>UUID</code> of the job that the <code>TaskWorker</code> * processes tasks for. */ private final UUID jobId; /** * The cached <code>TaskWorker</code>. */ private TaskWorker worker; /** * The <code>ReadWriteLock</code> to use before reading from or writing * to the <code>worker</code> field. */ private final ReadWriteLock workerGuard = new ReentrantReadWriteLock(); } /** * Searches for the <code>WorkerCacheEntry</code> matching the job with the * specified <code>UUID</code>. * @param jobId The <code>UUID</code> of the job whose * <code>WorkerCacheEntry</code> to search for. * @return The <code>WorkerCacheEntry</code> corresponding to the job with * the specified <code>UUID</code>, or <code>null</code> if the * no such entry exists. */ private WorkerCacheEntry getCacheEntry(UUID jobId) { assert(jobId != null); synchronized (this.workerCache) { Iterator<WorkerCacheEntry> i = this.workerCache.iterator(); /* Search for the worker for the specified job. */ while (i.hasNext()) { WorkerCacheEntry entry = i.next(); if (entry.matches(jobId)) { /* Remove the entry and re-insert it at the end of the list. * This will ensure that when an item is removed from the list, * the item that is removed will always be the least recently * used. */ i.remove(); this.workerCache.add(entry); return entry; } } /* cache miss */ return null; } } /** * Removes the specified entry from the task worker cache. * @param entry The <code>WorkerCacheEntry</code> to remove. */ private void removeCacheEntry(WorkerCacheEntry entry) { assert(entry != null); synchronized (this.workerCache) { this.workerCache.remove(entry); } } /** * Removes least recently used entries from the task worker cache until * there are at most <code>this.maxCachedWorkers</code> entries. */ private void removeOldCacheEntries() { synchronized (this.workerCache) { /* If the cache has exceeded capacity, then remove the least * recently used entry. */ assert(this.maxCachedWorkers > 0); while (this.workerCache.size() > this.maxCachedWorkers) { this.workerCache.remove(0); } } } /** * Obtains the task worker to process tasks for the job with the specified * <code>UUID</code>. * @param jobId The <code>UUID</code> of the job to obtain the task worker * for. * @return The <code>TaskWorker</code> to process tasks for the job with * the specified <code>UUID</code>, or <code>null</code> if the job * is invalid or has already been completed. * @throws RemoteException * @throws ClassNotFoundException */ private TaskWorker getTaskWorker(UUID jobId) throws RemoteException, ClassNotFoundException { WorkerCacheEntry entry = null; boolean hit; synchronized (this.workerCache) { /* First try to get the worker from the cache. */ entry = this.getCacheEntry(jobId); hit = (entry != null); /* If there was no matching cache entry, then add a new entry to * the cache. */ if (!hit) { entry = new WorkerCacheEntry(jobId); this.workerCache.add(entry); } } if (hit) { /* We found a cache entry, so get the worker from that entry. */ return entry.getWorker(); } else { /* cache miss */ /* The task worker was not in the cache, so use the service to * obtain the task worker. */ Serialized<TaskWorker> envelope = this.service.getTaskWorker(jobId); ClassLoaderStrategy strategy; try { strategy = new PersistenceCachingJobServiceClassLoaderStrategy(service, jobId); } catch (UnavailableServiceException e) { strategy = new FileCachingJobServiceClassLoaderStrategy(service, jobId, "./worker"); } ClassLoader loader = new StrategyClassLoader(strategy, ThreadServiceWorkerJob.class.getClassLoader()); TaskWorker worker = envelope.deserialize(loader); entry.setWorker(worker); /* If we couldn't get a worker from the service, then don't keep * the cache entry. */ if (worker == null) { this.removeCacheEntry(entry); } /* Clean up the cache. */ this.removeOldCacheEntries(); return worker; } } /** * Used to process tasks in threads. * @author bkimmel */ private class Worker implements Runnable { /** * Initializes the progress monitor to report to. * @param monitor The <code>ProgressMonitor</code> to report * the progress of the task to. */ public Worker(ProgressMonitor monitor) { this.monitor = monitor; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { try { this.monitor.notifyIndeterminantProgress(); this.monitor.notifyStatusChanged("Requesting task..."); if (service != null) { TaskDescription taskDesc = service.requestTask(); if (taskDesc != null) { UUID jobId = taskDesc.getJobId(); if (jobId != null) { this.monitor.notifyStatusChanged("Obtaining task worker..."); TaskWorker worker; try { worker = getTaskWorker(jobId); } catch (ClassNotFoundException e) { service.reportException(jobId, 0, e); worker = null; } if (worker == null) { this.monitor.notifyStatusChanged("Could not obtain worker..."); this.monitor.notifyCancelled(); return; } this.monitor.notifyStatusChanged("Performing task..."); ClassLoader loader = worker.getClass().getClassLoader(); Object results; try { Object task = taskDesc.getTask().deserialize(loader); results = worker.performTask(task, monitor); } catch (Exception e) { service.reportException(jobId, taskDesc.getTaskId(), e); results = null; } this.monitor.notifyStatusChanged("Submitting task results..."); if (results != null) { service.submitTaskResults(jobId, taskDesc.getTaskId(), new Serialized<Object>(results)); } } else { try { int seconds = (Integer) taskDesc.getTask().deserialize(); this.idle(seconds); } catch (ClassNotFoundException e) { throw new UnexpectedException(e); } } } else { this.idle(); } this.monitor.notifyComplete(); } else { this.monitor.notifyStatusChanged("No service at " + ThreadServiceWorkerJob.this.masterHost); this.waitForService(); this.monitor.notifyCancelled(); } } catch (RemoteException e) { System.err.println("Remote exception: " + e.toString()); e.printStackTrace(); this.monitor.notifyStatusChanged("Failed to communicate with master."); this.waitForService(); this.monitor.notifyCancelled(); } finally { workerQueue.add(this); } } /** * Blocks until a successful attempt is made to reconnect to the * service. This method will idle for some time between attempts. */ private void waitForService() { synchronized (registry) { while (!initializeService()) { this.idle(); } } } /** * Idles for a period of time before finishing the task. */ private void idle() { idle(idleTime); } /** * Idles for the specified number of seconds. * @param seconds The number of seconds to idle for. */ private void idle(int seconds) { monitor.notifyStatusChanged("Idling..."); for (int i = 0; i < seconds; i++) { if (!monitor.notifyProgress(i, seconds)) { monitor.notifyCancelled(); } this.sleep(); } monitor.notifyProgress(seconds, seconds); monitor.notifyComplete(); } /** * Sleeps for one second. */ private void sleep() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } /** * The <code>ProgressMonitor</code> to report to. */ private final ProgressMonitor monitor; } /** The URL of the master. */ private final String masterHost; /** * The amount of time (in seconds) to idle when no task is available. */ private final int idleTime; /** The <code>Executor</code> to use to process tasks. */ private final Executor executor; /** * The <code>Registry</code> to obtain the service from. */ private Registry registry = null; /** * The <code>JobService</code> to obtain tasks from and submit * results to. */ private JobService service = null; /** The maximum number of workers that may be executing simultaneously. */ private final int maxConcurrentWorkers; /** A queue containing the available workers. */ private final BlockingQueue<Worker> workerQueue = new LinkedBlockingQueue<Worker>(); /** * A list of recently used <code>TaskWorker</code>s and their associated * job's <code>UUID</code>s, in order from least recently used to most * recently used. */ private final List<WorkerCacheEntry> workerCache = new LinkedList<WorkerCacheEntry>(); /** * The maximum number of <code>TaskWorker</code>s to retain in the cache. */ private final int maxCachedWorkers = 5; }
package org.innovateuk.ifs.management.controller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.innovateuk.ifs.BaseController; import org.innovateuk.ifs.application.form.ApplicationForm; import org.innovateuk.ifs.application.populator.ApplicationModelPopulator; import org.innovateuk.ifs.application.populator.ApplicationPrintPopulator; import org.innovateuk.ifs.application.populator.OpenApplicationFinanceSectionModelPopulator; import org.innovateuk.ifs.application.resource.AppendixResource; import org.innovateuk.ifs.application.resource.ApplicationResource; import org.innovateuk.ifs.application.resource.FormInputResponseFileEntryResource; import org.innovateuk.ifs.application.resource.SectionResource; import org.innovateuk.ifs.application.service.ApplicationService; import org.innovateuk.ifs.application.service.AssessorFeedbackRestService; import org.innovateuk.ifs.application.service.CompetitionService; import org.innovateuk.ifs.application.service.SectionService; import org.innovateuk.ifs.application.viewmodel.OpenFinanceSectionViewModel; import org.innovateuk.ifs.commons.error.exception.ObjectNotFoundException; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.commons.security.UserAuthenticationService; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.controller.ValidationHandler; import org.innovateuk.ifs.file.controller.viewmodel.OptionalFileDetailsViewModel; import org.innovateuk.ifs.file.resource.FileEntryResource; import org.innovateuk.ifs.file.service.FileEntryRestService; import org.innovateuk.ifs.form.resource.FormInputResource; import org.innovateuk.ifs.form.resource.FormInputResponseResource; import org.innovateuk.ifs.form.service.FormInputResponseService; import org.innovateuk.ifs.form.service.FormInputService; import org.innovateuk.ifs.populator.OrganisationDetailsModelPopulator; import org.innovateuk.ifs.user.resource.ProcessRoleResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.resource.UserRoleType; import org.innovateuk.ifs.user.service.ProcessRoleService; import org.innovateuk.ifs.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.MultiValueMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.innovateuk.ifs.competition.resource.CompetitionStatus.ASSESSOR_FEEDBACK; import static org.innovateuk.ifs.competition.resource.CompetitionStatus.FUNDERS_PANEL; import static org.innovateuk.ifs.controller.ErrorToObjectErrorConverterFactory.toField; import static org.innovateuk.ifs.controller.FileUploadControllerUtils.getMultipartFileBytes; import static org.innovateuk.ifs.file.controller.FileDownloadControllerUtils.getFileResponseEntity; import static org.innovateuk.ifs.util.MapFunctions.asMap; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; /** * Handles the Competition Management Application overview page (and associated actions). */ @Controller @RequestMapping("/competition/{competitionId}/application") @PreAuthorize("hasAnyAuthority('applicant', 'project_finance', 'comp_admin')") public class CompetitionManagementApplicationController extends BaseController { @SuppressWarnings("unused") private static final Log LOG = LogFactory.getLog(CompetitionManagementApplicationController.class); enum ApplicationOverviewOrigin { ALL_APPLICATIONS("/competition/{competitionId}/applications/all"), SUBMITTED_APPLICATIONS("/competition/{competitionId}/applications/submitted"), MANAGE_APPLICATIONS("/assessment/competition/{competitionId}"), FUNDING_APPLICATIONS("/competition/{competitionId}/funding"), APPLICATION_PROGRESS("/competition/{competitionId}/application/{applicationId}/assessors"); private String baseOriginUrl; ApplicationOverviewOrigin(String baseOriginUrl) { this.baseOriginUrl = baseOriginUrl; } public String getBaseOriginUrl() { return baseOriginUrl; } } @Autowired private FormInputResponseService formInputResponseService; @Autowired private FileEntryRestService fileEntryRestService; @Autowired private OrganisationDetailsModelPopulator organisationDetailsModelPopulator; @Autowired private OpenApplicationFinanceSectionModelPopulator openFinanceSectionSectionModelPopulator; @Autowired private AssessorFeedbackRestService assessorFeedbackRestService; @Autowired private UserService userService; @Autowired protected ApplicationModelPopulator applicationModelPopulator; @Autowired protected CompetitionService competitionService; @Autowired protected SectionService sectionService; @Autowired protected ProcessRoleService processRoleService; @Autowired protected ApplicationPrintPopulator applicationPrintPopulator; @Autowired protected UserAuthenticationService userAuthenticationService; @Autowired protected FormInputService formInputService; @Autowired protected ApplicationService applicationService; public static String buildOriginQueryString(ApplicationOverviewOrigin origin, MultiValueMap<String, String> queryParams) { return UriComponentsBuilder.newInstance() .queryParam("origin", origin.toString()) .queryParams(queryParams) .build() .encode() .toUriString(); } @RequestMapping(value = "/{applicationId}", method = GET) public String displayApplicationOverview(@PathVariable("applicationId") final Long applicationId, @PathVariable("competitionId") final Long competitionId, @ModelAttribute("form") ApplicationForm form, @RequestParam(value = "origin", defaultValue = "ALL_APPLICATIONS") String origin, @RequestParam MultiValueMap<String, String> queryParams, Model model, HttpServletRequest request ) { return validateApplicationAndCompetitionIds(applicationId, competitionId, (application) -> { UserResource user = getLoggedUser(request); form.setAdminMode(true); List<FormInputResponseResource> responses = formInputResponseService.getByApplication(applicationId); // so the mode is viewonly application.enableViewMode(); CompetitionResource competition = competitionService.getById(application.getCompetition()); applicationModelPopulator.addApplicationAndSections(application, competition, user.getId(), Optional.empty(), Optional.empty(), model, form); organisationDetailsModelPopulator.populateModel(model, application.getId()); // Having to pass getImpersonateOrganisationId here because look at the horrible code inside addOrganisationAndUserFinanceDetails with impersonation org id :( applicationModelPopulator.addOrganisationAndUserFinanceDetails(competition.getId(), applicationId, user, model, form, form.getImpersonateOrganisationId()); addAppendices(applicationId, responses, model); model.addAttribute("form", form); model.addAttribute("applicationReadyForSubmit", false); model.addAttribute("isCompManagementDownload", true); OptionalFileDetailsViewModel assessorFeedbackViewModel = getAssessorFeedbackViewModel(application, competition); model.addAttribute("assessorFeedback", assessorFeedbackViewModel); model.addAttribute("backUrl", buildBackUrl(origin, applicationId, competitionId, queryParams)); return "competition-mgt-application-overview"; }); } private String buildBackUrl(String origin, Long applicationId, Long competitionId, MultiValueMap<String, String> queryParams) { String baseUrl = ApplicationOverviewOrigin.valueOf(origin).getBaseOriginUrl(); queryParams.remove("origin"); return UriComponentsBuilder.fromPath(baseUrl) .queryParams(queryParams) .buildAndExpand(asMap( "competitionId", competitionId, "applicationId", applicationId )) .encode() .toUriString(); } @RequestMapping(value = "/{applicationId}/assessorFeedback", method = GET) @ResponseBody public ResponseEntity<ByteArrayResource> downloadAssessorFeedbackFile( @PathVariable("applicationId") final Long applicationId) { final ByteArrayResource resource = assessorFeedbackRestService.getAssessorFeedbackFile(applicationId).getSuccessObjectOrThrowException(); final FileEntryResource fileDetails = assessorFeedbackRestService.getAssessorFeedbackFileDetails(applicationId).getSuccessObjectOrThrowException(); return getFileResponseEntity(resource, fileDetails); } @RequestMapping(value = "/{applicationId}", params = "uploadAssessorFeedback", method = POST) public String uploadAssessorFeedbackFile( @PathVariable("competitionId") final Long competitionId, @PathVariable("applicationId") final Long applicationId, @RequestParam(value = "origin", defaultValue = "ALL_APPLICATIONS") String origin, @RequestParam MultiValueMap<String, String> queryParams, @ModelAttribute("form") ApplicationForm applicationForm, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, Model model, HttpServletRequest request) { Supplier<String> failureView = () -> displayApplicationOverview(applicationId, competitionId, applicationForm, origin, queryParams, model, request); return validationHandler.failNowOrSucceedWith(failureView, () -> { MultipartFile file = applicationForm.getAssessorFeedback(); RestResult<FileEntryResource> uploadFileResult = assessorFeedbackRestService.addAssessorFeedbackDocument(applicationId, file.getContentType(), file.getSize(), file.getOriginalFilename(), getMultipartFileBytes(file)); return validationHandler. addAnyErrors(uploadFileResult, toField("assessorFeedback")). failNowOrSucceedWith(failureView, () -> redirectToApplicationOverview(competitionId, applicationId)); }); } @RequestMapping(value = "/{applicationId}", params = "removeAssessorFeedback", method = POST) public String removeAssessorFeedbackFile(@PathVariable("competitionId") final Long competitionId, @PathVariable("applicationId") final Long applicationId, @RequestParam(value = "origin", defaultValue = "ALL_APPLICATIONS") String origin, @RequestParam MultiValueMap<String, String> queryParams, Model model, @ModelAttribute("form") ApplicationForm applicationForm, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, HttpServletRequest request) { Supplier<String> failureView = () -> displayApplicationOverview(applicationId, competitionId, applicationForm, origin, queryParams, model, request); return validationHandler.failNowOrSucceedWith(failureView, () -> { RestResult<Void> removeFileResult = assessorFeedbackRestService.removeAssessorFeedbackDocument(applicationId); return validationHandler. addAnyErrors(removeFileResult, toField("assessorFeedback")). failNowOrSucceedWith(failureView, () -> redirectToApplicationOverview(competitionId, applicationId)); }); } @RequestMapping(value = "/{applicationId}/finances/{organisationId}", method = RequestMethod.GET) public String displayApplicationFinances(@PathVariable("applicationId") final Long applicationId, @PathVariable("competitionId") final Long competitionId, @PathVariable("organisationId") final Long organisationId, @ModelAttribute("form") ApplicationForm form, Model model, BindingResult bindingResult ) throws ExecutionException, InterruptedException { return validateApplicationAndCompetitionIds(applicationId, competitionId, (application) -> { SectionResource financeSection = sectionService.getFinanceSection(application.getCompetition()); List<SectionResource> allSections = sectionService.getAllByCompetitionId(application.getCompetition()); List<FormInputResponseResource> responses = formInputResponseService.getByApplication(applicationId); UserResource impersonatingUser; try { impersonatingUser = getImpersonateUserByOrganisationId(organisationId, form, applicationId); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } // so the mode is viewonly form.setAdminMode(true); application.enableViewMode(); model.addAttribute("responses", formInputResponseService.mapFormInputResponsesToFormInput(responses)); model.addAttribute("applicationReadyForSubmit", false); //TODO - INFUND-7498 - ViewModel is changed so template should be changed as well OpenFinanceSectionViewModel openFinanceSectionViewModel = (OpenFinanceSectionViewModel) openFinanceSectionSectionModelPopulator.populateModel(form, model, application, financeSection, impersonatingUser, bindingResult, allSections, organisationId); model.addAttribute("model", openFinanceSectionViewModel); return "comp-mgt-application-finances"; }); } private UserResource getImpersonateUserByOrganisationId(@PathVariable("organisationId") Long organisationId, @ModelAttribute("form") ApplicationForm form, Long applicationId) throws InterruptedException, ExecutionException { UserResource user; form.setImpersonateOrganisationId(Long.valueOf(organisationId)); List<ProcessRoleResource> processRoles = processRoleService.findProcessRolesByApplicationId(applicationId); Optional<Long> userId = processRoles.stream() .filter(p -> p.getOrganisationId().equals(Long.valueOf(organisationId))) .map(p -> p.getUser()) .findAny(); if (!userId.isPresent()) { LOG.error("Found no user to impersonate."); return null; } user = userService.retrieveUserById(userId.get()).getSuccessObject(); return user; } @RequestMapping(value = "/{applicationId}/forminput/{formInputId}/download", method = GET) public @ResponseBody ResponseEntity<ByteArrayResource> downloadQuestionFile( @PathVariable("applicationId") final Long applicationId, @PathVariable("formInputId") final Long formInputId, HttpServletRequest request) throws ExecutionException, InterruptedException { final UserResource user = userAuthenticationService.getAuthenticatedUser(request); ProcessRoleResource processRole; if (user.hasRole(UserRoleType.COMP_ADMIN)) { long processRoleId = formInputResponseService.getByFormInputIdAndApplication(formInputId, applicationId).getSuccessObjectOrThrowException().get(0).getUpdatedBy(); processRole = processRoleService.getById(processRoleId).get(); } else { processRole = processRoleService.findProcessRole(user.getId(), applicationId); } final ByteArrayResource resource = formInputResponseService.getFile(formInputId, applicationId, processRole.getId()).getSuccessObjectOrThrowException(); final FormInputResponseFileEntryResource fileDetails = formInputResponseService.getFileDetails(formInputId, applicationId, processRole.getId()).getSuccessObjectOrThrowException(); return getFileResponseEntity(resource, fileDetails.getFileEntryResource()); } /** * Printable version of the application */ @RequestMapping(value = "/{applicationId}/print") public String printManagementApplication(@PathVariable("applicationId") Long applicationId, @PathVariable("competitionId") Long competitionId, Model model, HttpServletRequest request) { return validateApplicationAndCompetitionIds(applicationId, competitionId, (application) -> applicationPrintPopulator.print(applicationId, model, request)); } private void addAppendices(Long applicationId, List<FormInputResponseResource> responses, Model model) { final List<AppendixResource> appendices = responses.stream().filter(fir -> fir.getFileEntry() != null). map(fir -> { FormInputResource formInputResource = formInputService.getOne(fir.getFormInput()); FileEntryResource fileEntryResource = fileEntryRestService.findOne(fir.getFileEntry()).getSuccessObject(); String title = formInputResource.getDescription() != null ? formInputResource.getDescription() : fileEntryResource.getName(); return new AppendixResource(applicationId, formInputResource.getId(), title, fileEntryResource); }). collect(Collectors.toList()); model.addAttribute("appendices", appendices); } private OptionalFileDetailsViewModel getAssessorFeedbackViewModel(ApplicationResource application, CompetitionResource competition) { boolean readonly = !asList(FUNDERS_PANEL, ASSESSOR_FEEDBACK).contains(competition.getCompetitionStatus()); Long assessorFeedbackFileEntry = application.getAssessorFeedbackFileEntry(); if (assessorFeedbackFileEntry != null) { RestResult<FileEntryResource> fileEntry = assessorFeedbackRestService.getAssessorFeedbackFileDetails(application.getId()); return OptionalFileDetailsViewModel.withExistingFile(fileEntry.getSuccessObjectOrThrowException(), readonly); } else { return OptionalFileDetailsViewModel.withNoFile(readonly); } } private String redirectToApplicationOverview(Long competitionId, Long applicationId) { return "redirect:/competition/" + competitionId + "/application/" + applicationId; } private String validateApplicationAndCompetitionIds(Long applicationId, Long competitionId, Function<ApplicationResource, String> success) { ApplicationResource application = applicationService.getById(applicationId); if (application.getCompetition().equals(competitionId)) { return success.apply(application); } else { throw new ObjectNotFoundException(); } } }
package com.jmex.model.XMLparser; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.FloatBuffer; import java.util.HashMap; import java.util.Hashtable; import java.util.Stack; import java.util.logging.Level; import com.jme.animation.SpatialTransformer; import com.jme.bounding.BoundingBox; import com.jme.bounding.BoundingSphere; import com.jme.bounding.BoundingVolume; import com.jme.bounding.OrientedBoundingBox; import com.jme.image.Image; import com.jme.image.Texture; import com.jme.light.Light; import com.jme.light.PointLight; import com.jme.light.SpotLight; import com.jme.math.FastMath; import com.jme.math.Matrix3f; import com.jme.math.Quaternion; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.Controller; import com.jme.scene.Geometry; import com.jme.scene.Node; import com.jme.scene.Spatial; import com.jme.scene.TriMesh; import com.jme.scene.batch.GeomBatch; import com.jme.scene.batch.TriangleBatch; import com.jme.scene.lod.AreaClodMesh; import com.jme.scene.lod.ClodMesh; import com.jme.scene.lod.CollapseRecord; import com.jme.scene.shape.Box; import com.jme.scene.state.AlphaState; import com.jme.scene.state.CullState; import com.jme.scene.state.LightState; import com.jme.scene.state.MaterialState; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; import com.jme.scene.state.WireframeState; import com.jme.system.DisplaySystem; import com.jme.system.JmeException; import com.jme.util.LoggingSystem; import com.jme.util.TextureManager; import com.jme.util.geom.BufferUtils; import com.jmex.model.JointMesh; import com.jmex.model.animation.JointController; import com.jmex.model.animation.KeyframeController; import com.jmex.terrain.TerrainBlock; import com.jmex.terrain.TerrainPage; public class JmeBinaryReader { /** * Holds a list of objects that have encountered a being_tag but not an end_tag yet. */ private Stack<Object> objStack=new Stack<Object>(); /** * Holds already loaded objects that are to be shared at various locations in the file. */ private Hashtable<String, Object> shares=new Hashtable<String, Object>(); /** * Holds the attributes of a tag for processing. */ private HashMap<String, Object> attributes=new HashMap<String, Object>(); /** * Holds properties that modify how JmeBinaryReader loads a file. */ private HashMap<String, Object> properties=new HashMap<String, Object>(); private Hashtable<Object, Object> repeatShare=new Hashtable<Object, Object>(); /** * The scene that was last loaded. */ private Node myScene; private Renderer renderer; private DataInputStream myIn; private final static boolean DEBUG=false; /** * Constructs a new JmeBinaryReader. This must be called after a DisplaySystem * has been initialized. */ public JmeBinaryReader(){ renderer=DisplaySystem.getDisplaySystem().getRenderer(); } /** * Reads the binaryJme InputStream and saves it to storeNode * @param storeNode Place to save the jME Scene * @param binaryJme InputStream with the jME Scene * @return The given storeNode * @throws IOException If anything wierd goes on while reading. */ public Node loadBinaryFormat(Node storeNode, InputStream binaryJme) throws IOException { if (DEBUG) System.out.println("Begining read"); clearValues(); myScene=storeNode; myIn=new DataInputStream(binaryJme); readHeader(); objStack.push(storeNode); // This will be pop'd off when </scene> is encountered and saved into myScene byte flag=myIn.readByte(); while (flag!=BinaryFormatConstants.END_FILE){ if (flag==BinaryFormatConstants.BEGIN_TAG) readBegining(); else if (flag==BinaryFormatConstants.END_TAG) readEnd(); else{ throw new IOException("Unknown flag:" + flag); } flag=myIn.readByte(); } if (DEBUG) System.out.println("Done reading"); clearValues(); return myScene; } private void clearValues() { repeatShare.clear(); objStack.clear(); shares.clear(); attributes.clear(); myIn=null; } /** * Reads the binaryJme InputStream to * convert jME's binary format to a Node. * @param binaryJme The binary format jME scene * @return A Node representing the binary file * @throws IOException If anything wierd goes on while reading */ public Node loadBinaryFormat(InputStream binaryJme) throws IOException { return loadBinaryFormat(new Node("XML loaded scene"),binaryJme); } /** * Processes a BEGIN_TAG flag, which signals that a tag has begun. Attributes for the * tag are read, and if needed an object is pushed on the stack * @throws IOException If anything wierd goes on in reading */ private void readBegining() throws IOException { String tagName=myIn.readUTF().trim(); if (DEBUG) System.out.println("Reading tagName:" + tagName); readInObjects(attributes); if (tagName.equals("scene")){ // s.push(new Node("XML Scene")); Already on stack } else if (tagName.equals("node")){ objStack.push(processSpatial(new Node((String) attributes.get("name")),attributes)); } else if (tagName.equals("terrainpage")){ objStack.push(processTerrainPage(new TerrainPage((String) attributes.get("name")),attributes)); } else if (tagName.equals("repeatobject")){ objStack.push(repeatShare.get(attributes.get("ident"))); } else if (tagName.equals("materialstate")){ objStack.push(buildMaterial(attributes)); } else if (tagName.equals("alphastate")){ objStack.push(buildAlphaState(attributes)); } else if (tagName.equals("texturestate")){ objStack.push(renderer.createTextureState()); } else if (tagName.equals("texture")){ Texture t=buildTexture(attributes); if (t!=null){ TextureState ts=(TextureState) objStack.pop(); Integer retrieveNumber=(Integer)attributes.get("texnum"); int textureNum=(retrieveNumber==null ? 0 : retrieveNumber.intValue()); ts.setTexture(t,textureNum); objStack.push(ts); } } else if (tagName.equals("clod")){ objStack.push(processSpatial(new ClodMesh((String) attributes.get("name")),attributes)); } else if (tagName.equals("obb")){ objStack.push(processOBB(new OrientedBoundingBox(),attributes)); } else if (tagName.equals("boundsphere")){ objStack.push(processBSphere(new BoundingSphere(),attributes)); } else if (tagName.equals("boundbox")){ objStack.push(processBBox(new BoundingBox(),attributes)); } else if (tagName.equals("terrainblock")){ objStack.push(processTerrainBlock(new TerrainBlock((String) attributes.get("name")),attributes)); } else if (tagName.equals("areaclod")){ objStack.push(processAreaClod(new AreaClodMesh((String) attributes.get("name")),attributes)); } else if (tagName.equals("clodrecords")){ objStack.push(new CollapseRecord[((Integer)attributes.get("numrec")).intValue()]); } else if (tagName.equals("crecord")){ writeCollapseRecord(attributes); } else if (tagName.equals("mesh")){ TriMesh t = new TriMesh((String) attributes.get("name")); t.getBatch(0).setIndexBuffer(BufferUtils.createIntBuffer(0)); t.getBatch(0).setNormalBuffer(BufferUtils.createFloatBuffer(0)); t.getBatch(0).setVertexBuffer(BufferUtils.createFloatBuffer(0)); t.getBatch(0).setColorBuffer(null); t.getBatch(0).setTextureBuffer(null, 0); objStack.push(processSpatial(t, attributes)); }else if (tagName.startsWith("batch")) { if(!"batch0".equals(tagName)) { Object o = objStack.pop(); if(o instanceof GeomBatch) { o = objStack.pop(); } Geometry geo=(Geometry)o; GeomBatch batch = null; if(geo instanceof TriMesh) { batch = new TriangleBatch(); ((TriangleBatch)batch).setIndexBuffer(BufferUtils.createIntBuffer(0)); } else { batch = new GeomBatch(); } batch.setNormalBuffer(BufferUtils.createFloatBuffer(0)); batch.setVertexBuffer(BufferUtils.createFloatBuffer(0)); batch.setColorBuffer(BufferUtils.createFloatBuffer(0)); batch.setTextureBuffer(BufferUtils.createFloatBuffer(0), 0); geo.addBatch(batch); objStack.push(geo); objStack.push(batch); } }else if (tagName.equals("vertex")){ Object o = objStack.pop(); GeomBatch batch = null; if(o instanceof Geometry) { Geometry geo=(Geometry) o; batch = geo.getBatch(0); } else if(o instanceof GeomBatch) { batch = (GeomBatch)o; } if (attributes.get("q3vert")!=null) batch.setVertexBuffer(BufferUtils.createFloatBuffer(decodeShortCompress((short[])attributes.get("q3vert")))); else batch.setVertexBuffer(BufferUtils.createFloatBuffer((Vector3f[]) attributes.get("data"))); objStack.push(o); } else if (tagName.equals("normal")){ Object o = objStack.pop(); GeomBatch batch = null; if(o instanceof Geometry) { Geometry geo=(Geometry) o; batch = geo.getBatch(0); } else if(o instanceof GeomBatch) { batch = (GeomBatch)o; } // FIXME: The reading/writing could skip the intermediate Vector3f[] array. if (attributes.get("q3norm")!=null) batch.setNormalBuffer(BufferUtils.createFloatBuffer(decodeLatLong((byte[])attributes.get("q3norm")))); else batch.setNormalBuffer(BufferUtils.createFloatBuffer((Vector3f[]) attributes.get("data"))); objStack.push(o); } else if (tagName.equals("texturecoords")){ Object o = objStack.pop(); GeomBatch batch = null; if(o instanceof Geometry) { Geometry geo=(Geometry) o; batch = geo.getBatch(0); } else if(o instanceof GeomBatch) { batch = (GeomBatch)o; } if (attributes.get("texindex")==null) batch.setTextureBuffer(BufferUtils.createFloatBuffer((Vector2f[]) attributes.get("data")),0); else batch.setTextureBuffer(BufferUtils.createFloatBuffer((Vector2f[]) attributes.get("data")),((Integer)attributes.get("texindex")).intValue()); objStack.push(o); } else if (tagName.equals("color")){ Object o = objStack.pop(); GeomBatch batch = null; if(o instanceof Geometry) { Geometry geo=(Geometry) o; batch = geo.getBatch(0); } else if(o instanceof GeomBatch) { batch = (GeomBatch)o; } batch.setColorBuffer((FloatBuffer) attributes.get("data")); objStack.push(o); } else if (tagName.equals("defcolor")){ Object o = objStack.pop(); Geometry geo = null; if(o instanceof Geometry) { geo=(Geometry) o; } else if(o instanceof GeomBatch) { geo = (Geometry)objStack.pop(); objStack.push(geo); } geo.setDefaultColor((ColorRGBA) attributes.get("data")); objStack.push(o); } else if (tagName.equals("index")){ Object o = objStack.pop(); TriangleBatch batch = null; if(o instanceof TriMesh) { TriMesh m = (TriMesh)o; batch = m.getBatch(0); } else if(o instanceof TriangleBatch) { batch = (TriangleBatch)o; } batch.setIndexBuffer(BufferUtils.createIntBuffer((int[]) attributes.get("data"))); if (batch.getIndexBuffer() == null) batch.setIndexBuffer(BufferUtils.createIntBuffer(0)); objStack.push(o); } else if (tagName.equals("origvertex")){ JointMesh jm=(JointMesh) objStack.pop(); jm.originalVertex=(Vector3f[]) attributes.get("data"); objStack.push(jm); } else if (tagName.equals("orignormal")){ JointMesh jm=(JointMesh) objStack.pop(); jm.originalNormal=(Vector3f[]) attributes.get("data"); objStack.push(jm); } else if (tagName.equals("jointindex")){ JointMesh jm=(JointMesh) objStack.pop(); jm.jointIndex=(int[]) attributes.get("data"); objStack.push(jm); } else if (tagName.equals("sharedtypes")){ // Do nothing, these have no attributes } else if (tagName.equals("primitive")){ objStack.push(processPrimitive(attributes)); } else if (tagName.equals("sharedrenderstate")){ objStack.push(new XMLSharedNode((String) attributes.get("ident"))); } else if (tagName.equals("sharedtrimesh")){ objStack.push(new XMLSharedNode((String) attributes.get("ident"))); } else if (tagName.equals("sharednode")){ objStack.push(new XMLSharedNode((String) attributes.get("ident"))); } else if (tagName.equals("publicobject")){ Object toAdd=shares.get(attributes.get("ident")); // if (toAdd==null){ // throw new JmeException("Unknown publicobject: " +shares.get(attributes.get("ident"))); objStack.push(toAdd); } else if (tagName.equals("xmlloadable")){ try { Class c=Class.forName((String) attributes.get("class")); if (!XMLloadable.class.isAssignableFrom(c)){ throw new JmeException("Given XML class must implement XMLloadable"); } XMLloadable x=(XMLloadable) c.newInstance(); Object o=x.loadFromXML((String) attributes.get("args")); if (o instanceof Spatial){ processSpatial((Spatial) o,attributes); } objStack.push(o); } catch (ClassNotFoundException e) { throw new JmeException("Unknown class type:" + attributes.get("class")); } catch (IllegalAccessException e) { throw new JmeException("XMLloadable classes must have a default() constructor: " + attributes.get("class")); } catch (InstantiationException e) { throw new JmeException("XMLloadable classes cannot be abstract: " + attributes.get("class")); } } else if (tagName.equals("jointcontroller")){ JointController jc=new JointController(((Integer)attributes.get("numJoints")).intValue()); processController(jc,attributes); jc.FPS = ((Float)attributes.get("fps")).floatValue(); objStack.push(jc); } else if (tagName.equals("keyframe")){ Integer jointIndex=(Integer) objStack.pop(); JointController jc=(JointController) objStack.pop(); if (attributes.get("rot")!=null) jc.setRotation(jointIndex.intValue(),((Float)attributes.get("time")).floatValue(),(Quaternion) attributes.get("rot")); if (attributes.get("trans")!=null) jc.setTranslation(jointIndex.intValue(),((Float)attributes.get("time")).floatValue(),(Vector3f) attributes.get("trans")); objStack.push(jc); objStack.push(jointIndex); } else if (tagName.equals("joint")){ JointController jc=(JointController) objStack.pop(); jc.parentIndex[((Integer)attributes.get("index")).intValue()]=((Integer)attributes.get("parentindex")).intValue(); // jc.localRefMatrix[((Integer)attributes.get("index")).intValue()].set((Matrix3f) attributes.get("localrot"),(Vector3f) attributes.get("localvec")); jc.localRefMatrix[((Integer)attributes.get("index")).intValue()].setRotation((Matrix3f) attributes.get("localrot")); jc.localRefMatrix[((Integer)attributes.get("index")).intValue()].setTranslation((Vector3f) attributes.get("localvec")); objStack.push(jc); objStack.push(attributes.get("index")); } else if (tagName.equals("jointmesh")){ objStack.push(processSpatial(new JointMesh((String) attributes.get("name")),attributes)); } else if (tagName.equals("keyframecontroller")){ KeyframeController kc=new KeyframeController(); kc.setActive(true); TriMesh parentMesh=(TriMesh) objStack.pop(); kc.setMorphingMesh(parentMesh); objStack.push(parentMesh); objStack.push(kc); } else if (tagName.equals("keyframepointintime")){ objStack.push(attributes.get("time")); // Store the current time on the stack objStack.push(new TriMesh()); } else if (tagName.equals("lightstate")){ objStack.push(buildLightState(attributes)); } else if (tagName.equals("spotlight")){ LightState parentLS=(LightState) objStack.pop(); parentLS.attach(buildSpotLight(attributes)); objStack.push(parentLS); } else if (tagName.equals("pointlight")){ LightState parentLS=(LightState) objStack.pop(); parentLS.attach(buildPointLight(attributes)); objStack.push(parentLS); } else if (tagName.equals("jmefile")){ if (attributes.get("file")!=null){ LoaderNode i=new LoaderNode("file "+(String) attributes.get("file")); i.loadFromFilePath((String)attributes.get("type"),(String) attributes.get("file"),properties); objStack.push(i); } else if (attributes.get("classloader")!=null){ LoaderNode i=new LoaderNode("classloader "+(String) attributes.get("classloader")); i.loadFromClassLoader((String)attributes.get("type"),(String) attributes.get("classloader"),properties); objStack.push(i); } else if (attributes.get("url")!=null){ LoaderNode i=new LoaderNode("classloader "+ attributes.get("url")); i.loadFromURLPath((String)attributes.get("type"),(URL) attributes.get("url"),properties); objStack.push(i); } } else if (tagName.equals("spatialtransformer")){ SpatialTransformer st=new SpatialTransformer(((Integer)attributes.get("numobjects")).intValue()); processController( st, attributes ); objStack.push(st); } else if (tagName.equals("stobj")){ objStack.push(attributes.get("obnum")); objStack.push(attributes.get("parnum")); objStack.push(new XMLSharedNode(null)); } else if (tagName.equals("spatialpointtime")){ objStack.push(attributes.get("time")); } else if (tagName.equals("sptscale")){ Float oldTime=(Float) objStack.pop(); float time=oldTime.floatValue(); int[] scaleIndexes=(int[]) attributes.get("index"); Vector3f[] scalevalues=(Vector3f[]) attributes.get("scalevalues"); SpatialTransformer st=(SpatialTransformer) objStack.pop(); if (scalevalues!=null) for (int i=0;i<scaleIndexes.length;i++) st.setScale(scaleIndexes[i],time,scalevalues[i]); objStack.push(st); objStack.push(oldTime); } else if (tagName.equals("sptrot")){ Float oldTime=(Float) objStack.pop(); float time=oldTime.floatValue(); int[] rotIndexes=(int[]) attributes.get("index"); Quaternion[] rotvalues=(Quaternion[]) attributes.get("rotvalues"); SpatialTransformer st=(SpatialTransformer) objStack.pop(); if (rotvalues!=null) for (int i=0;i<rotIndexes.length;i++) st.setRotation(rotIndexes[i],time,rotvalues[i]); objStack.push(st); objStack.push(oldTime); } else if (tagName.equals("spttrans")){ Float oldTime=(Float) objStack.pop(); float time=oldTime.floatValue(); int[] transIndexes=(int[]) attributes.get("index"); Vector3f[] transvalues=(Vector3f[]) attributes.get("transvalues"); SpatialTransformer st=(SpatialTransformer) objStack.pop(); if (transvalues!=null) for (int i=0;i<transIndexes.length;i++) st.setPosition(transIndexes[i],time,transvalues[i]); objStack.push(st); objStack.push(oldTime); } else if (tagName.equals("cullstate")){ objStack.push(buildCullState(attributes)); } else if (tagName.equals("wirestate")){ objStack.push(buildWireState(attributes)); } else{ throw new JmeException("Illegale Qualified name: '" + tagName + "'"); } if (attributes.containsKey("sharedident")){ Object temp=objStack.pop(); repeatShare.put(attributes.get("sharedident"),temp); objStack.push(temp); } return; } private void processController(Controller jc, HashMap attributes) { if (attributes.containsKey("speed")) jc.setSpeed(((Float)attributes.get("speed")).floatValue()); if (attributes.containsKey("rptype")) jc.setRepeatType(((Integer)attributes.get("rptype")).intValue()); } /** * Processes an END_TAG flag, which signals a tag has finished reading all children information. * @throws IOException If anything bad happens in reading the binary file */ private void readEnd() throws IOException { String tagName=myIn.readUTF(); if (DEBUG) System.out.println("reading endtag:" + tagName); Node childNode,parentNode; Spatial parentSpatial,childSpatial; if (tagName.equals("scene")){ myScene=(Node) objStack.pop(); } else if (tagName.equals("node") || tagName.equals("terrainpage")){ childNode=(Node) objStack.pop(); parentNode=(Node) objStack.pop(); parentNode.attachChild(childNode); objStack.push(parentNode); } else if (tagName.equals("repeatobject")){ Object childObject=objStack.pop(); if (childObject instanceof RenderState){ parentSpatial=(Spatial) objStack.pop(); parentSpatial.setRenderState((RenderState) childObject); objStack.push(parentSpatial); } else if (childObject instanceof Controller){ parentSpatial=(Spatial) objStack.pop(); parentSpatial.addController((Controller) childObject); objStack.push(parentSpatial); } else if (childObject instanceof Spatial){ parentNode=(Node) objStack.pop(); parentNode.attachChild((Spatial) childObject); objStack.push(parentNode); } else throw new IOException("Unknown child repeat object " + childObject.getClass()); } else if (tagName.equals("materialstate")){ MaterialState childMaterial=(MaterialState) objStack.pop(); Object o = objStack.pop(); if(o instanceof Spatial) { parentSpatial=(Spatial) o; parentSpatial.setRenderState(childMaterial); } else if(o instanceof GeomBatch) { ((GeomBatch) o).setRenderState(childMaterial); } objStack.push(o); } else if (tagName.equals("alphastate")){ AlphaState childAlphaState=(AlphaState) objStack.pop(); Object o = objStack.pop(); if(o instanceof Spatial) { parentSpatial=(Spatial) o; parentSpatial.setRenderState(childAlphaState); if (childAlphaState.isBlendEnabled()) { Spatial parent = parentSpatial; parent.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT); } } else if(o instanceof GeomBatch) { ((GeomBatch) o).setRenderState(childAlphaState); if (childAlphaState.isBlendEnabled()) { Spatial parent = (Spatial)objStack.pop(); parent.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT); objStack.push(parent); } } objStack.push(o); } else if (tagName.equals("texturestate")){ TextureState childMaterial=(TextureState) objStack.pop(); Object o = objStack.pop(); if(o instanceof Spatial) { parentSpatial=(Spatial) o; parentSpatial.setRenderState(childMaterial); } else if(o instanceof GeomBatch) { ((GeomBatch) o).setRenderState(childMaterial); } objStack.push(o); } else if (tagName.equals("texture")){ } else if (tagName.equals("cullstate")){ CullState childCull=(CullState) objStack.pop(); Object o = objStack.pop(); if(o instanceof Spatial) { parentSpatial=(Spatial) o; parentSpatial.setRenderState(childCull); } else if(o instanceof GeomBatch) { ((GeomBatch) o).setRenderState(childCull); } objStack.push(o); } else if (tagName.startsWith("batch")) { } else if (tagName.equals("mesh") || tagName.equals("jointmesh") || tagName.equals("clod")|| tagName.equals("areaclod") ||tagName.equals("terrainblock")){ Object o = objStack.pop(); Geometry childMesh=null; if(o instanceof GeomBatch) { childMesh = (Geometry)objStack.pop(); } else if(o instanceof Geometry){ childMesh = (Geometry )o; } if (childMesh.getBatch(0).getModelBound()==null){ if ("box".equals(properties.get("bound"))) childMesh.setModelBound(new BoundingBox()); else if ("obb".equals(properties.get("bound"))) childMesh.setModelBound(new OrientedBoundingBox()); else childMesh.setModelBound(new BoundingSphere()); childMesh.updateModelBound(); } parentNode=(Node) objStack.pop(); parentNode.attachChild(childMesh); objStack.push(parentNode); } else if (tagName.equals("vertex")){ } else if (tagName.equals("normal")){ } else if (tagName.equals("color")){ } else if (tagName.equals("defcolor")){ } else if (tagName.equals("texturecoords")){ } else if (tagName.equals("index")){ } else if (tagName.equals("primitive")){ childSpatial=(Spatial) objStack.pop(); parentNode=(Node) objStack.pop(); parentNode.attachChild(childSpatial); objStack.push(parentNode); } else if (tagName.equals("pointlight") || tagName.equals("spotlight") || tagName.equals("sharedtypes") || tagName.equals("keyframe")){ // Nothing to do, these only identify XML areas } else if (tagName.equals("xmlloadable")){ Object o=objStack.pop(); if (o instanceof RenderState){ parentSpatial=(Spatial) objStack.pop(); parentSpatial.setRenderState((RenderState) o); objStack.push(parentSpatial); } else if (o instanceof Controller){ parentSpatial=(Spatial) objStack.pop(); parentSpatial.addController((Controller) o); objStack.push(parentSpatial); } else if (o instanceof Spatial){ parentNode=(Node) objStack.pop(); parentNode.attachChild((Spatial) o); objStack.push(parentNode); } } else if (tagName.equals("sharedrenderstate")){ XMLSharedNode XMLShare=(XMLSharedNode) objStack.pop(); if (XMLShare.whatIReallyAm!=null) shares.put(XMLShare.myIdent,XMLShare.whatIReallyAm); } else if (tagName.equals("sharedtrimesh")){ XMLSharedNode XMLShare=(XMLSharedNode) objStack.pop(); shares.put(XMLShare.myIdent,XMLShare.whatIReallyAm); } else if (tagName.equals("sharednode")){ XMLSharedNode XMLShare=(XMLSharedNode) objStack.pop(); shares.put(XMLShare.myIdent,XMLShare.whatIReallyAm); } else if (tagName.equals("publicobject")){ Object o=objStack.pop(); if (o instanceof RenderState){ parentSpatial=(Spatial) objStack.pop(); parentSpatial.setRenderState((RenderState) o); objStack.push(parentSpatial); } else if (o instanceof Controller){ parentSpatial=(Spatial) objStack.pop(); parentSpatial.addController((Controller) o); objStack.push(parentSpatial); } else if (o instanceof Spatial){ parentNode=(Node) objStack.pop(); parentNode.attachChild((Spatial) o); objStack.push(parentNode); } } else if (tagName.equals("jointcontroller")){ JointController jc=(JointController) objStack.pop(); parentNode=(Node) objStack.pop(); for (int i=0;i<parentNode.getQuantity();i++){ if (parentNode.getChild(i) instanceof JointMesh) jc.addJointMesh((JointMesh) parentNode.getChild(i)); } jc.processController(); if (jc.numJoints!=0) parentNode.addController(jc); objStack.push(parentNode); } else if (tagName.equals("joint")){ objStack.pop(); // remove unneeded information tag } else if (tagName.equals("obb") || tagName.equals("boundsphere") || tagName.equals("boundbox")){ BoundingVolume bv=(BoundingVolume) objStack.pop(); Object o = objStack.pop(); if(o instanceof Geometry) { Geometry parentGeo=(Geometry) o; parentGeo.setModelBound(bv); } objStack.push(o); } else if (tagName.equals("jointindex")){ } else if (tagName.equals("origvertex")){ } else if (tagName.equals("orignormal")){ } else if (tagName.equals("keyframecontroller")){ KeyframeController kc=(KeyframeController) objStack.pop(); TriMesh parentMesh=(TriMesh) objStack.pop(); parentMesh.addController(kc); objStack.push(parentMesh); } else if (tagName.equals("lightstate")){ LightState ls=(LightState) objStack.pop(); Object o = objStack.pop(); if(o instanceof Spatial) { parentSpatial=(Spatial) o; parentSpatial.setRenderState(ls); } else if(o instanceof GeomBatch) { ((GeomBatch) o).setRenderState(ls); } objStack.push(o); } else if (tagName.equals("keyframepointintime")){ TriMesh parentMesh=(TriMesh) objStack.pop(); float time=((Float) objStack.pop()).floatValue(); KeyframeController kc=(KeyframeController)objStack.pop(); kc.setKeyframe(time,parentMesh); objStack.push(kc); } else if (tagName.equals("jmefile")){ LoaderNode childLoaderNode=(LoaderNode) objStack.pop(); parentNode=(Node) objStack.pop(); parentNode.attachChild(childLoaderNode); objStack.push(parentNode); } else if (tagName.equals("spatialtransformer")){ SpatialTransformer st=(SpatialTransformer) objStack.pop(); parentSpatial=(Spatial) objStack.pop(); st.interpolateMissing(); st.setActive(true); parentSpatial.addController(st); objStack.push(parentSpatial); } else if (tagName.equals("stobj")){ XMLSharedNode xsn=(XMLSharedNode) objStack.pop(); int parNum=((Integer)objStack.pop()).intValue(); int obNum=((Integer)objStack.pop()).intValue(); SpatialTransformer parentST=(SpatialTransformer) objStack.pop(); parentST.setObject((Spatial) xsn.whatIReallyAm,obNum,parNum); objStack.push(parentST); } else if (tagName.equals("spatialpointtime")){ objStack.pop(); } else if (tagName.equals("clodrecords")){ CollapseRecord[] toPut=(CollapseRecord[]) objStack.pop(); ClodMesh parentClod=(ClodMesh) objStack.pop(); parentClod.create(toPut); objStack.push(parentClod); } else if (tagName.equals("wirestate")){ WireframeState ws=(WireframeState) objStack.pop(); Object o = objStack.pop(); if(o instanceof Spatial) { parentSpatial=(Spatial) o; parentSpatial.setRenderState(ws); } else if(o instanceof GeomBatch) { ((GeomBatch) o).setRenderState(ws); } objStack.push(o); } else if (tagName.equals("crecord") || tagName.equals("sptscale") || tagName.equals("sptrot") || tagName.equals("spttrans")){ // nothing to do at these ends } else { throw new JmeException("Illegal Qualified name: " + tagName); } } private OrientedBoundingBox processOBB(OrientedBoundingBox obb, HashMap attributes) { obb.setCenter((Vector3f) attributes.get("center")); obb.setXAxis((Vector3f) attributes.get("xaxis")); obb.setYAxis((Vector3f) attributes.get("yaxis")); obb.setZAxis((Vector3f) attributes.get("zaxis")); obb.setExtent((Vector3f) attributes.get("extent")); return obb; } private BoundingSphere processBSphere(BoundingSphere v, HashMap attributes) { v.setCenter((Vector3f) attributes.get("center")); v.setRadius(((Float)attributes.get("radius")).floatValue()); return v; } private BoundingBox processBBox(BoundingBox v, HashMap attributes) { v.setCenter((Vector3f) attributes.get("nowcent")); Vector3f ext=(Vector3f) attributes.get("nowext"); v.xExtent=ext.x; v.yExtent=ext.y; v.zExtent=ext.z; return v; } private void writeCollapseRecord(HashMap attributes) { CollapseRecord temp=new CollapseRecord(); temp.indices=(int[]) attributes.get("indexary"); temp.numbIndices=((Integer)attributes.get("numi")).intValue(); temp.numbTriangles=((Integer)attributes.get("numt")).intValue(); temp.numbVerts=((Integer)attributes.get("numv")).intValue(); temp.vertToKeep=((Integer)attributes.get("vkeep")).intValue(); temp.vertToThrow=((Integer)attributes.get("vthrow")).intValue(); CollapseRecord[] toPut=(CollapseRecord[]) objStack.pop(); toPut[((Integer)attributes.get("index")).intValue()]=temp; objStack.push(toPut); } private TerrainPage processTerrainPage(TerrainPage terrainPage, HashMap attributes) { processSpatial(terrainPage,attributes); terrainPage.setOffset((Vector2f) attributes.get("offset")); terrainPage.setTotalSize(((Integer)attributes.get("totsize")).intValue()); terrainPage.setSize(((Integer)attributes.get("size")).intValue()); terrainPage.setStepScale((Vector3f) attributes.get("stepscale")); terrainPage.setOffsetAmount(((Float)attributes.get("offamnt")).floatValue()); return terrainPage; } private TerrainBlock processTerrainBlock(TerrainBlock terrainBlock, HashMap attributes) { processAreaClod(terrainBlock,attributes); terrainBlock.setSize(((Integer)attributes.get("tbsize")).intValue()); terrainBlock.setTotalSize(((Integer)attributes.get("totsize")).intValue()); terrainBlock.setStepScale((Vector3f)attributes.get("step")); terrainBlock.setUseClod(((Boolean)attributes.get("isclod")).booleanValue()); terrainBlock.setOffset((Vector2f) attributes.get("offset")); terrainBlock.setOffsetAmount(((Float)attributes.get("offamnt")).floatValue()); terrainBlock.setHeightMap((int[]) attributes.get("hmap")); return terrainBlock; } private AreaClodMesh processAreaClod(AreaClodMesh areaClodMesh, HashMap attributes) { processSpatial(areaClodMesh,attributes); areaClodMesh.setDistanceTolerance(((Float)attributes.get("disttol")).floatValue()); areaClodMesh.setTrisPerPixel(((Float)attributes.get("trisppix")).floatValue()); return areaClodMesh; } private Vector3f[] decodeShortCompress(short[] shorts) throws IOException { if (shorts.length%3!=0) throw new IOException("Illeagle short[] length of " + shorts.length); Vector3f[] toReturn=new Vector3f[shorts.length/3]; for (int i=0;i<toReturn.length;i++){ toReturn[i]=new Vector3f(); toReturn[i].x = shorts[i*3+0]*BinaryFormatConstants.XYZ_SCALE; toReturn[i].y = shorts[i*3+1]*BinaryFormatConstants.XYZ_SCALE; toReturn[i].z = shorts[i*3+2]*BinaryFormatConstants.XYZ_SCALE; } return toReturn; } private Vector3f[] decodeLatLong(byte[] bytes) throws IOException { if (bytes==null) return null; if (bytes.length%2!=0){ throw new IOException("Illeagle bytes[] length of " + bytes.length); } Vector3f[] vecs=new Vector3f[bytes.length/2]; for (int i=0;i<bytes.length;i+=2){ vecs[i/2]=new Vector3f(); byte lng=bytes[i]; byte lat=bytes[i+1]; float newlat=FastMath.DEG_TO_RAD*lat; float newlng=FastMath.DEG_TO_RAD*lng; vecs[i/2].x = FastMath.cos(newlat)*FastMath.sin(newlng); vecs[i/2].y = FastMath.sin(newlat)*FastMath.sin(newlng); vecs[i/2].z = FastMath.cos(newlng); } return vecs; } private Object buildCullState(HashMap attributes) { CullState cs=renderer.createCullState(); cs.setEnabled(true); String state=(String) attributes.get("cull"); if ("none".equals(state)) cs.setCullMode(CullState.CS_NONE); else if ("back".equals(state)) cs.setCullMode(CullState.CS_BACK); else if ("front".equals(state)) cs.setCullMode(CullState.CS_FRONT); return cs; } private PointLight buildPointLight(HashMap attributes) { PointLight toReturn=new PointLight(); putLightInfo(toReturn,attributes); toReturn.setLocation((Vector3f)attributes.get("loc")); toReturn.setEnabled(true); return toReturn; } private SpotLight buildSpotLight(HashMap attributes) { SpotLight toReturn=new SpotLight(); putLightInfo(toReturn,attributes); toReturn.setLocation((Vector3f)attributes.get("loc")); toReturn.setAngle(((Float)attributes.get("fangle")).floatValue()); toReturn.setDirection((Vector3f)attributes.get("dir")); toReturn.setExponent(((Float)attributes.get("fexponent")).floatValue()); toReturn.setEnabled(true); return toReturn; } private WireframeState buildWireState(HashMap attributes) { WireframeState ws=renderer.createWireframeState(); ws.setFace(((Integer)attributes.get("facetype")).intValue()); ws.setLineWidth(((Float)attributes.get("width")).floatValue()); ws.setEnabled(true); return ws; } private void putLightInfo(Light light, HashMap attributes) { light.setAmbient((ColorRGBA) attributes.get("ambient")); light.setConstant(((Float)attributes.get("fconstant")).floatValue()); light.setDiffuse((ColorRGBA) attributes.get("diffuse")); light.setLinear(((Float)attributes.get("flinear")).floatValue()); light.setQuadratic(((Float)attributes.get("fquadratic")).floatValue()); light.setSpecular((ColorRGBA) attributes.get("specular")); light.setAttenuate(((Boolean)attributes.get("isattenuate")).booleanValue()); } private LightState buildLightState(HashMap attributes) { LightState ls=renderer.createLightState(); ColorRGBA globalAmbient = (ColorRGBA) attributes.get( "ambient" ); if ( globalAmbient != null ) { ls.setGlobalAmbient( globalAmbient ); } Boolean twoSided = ( (Boolean) attributes.get( "twosided" ) ); if ( twoSided != null ) { ls.setTwoSidedLighting( twoSided.booleanValue() ); } Boolean local = ( (Boolean) attributes.get( "local" ) ); if ( local != null ) { ls.setLocalViewer( local.booleanValue() ); } Boolean sepspec = ( (Boolean) attributes.get( "sepspec" ) ); if ( sepspec != null ) { ls.setSeparateSpecular( sepspec.booleanValue() ); } ls.setEnabled(true); return ls; } /** * Builds a primitive given attributes. * @param atts Attributes to build with * @return The loaded primitive */ private Spatial processPrimitive(HashMap atts){ String parameters=(String) atts.get("params"); String type=(String) atts.get("type"); if (parameters==null) throw new JmeException("Must specify parameters"); Spatial toReturn; String[] parts=parameters.trim().split(" "); if (type.equalsIgnoreCase("box")){ if (parts.length!=7) throw new JmeException("Box must have 7 parameters"); Box box=new Box(parts[0],new Vector3f( Float.parseFloat(parts[1]), Float.parseFloat(parts[2]), Float.parseFloat(parts[3])), new Vector3f(Float.parseFloat(parts[4]), Float.parseFloat(parts[5]), Float.parseFloat(parts[6]))); box.setModelBound(new BoundingSphere()); box.updateModelBound(); toReturn=box; }else{ throw new JmeException("Unknown primitive type: " + type); } return processSpatial(toReturn,atts); } /** * Builds a texture with the given attributes. Will use the "texurl" property if needed to * help build the texture * @param atts The attributes of the Texture * @return The new texture */ private Texture buildTexture(HashMap atts){ Texture p=null; int mipMap = Texture.MM_LINEAR; int filter = Texture.FM_LINEAR; int imageType = TextureManager.COMPRESS_BY_DEFAULT ? Image.GUESS_FORMAT : Image.GUESS_FORMAT_NO_S3TC; float aniso = 1.0f; boolean flip = true; if (properties.containsKey("tex_mm")) mipMap = ((Integer)properties.get("tex_mm")).intValue(); if (properties.containsKey("tex_fm")) filter = ((Integer)properties.get("tex_fm")).intValue(); if (properties.containsKey("tex_type")) imageType = ((Integer)properties.get("tex_type")).intValue(); if (properties.containsKey("tex_aniso")) aniso = ((Float)properties.get("tex_aniso")).floatValue(); if (properties.containsKey("tex_flip")) flip = ((Boolean)properties.get("tex_flip")).booleanValue(); try { if (atts.get("URL")!=null && !atts.get("URL").equals("null")){ p=TextureManager.loadTexture( (URL) atts.get("URL"), mipMap, filter, imageType, aniso, flip); } else if (atts.get("file")!=null && !atts.get("file").equals("null")){ URL context; if (properties.containsKey("texurl")){ context=new URL((URL) properties.get("texurl"),(String) atts.get("file")); } else if (properties.containsKey("texclasspath")){ context=JmeBinaryReader.class.getClassLoader().getResource( (String)properties.get("texclasspath")+(String)atts.get("file") ); } else if (properties.containsKey("texdirfile")){ context=new File((String) properties.get("texdirfile")+File.separator+(String)atts.get("file")).toURL(); } else { context=new File((String) atts.get("file")).toURI().toURL(); } p=TextureManager.loadTexture(context, mipMap, filter, imageType, aniso, flip); if (p==null) { return p; } p.setImageLocation("file:/"+atts.get("file")); } if (p==null) LoggingSystem.getLogger().log(Level.INFO,"Unable to load file: " + atts.get("file")); else{ // t.setTexture(p); if (atts.get("wrap")!=null) { p.setWrap(((Integer)atts.get("wrap")).intValue()); } if ( atts.get( "scale" ) != null ) { p.setScale( (Vector3f) atts.get( "scale" ) ); } } } catch (MalformedURLException e) { throw new JmeException("Bad file name: " + atts.get("file") + " (" + atts.get("URL") + ")"); } // t.setEnabled(true); // return t; return p; } /** * Changes a Spatial's parameters acording to the attributes. * @param toAdd The spatial to change * @param atts The attributes * @return The given (<code>toAdd</code>) Spatial */ private Spatial processSpatial(Spatial toAdd, HashMap atts) { if (atts.get("name")!=null) toAdd.setName((String) atts.get("name")); if (atts.get("translation")!=null) toAdd.setLocalTranslation((Vector3f) atts.get("translation")); if (atts.get("rotation")!=null) toAdd.setLocalRotation((Quaternion)atts.get("rotation")); if (atts.get("scale")!=null) toAdd.setLocalScale((Vector3f) atts.get("scale")); return toAdd; } /** * Builds a MaterialState with the given attributes. * @param atts The attributes * @return A new material state */ private MaterialState buildMaterial(HashMap atts) { MaterialState m=renderer.createMaterialState(); m.setAmbient((ColorRGBA) atts.get("ambient")); m.setDiffuse((ColorRGBA) atts.get("diffuse")); m.setEmissive((ColorRGBA) atts.get("emissive")); m.setShininess(((Float)atts.get("shiny")).floatValue()); m.setSpecular((ColorRGBA) atts.get("specular")); Integer temp; if ((temp = (Integer) atts.get("color")) != null) m.setColorMaterial(temp.intValue()); if ((temp = (Integer) atts.get("face")) != null) m.setMaterialFace(temp.intValue()); m.setEnabled(true); return m; } /** * Builds an AlphaState with the given attributes. * @param atts The attributes * @return A new AlphaState */ private AlphaState buildAlphaState(HashMap atts) { AlphaState a = renderer.createAlphaState(); a.setSrcFunction(((Integer)atts.get("srcfunc")).intValue()); a.setDstFunction(((Integer)atts.get("dstfunc")).intValue()); a.setTestFunction(((Integer)atts.get("testfunc")).intValue()); a.setReference(((Float)atts.get("reference")).floatValue()); a.setBlendEnabled(((Boolean)atts.get("blend")).booleanValue()); a.setTestEnabled(((Boolean)atts.get("test")).booleanValue()); a.setEnabled(((Boolean)atts.get("enabled")).booleanValue()); return a; } /** * Reads byte information from the binary file to put the needed attributes into a hashmap. For * example, the hashmap may contain {"translation":new Vector3f(1,1,1),"name":new String("guy")} * @param atribMap The hashmap to hold the attributes * @throws IOException If reading goes wrong */ private void readInObjects(HashMap<String, Object> atribMap) throws IOException { atribMap.clear(); byte numFlags=myIn.readByte(); for (int i=0;i<numFlags;i++){ String name=myIn.readUTF(); byte type=myIn.readByte(); if (DEBUG) System.out.println("Reading attribute*" + name + "* with type " + type); switch (type){ case BinaryFormatConstants.DATA_COLORARRAY: atribMap.put(name,getColorBuffer()); break; case BinaryFormatConstants.DATA_INTARRAY: atribMap.put(name,getIntArray()); break; case BinaryFormatConstants.DATA_STRING: atribMap.put(name,myIn.readUTF()); break; case BinaryFormatConstants.DATA_V2FARRAY: atribMap.put(name,getVec2fArray()); break; case BinaryFormatConstants.DATA_V3FARRAY: atribMap.put(name,getVec3fArray()); break; case BinaryFormatConstants.DATA_V3F: atribMap.put(name,getVec3f()); if (DEBUG) System.out.println("readvec:"+atribMap.get(name)); break; case BinaryFormatConstants.DATA_V2F: atribMap.put(name,getVec2f()); if (DEBUG) System.out.println("readvec2f:"+atribMap.get(name)); break; case BinaryFormatConstants.DATA_QUAT: atribMap.put(name,getQuat()); if (DEBUG) System.out.println("readquat:"+atribMap.get(name)); break; case BinaryFormatConstants.DATA_FLOAT: atribMap.put(name,new Float(myIn.readFloat())); if (DEBUG) System.out.println("readfloat:"+atribMap.get(name)); break; case BinaryFormatConstants.DATA_COLOR: atribMap.put(name,getColor()); if (DEBUG) System.out.println("readcolor:"+atribMap.get(name)); break; case BinaryFormatConstants.DATA_URL: atribMap.put(name,new URL(myIn.readUTF())); break; case BinaryFormatConstants.DATA_INT: atribMap.put(name,new Integer(myIn.readInt())); if (DEBUG) System.out.println("readint:"+atribMap.get(name)); break; case BinaryFormatConstants.DATA_BOOLEAN: atribMap.put(name,new Boolean(myIn.readBoolean())); break; case BinaryFormatConstants.DATA_QUATARRAY: atribMap.put(name,getQuatArray()); break; case BinaryFormatConstants.DATA_BYTEARRAY: atribMap.put(name,getByteArray()); break; case BinaryFormatConstants.DATA_SHORTARRAY: atribMap.put(name,getShortArray()); break; case BinaryFormatConstants.DATA_MATRIX3: atribMap.put(name,getMat3()); break; default: throw new IOException("Unknown data type:" + type); } } } private Matrix3f getMat3() throws IOException { Matrix3f m=new Matrix3f(); m.m00=myIn.readFloat(); m.m01=myIn.readFloat(); m.m02=myIn.readFloat(); m.m10=myIn.readFloat(); m.m11=myIn.readFloat(); m.m12=myIn.readFloat(); m.m20=myIn.readFloat(); m.m21=myIn.readFloat(); m.m22=myIn.readFloat(); return m; } private short[] getShortArray() throws IOException { int length=myIn.readInt(); if (length==0) return null; short[] array=new short[length]; for (int i=0;i<length;i++) array[i]=myIn.readShort(); return array; } private byte[] getByteArray() throws IOException { int length=myIn.readInt(); if (length==0) return null; byte[] array=new byte[length]; for (int i=0;i<length;i++) array[i]=myIn.readByte(); return array; } // Note, a quat that is all NaN for values is considered null private Quaternion[] getQuatArray() throws IOException { int length=myIn.readInt(); if (length==0) return null; Quaternion[] array=new Quaternion[length]; for (int i=0;i<length;i++){ array[i]=new Quaternion(myIn.readFloat(),myIn.readFloat(),myIn.readFloat(),myIn.readFloat()); if ( Float.isNaN( array[i].x ) && Float.isNaN( array[i].y ) && Float.isNaN( array[i].z ) && Float.isNaN( array[i].w ) ) array[i]=null; } return array; } private Quaternion getQuat() throws IOException{ return new Quaternion(myIn.readFloat(),myIn.readFloat(),myIn.readFloat(),myIn.readFloat()); } private ColorRGBA getColor() throws IOException{ return new ColorRGBA(myIn.readFloat(),myIn.readFloat(),myIn.readFloat(),myIn.readFloat()); } private Vector2f getVec2f() throws IOException{ return new Vector2f(myIn.readFloat(),myIn.readFloat()); } private Vector3f getVec3f() throws IOException{ return new Vector3f(myIn.readFloat(),myIn.readFloat(),myIn.readFloat()); } private int[] getIntArray() throws IOException { int length=myIn.readInt(); if (length==0) return null; int[] array=new int[length]; for (int i=0;i<length;i++){ array[i]=myIn.readInt(); } return array; } private Vector2f[] getVec2fArray() throws IOException { int length=myIn.readInt(); if (length==0) return null; Vector2f[] array=new Vector2f[length]; for (int i=0;i<length;i++){ array[i]=new Vector2f(myIn.readFloat(),myIn.readFloat()); if ( Float.isNaN( array[i].x ) && Float.isNaN( array[i].y ) ) array[i]=null; } return array; } private FloatBuffer getColorBuffer() throws IOException { int length=myIn.readInt(); if (length==0) return null; FloatBuffer buff = BufferUtils.createColorBuffer(length); for (int i=0;i<length;i++) buff.put(myIn.readFloat()).put(myIn.readFloat()).put(myIn.readFloat()).put(myIn.readFloat()); return buff; } // Note, a vector3f that is all NaN is considered null private Vector3f[] getVec3fArray() throws IOException { int length=myIn.readInt(); if (length==0) return null; Vector3f[] array=new Vector3f[length]; for (int i=0;i<length;i++){ array[i]=new Vector3f(myIn.readFloat(),myIn.readFloat(),myIn.readFloat()); if ( Float.isNaN( array[i].x ) && Float.isNaN( array[i].y ) && Float.isNaN( array[i].z ) ) array[i]=null; } return array; } private void readHeader() throws IOException { if (BinaryFormatConstants.BEGIN_FILE!=myIn.readLong()){ throw new IOException("Binary Header doesn't match. Maybe wrong file?"); } } /** * Adds a property . Properties can tell this how to process the binary file.<br><br> * The only keys currently used are:<br> * key -> PropertyDataType<br> * "texurl" --> (URL) When loading a texture, will use this directory as the base texture directory <br> * "bound" --> "box","sphere","obb" ; Type of bounding Volume. "sphere" is default * * @param key Key to add (For example "texdir") * @param property Property for that key to have (For example "c:\\blarg\\") */ public void setProperty(String key, Object property) { properties.put(key,property); } /** * Removes a property. This is equivalent to setProperty(key,null) * @param key The property to remove */ public void clearProperty(String key){ properties.remove(key); } }
package dk.statsbiblioteket.doms.updatetracker.webservice; import dk.statsbiblioteket.doms.webservices.ConfigCollection; import dk.statsbiblioteket.doms.webservices.Credentials; import javax.annotation.Resource; import javax.jws.WebParam; import javax.jws.WebService; import javax.servlet.http.HttpServletRequest; import javax.xml.ws.WebServiceContext; import javax.xml.ws.handler.MessageContext; import java.lang.String; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; /** * Update tracker webservice. Provides upper layers of DOMS with info on changes * to objects in Fedora. Used by DOMS Server aka. Central to provide Summa with * said info. */ @WebService(endpointInterface = "dk.statsbiblioteket.doms.updatetracker.webservice" + ".UpdateTrackerWebservice") public class UpdateTrackerWebserviceImpl implements UpdateTrackerWebservice { @Resource WebServiceContext context; private DateFormat fedoraFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); public UpdateTrackerWebserviceImpl() throws MethodFailedException { } /** * Lists the entry objects of views (records) in Fedora, in the given * collection, that have changed since the given time. * * @param collectionPid The PID of the collection in which we are looking * for changes. * @param viewAngle ...TODO doc * @param beginTime The time since which we are looking for changes. * @param state ...TODO doc * @return returns java.util.List<dk.statsbiblioteket.doms.updatetracker * .webservice.PidDatePidPid> * @throws MethodFailedException * @throws InvalidCredentialsException */ public List<PidDatePidPid> listObjectsChangedSince( @WebParam(name = "collectionPid", targetNamespace = "") String collectionPid, @WebParam(name = "viewAngle", targetNamespace = "") String viewAngle, @WebParam(name = "beginTime", targetNamespace = "") long beginTime, @WebParam(name = "state", targetNamespace = "") String state, @WebParam(name = "offset", targetNamespace = "") Integer offset, @WebParam(name = "limit", targetNamespace = "") Integer limit) throws InvalidCredentialsException, MethodFailedException { return getModifiedObjects(collectionPid, viewAngle, beginTime, state, offset, limit, false); } public List<PidDatePidPid> getModifiedObjects(String collectionPid, String viewAngle, long beginTime, String state, Integer offset, Integer limit, boolean reverse ) throws InvalidCredentialsException, MethodFailedException { List<PidDatePidPid> result = new ArrayList<PidDatePidPid>(); List<String> allEntryObjectsInRadioTVCollection; Fedora fedora; String fedoralocation = ConfigCollection.getProperties().getProperty( "dk.statsbiblioteket.doms.updatetracker.fedoralocation"); fedora = new Fedora(getCredentials(), fedoralocation); if (state == null) { state = "Published"; } if (state.equals("Published")) { state = "<fedora-model:Active>"; } else if (state.equals("InProgress")) { state = "<fedora-model:Inactive>"; } else { state = "<fedora-model:Active>"; } String query = "select $object $cm $date\n" + "from <#ri>\n" + "where\n" + "$object <fedora-model:hasModel> $cm\n" + "and\n" + "$cm <http://ecm.sourceforge.net/relations/0/2/#isEntryForViewAngle> '" + viewAngle + "'\n" + "and\n" + "$object <http://doms.statsbiblioteket.dk/relations/default/0/1/#isPartOfCollection> <info:fedora/" + collectionPid + ">\n" + "and\n" + "$object <fedora-model:state> " + state + "\n" + "and\n" + "$object <fedora-view:lastModifiedDate> $date \n"; if (beginTime != 0){ String beginTimeDate = fedoraFormat.format(new Date(beginTime)); query = query + "and \n $date <mulgara:after> '"+beginTimeDate+"'^^<xml-schema:dateTime> in <#xsd> \n"; } if (reverse){ query = query + "order by $date desc"; } else { query = query + "order by $date asc"; } if (limit != 0) { query = query + "\n limit " + limit; } if (offset != 0) { query = query + "\n offset " + offset; } try { allEntryObjectsInRadioTVCollection = fedora.query(query); } catch (BackendInvalidCredsException e) { throw new InvalidCredentialsException("Invalid credentials", "", e); } catch (BackendMethodFailedException e) { throw new MethodFailedException("Method failed", "", e); } for (String line : allEntryObjectsInRadioTVCollection) { PidDatePidPid objectThatChanged = new PidDatePidPid(); String[] splitted = line.split(","); String pid = splitted[0]; String entryCMPid = splitted[1]; String lastModifiedFedoraDate = splitted[2]; objectThatChanged.setPid(pid); try { objectThatChanged.setLastChangedTime(fedoraFormat.parse( lastModifiedFedoraDate).getTime()); } catch (ParseException e) { throw new MethodFailedException("Failed to parse date for object",e.getMessage(),e); } objectThatChanged.setCollectionPid(collectionPid); objectThatChanged.setEntryCMPid(entryCMPid); result.add(objectThatChanged); } return result; } /** * Return the last time a view/record conforming to the content model of the * given content model entry, and in the given collection, has been changed. * * @param collectionPid The PID of the collection in which we are looking * for the last change. * @param viewAngle ...TODO doc * @return The date/time of the last change. * @throws InvalidCredentialsException * @throws MethodFailedException */ public long getLatestModificationTime( @WebParam(name = "collectionPid", targetNamespace = "") java.lang.String collectionPid, @WebParam(name = "viewAngle", targetNamespace = "") java.lang.String viewAngle, @WebParam(name = "state", targetNamespace = "") java.lang.String state) throws InvalidCredentialsException, MethodFailedException { List<PidDatePidPid> lastChanged = getModifiedObjects(collectionPid, viewAngle, 0, state, 0, 1, true); if (!lastChanged.isEmpty()){ return lastChanged.get(0).getLastChangedTime(); } else { throw new MethodFailedException("Did not find any elements in the collection","No elements in the collection"); } } /** * TODO doc * * @return TODO doc */ private Credentials getCredentials() { HttpServletRequest request = (HttpServletRequest) context .getMessageContext() .get(MessageContext.SERVLET_REQUEST); Credentials creds = (Credentials) request.getAttribute("Credentials"); if (creds == null) { // log.warn("Attempted call at Central without credentials"); creds = new Credentials("", ""); } return creds; } }
package org.opendaylight.controller.config.manager.impl.osgi.mapping; import java.util.Dictionary; import java.util.Hashtable; import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy; import org.opendaylight.mdsal.binding.generator.api.ModuleInfoRegistry; import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext; import org.opendaylight.yangtools.concepts.ObjectRegistration; import org.opendaylight.yangtools.yang.binding.YangModuleInfo; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Update SchemaContext service in Service Registry each time new YangModuleInfo is added or removed. */ public class RefreshingSCPModuleInfoRegistry implements ModuleInfoRegistry, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(RefreshingSCPModuleInfoRegistry.class); private final ModuleInfoRegistry moduleInfoRegistry; private final SchemaContextProvider schemaContextProvider; private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider; private final BindingContextProvider bindingContextProvider; private final ClassLoadingStrategy classLoadingStrat; private volatile ServiceRegistration<SchemaContextProvider> osgiReg; public RefreshingSCPModuleInfoRegistry(final ModuleInfoRegistry moduleInfoRegistry, final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat, final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final BindingContextProvider bindingContextProvider, final BundleContext bundleContext) { this.moduleInfoRegistry = moduleInfoRegistry; this.schemaContextProvider = schemaContextProvider; this.classLoadingStrat = classLoadingStrat; this.sourceProvider = sourceProvider; this.bindingContextProvider = bindingContextProvider; this.osgiReg = bundleContext .registerService(SchemaContextProvider.class, schemaContextProvider, new Hashtable<String, String>()); } public synchronized void updateService() { if (this.osgiReg != null) { try { this.bindingContextProvider.update(this.classLoadingStrat, this.schemaContextProvider); final Dictionary<String, Object> props = new Hashtable<>(); props.put(BindingRuntimeContext.class.getName(), this.bindingContextProvider.getBindingContext()); props.put(SchemaSourceProvider.class.getName(), this.sourceProvider); // send modifiedService event this.osgiReg.setProperties(props); } catch (final RuntimeException e) { // The ModuleInfoBackedContext throws a RuntimeException if it can't create the schema context. LOG.warn("Error updating the BindingContextProvider", e); } } } @Override public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) { final ObjectRegistration<YangModuleInfo> yangModuleInfoObjectRegistration = this.moduleInfoRegistry.registerModuleInfo(yangModuleInfo); return new ObjectRegistrationWrapper(yangModuleInfoObjectRegistration); } @Override public synchronized void close() throws Exception { if (this.osgiReg != null) { this.osgiReg.unregister(); } this.osgiReg = null; } private class ObjectRegistrationWrapper implements ObjectRegistration<YangModuleInfo> { private final ObjectRegistration<YangModuleInfo> inner; private ObjectRegistrationWrapper(final ObjectRegistration<YangModuleInfo> inner) { this.inner = inner; } @Override public YangModuleInfo getInstance() { return this.inner.getInstance(); } @Override public void close() throws Exception { this.inner.close(); // send modify event when a bundle disappears updateService(); } @Override public String toString() { return this.inner.toString(); } } }
package com.maddyhome.idea.vim.group; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.actionSystem.ActionPlan; import com.intellij.openapi.editor.actionSystem.TypedActionHandler; import com.intellij.openapi.editor.actionSystem.TypedActionHandlerEx; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.impl.TextRangeInterval; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.maddyhome.idea.vim.EventFacade; import com.maddyhome.idea.vim.KeyHandler; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.command.*; import com.maddyhome.idea.vim.common.Register; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.ex.LineRange; import com.maddyhome.idea.vim.helper.*; import com.maddyhome.idea.vim.option.BoundListOption; import com.maddyhome.idea.vim.option.Options; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.KeyEvent; import java.util.*; /** * Provides all the insert/replace related functionality * TODO - change cursor for the different modes */ public class ChangeGroup { public static final int MAX_REPEAT_CHARS_COUNT = 10000; /** * Creates the group */ public ChangeGroup() { // We want to know when a user clicks the mouse somewhere in the editor so we can clear any // saved text for the current insert mode. final EventFacade eventFacade = EventFacade.getInstance(); eventFacade.addEditorFactoryListener(new EditorFactoryAdapter() { public void editorCreated(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); eventFacade.addEditorMouseListener(editor, listener); EditorData.setChangeGroup(editor, true); } public void editorReleased(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); if (EditorData.getChangeGroup(editor)) { eventFacade.removeEditorMouseListener(editor, listener); EditorData.setChangeGroup(editor, false); } } @NotNull private final EditorMouseAdapter listener = new EditorMouseAdapter() { public void mouseClicked(@NotNull EditorMouseEvent event) { Editor editor = event.getEditor(); if (!VimPlugin.isEnabled()) { return; } if (CommandState.inInsertMode(editor)) { clearStrokes(editor); } } }; }, ApplicationManager.getApplication()); } public void setInsertRepeat(int lines, int column, boolean append) { repeatLines = lines; repeatColumn = column; repeatAppend = append; } /** * Begin insert before the cursor position * * @param editor The editor to insert into * @param context The data context */ public void insertBeforeCursor(@NotNull Editor editor, @NotNull DataContext context) { initInsert(editor, context, CommandState.Mode.INSERT); } /** * Begin insert before the first non-blank on the current line * * @param editor The editor to insert into * @param context The data context */ public void insertBeforeFirstNonBlank(@NotNull Editor editor, @NotNull DataContext context) { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor)); initInsert(editor, context, CommandState.Mode.INSERT); } /** * Begin insert before the start of the current line * * @param editor The editor to insert into * @param context The data context */ public void insertLineStart(@NotNull Editor editor, @NotNull DataContext context) { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretToLineStart(editor)); initInsert(editor, context, CommandState.Mode.INSERT); } /** * Begin insert after the cursor position * * @param editor The editor to insert into * @param context The data context */ public void insertAfterCursor(@NotNull Editor editor, @NotNull DataContext context) { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretHorizontal(editor, 1, true)); initInsert(editor, context, CommandState.Mode.INSERT); } /** * Begin insert after the end of the current line * * @param editor The editor to insert into * @param context The data context */ public void insertAfterLineEnd(@NotNull Editor editor, @NotNull DataContext context) { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretToLineEnd(editor)); initInsert(editor, context, CommandState.Mode.INSERT); } /** * Begin insert before the current line by creating a new blank line above the current line * * @param editor The editor to insert into * @param context The data context */ public void insertNewLineAbove(@NotNull final Editor editor, @NotNull final DataContext context) { if (editor.getCaretModel().getVisualPosition().line == 0) { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretToLineStart(editor)); initInsert(editor, context, CommandState.Mode.INSERT); if (!editor.isOneLineMode()) { runEnterAction(editor, context); MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretVertical(editor, -1)); } } else { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretVertical(editor, -1)); insertNewLineBelow(editor, context); } } /** * Begin insert after the current line by creating a new blank line below the current line * * @param editor The editor to insert into * @param context The data context */ public void insertNewLineBelow(@NotNull final Editor editor, @NotNull final DataContext context) { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretToLineEnd(editor)); initInsert(editor, context, CommandState.Mode.INSERT); runEnterAction(editor, context); } private void runEnterAction(Editor editor, @NotNull DataContext context) { CommandState state = CommandState.getInstance(editor); if (state.getMode() != CommandState.Mode.REPEAT) { final ActionManager actionManager = ActionManager.getInstance(); final AnAction action = actionManager.getAction("EditorEnter"); if (action != null) { strokes.add(action); KeyHandler.executeAction(action, context); } } } /** * Begin insert at the location of the previous insert * * @param editor The editor to insert into * @param context The data context */ public void insertAtPreviousInsert(@NotNull Editor editor, @NotNull DataContext context) { int offset = VimPlugin.getMotion().moveCaretToMark(editor, '^'); if (offset != -1) { MotionGroup.moveCaret(editor, offset); } insertAfterCursor(editor, context); } /** * Inserts the previously inserted text * * @param editor The editor to insert into * @param context The data context * @param exit true if insert mode should be exited after the insert, false should stay in insert mode */ public void insertPreviousInsert(@NotNull Editor editor, @NotNull DataContext context, boolean exit) { repeatInsertText(editor, context, 1); if (exit) { processEscape(editor, context); } } /** * Inserts the contents of the specified register * * @param editor The editor to insert the text into * @param context The data context * @param key The register name * @return true if able to insert the register contents, false if not */ public boolean insertRegister(@NotNull Editor editor, @NotNull DataContext context, char key) { final Register register = VimPlugin.getRegister().getRegister(key); if (register != null) { final String text = register.getText(); if (text != null) { final int length = text.length(); for (int i = 0; i < length; i++) { processKey(editor, context, KeyStroke.getKeyStroke(text.charAt(i))); } return true; } } return false; } /** * Inserts the character above/below the cursor at the cursor location * * @param editor The editor to insert into * @param context The data context * @param dir 1 for getting from line below cursor, -1 for getting from line above cursor * @return true if able to get the character and insert it, false if not */ public boolean insertCharacterAroundCursor(@NotNull Editor editor, @NotNull DataContext context, int dir) { boolean res = false; VisualPosition vp = editor.getCaretModel().getVisualPosition(); vp = new VisualPosition(vp.line + dir, vp.column); int len = EditorHelper.getLineLength(editor, EditorHelper.visualLineToLogicalLine(editor, vp.line)); if (vp.column < len) { int offset = EditorHelper.visualPositionToOffset(editor, vp); char ch = editor.getDocument().getCharsSequence().charAt(offset); processKey(editor, context, KeyStroke.getKeyStroke(ch)); res = true; } return res; } /** * If the cursor is currently after the start of the current insert this deletes all the newly inserted text. * Otherwise it deletes all text from the cursor back to the first non-blank in the line. * * @param editor The editor to delete the text from * @return true if able to delete the text, false if not */ public boolean insertDeleteInsertedText(@NotNull Editor editor) { int deleteTo = insertStart; int offset = editor.getCaretModel().getOffset(); if (offset == insertStart) { deleteTo = VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor); } if (deleteTo != -1) { deleteRange(editor, new TextRange(deleteTo, offset), SelectionType.CHARACTER_WISE, false); return true; } return false; } /** * Deletes the text from the cursor to the start of the previous word * * @param editor The editor to delete the text from * @return true if able to delete text, false if not */ public boolean insertDeletePreviousWord(@NotNull Editor editor) { final int deleteTo = VimPlugin.getMotion().moveCaretToNextWord(editor, -1, false); if (deleteTo == -1) { return false; } final TextRange range = new TextRange(deleteTo, editor.getCaretModel().getOffset()); deleteRange(editor, range, SelectionType.CHARACTER_WISE, true); return true; } /** * Begin insert/replace mode * * @param editor The editor to insert into * @param context The data context * @param mode The mode - indicate insert or replace */ private void initInsert(@NotNull Editor editor, @NotNull DataContext context, @NotNull CommandState.Mode mode) { CommandState state = CommandState.getInstance(editor); insertStart = editor.getCaretModel().getOffset(); VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_START, insertStart); // If we are repeating the last insert/replace final Command cmd = state.getCommand(); if (cmd != null && state.getMode() == CommandState.Mode.REPEAT) { if (mode == CommandState.Mode.REPLACE) { processInsert(editor, context); } // If this command doesn't allow repeating, set the count to 1 if ((cmd.getFlags() & Command.FLAG_NO_REPEAT) != 0) { repeatInsert(editor, context, 1, false); } else { repeatInsert(editor, context, cmd.getCount(), false); } if (mode == CommandState.Mode.REPLACE) { processInsert(editor, context); } } // Here we begin insert/replace mode else { lastInsert = cmd; strokes.clear(); repeatCharsCount = 0; final EventFacade eventFacade = EventFacade.getInstance(); if (document != null && documentListener != null) { eventFacade.removeDocumentListener(document, documentListener); } document = editor.getDocument(); documentListener = new InsertActionsDocumentListener(); eventFacade.addDocumentListener(document, documentListener); oldOffset = -1; inInsert = true; if (mode == CommandState.Mode.REPLACE) { processInsert(editor, context); } state.pushState(mode, CommandState.SubMode.NONE, MappingMode.INSERT); resetCursor(editor, true); } } private class InsertActionsDocumentListener extends DocumentAdapter { @Override public void documentChanged(@NotNull DocumentEvent e) { final String newFragment = e.getNewFragment().toString(); final String oldFragment = e.getOldFragment().toString(); final int newFragmentLength = newFragment.length(); final int oldFragmentLength = oldFragment.length(); // Repeat buffer limits if (repeatCharsCount > MAX_REPEAT_CHARS_COUNT) { return; } // <Enter> is added to strokes as an action during processing in order to indent code properly in the repeat // command if (newFragment.startsWith("\n") && newFragment.trim().isEmpty()) { strokes.addAll(getAdjustCaretActions(e)); oldOffset = -1; return; } // Ignore multi-character indents as they should be inserted automatically while repeating <Enter> actions if (newFragmentLength > 1 && newFragment.trim().isEmpty()) { return; } strokes.addAll(getAdjustCaretActions(e)); if (oldFragmentLength > 0) { final AnAction editorDelete = ActionManager.getInstance().getAction("EditorDelete"); for (int i = 0; i < oldFragmentLength; i++) { strokes.add(editorDelete); } } if (newFragmentLength > 0) { strokes.add(newFragment.toCharArray()); } repeatCharsCount += newFragmentLength; oldOffset = e.getOffset() + newFragmentLength; } @NotNull private List<AnAction> getAdjustCaretActions(DocumentEvent e) { final int delta = e.getOffset() - oldOffset; if (oldOffset >= 0 && delta != 0) { final List<AnAction> positionCaretActions = new ArrayList<AnAction>(); final String motionName = delta < 0 ? "VimMotionLeft" : "VimMotionRight"; final AnAction action = ActionManager.getInstance().getAction(motionName); final int count = Math.abs(delta); for (int i = 0; i < count; i++) { positionCaretActions.add(action); } return positionCaretActions; } return Collections.emptyList(); } } /** * This repeats the previous insert count times * * @param editor The editor to insert into * @param context The data context * @param count The number of times to repeat the previous insert */ private void repeatInsert(@NotNull Editor editor, @NotNull DataContext context, int count, boolean started) { int cpos; if (repeatLines > 0) { int vline = editor.getCaretModel().getVisualPosition().line; int lline = editor.getCaretModel().getLogicalPosition().line; cpos = editor.logicalPositionToOffset(new LogicalPosition(vline, repeatColumn)); for (int i = 0; i < repeatLines; i++) { if (repeatAppend && repeatColumn < MotionGroup.LAST_COLUMN && EditorHelper.getVisualLineLength(editor, vline + i) < repeatColumn) { String pad = EditorHelper.pad(editor, lline + i, repeatColumn); if (pad.length() > 0) { int off = editor.getDocument().getLineEndOffset(lline + i); insertText(editor, off, pad); } } if (repeatColumn >= MotionGroup.LAST_COLUMN) { editor.getCaretModel().moveToOffset(VimPlugin.getMotion().moveCaretToLineEnd(editor, lline + i, true)); repeatInsertText(editor, context, started ? (i == 0 ? count : count + 1) : count); } else if (EditorHelper.getVisualLineLength(editor, vline + i) >= repeatColumn) { editor.getCaretModel().moveToVisualPosition(new VisualPosition(vline + i, repeatColumn)); repeatInsertText(editor, context, started ? (i == 0 ? count : count + 1) : count); } } } else { repeatInsertText(editor, context, count); cpos = VimPlugin.getMotion().moveCaretHorizontal(editor, -1, false); } repeatLines = 0; repeatColumn = 0; repeatAppend = false; MotionGroup.moveCaret(editor, cpos); } /** * This repeats the previous insert count times * * @param editor The editor to insert into * @param context The data context * @param count The number of times to repeat the previous insert */ private void repeatInsertText(@NotNull Editor editor, @NotNull DataContext context, int count) { if (lastStrokes == null) { return; } for (int i = 0; i < count; i++) { // Treat other keys special by performing the appropriate action they represent in insert/replace mode for (Object lastStroke : lastStrokes) { if (lastStroke instanceof AnAction) { KeyHandler.executeAction((AnAction)lastStroke, context); strokes.add(lastStroke); } else if (lastStroke instanceof char[]) { final char[] chars = (char[])lastStroke; insertText(editor, editor.getCaretModel().getOffset(), new String(chars)); } } } } /** * Terminate insert/replace mode after the user presses Escape or Ctrl-C * * @param editor The editor that was being edited * @param context The data context */ public void processEscape(@NotNull Editor editor, @NotNull DataContext context) { logger.debug("processing escape"); int cnt = lastInsert != null ? lastInsert.getCount() : 0; // Turn off overwrite mode if we were in replace mode if (CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE) { KeyHandler.executeAction("VimInsertReplaceToggle", context); } // If this command doesn't allow repeats, set count to 1 if (lastInsert != null && (lastInsert.getFlags() & Command.FLAG_NO_REPEAT) != 0) { cnt = 1; } if (document != null && documentListener != null) { EventFacade.getInstance().removeDocumentListener(document, documentListener); documentListener = null; } // Save off current list of keystrokes lastStrokes = new ArrayList<Object>(strokes); // If the insert/replace command was preceded by a count, repeat again N - 1 times repeatInsert(editor, context, cnt == 0 ? 0 : cnt - 1, true); final MarkGroup markGroup = VimPlugin.getMark(); final int offset = editor.getCaretModel().getOffset(); markGroup.setMark(editor, '^', offset); markGroup.setMark(editor, MarkGroup.MARK_CHANGE_END, offset); markGroup.setMark(editor, MarkGroup.MARK_CHANGE_POS, offset); CommandState.getInstance(editor).popState(); if (!CommandState.inInsertMode(editor)) { resetCursor(editor, false); } } /** * Processes the Enter key by running the first successful action registered for "ENTER" keystroke. * * If this is REPLACE mode we need to turn off OVERWRITE before and then turn OVERWRITE back on after sending the * "ENTER" key. * * @param editor The editor to press "Enter" in * @param context The data context */ public void processEnter(@NotNull Editor editor, @NotNull DataContext context) { if (CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE) { KeyHandler.executeAction("EditorToggleInsertState", context); } final KeyStroke enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); final List<AnAction> actions = VimPlugin.getKey().getActions(editor.getComponent(), enterKeyStroke); for (AnAction action : actions) { if (KeyHandler.executeAction(action, context)) { break; } } if (CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE) { KeyHandler.executeAction("EditorToggleInsertState", context); } } /** * Processes the user pressing the Insert key while in INSERT or REPLACE mode. This simply toggles the * Insert/Overwrite state which updates the status bar. * * @param editor The editor to toggle the state in * @param context The data context */ public void processInsert(Editor editor, @NotNull DataContext context) { KeyHandler.executeAction("EditorToggleInsertState", context); CommandState.getInstance(editor).toggleInsertOverwrite(); inInsert = !inInsert; } /** * While in INSERT or REPLACE mode the user can enter a single NORMAL mode command and then automatically * return to INSERT or REPLACE mode. * * @param editor The editor to put into NORMAL mode for one command * */ public void processSingleCommand(@NotNull Editor editor) { CommandState.getInstance(editor).pushState(CommandState.Mode.COMMAND, CommandState.SubMode.SINGLE_COMMAND, MappingMode.NORMAL); clearStrokes(editor); } /** * Drafts an {@link ActionPlan} for preemptive rendering before "regular" keystroke processing in insert/replace mode. * * Like {@link #processKey(Editor, DataContext, KeyStroke)}, delegates the task to the original handler. * * @param editor The editor the character was typed into * @param context The data context * @param key The user entered keystroke * @param plan the current action plan draft */ public void beforeProcessKey(@NotNull final Editor editor, @NotNull final DataContext context, @NotNull final KeyStroke key, @NotNull ActionPlan plan) { final TypedActionHandler originalHandler = KeyHandler.getInstance().getOriginalHandler(); if (originalHandler instanceof TypedActionHandlerEx) { ((TypedActionHandlerEx)originalHandler).beforeExecute(editor, key.getKeyChar(), context, plan); } } /** * This processes all "regular" keystrokes entered while in insert/replace mode * * @param editor The editor the character was typed into * @param context The data context * @param key The user entered keystroke * @return true if this was a regular character, false if not */ public boolean processKey(@NotNull final Editor editor, @NotNull final DataContext context, @NotNull final KeyStroke key) { if (logger.isDebugEnabled()) { logger.debug("processKey(" + key + ")"); } if (key.getKeyChar() != KeyEvent.CHAR_UNDEFINED) { final Document doc = editor.getDocument(); CommandProcessor.getInstance().executeCommand(editor.getProject(), new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { KeyHandler.getInstance().getOriginalHandler().execute(editor, key.getKeyChar(), context); } }); } }, "", doc, UndoConfirmationPolicy.DEFAULT, doc); return true; } return false; } /** * This processes all keystrokes in Insert/Replace mode that were converted into Commands. Some of these * commands need to be saved off so the inserted/replaced text can be repeated properly later if needed. * * @param editor The editor the command was executed in * @param cmd The command that was executed * @return true if the command was stored for later repeat, false if not */ public boolean processCommand(@NotNull Editor editor, @NotNull Command cmd) { if ((cmd.getFlags() & Command.FLAG_SAVE_STROKE) != 0) { strokes.add(cmd.getAction()); return true; } else if ((cmd.getFlags() & Command.FLAG_CLEAR_STROKES) != 0) { clearStrokes(editor); return false; } else { return false; } } /** * Clears all the keystrokes from the current insert command * * @param editor The editor to clear strokes from. */ private void clearStrokes(@NotNull Editor editor) { strokes.clear(); repeatCharsCount = 0; insertStart = editor.getCaretModel().getOffset(); } /** * Deletes count characters from the editor * * @param editor The editor to remove the characters from * @param count The number of characters to delete * @return true if able to delete, false if not */ public boolean deleteCharacter(@NotNull Editor editor, int count, boolean isChange) { int offset = VimPlugin.getMotion().moveCaretHorizontal(editor, count, true); if (offset != -1) { boolean res = deleteText(editor, new TextRange(editor.getCaretModel().getOffset(), offset), SelectionType.CHARACTER_WISE); int pos = editor.getCaretModel().getOffset(); int norm = EditorHelper.normalizeOffset(editor, editor.getCaretModel().getLogicalPosition().line, pos, isChange); if (norm != pos) { MotionGroup.moveCaret(editor, norm); } return res; } return false; } /** * Deletes count lines including the current line * * @param editor The editor to remove the lines from * @param count The number of lines to delete * @return true if able to delete the lines, false if not */ public boolean deleteLine(@NotNull Editor editor, int count) { int start = VimPlugin.getMotion().moveCaretToLineStart(editor); int offset = Math.min(VimPlugin.getMotion().moveCaretToLineEndOffset(editor, count - 1, true) + 1, EditorHelper.getFileSize(editor, true)); if (logger.isDebugEnabled()) { logger.debug("start=" + start); logger.debug("offset=" + offset); } if (offset != -1) { boolean res = deleteText(editor, new TextRange(start, offset), SelectionType.LINE_WISE); if (res && editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) && editor.getCaretModel().getOffset() != 0) { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretToLineStartSkipLeadingOffset(editor, -1)); } return res; } return false; } /** * Delete from the cursor to the end of count - 1 lines down * * @param editor The editor to delete from * @param count The number of lines affected * @return true if able to delete the text, false if not */ public boolean deleteEndOfLine(@NotNull Editor editor, int count) { int offset = VimPlugin.getMotion().moveCaretToLineEndOffset(editor, count - 1, true); if (offset != -1) { boolean res = deleteText(editor, new TextRange(editor.getCaretModel().getOffset(), offset), SelectionType.CHARACTER_WISE); int pos = VimPlugin.getMotion().moveCaretHorizontal(editor, -1, false); if (pos != -1) { MotionGroup.moveCaret(editor, pos); } return res; } return false; } /** * Joins count lines together starting at the cursor. No count or a count of one still joins two lines. * * @param editor The editor to join the lines in * @param count The number of lines to join * @param spaces If true the joined lines will have one space between them and any leading space on the second line * will be removed. If false, only the newline is removed to join the lines. * @return true if able to join the lines, false if not */ public boolean deleteJoinLines(@NotNull Editor editor, int count, boolean spaces) { if (count < 2) count = 2; int lline = editor.getCaretModel().getLogicalPosition().line; int total = EditorHelper.getLineCount(editor); //noinspection SimplifiableIfStatement if (lline + count > total) { return false; } return deleteJoinNLines(editor, lline, count, spaces); } /** * Joins all the lines selected by the current visual selection. * * @param editor The editor to join the lines in * @param range The range of the visual selection * @param spaces If true the joined lines will have one space between them and any leading space on the second line * will be removed. If false, only the newline is removed to join the lines. * @return true if able to join the lines, false if not */ public boolean deleteJoinRange(@NotNull Editor editor, @NotNull TextRange range, boolean spaces) { int startLine = editor.offsetToLogicalPosition(range.getStartOffset()).line; int endLine = editor.offsetToLogicalPosition(range.getEndOffset()).line; int count = endLine - startLine + 1; if (count < 2) count = 2; return deleteJoinNLines(editor, startLine, count, spaces); } /** * This does the actual joining of the lines * * @param editor The editor to join the lines in * @param startLine The starting logical line * @param count The number of lines to join including startLine * @param spaces If true the joined lines will have one space between them and any leading space on the second line * will be removed. If false, only the newline is removed to join the lines. * @return true if able to join the lines, false if not */ private boolean deleteJoinNLines(@NotNull Editor editor, int startLine, int count, boolean spaces) { // start my moving the cursor to the very end of the first line MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretToLineEnd(editor, startLine, true)); for (int i = 1; i < count; i++) { int start = VimPlugin.getMotion().moveCaretToLineEnd(editor); int trailingWhitespaceStart = VimPlugin.getMotion().moveCaretToLineEndSkipLeading(editor); boolean hasTrailingWhitespace = start != trailingWhitespaceStart + 1; MotionGroup.moveCaret(editor, start); int offset; if (spaces) { offset = VimPlugin.getMotion().moveCaretToLineStartSkipLeadingOffset(editor, 1); } else { offset = VimPlugin.getMotion().moveCaretToLineStartOffset(editor); } deleteText(editor, new TextRange(editor.getCaretModel().getOffset(), offset), null); if (spaces && !hasTrailingWhitespace) { insertText(editor, start, " "); MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretHorizontal(editor, -1, false)); } } return true; } /** * Delete all text moved over by the supplied motion command argument. * * @param editor The editor to delete the text from * @param context The data context * @param count The number of times to repeat the deletion * @param rawCount The actual count entered by the user * @param argument The motion command * @param isChange if from a change * @return true if able to delete the text, false if not */ public boolean deleteMotion(@NotNull Editor editor, DataContext context, int count, int rawCount, @NotNull final Argument argument, boolean isChange) { final TextRange range = getDeleteMotionRange(editor, context, count, rawCount, argument); if (range == null) { return (EditorHelper.getFileSize(editor) == 0); } // Delete motion commands that are not linewise become linewise if all the following are true: // 1) The range is across multiple lines // 2) There is only whitespace before the start of the range // 3) There is only whitespace after the end of the range final Command motion = argument.getMotion(); if (motion == null) { return false; } if (!isChange && (motion.getFlags() & Command.FLAG_MOT_LINEWISE) == 0) { LogicalPosition start = editor.offsetToLogicalPosition(range.getStartOffset()); LogicalPosition end = editor.offsetToLogicalPosition(range.getEndOffset()); if (start.line != end.line) { if (!SearchHelper.anyNonWhitespace(editor, range.getStartOffset(), -1) && !SearchHelper.anyNonWhitespace(editor, range.getEndOffset(), 1)) { int flags = motion.getFlags(); flags &= ~Command.FLAG_MOT_EXCLUSIVE; flags &= ~Command.FLAG_MOT_INCLUSIVE; flags |= Command.FLAG_MOT_LINEWISE; motion.setFlags(flags); } } } return deleteRange(editor, range, SelectionType.fromCommandFlags(motion.getFlags()), isChange); } @Nullable public static TextRange getDeleteMotionRange(@NotNull Editor editor, DataContext context, int count, int rawCount, @NotNull Argument argument) { TextRange range = MotionGroup.getMotionRange(editor, context, count, rawCount, argument, true); // This is a kludge for dw, dW, and d[w. Without this kludge, an extra newline is deleted when it shouldn't be. if (range != null) { String text = editor.getDocument().getCharsSequence().subSequence(range.getStartOffset(), range.getEndOffset()).toString(); final int lastNewLine = text.lastIndexOf('\n'); if (lastNewLine > 0) { final Command motion = argument.getMotion(); if (motion != null) { final String id = ActionManager.getInstance().getId(motion.getAction()); if (id.equals("VimMotionWordRight") || id.equals("VimMotionBigWordRight") || id.equals("VimMotionCamelRight")) { if (!SearchHelper.anyNonWhitespace(editor, range.getEndOffset(), -1)) { final int start = range.getStartOffset(); range = new TextRange(start, start + lastNewLine); } } } } } return range; } /** * Delete the range of text. * * @param editor The editor to delete the text from * @param range The range to delete * @param type The type of deletion * @param isChange is from a change action * @return true if able to delete the text, false if not */ public boolean deleteRange(@NotNull Editor editor, @NotNull TextRange range, @Nullable SelectionType type, boolean isChange) { final boolean res = deleteText(editor, range, type); final int size = EditorHelper.getFileSize(editor); if (res) { final int pos; if (editor.getCaretModel().getOffset() > size) { pos = size - 1; } else { pos = EditorHelper.normalizeOffset(editor, range.getStartOffset(), isChange); } MotionGroup.moveCaret(editor, pos); } return res; } /** * Begin Replace mode * * @param editor The editor to replace in * @param context The data context * @return true */ public boolean changeReplace(@NotNull Editor editor, @NotNull DataContext context) { initInsert(editor, context, CommandState.Mode.REPLACE); return true; } /** * Replace each of the next count characters with the character ch * * @param editor The editor to change * @param count The number of characters to change * @param ch The character to change to * @return true if able to change count characters, false if not */ public boolean changeCharacter(@NotNull Editor editor, int count, char ch) { int col = editor.getCaretModel().getLogicalPosition().column; int len = EditorHelper.getLineLength(editor); int offset = editor.getCaretModel().getOffset(); if (len - col < count) { return false; } // Special case - if char is newline, only add one despite count int num = count; String space = null; if (ch == '\n') { num = 1; space = EditorHelper.getLeadingWhitespace(editor, editor.offsetToLogicalPosition(offset).line); if (logger.isDebugEnabled()) { logger.debug("space='" + space + "'"); } } StringBuilder repl = new StringBuilder(count); for (int i = 0; i < num; i++) { repl.append(ch); } replaceText(editor, offset, offset + count, repl.toString()); // Indent new line if we replaced with a newline if (ch == '\n') { insertText(editor, offset + 1, space); int slen = space.length(); if (slen == 0) { slen++; } editor.getCaretModel().moveToOffset(offset + slen); } return true; } /** * Each character in the supplied range gets replaced with the character ch * * @param editor The editor to change * @param range The range to change * @param ch The replacing character * @return true if able to change the range, false if not */ public boolean changeCharacterRange(@NotNull Editor editor, @NotNull TextRange range, char ch) { if (logger.isDebugEnabled()) { logger.debug("change range: " + range + " to " + ch); } CharSequence chars = editor.getDocument().getCharsSequence(); int[] starts = range.getStartOffsets(); int[] ends = range.getEndOffsets(); for (int j = ends.length - 1; j >= 0; j for (int i = starts[j]; i < ends[j]; i++) { if (i < chars.length() && '\n' != chars.charAt(i)) { replaceText(editor, i, i + 1, Character.toString(ch)); } } } return true; } /** * Delete count characters and then enter insert mode * * @param editor The editor to change * @param context The data context * @param count The number of characters to change * @return true if able to delete count characters, false if not */ public boolean changeCharacters(@NotNull Editor editor, @NotNull DataContext context, int count) { int len = EditorHelper.getLineLength(editor); int col = editor.getCaretModel().getLogicalPosition().column; if (col + count >= len) { return changeEndOfLine(editor, context, 1); } boolean res = deleteCharacter(editor, count, true); if (res) { initInsert(editor, context, CommandState.Mode.INSERT); } return res; } /** * Delete count lines and then enter insert mode * * @param editor The editor to change * @param context The data context * @param count The number of lines to change * @return true if able to delete count lines, false if not */ public boolean changeLine(@NotNull Editor editor, @NotNull DataContext context, int count) { final LogicalPosition pos = editor.offsetToLogicalPosition(editor.getCaretModel().getOffset()); final boolean insertBelow = pos.line + count >= EditorHelper.getLineCount(editor); boolean res = deleteLine(editor, count); if (res) { if (insertBelow) { insertNewLineBelow(editor, context); } else { insertNewLineAbove(editor, context); } } return res; } /** * Delete from the cursor to the end of count - 1 lines down and enter insert mode * * @param editor The editor to change * @param context The data context * @param count The number of lines to change * @return true if able to delete count lines, false if not */ public boolean changeEndOfLine(@NotNull Editor editor, @NotNull DataContext context, int count) { boolean res = deleteEndOfLine(editor, count); if (res) { insertAfterLineEnd(editor, context); } return res; } /** * Delete the text covered by the motion command argument and enter insert mode * * @param editor The editor to change * @param context The data context * @param count The number of time to repeat the change * @param rawCount The actual count entered by the user * @param argument The motion command * @return true if able to delete the text, false if not */ public boolean changeMotion(@NotNull Editor editor, @NotNull DataContext context, int count, int rawCount, @NotNull Argument argument) { // TODO: Hack - find better way to do this exceptional case - at least make constants out of these strings // Vim treats cw as ce and cW as cE if cursor is on a non-blank character final Command motion = argument.getMotion(); if (motion == null) { return false; } String id = ActionManager.getInstance().getId(motion.getAction()); boolean kludge = false; boolean bigWord = id.equals("VimMotionBigWordRight"); final CharSequence chars = editor.getDocument().getCharsSequence(); final int offset = editor.getCaretModel().getOffset(); final CharacterHelper.CharacterType charType = CharacterHelper.charType(chars.charAt(offset), bigWord); if (EditorHelper.getFileSize(editor) > 0 && charType != CharacterHelper.CharacterType.WHITESPACE) { final boolean lastWordChar = offset > EditorHelper.getFileSize(editor) || CharacterHelper.charType(chars.charAt(offset + 1), bigWord) != charType; final ImmutableSet<String> wordMotions = ImmutableSet.of( "VimMotionWordRight", "VimMotionBigWordRight", "VimMotionCamelRight"); if (wordMotions.contains(id) && lastWordChar) { final boolean res = deleteCharacter(editor, 1, true); if (res) { insertBeforeCursor(editor, context); } return res; } if (id.equals("VimMotionWordRight")) { kludge = true; motion.setAction(ActionManager.getInstance().getAction("VimMotionWordEndRight")); motion.setFlags(Command.FLAG_MOT_INCLUSIVE); } else if (id.equals("VimMotionBigWordRight")) { kludge = true; motion.setAction(ActionManager.getInstance().getAction("VimMotionBigWordEndRight")); motion.setFlags(Command.FLAG_MOT_INCLUSIVE); } else if (id.equals("VimMotionCamelRight")) { kludge = true; motion.setAction(ActionManager.getInstance().getAction("VimMotionCamelEndRight")); motion.setFlags(Command.FLAG_MOT_INCLUSIVE); } } if (kludge) { int size = EditorHelper.getFileSize(editor); int cnt = count * motion.getCount(); int pos1 = SearchHelper.findNextWordEnd(chars, offset, size, cnt, bigWord, false); int pos2 = SearchHelper.findNextWordEnd(chars, pos1, size, -cnt, bigWord, false); if (logger.isDebugEnabled()) { logger.debug("pos=" + offset); logger.debug("pos1=" + pos1); logger.debug("pos2=" + pos2); logger.debug("count=" + count); logger.debug("arg.count=" + motion.getCount()); } if (pos2 == offset) { if (count > 1) { count rawCount } else if (motion.getCount() > 1) { motion.setCount(motion.getCount() - 1); } else { motion.setFlags(Command.FLAG_MOT_EXCLUSIVE); } } } boolean res = deleteMotion(editor, context, count, rawCount, argument, true); if (res) { insertBeforeCursor(editor, context); } return res; } public boolean blockInsert(@NotNull Editor editor, @NotNull DataContext context, @NotNull TextRange range, boolean append) { int lines = getLinesCountInVisualBlock(editor, range); LogicalPosition start = editor.offsetToLogicalPosition(range.getStartOffset()); int line = start.line; int col = start.column; if (!range.isMultiple()) { col = 0; } else if (append) { col += range.getMaxLength(); if (EditorData.getLastColumn(editor) == MotionGroup.LAST_COLUMN) { col = MotionGroup.LAST_COLUMN; } } int len = EditorHelper.getLineLength(editor, line); if (col < MotionGroup.LAST_COLUMN && len < col) { String pad = EditorHelper.pad(editor, line, col); int off = editor.getDocument().getLineEndOffset(line); insertText(editor, off, pad); } if (range.isMultiple() || !append) { editor.getCaretModel().moveToOffset(editor.logicalPositionToOffset(new LogicalPosition(line, col))); } if (range.isMultiple()) { setInsertRepeat(lines, col, append); } if (range.isMultiple() || !append) { insertBeforeCursor(editor, context); } else { insertAfterCursor(editor, context); } return true; } /** * Deletes the range of text and enters insert mode * * @param editor The editor to change * @param context The data context * @param range The range to change * @param type The type of the range * @return true if able to delete the range, false if not */ public boolean changeRange(@NotNull Editor editor, @NotNull DataContext context, @NotNull TextRange range, @NotNull SelectionType type) { int col = 0; int lines = 0; if (type == SelectionType.BLOCK_WISE) { lines = getLinesCountInVisualBlock(editor, range); col = editor.offsetToLogicalPosition(range.getStartOffset()).column; if (EditorData.getLastColumn(editor) == MotionGroup.LAST_COLUMN) { col = MotionGroup.LAST_COLUMN; } } boolean after = range.getEndOffset() >= EditorHelper.getFileSize(editor); boolean res = deleteRange(editor, range, type, true); if (res) { if (type == SelectionType.LINE_WISE) { if (after) { insertNewLineBelow(editor, context); } else { insertNewLineAbove(editor, context); } } else { if (type == SelectionType.BLOCK_WISE) { setInsertRepeat(lines, col, false); } insertBeforeCursor(editor, context); } } return res; } /** * Counts number of lines in the visual block. * <p> * The result includes empty and short lines which does not have explicit start position (caret). * * @param editor The editor the block was selected in * @param range The range corresponding to the selected block * @return total number of lines */ private static int getLinesCountInVisualBlock(@NotNull Editor editor, @NotNull TextRange range) { final int[] startOffsets = range.getStartOffsets(); if (startOffsets.length == 0) return 0; final LogicalPosition firstStart = editor.offsetToLogicalPosition(startOffsets[0]); final LogicalPosition lastStart = editor.offsetToLogicalPosition(startOffsets[range.size() - 1]); return lastStart.line - firstStart.line + 1; } /** * Toggles the case of count characters * * @param editor The editor to change * @param count The number of characters to change * @return true if able to change count characters */ public boolean changeCaseToggleCharacter(@NotNull Editor editor, int count) { final int offset = VimPlugin.getMotion().moveCaretHorizontal(editor, count, true); if (offset == -1) { return false; } changeCase(editor, editor.getCaretModel().getOffset(), offset, CharacterHelper.CASE_TOGGLE); MotionGroup.moveCaret(editor, EditorHelper.normalizeOffset(editor, offset, false)); return true; } /** * Changes the case of all the character moved over by the motion argument. * * @param editor The editor to change * @param context The data context * @param count The number of times to repeat the change * @param rawCount The actual count entered by the user * @param type The case change type (TOGGLE, UPPER, LOWER) * @param argument The motion command * @return true if able to delete the text, false if not */ public boolean changeCaseMotion(@NotNull Editor editor, DataContext context, int count, int rawCount, char type, @NotNull Argument argument) { final TextRange range = MotionGroup.getMotionRange(editor, context, count, rawCount, argument, true); return range != null && changeCaseRange(editor, range, type); } /** * Changes the case of all the characters in the range * * @param editor The editor to change * @param range The range to change * @param type The case change type (TOGGLE, UPPER, LOWER) * @return true if able to delete the text, false if not */ public boolean changeCaseRange(@NotNull Editor editor, @NotNull TextRange range, char type) { int[] starts = range.getStartOffsets(); int[] ends = range.getEndOffsets(); for (int i = ends.length - 1; i >= 0; i changeCase(editor, starts[i], ends[i], type); } MotionGroup.moveCaret(editor, range.getStartOffset()); return true; } /** * This performs the actual case change. * * @param editor The editor to change * @param start The start offset to change * @param end The end offset to change * @param type The type of change (TOGGLE, UPPER, LOWER) */ private void changeCase(@NotNull Editor editor, int start, int end, char type) { if (start > end) { int t = end; end = start; start = t; } end = EditorHelper.normalizeOffset(editor, end); CharSequence chars = editor.getDocument().getCharsSequence(); StringBuilder sb = new StringBuilder(); for (int i = start; i < end; i++) { sb.append(CharacterHelper.changeCase(chars.charAt(i), type)); } replaceText(editor, start, end, sb.toString()); } public void autoIndentLines(@NotNull Editor editor, @NotNull DataContext context, int lines) { CaretModel caretModel = editor.getCaretModel(); int startLine = caretModel.getLogicalPosition().line; int endLine = startLine + lines - 1; if (endLine <= EditorHelper.getLineCount(editor)) { TextRange textRange = new TextRange(caretModel.getOffset(), editor.getDocument().getLineEndOffset(endLine)); autoIndentRange(editor, context, textRange); } } public void autoIndentMotion(@NotNull Editor editor, @NotNull DataContext context, int count, int rawCount, @NotNull Argument argument) { TextRange range = MotionGroup.getMotionRange(editor, context, count, rawCount, argument, false); if (range != null) { autoIndentRange(editor, context, range); } } public void autoIndentRange(@NotNull Editor editor, @NotNull DataContext context, @NotNull TextRange range) { int startLineOffset = EditorHelper.getLineStartForOffset(editor, range.getStartOffset()); int endLineOffset = EditorHelper.getLineEndForOffset(editor, range.getEndOffset()); editor.getSelectionModel().setSelection(startLineOffset, endLineOffset); KeyHandler.executeAction("AutoIndentLines", context); int firstLine = editor.offsetToLogicalPosition(Math.min(startLineOffset, endLineOffset)).line; int newOffset = VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, firstLine); MotionGroup.moveCaret(editor, newOffset); } public void reformatCode(@NotNull DataContext context) { KeyHandler.executeAction("ReformatCode", context); } public void indentLines(@NotNull Editor editor, @NotNull DataContext context, int lines, int dir) { int start = editor.getCaretModel().getOffset(); int end = VimPlugin.getMotion().moveCaretToLineEndOffset(editor, lines - 1, false); indentRange(editor, context, new TextRange(start, end), 1, dir); } public void indentMotion(@NotNull Editor editor, @NotNull DataContext context, int count, int rawCount, @NotNull Argument argument, int dir) { final TextRange range = MotionGroup.getMotionRange(editor, context, count, rawCount, argument, false); if (range != null) { indentRange(editor, context, range, 1, dir); } } public void indentRange(@NotNull Editor editor, @NotNull DataContext context, @NotNull TextRange range, int count, int dir) { if (logger.isDebugEnabled()) { logger.debug("count=" + count); } Project proj = PlatformDataKeys.PROJECT.getData(context); // API change - don't merge int tabSize = 8; int indentSize = 8; boolean useTabs = true; VirtualFile file = EditorData.getVirtualFile(editor); if (file != null) { FileType type = FileTypeManager.getInstance().getFileTypeByFile(file); CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(proj); tabSize = settings.getTabSize(type); indentSize = settings.getIndentSize(type); useTabs = settings.useTabCharacter(type); } int sline = editor.offsetToLogicalPosition(range.getStartOffset()).line; int eline = editor.offsetToLogicalPosition(range.getEndOffset()).line; if (range.isMultiple()) { int col = editor.offsetToLogicalPosition(range.getStartOffset()).column; int size = indentSize * count; if (dir == 1) { // Right shift blockwise selection StringBuilder space = new StringBuilder(); int tabCnt = 0; int spcCnt; if (useTabs) { tabCnt = size / tabSize; spcCnt = size % tabSize; } else { spcCnt = size; } for (int i = 0; i < tabCnt; i++) { space.append('\t'); } for (int i = 0; i < spcCnt; i++) { space.append(' '); } for (int l = sline; l <= eline; l++) { int len = EditorHelper.getLineLength(editor, l); if (len > col) { LogicalPosition spos = new LogicalPosition(l, col); insertText(editor, editor.logicalPositionToOffset(spos), space.toString()); } } } else { // Left shift blockwise selection CharSequence chars = editor.getDocument().getCharsSequence(); for (int l = sline; l <= eline; l++) { int len = EditorHelper.getLineLength(editor, l); if (len > col) { LogicalPosition spos = new LogicalPosition(l, col); LogicalPosition epos = new LogicalPosition(l, col + size - 1); int wsoff = editor.logicalPositionToOffset(spos); int weoff = editor.logicalPositionToOffset(epos); int pos; for (pos = wsoff; pos <= weoff; pos++) { if (CharacterHelper.charType(chars.charAt(pos), false) != CharacterHelper.CharacterType.WHITESPACE) { break; } } if (pos > wsoff) { deleteText(editor, new TextRange(wsoff, pos), null); } } } } } else { // Shift non-blockwise selection for (int l = sline; l <= eline; l++) { int soff = EditorHelper.getLineStartOffset(editor, l); int eoff = EditorHelper.getLineEndOffset(editor, l, true); int woff = VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, l); int col = editor.offsetToVisualPosition(woff).column; int newCol = Math.max(0, col + dir * indentSize * count); if (col > 0 || soff != eoff) { StringBuilder space = new StringBuilder(); int tabCnt = 0; int spcCnt; if (useTabs) { tabCnt = newCol / tabSize; spcCnt = newCol % tabSize; } else { spcCnt = newCol; } for (int i = 0; i < tabCnt; i++) { space.append('\t'); } for (int i = 0; i < spcCnt; i++) { space.append(' '); } replaceText(editor, soff, woff, space.toString()); } } } if (!CommandState.inInsertMode(editor)) { if (!range.isMultiple()) { MotionGroup.moveCaret(editor, VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, sline)); } else { MotionGroup.moveCaret(editor, range.getStartOffset()); } } EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column); } /** * Insert text into the document * * @param editor The editor to insert into * @param start The starting offset to insert at * @param str The text to insert */ public void insertText(@NotNull Editor editor, int start, @NotNull String str) { editor.getDocument().insertString(start, str); editor.getCaretModel().moveToOffset(start + str.length()); VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, start); } /** * Delete text from the document. This will fail if being asked to store the deleted text into a read-only * register. * * @param editor The editor to delete from * @param range The range to delete * @param type The type of deletion * @return true if able to delete the text, false if not */ private boolean deleteText(@NotNull final Editor editor, @NotNull final TextRange range, @Nullable SelectionType type) { if (!range.normalize(EditorHelper.getFileSize(editor, true))) { return false; } if (type == null || VimPlugin.getRegister().storeText(editor, range, type, true)) { final Document document = editor.getDocument(); final int[] startOffsets = range.getStartOffsets(); final int[] endOffsets = range.getEndOffsets(); for (int i = range.size() - 1; i >= 0; i document.deleteString(startOffsets[i], endOffsets[i]); } if (type != null) { int start = range.getStartOffset(); VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, start); VimPlugin.getMark().setChangeMarks(editor, new TextRange(start, start)); } return true; } return false; } /** * Replace text in the editor * * @param editor The editor to replace text in * @param start The start offset to change * @param end The end offset to change * @param str The new text */ private void replaceText(@NotNull Editor editor, int start, int end, @NotNull String str) { editor.getDocument().replaceString(start, end, str); final int newEnd = start + str.length(); VimPlugin.getMark().setChangeMarks(editor, new TextRange(start, newEnd)); VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, newEnd); } /** * Sort range of text with a given comparator * * @param editor The editor to replace text in * @param range The range to sort * @param lineComparator The comparator to use to sort * @return true if able to sort the text, false if not */ public boolean sortRange(@NotNull Editor editor, @NotNull LineRange range, @NotNull Comparator<String> lineComparator) { final int startLine = range.getStartLine(); final int endLine = range.getEndLine(); final int count = endLine - startLine + 1; if (count < 2) { return false; } final int startOffset = editor.getDocument().getLineStartOffset(startLine); final int endOffset = editor.getDocument().getLineEndOffset(endLine); return sortTextRange(editor, startOffset, endOffset, lineComparator); } /** * Sorts a text range with a comparator. Returns true if a replace was performed, false otherwise. * * @param editor The editor to replace text in * @param start The starting position for the sort * @param end The ending position for the sort * @param lineComparator The comparator to use to sort * @return true if able to sort the text, false if not */ private boolean sortTextRange(@NotNull Editor editor, int start, int end, @NotNull Comparator<String> lineComparator) { final String selectedText = editor.getDocument().getText(new TextRangeInterval(start, end)); final List<String> lines = Lists.newArrayList(Splitter.on("\n").split(selectedText)); if (lines.size() < 1) { return false; } Collections.sort(lines, lineComparator); replaceText(editor, start, end, StringUtil.join(lines, "\n")); return true; } public static void resetCursor(@NotNull Editor editor, boolean insert) { Document doc = editor.getDocument(); VirtualFile vf = FileDocumentManager.getInstance().getFile(doc); if (vf != null) { resetCursor(vf, editor.getProject(), insert); } else { editor.getSettings().setBlockCursor(!insert); } } private static void resetCursor(@NotNull VirtualFile virtualFile, Project proj, boolean insert) { logger.debug("resetCursor"); Document doc = FileDocumentManager.getInstance().getDocument(virtualFile); if (doc == null) return; // Must be no text editor (such as image) Editor[] editors = EditorFactory.getInstance().getEditors(doc, proj); if (logger.isDebugEnabled()) { logger.debug("There are " + editors.length + " editors for virtual file " + virtualFile.getName()); } for (Editor editor : editors) { editor.getSettings().setBlockCursor(!insert); } } public boolean changeNumber(@NotNull final Editor editor, final int count) { final BoundListOption nf = (BoundListOption)Options.getInstance().getOption("nrformats"); final boolean alpha = nf.contains("alpha"); final boolean hex = nf.contains("hex"); final boolean octal = nf.contains("octal"); final TextRange range = SearchHelper.findNumberUnderCursor(editor, alpha, hex, octal); if (range == null) { logger.debug("no number on line"); return false; } else { String text = EditorHelper.getText(editor, range); if (logger.isDebugEnabled()) { logger.debug("found range " + range); logger.debug("text=" + text); } String number = text; if (text.length() == 0) { return false; } char ch = text.charAt(0); if (hex && text.toLowerCase().startsWith("0x")) { for (int i = text.length() - 1; i >= 2; i int index = "abcdefABCDEF".indexOf(text.charAt(i)); if (index >= 0) { lastLower = index < 6; break; } } int num = (int)Long.parseLong(text.substring(2), 16); num += count; number = Integer.toHexString(num); number = StringHelper.rightJustify(number, text.length() - 2, '0'); if (!lastLower) { number = number.toUpperCase(); } number = text.substring(0, 2) + number; } else if (octal && text.startsWith("0") && text.length() > 1) { int num = (int)Long.parseLong(text, 8); num += count; number = Integer.toOctalString(num); number = "0" + StringHelper.rightJustify(number, text.length() - 1, '0'); } else if (alpha && Character.isLetter(ch)) { ch += count; if (Character.isLetter(ch)) { number = "" + ch; } } else if (ch == '-' || Character.isDigit(ch)) { boolean pad = ch == '0'; int len = text.length(); if (ch == '-' && text.charAt(1) == '0') { pad = true; len } int num = Integer.parseInt(text); num += count; number = Integer.toString(num); if (!octal && pad) { boolean neg = false; if (number.charAt(0) == '-') { neg = true; number = number.substring(1); } number = StringHelper.rightJustify(number, len, '0'); if (neg) { number = "-" + number; } } } if (!text.equals(number)) { replaceText(editor, range.getStartOffset(), range.getEndOffset(), number); editor.getCaretModel().moveToOffset(range.getStartOffset() + number.length() - 1); } return true; } } private final List<Object> strokes = new ArrayList<Object>(); private int repeatCharsCount; private List<Object> lastStrokes; private int insertStart; @Nullable private Command lastInsert; private boolean inInsert; private int repeatLines; private int repeatColumn; private boolean repeatAppend; private boolean lastLower = true; private Document document; @Nullable private DocumentAdapter documentListener; private int oldOffset = -1; private static final Logger logger = Logger.getInstance(ChangeGroup.class.getName()); }
package com.maddyhome.idea.vim.group; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManagerAdapter; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.impl.EditorTabbedContainer; import com.intellij.openapi.fileEditor.impl.EditorWindow; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.maddyhome.idea.vim.EventFacade; import com.maddyhome.idea.vim.KeyHandler; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.action.motion.MotionEditorAction; import com.maddyhome.idea.vim.action.motion.TextObjectAction; import com.maddyhome.idea.vim.command.*; import com.maddyhome.idea.vim.common.Jump; import com.maddyhome.idea.vim.common.Mark; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.ex.ExOutputModel; import com.maddyhome.idea.vim.helper.EditorData; import com.maddyhome.idea.vim.helper.EditorHelper; import com.maddyhome.idea.vim.helper.SearchHelper; import com.maddyhome.idea.vim.option.BoundStringOption; import com.maddyhome.idea.vim.option.NumberOption; import com.maddyhome.idea.vim.option.Options; import com.maddyhome.idea.vim.ui.ExEntryPanel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.event.MouseEvent; import java.io.File; /** * This handles all motion related commands and marks */ public class MotionGroup { public static final int LAST_F = 1; public static final int LAST_f = 2; public static final int LAST_T = 3; public static final int LAST_t = 4; public static final int LAST_COLUMN = 9999; /** * Create the group */ public MotionGroup() { EventFacade.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() { public void editorCreated(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); // This ridiculous code ensures that a lot of events are processed BEFORE we finally start listening // to visible area changes. The primary reason for this change is to fix the cursor position bug // using the gd and gD commands (Goto Declaration). This bug has been around since Idea 6.0.4? // Prior to this change the visible area code was moving the cursor around during file load and messing // with the cursor position of the Goto Declaration processing. ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { addEditorListener(editor); EditorData.setMotionGroup(editor, true); } }); } }); } }); } public void editorReleased(@NotNull EditorFactoryEvent event) { Editor editor = event.getEditor(); if (EditorData.getMotionGroup(editor)) { removeEditorListener(editor); EditorData.setMotionGroup(editor, false); } } }, ApplicationManager.getApplication()); } public void turnOn() { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { if (!EditorData.getMotionGroup(editor)){ addEditorListener(editor); EditorData.setMotionGroup(editor, true); } } } public void turnOff() { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { if (EditorData.getMotionGroup(editor)){ removeEditorListener(editor); EditorData.setMotionGroup(editor, false); } } } private void addEditorListener(@NotNull Editor editor) { final EventFacade eventFacade = EventFacade.getInstance(); eventFacade.addEditorMouseListener(editor, mouseHandler); eventFacade.addEditorMouseMotionListener(editor, mouseHandler); eventFacade.addEditorSelectionListener(editor, selectionHandler); } private void removeEditorListener(@NotNull Editor editor) { final EventFacade eventFacade = EventFacade.getInstance(); eventFacade.removeEditorMouseListener(editor, mouseHandler); eventFacade.removeEditorMouseMotionListener(editor, mouseHandler); eventFacade.removeEditorSelectionListener(editor, selectionHandler); } /** * Process mouse clicks by setting/resetting visual mode. There are some strange scenarios to handle. * * @param editor The editor * @param event The mouse event */ private void processMouseClick(@NotNull Editor editor, @NotNull MouseEvent event) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } ExOutputModel.getInstance(editor).clear(); CommandState.SubMode visualMode = CommandState.SubMode.NONE; switch (event.getClickCount() % 3) { case 1: // Single click or quad click visualMode = CommandState.SubMode.NONE; break; case 2: // Double click visualMode = CommandState.SubMode.VISUAL_CHARACTER; break; case 0: // Triple click visualMode = CommandState.SubMode.VISUAL_LINE; // Pop state of being in Visual Char mode if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); editor.getSelectionModel().setSelection(start, Math.max(start, end - 1)); break; } setVisualMode(editor, visualMode); switch (CommandState.getInstance(editor).getSubMode()) { case NONE: VisualPosition vp = editor.getCaretModel().getVisualPosition(); int col = EditorHelper.normalizeVisualColumn(editor, vp.line, vp.column, CommandState.getInstance(editor).getMode() == CommandState.Mode.INSERT || CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE); if (col != vp.column) { editor.getCaretModel().moveToVisualPosition(new VisualPosition(vp.line, col)); } MotionGroup.scrollCaretIntoView(editor); break; case VISUAL_CHARACTER: editor.getCaretModel().moveToOffset(visualEnd); break; case VISUAL_LINE: editor.getCaretModel().moveToLogicalPosition(editor.xyToLogicalPosition(event.getPoint())); break; } visualOffset = editor.getCaretModel().getOffset(); EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column); } /** * Handles mouse drags by properly setting up visual mode based on the new selection. * * @param editor The editor the mouse drag occurred in. * @param update True if update, false if not. */ private void processLineSelection(@NotNull Editor editor, boolean update) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } ExOutputModel.getInstance(editor).clear(); if (update) { if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { updateSelection(editor, editor.getCaretModel().getOffset()); } } else { if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); editor.getSelectionModel().setSelection(start, Math.max(start, end - 1)); setVisualMode(editor, CommandState.SubMode.VISUAL_LINE); VisualChange range = getVisualOperatorRange(editor, Command.FLAG_MOT_LINEWISE); if (range.getLines() > 1) { MotionGroup.moveCaret(editor, moveCaretVertical(editor, -1)); } } } private void processMouseReleased(@NotNull Editor editor, @NotNull CommandState.SubMode mode, int startOff, int endOff) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } ExOutputModel.getInstance(editor).clear(); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); if (mode == CommandState.SubMode.VISUAL_LINE) { end endOff } if (end == startOff || end == endOff) { int t = start; start = end; end = t; if (mode == CommandState.SubMode.VISUAL_CHARACTER) { start } } MotionGroup.moveCaret(editor, start); toggleVisual(editor, 1, 0, mode); MotionGroup.moveCaret(editor, end); KeyHandler.getInstance().reset(editor); } @NotNull public TextRange getWordRange(@NotNull Editor editor, int count, boolean isOuter, boolean isBig) { int dir = 1; boolean selection = false; if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { if (visualEnd < visualStart) { dir = -1; } if (visualStart != visualEnd) { selection = true; } } return SearchHelper.findWordUnderCursor(editor, count, dir, isOuter, isBig, selection); } @Nullable public TextRange getBlockQuoteRange(@NotNull Editor editor, char quote, boolean isOuter) { return SearchHelper.findBlockQuoteInLineRange(editor, quote, isOuter); } @Nullable public TextRange getBlockRange(@NotNull Editor editor, int count, boolean isOuter, char type) { return SearchHelper.findBlockRange(editor, type, count, isOuter); } @NotNull public TextRange getSentenceRange(@NotNull Editor editor, int count, boolean isOuter) { return SearchHelper.findSentenceRange(editor, count, isOuter); } @Nullable public TextRange getParagraphRange(@NotNull Editor editor, int count, boolean isOuter) { return SearchHelper.findParagraphRange(editor, count, isOuter); } /** * This helper method calculates the complete range a motion will move over taking into account whether * the motion is FLAG_MOT_LINEWISE or FLAG_MOT_CHARACTERWISE (FLAG_MOT_INCLUSIVE or FLAG_MOT_EXCLUSIVE). * * @param editor The editor the motion takes place in * @param context The data context * @param count The count applied to the motion * @param rawCount The actual count entered by the user * @param argument Any argument needed by the motion * @param incNewline True if to include newline * @return The motion's range */ @Nullable public static TextRange getMotionRange(@NotNull Editor editor, DataContext context, int count, int rawCount, @NotNull Argument argument, boolean incNewline) { final Command cmd = argument.getMotion(); if (cmd == null) { return null; } // Normalize the counts between the command and the motion argument int cnt = cmd.getCount() * count; int raw = rawCount == 0 && cmd.getRawCount() == 0 ? 0 : cnt; int start = 0; int end = 0; if (cmd.getAction() instanceof MotionEditorAction) { MotionEditorAction action = (MotionEditorAction)cmd.getAction(); // This is where we are now start = editor.getCaretModel().getOffset(); // Execute the motion (without moving the cursor) and get where we end end = action.getOffset(editor, context, cnt, raw, cmd.getArgument()); // Invalid motion if (end == -1) { return null; } } else if (cmd.getAction() instanceof TextObjectAction) { TextObjectAction action = (TextObjectAction)cmd.getAction(); TextRange range = action.getRange(editor, context, cnt, raw, cmd.getArgument()); if (range == null) { return null; } start = range.getStartOffset(); end = range.getEndOffset(); } // If we are a linewise motion we need to normalize the start and stop then move the start to the beginning // of the line and move the end to the end of the line. int flags = cmd.getFlags(); if ((flags & Command.FLAG_MOT_LINEWISE) != 0) { if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.getLineStartForOffset(editor, start); end = Math.min(EditorHelper.getLineEndForOffset(editor, end) + (incNewline ? 1 : 0), EditorHelper.getFileSize(editor)); } // If characterwise and inclusive, add the last character to the range else if ((flags & Command.FLAG_MOT_INCLUSIVE) != 0) { end++; } // Normalize the range if (start > end) { int t = start; start = end; end = t; } return new TextRange(start, end); } public int moveCaretToNthCharacter(@NotNull Editor editor, int count) { return Math.max(0, Math.min(count, EditorHelper.getFileSize(editor) - 1)); } public int moveCaretToMarkLine(final @NotNull Editor editor, char ch) { final Mark mark = VimPlugin.getMark().getMark(editor, ch); if (mark != null) { final VirtualFile vf = EditorData.getVirtualFile(editor); if (vf == null) { return -1; } final int line = mark.getLogicalLine(); if (!vf.getPath().equals(mark.getFilename())) { final Editor selectedEditor = selectEditor(editor, vf); if (selectedEditor != null) { moveCaret(selectedEditor, moveCaretToLineStartSkipLeading(selectedEditor, line)); } return -2; } else { return moveCaretToLineStartSkipLeading(editor, line); } } else { return -1; } } public int moveCaretToFileMarkLine(@NotNull Editor editor, char ch) { Mark mark = VimPlugin.getMark().getFileMark(editor, ch); if (mark != null) { int line = mark.getLogicalLine(); return moveCaretToLineStartSkipLeading(editor, line); } else { return -1; } } public int moveCaretToMark(@NotNull final Editor editor, char ch) { final Mark mark = VimPlugin.getMark().getMark(editor, ch); if (mark != null) { final VirtualFile vf = EditorData.getVirtualFile(editor); if (vf == null) { return -1; } final LogicalPosition lp = new LogicalPosition(mark.getLogicalLine(), mark.getCol()); if (!vf.getPath().equals(mark.getFilename())) { final Editor selectedEditor = selectEditor(editor, vf); if (selectedEditor != null) { moveCaret(selectedEditor, selectedEditor.logicalPositionToOffset(lp)); } return -2; } else { return editor.logicalPositionToOffset(lp); } } else { return -1; } } public int moveCaretToJump(@NotNull Editor editor, int count) { int spot = VimPlugin.getMark().getJumpSpot(); Jump jump = VimPlugin.getMark().getJump(count); if (jump != null) { VirtualFile vf = EditorData.getVirtualFile(editor); if (vf == null) return -1; LogicalPosition lp = new LogicalPosition(jump.getLogicalLine(), jump.getCol()); final String filename = jump.getFilename(); if (!vf.getPath().equals(filename) && filename != null) { VirtualFile newFile = LocalFileSystem.getInstance().findFileByPath(filename.replace(File.separatorChar, '/')); if (newFile == null) return -2; Editor newEditor = selectEditor(editor, newFile); if (newEditor != null) { if (spot == -1) { VimPlugin.getMark().addJump(editor, false); } moveCaret(newEditor, EditorHelper.normalizeOffset(newEditor, newEditor.logicalPositionToOffset(lp), false)); } return -2; } else { if (spot == -1) { VimPlugin.getMark().addJump(editor, false); } return editor.logicalPositionToOffset(lp); } } else { return -1; } } public int moveCaretToFileMark(@NotNull Editor editor, char ch) { Mark mark = VimPlugin.getMark().getFileMark(editor, ch); if (mark != null) { LogicalPosition lp = new LogicalPosition(mark.getLogicalLine(), mark.getCol()); return editor.logicalPositionToOffset(lp); } else { return -1; } } @Nullable private Editor selectEditor(@NotNull Editor editor, @NotNull VirtualFile file) { return VimPlugin.getFile().selectEditor(editor.getProject(), file); } public int moveCaretToMatchingPair(@NotNull Editor editor) { int pos = SearchHelper.findMatchingPairOnCurrentLine(editor); if (pos >= 0) { return pos; } else { return -1; } } /** * This moves the caret to the start of the next/previous camel word. * * @param editor The editor to move in * @param count The number of words to skip * @return position */ public int moveCaretToNextCamel(@NotNull Editor editor, int count) { if ((editor.getCaretModel().getOffset() == 0 && count < 0) || (editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { return SearchHelper.findNextCamelStart(editor, count); } } /** * This moves the caret to the start of the next/previous camel word. * * @param editor The editor to move in * @param count The number of words to skip * @return position */ public int moveCaretToNextCamelEnd(@NotNull Editor editor, int count) { if ((editor.getCaretModel().getOffset() == 0 && count < 0) || (editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { return SearchHelper.findNextCamelEnd(editor, count); } } /** * This moves the caret to the start of the next/previous word/WORD. * * @param editor The editor to move in * @param count The number of words to skip * @param bigWord If true then find WORD, if false then find word * @return position */ public int moveCaretToNextWord(@NotNull Editor editor, int count, boolean bigWord) { final int offset = editor.getCaretModel().getOffset(); final int size = EditorHelper.getFileSize(editor); if ((offset == 0 && count < 0) || (offset >= size - 1 && count > 0)) { return -1; } return SearchHelper.findNextWord(editor, count, bigWord); } /** * This moves the caret to the end of the next/previous word/WORD. * * @param editor The editor to move in * @param count The number of words to skip * @param bigWord If true then find WORD, if false then find word * @return position */ public int moveCaretToNextWordEnd(@NotNull Editor editor, int count, boolean bigWord) { if ((editor.getCaretModel().getOffset() == 0 && count < 0) || (editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } // If we are doing this move as part of a change command (e.q. cw), we need to count the current end of // word if the cursor happens to be on the end of a word already. If this is a normal move, we don't count // the current word. int pos = SearchHelper.findNextWordEnd(editor, count, bigWord); if (pos == -1) { if (count < 0) { return moveCaretToLineStart(editor, 0); } else { return moveCaretToLineEnd(editor, EditorHelper.getLineCount(editor) - 1, false); } } else { return pos; } } /** * This moves the caret to the start of the next/previous paragraph. * * @param editor The editor to move in * @param count The number of paragraphs to skip * @return position */ public int moveCaretToNextParagraph(@NotNull Editor editor, int count) { int res = SearchHelper.findNextParagraph(editor, count, false); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, true); } else { res = -1; } return res; } public int moveCaretToNextSentenceStart(@NotNull Editor editor, int count) { int res = SearchHelper.findNextSentenceStart(editor, count, false, true); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, true); } else { res = -1; } return res; } public int moveCaretToNextSentenceEnd(@NotNull Editor editor, int count) { int res = SearchHelper.findNextSentenceEnd(editor, count, false, true); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, false); } else { res = -1; } return res; } public int moveCaretToUnmatchedBlock(@NotNull Editor editor, int count, char type) { if ((editor.getCaretModel().getOffset() == 0 && count < 0) || (editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { int res = SearchHelper.findUnmatchedBlock(editor, type, count); if (res != -1) { res = EditorHelper.normalizeOffset(editor, res, false); } return res; } } public int moveCaretToSection(@NotNull Editor editor, char type, int dir, int count) { if ((editor.getCaretModel().getOffset() == 0 && count < 0) || (editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { int res = SearchHelper.findSection(editor, type, dir, count); if (res != -1) { res = EditorHelper.normalizeOffset(editor, res, false); } return res; } } public int moveCaretToMethodStart(@NotNull Editor editor, int count) { return SearchHelper.findMethodStart(editor, count); } public int moveCaretToMethodEnd(@NotNull Editor editor, int count) { return SearchHelper.findMethodEnd(editor, count); } public void setLastFTCmd(int lastFTCmd, char lastChar) { this.lastFTCmd = lastFTCmd; this.lastFTChar = lastChar; } public int repeatLastMatchChar(@NotNull Editor editor, int count) { int res = -1; int startPos = editor.getCaretModel().getOffset(); switch (lastFTCmd) { case LAST_F: res = moveCaretToNextCharacterOnLine(editor, -count, lastFTChar); break; case LAST_f: res = moveCaretToNextCharacterOnLine(editor, count, lastFTChar); break; case LAST_T: res = moveCaretToBeforeNextCharacterOnLine(editor, -count, lastFTChar); if (res == startPos && Math.abs(count) == 1) { res = moveCaretToBeforeNextCharacterOnLine(editor, 2 * count, lastFTChar); } break; case LAST_t: res = moveCaretToBeforeNextCharacterOnLine(editor, count, lastFTChar); if (res == startPos && Math.abs(count) == 1) { res = moveCaretToBeforeNextCharacterOnLine(editor, 2 * count, lastFTChar); } break; } return res; } /** * This moves the caret to the next/previous matching character on the current line * * @param count The number of occurrences to move to * @param ch The character to search for * @param editor The editor to search in * @return True if [count] character matches were found, false if not */ public int moveCaretToNextCharacterOnLine(@NotNull Editor editor, int count, char ch) { int pos = SearchHelper.findNextCharacterOnLine(editor, count, ch); if (pos >= 0) { return pos; } else { return -1; } } /** * This moves the caret next to the next/previous matching character on the current line * * @param count The number of occurrences to move to * @param ch The character to search for * @param editor The editor to search in * @return True if [count] character matches were found, false if not */ public int moveCaretToBeforeNextCharacterOnLine(@NotNull Editor editor, int count, char ch) { int pos = SearchHelper.findNextCharacterOnLine(editor, count, ch); if (pos >= 0) { int step = count >= 0 ? 1 : -1; return pos - step; } else { return -1; } } public boolean scrollLineToFirstScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) { scrollLineToScreenLine(editor, 1, rawCount, count, start); return true; } public boolean scrollLineToMiddleScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) { scrollLineToScreenLine(editor, EditorHelper.getScreenHeight(editor) / 2 + 1, rawCount, count, start); return true; } public boolean scrollLineToLastScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) { scrollLineToScreenLine(editor, EditorHelper.getScreenHeight(editor), rawCount, count, start); return true; } public boolean scrollColumnToFirstScreenColumn(@NotNull Editor editor) { scrollColumnToScreenColumn(editor, 0); return true; } public boolean scrollColumnToLastScreenColumn(@NotNull Editor editor) { scrollColumnToScreenColumn(editor, EditorHelper.getScreenWidth(editor)); return true; } private void scrollColumnToScreenColumn(@NotNull Editor editor, int column) { int scrollOffset = ((NumberOption)Options.getInstance().getOption("sidescrolloff")).value(); int width = EditorHelper.getScreenWidth(editor); if (scrollOffset > width / 2) { scrollOffset = width / 2; } if (column <= width / 2) { if (column < scrollOffset + 1) { column = scrollOffset + 1; } } else { if (column > width - scrollOffset) { column = width - scrollOffset; } } int visualColumn = editor.getCaretModel().getVisualPosition().column; scrollColumnToLeftOfScreen(editor, EditorHelper .normalizeVisualColumn(editor, editor.getCaretModel().getVisualPosition().line, visualColumn - column + 1, false)); } private void scrollLineToScreenLine(@NotNull Editor editor, int line, int rawCount, int count, boolean start) { int scrollOffset = ((NumberOption)Options.getInstance().getOption("scrolloff")).value(); int height = EditorHelper.getScreenHeight(editor); if (scrollOffset > height / 2) { scrollOffset = height / 2; } if (line <= height / 2) { if (line < scrollOffset + 1) { line = scrollOffset + 1; } } else { if (line > height - scrollOffset) { line = height - scrollOffset; } } int visualLine = rawCount == 0 ? editor.getCaretModel().getVisualPosition().line : EditorHelper.logicalLineToVisualLine(editor, count - 1); scrollLineToTopOfScreen(editor, EditorHelper.normalizeVisualLine(editor, visualLine - line + 1)); if (visualLine != editor.getCaretModel().getVisualPosition().line || start) { int offset; if (start) { offset = moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, visualLine)); } else { offset = moveCaretVertical(editor, EditorHelper.visualLineToLogicalLine(editor, visualLine) - editor.getCaretModel().getLogicalPosition().line); } moveCaret(editor, offset); } } public int moveCaretToFirstScreenLine(@NotNull Editor editor, int count) { return moveCaretToScreenLine(editor, count); } public int moveCaretToLastScreenLine(@NotNull Editor editor, int count) { return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) - count + 1); } public int moveCaretToMiddleScreenLine(@NotNull Editor editor) { return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) / 2 + 1); } private int moveCaretToScreenLine(@NotNull Editor editor, int line) { //saveJumpLocation(editor, context); int scrollOffset = ((NumberOption)Options.getInstance().getOption("scrolloff")).value(); int height = EditorHelper.getScreenHeight(editor); if (scrollOffset > height / 2) { scrollOffset = height / 2; } int top = EditorHelper.getVisualLineAtTopOfScreen(editor); if (line > height - scrollOffset && top < EditorHelper.getLineCount(editor) - height) { line = height - scrollOffset; } else if (line <= scrollOffset && top > 0) { line = scrollOffset + 1; } return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, top + line - 1)); } public boolean scrollHalfPage(@NotNull Editor editor, int dir, int count) { NumberOption scroll = (NumberOption)Options.getInstance().getOption("scroll"); int height = EditorHelper.getScreenHeight(editor) / 2; if (count == 0) { count = scroll.value(); if (count == 0) { count = height; } } else { scroll.set(count); } return scrollPage(editor, dir, count, EditorHelper.getCurrentVisualScreenLine(editor), true); } public boolean scrollColumn(@NotNull Editor editor, int columns) { int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); visualColumn = EditorHelper.normalizeVisualColumn(editor, editor.getCaretModel().getVisualPosition().line, visualColumn + columns, false); scrollColumnToLeftOfScreen(editor, visualColumn); moveCaretToView(editor); return true; } public boolean scrollLine(@NotNull Editor editor, int lines) { int visualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); visualLine = EditorHelper.normalizeVisualLine(editor, visualLine + lines); scrollLineToTopOfScreen(editor, visualLine); moveCaretToView(editor); return true; } public static void moveCaretToView(@NotNull Editor editor) { int scrollOffset = ((NumberOption)Options.getInstance().getOption("scrolloff")).value(); int sideScrollOffset = ((NumberOption)Options.getInstance().getOption("sidescrolloff")).value(); int height = EditorHelper.getScreenHeight(editor); int width = EditorHelper.getScreenWidth(editor); if (scrollOffset > height / 2) { scrollOffset = height / 2; } if (sideScrollOffset > width / 2) { sideScrollOffset = width / 2; } int visualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); int cline = editor.getCaretModel().getVisualPosition().line; int newline = cline; if (cline < visualLine + scrollOffset) { newline = EditorHelper.normalizeVisualLine(editor, visualLine + scrollOffset); } else if (cline >= visualLine + height - scrollOffset) { newline = EditorHelper.normalizeVisualLine(editor, visualLine + height - scrollOffset - 1); } int col = editor.getCaretModel().getVisualPosition().column; int oldColumn = col; if (col >= EditorHelper.getLineLength(editor) - 1) { col = EditorData.getLastColumn(editor); } int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); int caretColumn = col; int newColumn = caretColumn; if (caretColumn < visualColumn + sideScrollOffset) { newColumn = visualColumn + sideScrollOffset; } else if (caretColumn >= visualColumn + width - sideScrollOffset) { newColumn = visualColumn + width - sideScrollOffset - 1; } if (newline == cline && newColumn != caretColumn) { col = newColumn; } newColumn = EditorHelper.normalizeVisualColumn(editor, newline, newColumn, CommandState.inInsertMode(editor)); if (newline != cline || newColumn != oldColumn) { int offset = EditorHelper.visualPositionToOffset(editor, new VisualPosition(newline, newColumn)); moveCaret(editor, offset); EditorData.setLastColumn(editor, col); } } public boolean scrollFullPage(@NotNull Editor editor, int pages) { int height = EditorHelper.getScreenHeight(editor); int line = pages > 0 ? 1 : height; return scrollPage(editor, pages, height - 2, line, false); } public boolean scrollPage(@NotNull Editor editor, int pages, int height, int line, boolean partial) { int visualTopLine = EditorHelper.getVisualLineAtTopOfScreen(editor); int newLine = visualTopLine + pages * height; int topLine = EditorHelper.normalizeVisualLine(editor, newLine); boolean moved = scrollLineToTopOfScreen(editor, topLine); visualTopLine = EditorHelper.getVisualLineAtTopOfScreen(editor); if (moved && topLine == newLine && topLine == visualTopLine) { moveCaret(editor, moveCaretToScreenLine(editor, line)); return true; } else if (moved && !partial) { int visualLine = Math.abs(visualTopLine - newLine) % height + 1; if (pages < 0) { visualLine = height - visualLine + 3; } moveCaret(editor, moveCaretToScreenLine(editor, visualLine)); return true; } else if (partial) { int cline = editor.getCaretModel().getVisualPosition().line; int visualLine = cline + pages * height; visualLine = EditorHelper.normalizeVisualLine(editor, visualLine); if (cline == visualLine) { return false; } int logicalLine = editor.visualToLogicalPosition(new VisualPosition(visualLine, 0)).line; moveCaret(editor, moveCaretToLineStartSkipLeading(editor, logicalLine)); return true; } else { moveCaret(editor, moveCaretToLineStartSkipLeading(editor)); return false; } } private static boolean scrollLineToTopOfScreen(@NotNull Editor editor, int line) { int pos = line * editor.getLineHeight(); int verticalPos = editor.getScrollingModel().getVerticalScrollOffset(); editor.getScrollingModel().scrollVertically(pos); return verticalPos != editor.getScrollingModel().getVerticalScrollOffset(); } private static void scrollColumnToLeftOfScreen(@NotNull Editor editor, int column) { editor.getScrollingModel().scrollHorizontally(column * EditorHelper.getColumnWidth(editor)); } public int moveCaretToMiddleColumn(@NotNull Editor editor) { int width = EditorHelper.getScreenWidth(editor) / 2; int len = EditorHelper.getLineLength(editor); return moveCaretToColumn(editor, Math.max(0, Math.min(len - 1, width)), false); } public int moveCaretToColumn(@NotNull Editor editor, int count, boolean allowEnd) { int line = editor.getCaretModel().getLogicalPosition().line; int pos = EditorHelper.normalizeColumn(editor, line, count, allowEnd); return editor.logicalPositionToOffset(new LogicalPosition(line, pos)); } public int moveCaretToLineStartSkipLeading(@NotNull Editor editor) { int logicalLine = editor.getCaretModel().getLogicalPosition().line; return moveCaretToLineStartSkipLeading(editor, logicalLine); } public int moveCaretToLineStartSkipLeadingOffset(@NotNull Editor editor, int offset) { int line = EditorHelper.normalizeVisualLine(editor, editor.getCaretModel().getVisualPosition().line + offset); return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line)); } public int moveCaretToLineStartSkipLeading(@NotNull Editor editor, int line) { return EditorHelper.getLeadingCharacterOffset(editor, line); } public int moveCaretToLineEndSkipLeading(@NotNull Editor editor) { int logicalLine = editor.getCaretModel().getLogicalPosition().line; return moveCaretToLineEndSkipLeading(editor, logicalLine); } public int moveCaretToLineEndSkipLeading(@NotNull Editor editor, int line) { int start = EditorHelper.getLineStartOffset(editor, line); int end = EditorHelper.getLineEndOffset(editor, line, true); CharSequence chars = editor.getDocument().getCharsSequence(); int pos = start; for (int offset = end; offset > start; offset if (offset >= chars.length()) { break; } if (!Character.isWhitespace(chars.charAt(offset))) { pos = offset; break; } } return pos; } public int moveCaretToLineEnd(@NotNull Editor editor) { return moveCaretToLineEnd(editor, editor.getCaretModel().getLogicalPosition().line, true); } public int moveCaretToLineEnd(@NotNull Editor editor, int line, boolean allowPastEnd) { return EditorHelper.normalizeOffset(editor, line, EditorHelper.getLineEndOffset(editor, line, allowPastEnd), allowPastEnd); } public int moveCaretToLineEndOffset(@NotNull Editor editor, int cntForward, boolean allowPastEnd) { int line = EditorHelper.normalizeVisualLine(editor, editor.getCaretModel().getVisualPosition().line + cntForward); if (line < 0) { return 0; } else { return moveCaretToLineEnd(editor, EditorHelper.visualLineToLogicalLine(editor, line), allowPastEnd); } } public int moveCaretToLineStart(@NotNull Editor editor) { int logicalLine = editor.getCaretModel().getLogicalPosition().line; return moveCaretToLineStart(editor, logicalLine); } public int moveCaretToLineStart(@NotNull Editor editor, int line) { if (line >= EditorHelper.getLineCount(editor)) { return EditorHelper.getFileSize(editor); } return EditorHelper.getLineStartOffset(editor, line); } public int moveCaretToLineStartOffset(@NotNull Editor editor) { int line = EditorHelper.normalizeVisualLine(editor, editor.getCaretModel().getVisualPosition().line + 1); return moveCaretToLineStart(editor, EditorHelper.visualLineToLogicalLine(editor, line)); } public int moveCaretToLineScreenStart(@NotNull Editor editor) { int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor); return moveCaretToColumn(editor, col, false); } public int moveCaretToLineScreenStartSkipLeading(@NotNull Editor editor) { int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor); int logicalLine = editor.getCaretModel().getLogicalPosition().line; return EditorHelper.getLeadingCharacterOffset(editor, logicalLine, col); } public int moveCaretToLineScreenEnd(@NotNull Editor editor, boolean allowEnd) { int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor) + EditorHelper.getScreenWidth(editor) - 1; return moveCaretToColumn(editor, col, allowEnd); } public int moveCaretHorizontalWrap(@NotNull Editor editor, int count) { // FIX - allows cursor over newlines int oldOffset = editor.getCaretModel().getOffset(); int offset = Math.min(Math.max(0, editor.getCaretModel().getOffset() + count), EditorHelper.getFileSize(editor)); if (offset == oldOffset) { return -1; } else { return offset; } } public int moveCaretHorizontal(@NotNull Editor editor, int count, boolean allowPastEnd) { int oldOffset = editor.getCaretModel().getOffset(); int offset = EditorHelper.normalizeOffset(editor, editor.getCaretModel().getLogicalPosition().line, oldOffset + count, allowPastEnd); if (offset == oldOffset) { return -1; } else { return offset; } } public int moveCaretVertical(@NotNull Editor editor, int count) { VisualPosition pos = editor.getCaretModel().getVisualPosition(); if ((pos.line == 0 && count < 0) || (pos.line >= EditorHelper.getVisualLineCount(editor) - 1 && count > 0)) { return -1; } else { int col = EditorData.getLastColumn(editor); int line = EditorHelper.normalizeVisualLine(editor, pos.line + count); VisualPosition newPos = new VisualPosition(line, EditorHelper.normalizeVisualColumn(editor, line, col, CommandState.inInsertMode(editor))); return EditorHelper.visualPositionToOffset(editor, newPos); } } public int moveCaretToLine(@NotNull Editor editor, int logicalLine) { int col = EditorData.getLastColumn(editor); int line = logicalLine; if (logicalLine < 0) { line = 0; col = 0; } else if (logicalLine >= EditorHelper.getLineCount(editor)) { line = EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1); col = EditorHelper.getLineLength(editor, line); } LogicalPosition newPos = new LogicalPosition(line, EditorHelper.normalizeColumn(editor, line, col, false)); return editor.logicalPositionToOffset(newPos); } public int moveCaretToLinePercent(@NotNull Editor editor, int count) { if (count > 100) count = 100; return moveCaretToLineStartSkipLeading(editor, EditorHelper.normalizeLine( editor, (EditorHelper.getLineCount(editor) * count + 99) / 100 - 1)); } public int moveCaretGotoLineLast(@NotNull Editor editor, int rawCount, int line) { return moveCaretToLineStartSkipLeading(editor, rawCount == 0 ? EditorHelper .normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : line); } public int moveCaretGotoLineLastEnd(@NotNull Editor editor, int rawCount, int line, boolean pastEnd) { return moveCaretToLineEnd(editor, rawCount == 0 ? EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : line, pastEnd); } public int moveCaretGotoLineFirst(@NotNull Editor editor, int line) { return moveCaretToLineStartSkipLeading(editor, line); } public static void moveCaret(@NotNull Editor editor, int offset) { moveCaret(editor, offset, false); } private static void moveCaret(@NotNull Editor editor, int offset, boolean forceKeepVisual) { if (offset >= 0 && offset <= editor.getDocument().getTextLength()) { final boolean keepVisual = forceKeepVisual || keepVisual(editor); if (editor.getCaretModel().getOffset() != offset) { if (!keepVisual) { // XXX: Hack for preventing the merge multiple carets that results in loosing the primary caret for |v_d| editor.getCaretModel().removeSecondaryCarets(); } editor.getCaretModel().moveToOffset(offset); EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column); scrollCaretIntoView(editor); } if (keepVisual) { VimPlugin.getMotion().updateSelection(editor, offset); } else { editor.getSelectionModel().removeSelection(); } } } private static boolean keepVisual(Editor editor) { final CommandState commandState = CommandState.getInstance(editor); if (commandState.getMode() == CommandState.Mode.VISUAL) { final Command command = commandState.getCommand(); if (command == null || (command.getFlags() & Command.FLAG_EXIT_VISUAL) == 0) { return true; } } return false; } /** * If 'absolute' is true, then set tab index to 'value', otherwise add 'value' to tab index with wraparound. */ private void switchEditorTab(@Nullable EditorWindow editorWindow, int value, boolean absolute) { if (editorWindow != null) { final EditorTabbedContainer tabbedPane = editorWindow.getTabbedPane(); if (tabbedPane != null) { if (absolute) { tabbedPane.setSelectedIndex(value); } else { int tabIndex = (value + tabbedPane.getSelectedIndex()) % tabbedPane.getTabCount(); tabbedPane.setSelectedIndex(tabIndex < 0 ? tabIndex + tabbedPane.getTabCount() : tabIndex); } } } } public int moveCaretGotoPreviousTab(@NotNull Editor editor, @NotNull DataContext context, int rawCount) { switchEditorTab(EditorWindow.DATA_KEY.getData(context), rawCount >= 1 ? -rawCount : -1, false); return editor.getCaretModel().getOffset(); } public int moveCaretGotoNextTab(@NotNull Editor editor, @NotNull DataContext context, int rawCount) { final boolean absolute = rawCount >= 1; switchEditorTab(EditorWindow.DATA_KEY.getData(context), absolute ? rawCount - 1 : 1, absolute); return editor.getCaretModel().getOffset(); } public static void scrollCaretIntoView(@NotNull Editor editor) { int cline = editor.getCaretModel().getVisualPosition().line; int visualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); boolean scrollJump = (CommandState.getInstance(editor).getFlags() & Command.FLAG_IGNORE_SCROLL_JUMP) == 0; int scrollOffset = ((NumberOption)Options.getInstance().getOption("scrolloff")).value(); int sjSize = 0; if (scrollJump) { sjSize = Math.max(0, ((NumberOption)Options.getInstance().getOption("scrolljump")).value() - 1); } int height = EditorHelper.getScreenHeight(editor); int visualTop = visualLine + scrollOffset; int visualBottom = visualLine + height - scrollOffset; if (scrollOffset >= height / 2) { scrollOffset = height / 2; visualTop = visualLine + scrollOffset; visualBottom = visualLine + height - scrollOffset; if (visualTop == visualBottom) { visualBottom++; } } int diff; if (cline < visualTop) { diff = cline - visualTop; sjSize = -sjSize; } else { diff = cline - visualBottom + 1; if (diff < 0) { diff = 0; } } if (diff != 0) { int line; // If we need to move the top line more than a half screen worth then we just center the cursor line if (Math.abs(diff) > height / 2) { line = cline - height / 2 - 1; } // Otherwise put the new cursor line "scrolljump" lines from the top/bottom else { line = visualLine + diff + sjSize; } line = Math.min(line, EditorHelper.getVisualLineCount(editor) - height); line = Math.max(0, line); scrollLineToTopOfScreen(editor, line); } int caretColumn = editor.getCaretModel().getVisualPosition().column; int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); int width = EditorHelper.getScreenWidth(editor); scrollJump = (CommandState.getInstance(editor).getFlags() & Command.FLAG_IGNORE_SIDE_SCROLL_JUMP) == 0; scrollOffset = ((NumberOption)Options.getInstance().getOption("sidescrolloff")).value(); sjSize = 0; if (scrollJump) { sjSize = Math.max(0, ((NumberOption)Options.getInstance().getOption("sidescroll")).value() - 1); if (sjSize == 0) { sjSize = width / 2; } } int visualLeft = visualColumn + scrollOffset; int visualRight = visualColumn + width - scrollOffset; if (scrollOffset >= width / 2) { scrollOffset = width / 2; visualLeft = visualColumn + scrollOffset; visualRight = visualColumn + width - scrollOffset; if (visualLeft == visualRight) { visualRight++; } } sjSize = Math.min(sjSize, width / 2 - scrollOffset); if (caretColumn < visualLeft) { diff = caretColumn - visualLeft + 1; sjSize = -sjSize; } else { diff = caretColumn - visualRight + 1; if (diff < 0) { diff = 0; } } if (diff != 0) { int col; if (Math.abs(diff) > width / 2) { col = caretColumn - width / 2 - 1; } else { col = visualColumn + diff + sjSize; } col = Math.max(0, col); scrollColumnToLeftOfScreen(editor, col); } } public boolean selectPreviousVisualMode(@NotNull Editor editor) { final SelectionType lastSelectionType = EditorData.getLastSelectionType(editor); if (lastSelectionType == null) { return false; } final TextRange visualMarks = VimPlugin.getMark().getVisualSelectionMarks(editor); if (visualMarks == null) { return false; } CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, lastSelectionType.toSubMode(), MappingMode.VISUAL); visualStart = visualMarks.getStartOffset(); visualEnd = visualMarks.getEndOffset(); visualOffset = visualEnd; updateSelection(editor, visualEnd); editor.getCaretModel().moveToOffset(visualOffset); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); return true; } public boolean swapVisualSelections(@NotNull Editor editor) { final SelectionType lastSelectionType = EditorData.getLastSelectionType(editor); final TextRange lastVisualRange = EditorData.getLastVisualRange(editor); if (lastSelectionType == null || lastVisualRange == null) { return false; } final SelectionType selectionType = SelectionType.fromSubMode(CommandState.getInstance(editor).getSubMode()); EditorData.setLastSelectionType(editor, selectionType); visualStart = lastVisualRange.getStartOffset(); visualEnd = lastVisualRange.getEndOffset(); visualOffset = visualEnd; CommandState.getInstance(editor).setSubMode(lastSelectionType.toSubMode()); updateSelection(editor, visualEnd); editor.getCaretModel().moveToOffset(visualOffset); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); return true; } public void setVisualMode(@NotNull Editor editor, @NotNull CommandState.SubMode mode) { CommandState.SubMode oldMode = CommandState.getInstance(editor).getSubMode(); if (mode == CommandState.SubMode.NONE) { int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); if (start != end) { int line = editor.offsetToLogicalPosition(start).line; int logicalStart = EditorHelper.getLineStartOffset(editor, line); int lend = EditorHelper.getLineEndOffset(editor, line, true); if (logicalStart == start && lend + 1 == end) { mode = CommandState.SubMode.VISUAL_LINE; } else { mode = CommandState.SubMode.VISUAL_CHARACTER; } } } if (oldMode == CommandState.SubMode.NONE && mode == CommandState.SubMode.NONE) { editor.getSelectionModel().removeSelection(); return; } if (mode == CommandState.SubMode.NONE) { exitVisual(editor); } else { CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL); } KeyHandler.getInstance().reset(editor); visualStart = editor.getSelectionModel().getSelectionStart(); visualEnd = editor.getSelectionModel().getSelectionEnd(); if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_CHARACTER) { BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection"); int adj = 1; if (opt.getValue().equals("exclusive")) { adj = 0; } visualEnd -= adj; } visualOffset = editor.getCaretModel().getOffset(); VimPlugin.getMark().setVisualSelectionMarks(editor, getRawVisualRange()); } public boolean toggleVisual(@NotNull Editor editor, int count, int rawCount, @NotNull CommandState.SubMode mode) { CommandState.SubMode currentMode = CommandState.getInstance(editor).getSubMode(); if (CommandState.getInstance(editor).getMode() != CommandState.Mode.VISUAL) { int start; int end; if (rawCount > 0) { VisualChange range = EditorData.getLastVisualOperatorRange(editor); if (range == null) { return false; } switch (range.getType()) { case CHARACTER_WISE: mode = CommandState.SubMode.VISUAL_CHARACTER; break; case LINE_WISE: mode = CommandState.SubMode.VISUAL_LINE; break; case BLOCK_WISE: mode = CommandState.SubMode.VISUAL_BLOCK; break; } start = editor.getCaretModel().getOffset(); end = calculateVisualRange(editor, range, count); } else { start = end = editor.getSelectionModel().getSelectionStart(); } CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL); visualStart = start; updateSelection(editor, end); MotionGroup.moveCaret(editor, visualEnd, true); } else if (mode == currentMode) { exitVisual(editor); } else { CommandState.getInstance(editor).setSubMode(mode); updateSelection(editor, visualEnd); } return true; } private int calculateVisualRange(@NotNull Editor editor, @NotNull VisualChange range, int count) { int lines = range.getLines(); int chars = range.getColumns(); if (range.getType() == SelectionType.LINE_WISE || range.getType() == SelectionType.BLOCK_WISE || lines > 1) { lines *= count; } if ((range.getType() == SelectionType.CHARACTER_WISE && lines == 1) || range.getType() == SelectionType.BLOCK_WISE) { chars *= count; } int start = editor.getCaretModel().getOffset(); LogicalPosition sp = editor.offsetToLogicalPosition(start); int endLine = sp.line + lines - 1; int res; if (range.getType() == SelectionType.LINE_WISE) { res = moveCaretToLine(editor, endLine); } else if (range.getType() == SelectionType.CHARACTER_WISE) { if (lines > 1) { res = moveCaretToLineStart(editor, endLine) + Math.min(EditorHelper.getLineLength(editor, endLine), chars); } else { res = EditorHelper.normalizeOffset(editor, sp.line, start + chars - 1, false); } } else { int endColumn = Math.min(EditorHelper.getLineLength(editor, endLine), sp.column + chars - 1); res = editor.logicalPositionToOffset(new LogicalPosition(endLine, endColumn)); } return res; } public void exitVisual(@NotNull final Editor editor) { resetVisual(editor, true); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } } public void resetVisual(@NotNull final Editor editor, final boolean removeSelection) { final SelectionType selectionType = SelectionType.fromSubMode(CommandState.getInstance(editor).getSubMode()); EditorData.setLastSelectionType(editor, selectionType); final TextRange visualMarks = VimPlugin.getMark().getVisualSelectionMarks(editor); if (visualMarks != null) { EditorData.setLastVisualRange(editor, visualMarks); } if (removeSelection) { editor.getSelectionModel().removeSelection(); editor.getCaretModel().removeSecondaryCarets(); } CommandState.getInstance(editor).setSubMode(CommandState.SubMode.NONE); } @NotNull public VisualChange getVisualOperatorRange(@NotNull Editor editor, int cmdFlags) { int start = visualStart; int end = visualEnd; if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.normalizeOffset(editor, start, false); end = EditorHelper.normalizeOffset(editor, end, false); LogicalPosition sp = editor.offsetToLogicalPosition(start); LogicalPosition ep = editor.offsetToLogicalPosition(end); int lines = ep.line - sp.line + 1; int chars; SelectionType type; if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_LINE || (cmdFlags & Command.FLAG_MOT_LINEWISE) != 0) { chars = ep.column; type = SelectionType.LINE_WISE; } else if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_CHARACTER) { type = SelectionType.CHARACTER_WISE; if (lines > 1) { chars = ep.column; } else { chars = ep.column - sp.column + 1; } } else { chars = ep.column - sp.column + 1; if (EditorData.getLastColumn(editor) == MotionGroup.LAST_COLUMN) { chars = MotionGroup.LAST_COLUMN; } type = SelectionType.BLOCK_WISE; } return new VisualChange(lines, chars, type); } @NotNull public TextRange getVisualRange(@NotNull Editor editor) { final TextRange res = new TextRange(editor.getSelectionModel().getBlockSelectionStarts(), editor.getSelectionModel().getBlockSelectionEnds()); final CommandState.SubMode subMode = CommandState.getInstance(editor).getSubMode(); if (subMode == CommandState.SubMode.VISUAL_BLOCK) { final int[] ends = res.getEndOffsets(); // If the last left/right motion was the $ command, simulate each line being selected to end-of-line if (EditorData.getLastColumn(editor) >= MotionGroup.LAST_COLUMN) { final int[] starts = res.getStartOffsets(); for (int i = 0; i < starts.length; i++) { if (ends[i] > starts[i]) { ends[i] = EditorHelper.getLineEndForOffset(editor, starts[i]); } } } else { for (int i = 0; i < ends.length; ++i) { ends[i] = EditorHelper.normalizeOffset(editor, ends[i] + 1, false); } } } return res; } @NotNull public TextRange getRawVisualRange() { return new TextRange(visualStart, visualEnd); } private void updateSelection(@NotNull Editor editor, int offset) { visualEnd = offset; visualOffset = offset; int start = visualStart; int end = visualEnd; final CommandState.SubMode subMode = CommandState.getInstance(editor).getSubMode(); if (subMode == CommandState.SubMode.VISUAL_CHARACTER) { if (start > end) { int t = start; start = end; end = t; } final BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection"); int lineEnd = EditorHelper.getLineEndForOffset(editor, end); final int adj = opt.getValue().equals("exclusive") || end == lineEnd ? 0 : 1; end = Math.min(EditorHelper.getFileSize(editor), end + adj); editor.getSelectionModel().setSelection(start, end); } else if (subMode == CommandState.SubMode.VISUAL_LINE) { if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.getLineStartForOffset(editor, start); end = EditorHelper.getLineEndForOffset(editor, end); editor.getSelectionModel().setSelection(start, end); } else if (subMode == CommandState.SubMode.VISUAL_BLOCK) { final LogicalPosition lineStart = editor.offsetToLogicalPosition(start); final LogicalPosition lineEnd = editor.offsetToLogicalPosition(end); editor.getSelectionModel().setBlockSelection(lineStart, lineEnd); } VimPlugin.getMark().setVisualSelectionMarks(editor, new TextRange(start, end)); } public boolean swapVisualEnds(@NotNull Editor editor) { int t = visualEnd; visualEnd = visualStart; visualStart = t; moveCaret(editor, visualEnd); return true; } public boolean swapVisualEndsBlock(@NotNull Editor editor) { if (CommandState.getInstance(editor).getSubMode() != CommandState.SubMode.VISUAL_BLOCK) { return swapVisualEnds(editor); } LogicalPosition lineStart = editor.getSelectionModel().getBlockStart(); LogicalPosition lineEnd = editor.getSelectionModel().getBlockEnd(); if (lineStart == null || lineEnd == null) { return false; } if (visualStart > visualEnd) { LogicalPosition t = lineEnd; lineEnd = lineStart; lineStart = t; } LogicalPosition start = new LogicalPosition(lineStart.line, lineEnd.column); LogicalPosition end = new LogicalPosition(lineEnd.line, lineStart.column); visualStart = editor.logicalPositionToOffset(start); visualEnd = editor.logicalPositionToOffset(end); moveCaret(editor, visualEnd); return true; } public void moveVisualStart(int startOffset) { visualStart = startOffset; } public void processEscape(@NotNull Editor editor) { exitVisual(editor); } public static class MotionEditorChange extends FileEditorManagerAdapter { public void selectionChanged(@NotNull FileEditorManagerEvent event) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } final FileEditor fileEditor = event.getOldEditor(); if (fileEditor instanceof TextEditor) { final Editor editor = ((TextEditor)fileEditor).getEditor(); ExOutputModel.getInstance(editor).clear(); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { VimPlugin.getMotion().exitVisual(editor); } } } } private static class EditorSelectionHandler implements SelectionListener { private boolean myMakingChanges = false; public void selectionChanged(@NotNull SelectionEvent selectionEvent) { if (myMakingChanges) { return; } myMakingChanges = true; try { final Editor editor = selectionEvent.getEditor(); final com.intellij.openapi.util.TextRange newRange = selectionEvent.getNewRange(); for (Editor e : EditorFactory.getInstance().getEditors(editor.getDocument())) { if (!e.equals(editor)) { e.getSelectionModel().setSelection(newRange.getStartOffset(), newRange.getEndOffset()); } } } finally { myMakingChanges = false; } } } private static class EditorMouseHandler implements EditorMouseListener, EditorMouseMotionListener { public void mouseMoved(EditorMouseEvent event) { } public void mouseDragged(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getArea() == EditorMouseEventArea.EDITING_AREA || event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) { if (dragEditor == null) { if (event.getArea() == EditorMouseEventArea.EDITING_AREA) { mode = CommandState.SubMode.VISUAL_CHARACTER; } else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) { mode = CommandState.SubMode.VISUAL_LINE; } startOff = event.getEditor().getSelectionModel().getSelectionStart(); endOff = event.getEditor().getSelectionModel().getSelectionEnd(); } dragEditor = event.getEditor(); } } public void mousePressed(EditorMouseEvent event) { } public void mouseClicked(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getArea() == EditorMouseEventArea.EDITING_AREA) { VimPlugin.getMotion().processMouseClick(event.getEditor(), event.getMouseEvent()); } else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA && event.getArea() != EditorMouseEventArea.FOLDING_OUTLINE_AREA) { VimPlugin.getMotion() .processLineSelection(event.getEditor(), event.getMouseEvent().getButton() == MouseEvent.BUTTON3); } } public void mouseReleased(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getEditor().equals(dragEditor)) { VimPlugin.getMotion().processMouseReleased(event.getEditor(), mode, startOff, endOff); dragEditor = null; } } public void mouseEntered(EditorMouseEvent event) { } public void mouseExited(EditorMouseEvent event) { } @Nullable private Editor dragEditor = null; @NotNull private CommandState.SubMode mode = CommandState.SubMode.NONE; private int startOff; private int endOff; } private int lastFTCmd = 0; private char lastFTChar; private int visualStart; private int visualEnd; private int visualOffset; @NotNull private final EditorMouseHandler mouseHandler = new EditorMouseHandler(); @NotNull private final EditorSelectionHandler selectionHandler = new EditorSelectionHandler(); }
package liquibase; import liquibase.change.CheckSum; import liquibase.change.core.RawSQLChange; import liquibase.changelog.*; import liquibase.changelog.filter.*; import liquibase.changelog.visitor.*; import liquibase.command.CommandExecutionException; import liquibase.command.CommandFactory; import liquibase.command.core.DropAllCommand; import liquibase.database.Database; import liquibase.database.DatabaseConnection; import liquibase.database.DatabaseFactory; import liquibase.database.ObjectQuotingStrategy; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.OracleDatabase; import liquibase.diff.DiffGeneratorFactory; import liquibase.diff.DiffResult; import liquibase.diff.compare.CompareControl; import liquibase.diff.output.changelog.DiffToChangeLog; import liquibase.exception.DatabaseException; import liquibase.exception.LiquibaseException; import liquibase.exception.LockException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.Executor; import liquibase.executor.ExecutorService; import liquibase.executor.LoggingExecutor; import liquibase.lockservice.DatabaseChangeLogLock; import liquibase.lockservice.LockService; import liquibase.lockservice.LockServiceFactory; import liquibase.logging.LogService; import liquibase.logging.LogType; import liquibase.logging.Logger; import liquibase.parser.ChangeLogParser; import liquibase.parser.ChangeLogParserFactory; import liquibase.resource.ResourceAccessor; import liquibase.serializer.ChangeLogSerializer; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.InvalidExampleException; import liquibase.snapshot.SnapshotControl; import liquibase.snapshot.SnapshotGeneratorFactory; import liquibase.statement.core.RawSqlStatement; import liquibase.statement.core.UpdateStatement; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Catalog; import liquibase.util.LiquibaseUtil; import liquibase.util.StreamUtil; import liquibase.util.StringUtils; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.text.DateFormat; import java.util.*; import static java.util.ResourceBundle.getBundle; /** * Primary facade class for interacting with Liquibase. * The built in command line, Ant, Maven and other ways of running Liquibase are wrappers around methods in this class. */ public class Liquibase { private static final Logger LOG = LogService.getLog(Liquibase.class); protected static final int CHANGESET_ID_NUM_PARTS = 3; protected static final int CHANGESET_ID_AUTHOR_PART = 2; protected static final int CHANGESET_ID_CHANGESET_PART = 1; protected static final int CHANGESET_ID_CHANGELOG_PART = 0; private static ResourceBundle coreBundle = getBundle("liquibase/i18n/liquibase-core"); protected static final String MSG_COULD_NOT_RELEASE_LOCK = coreBundle.getString("could.not.release.lock"); protected Database database; private DatabaseChangeLog databaseChangeLog; private String changeLogFile; private ResourceAccessor resourceAccessor; private ChangeLogParameters changeLogParameters; private ChangeExecListener changeExecListener; private ChangeLogSyncListener changeLogSyncListener; private boolean ignoreClasspathPrefix = true; /** * Creates a Liquibase instance for a given DatabaseConnection. The Database instance used will be found with {@link DatabaseFactory#findCorrectDatabaseImplementation(liquibase.database.DatabaseConnection)} * * @See DatabaseConnection * @See Database * @see #Liquibase(String, liquibase.resource.ResourceAccessor, liquibase.database.Database) * @see ResourceAccessor */ public Liquibase(String changeLogFile, ResourceAccessor resourceAccessor, DatabaseConnection conn) throws LiquibaseException { this(changeLogFile, resourceAccessor, DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn)); } /** * Creates a Liquibase instance. The changeLogFile parameter must be a path that can be resolved by the passed * ResourceAccessor. If windows style path separators are used for the changeLogFile, they will be standardized to * unix style for better cross-system compatib. * * @see DatabaseConnection * @see Database * @see ResourceAccessor */ public Liquibase(String changeLogFile, ResourceAccessor resourceAccessor, Database database) { if (changeLogFile != null) { // Convert to STANDARD / if using absolute path on windows: this.changeLogFile = changeLogFile.replace('\\', '/'); } this.resourceAccessor = resourceAccessor; this.changeLogParameters = new ChangeLogParameters(database); this.database = database; } public Liquibase(DatabaseChangeLog changeLog, ResourceAccessor resourceAccessor, Database database) { this.databaseChangeLog = changeLog; if (changeLog != null) { this.changeLogFile = changeLog.getPhysicalFilePath(); } if (this.changeLogFile != null) { // Convert to STANDARD "/" if using an absolute path on Windows: changeLogFile = changeLogFile.replace('\\', '/'); } this.resourceAccessor = resourceAccessor; this.database = database; this.changeLogParameters = new ChangeLogParameters(database); } /** * Return the change log file used by this Liquibase instance. */ public String getChangeLogFile() { return changeLogFile; } /** * Return the log used by this Liquibase instance. */ public Logger getLog() { return LOG; } /** * Returns the ChangeLogParameters container used by this Liquibase instance. */ public ChangeLogParameters getChangeLogParameters() { return changeLogParameters; } /** * Returns the Database used by this Liquibase instance. */ public Database getDatabase() { return database; } /** * Return ResourceAccessor used by this Liquibase instance. */ public ResourceAccessor getResourceAccessor() { return resourceAccessor; } /** * Convience method for {@link #update(Contexts)} that constructs the Context object from the passed string. */ public void update(String contexts) throws LiquibaseException { this.update(new Contexts(contexts)); } /** * Executes Liquibase "update" logic which ensures that the configured {@link Database} is up to date according to * the configured changelog file. To run in "no context mode", pass a null or empty context object. */ public void update(Contexts contexts) throws LiquibaseException { update(contexts, new LabelExpression()); } public void update(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { update(contexts, labelExpression, true); } public void update(Contexts contexts, LabelExpression labelExpression, boolean checkLiquibaseTables) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(true, changeLog, contexts, labelExpression); } ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator changeLogIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog); changeLogIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY); try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } resetServices(); } } public DatabaseChangeLog getDatabaseChangeLog() throws LiquibaseException { if (databaseChangeLog == null) { ChangeLogParser parser = ChangeLogParserFactory.getInstance().getParser(changeLogFile, resourceAccessor); databaseChangeLog = parser.parse(changeLogFile, changeLogParameters, resourceAccessor); } return databaseChangeLog; } protected UpdateVisitor createUpdateVisitor() { return new UpdateVisitor(database, changeExecListener); } protected ChangeLogIterator getStandardChangelogIterator(Contexts contexts, LabelExpression labelExpression, DatabaseChangeLog changeLog) throws DatabaseException { return new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); } public void update(String contexts, Writer output) throws LiquibaseException { this.update(new Contexts(contexts), output); } public void update(Contexts contexts, Writer output) throws LiquibaseException { update(contexts, new LabelExpression(), output); } public void update(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { update(contexts, labelExpression, output, true); } public void update(Contexts contexts, LabelExpression labelExpression, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); /* We have no other choice than to save the current Executer here. */ @SuppressWarnings("squid:S1941") Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); LoggingExecutor loggingExecutor = new LoggingExecutor( ExecutorService.getInstance().getExecutor(database), output, database ); ExecutorService.getInstance().setExecutor(database, loggingExecutor); outputHeader("Update Database Script"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { update(contexts, labelExpression, checkLiquibaseTables); output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); } public void update(int changesToApply, String contexts) throws LiquibaseException { update(changesToApply, new Contexts(contexts), new LabelExpression()); } public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(changesToApply)); logIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } resetServices(); } } public void update(String tag, String contexts) throws LiquibaseException { update(tag, new Contexts(contexts), new LabelExpression()); } public void update(String tag, Contexts contexts) throws LiquibaseException { update(tag, contexts, new LabelExpression()); } public void update(String tag, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { if (tag == null) { update(contexts, labelExpression); return; } changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new UpToTagChangeSetFilter(tag, ranChangeSetList)); logIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } resetServices(); } } public void update(int changesToApply, String contexts, Writer output) throws LiquibaseException { this.update(changesToApply, new Contexts(contexts), new LabelExpression(), output); } public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); /* We have no other choice than to save the current Executer here. */ @SuppressWarnings("squid:S1941") Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); LoggingExecutor loggingExecutor = new LoggingExecutor( ExecutorService.getInstance().getExecutor(database), output, database ); ExecutorService.getInstance().setExecutor(database, loggingExecutor); outputHeader("Update " + changesToApply + " Change Sets Database Script"); update(changesToApply, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } resetServices(); ExecutorService.getInstance().setExecutor(database, oldTemplate); } public void update(String tag, String contexts, Writer output) throws LiquibaseException { update(tag, new Contexts(contexts), new LabelExpression(), output); } public void update(String tag, Contexts contexts, Writer output) throws LiquibaseException { update(tag, contexts, new LabelExpression(), output); } public void update(String tag, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { if (tag == null) { update(contexts, labelExpression, output); return; } changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); /* We have no other choice than to save the current Executer here. */ @SuppressWarnings("squid:S1941") Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); LoggingExecutor loggingExecutor = new LoggingExecutor( ExecutorService.getInstance().getExecutor(database), output, database ); ExecutorService.getInstance().setExecutor(database, loggingExecutor); outputHeader("Update to '" + tag + "' Database Script"); update(tag, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } resetServices(); ExecutorService.getInstance().setExecutor(database, oldTemplate); } private void outputHeader(String message) throws DatabaseException { Executor executor = ExecutorService.getInstance().getExecutor(database); executor.comment("*********************************************************************"); executor.comment(message); executor.comment("*********************************************************************"); executor.comment("Change Log: " + changeLogFile); executor.comment("Ran at: " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date()) ); DatabaseConnection connection = getDatabase().getConnection(); if (connection != null) { executor.comment("Against: " + connection.getConnectionUserName() + "@" + connection.getURL()); } executor.comment("DB-Manul version: " + LiquibaseUtil.getBuildVersion()); executor.comment("*********************************************************************" + StreamUtil.getLineSeparator() ); if (database instanceof OracleDatabase) { executor.execute(new RawSqlStatement("SET DEFINE OFF;")); } if ((database instanceof MSSQLDatabase) && (database.getDefaultCatalogName() != null)) { executor.execute(new RawSqlStatement("USE " + database.escapeObjectName(database.getDefaultCatalogName(), Catalog.class) + ";") ); } } public void rollback(int changesToRollback, String contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, null, contexts, output); } public void rollback(int changesToRollback, Contexts contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, null, contexts, output); } public void rollback(int changesToRollback, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { rollback(changesToRollback, null, contexts, labelExpression, output); } public void rollback(int changesToRollback, String rollbackScript, String contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, rollbackScript, new Contexts(contexts), output); } public void rollback(int changesToRollback, String rollbackScript, Contexts contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, rollbackScript, contexts, new LabelExpression(), output); } public void rollback(int changesToRollback, String rollbackScript, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); /* We have no other choice than to save the current Executer here. */ @SuppressWarnings("squid:S1941") Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database) ); outputHeader("Rollback " + changesToRollback + " Change(s) Script"); rollback(changesToRollback, rollbackScript, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(int changesToRollback, String contexts) throws LiquibaseException { rollback(changesToRollback, null, contexts); } public void rollback(int changesToRollback, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { rollback(changesToRollback, null, contexts, labelExpression); } public void rollback(int changesToRollback, String rollbackScript, String contexts) throws LiquibaseException { rollback(changesToRollback, rollbackScript, new Contexts(contexts), new LabelExpression()); } public void rollback(int changesToRollback, String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); ChangeLogIterator logIterator = new ChangeLogIterator(database.getRanChangeSetList(), changeLog, new AlreadyRanChangeSetFilter(database.getRanChangeSetList(), ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(changesToRollback)); if (rollbackScript == null) { logIterator.run( new RollbackVisitor(database,changeExecListener), new RuntimeEnvironment(database, contexts, labelExpression) ); } else { executeRollbackScript(rollbackScript, contexts, labelExpression); removeRunStatus(logIterator, contexts, labelExpression); } } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, "Error releasing lock", e); } resetServices(); } } protected void removeRunStatus(ChangeLogIterator logIterator, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { logIterator.run(new ChangeSetVisitor() { @Override public Direction getDirection() { return Direction.REVERSE; } @Override public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Set<ChangeSetFilterResult> filterResults) throws LiquibaseException { database.removeRanStatus(changeSet); database.commit(); } }, new RuntimeEnvironment(database, contexts, labelExpression)); } protected void executeRollbackScript(String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { final Executor executor = ExecutorService.getInstance().getExecutor(database); String rollbackScriptContents; try { Set<InputStream> streams = resourceAccessor.getResourcesAsStream(rollbackScript); if ((streams == null) || streams.isEmpty()) { throw new LiquibaseException("Cannot find rollbackScript "+rollbackScript); } else if (streams.size() > 1) { throw new LiquibaseException("Found multiple rollbackScripts named "+rollbackScript); } rollbackScriptContents = StreamUtil.getStreamContents(streams.iterator().next()); } catch (IOException e) { throw new LiquibaseException("Error reading rollbackScript "+executor+": "+e.getMessage()); } RawSQLChange rollbackChange = new RawSQLChange(rollbackScriptContents); rollbackChange.setSplitStatements(true); rollbackChange.setStripComments(true); try { executor.execute(rollbackChange); } catch (DatabaseException e) { DatabaseException ex = new DatabaseException( "Error executing rollback script. ChangeSets will still be marked as rolled back: " + e.getMessage(), e ); LogService.getLog(getClass()).severe(LogType.LOG, ex.getMessage()); LOG.severe(LogType.LOG, "Error executing rollback script", ex); if (changeExecListener != null) { changeExecListener.runFailed(null, databaseChangeLog, database, ex); } } database.commit(); } public void rollback(String tagToRollBackTo, String contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts, output); } public void rollback(String tagToRollBackTo, Contexts contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts, output); } public void rollback(String tagToRollBackTo, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts, labelExpression, output); } public void rollback(String tagToRollBackTo, String rollbackScript, String contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, rollbackScript, new Contexts(contexts), output); } public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, rollbackScript, contexts, new LabelExpression(), output); } public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); /* We have no other choice than to save the current Executor here. */ @SuppressWarnings("squid:S1941") Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor( ExecutorService.getInstance().getExecutor(database), output, database) ); outputHeader("Rollback to '" + tagToRollBackTo + "' Script"); rollback(tagToRollBackTo, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(String tagToRollBackTo, String contexts) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts); } public void rollback(String tagToRollBackTo, Contexts contexts) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts); } public void rollback(String tagToRollBackTo, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts, labelExpression); } public void rollback(String tagToRollBackTo, String rollbackScript, String contexts) throws LiquibaseException { rollback(tagToRollBackTo, rollbackScript, new Contexts(contexts)); } public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts) throws LiquibaseException { rollback(tagToRollBackTo, rollbackScript, contexts, new LabelExpression()); } public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new AfterTagChangeSetFilter(tagToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); if (rollbackScript == null) { logIterator.run(new RollbackVisitor(database, changeExecListener), new RuntimeEnvironment(database, contexts, labelExpression)); } else { executeRollbackScript(rollbackScript, contexts, labelExpression); removeRunStatus(logIterator, contexts, labelExpression); } } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } resetServices(); } public void rollback(Date dateToRollBackTo, String contexts, Writer output) throws LiquibaseException { rollback(dateToRollBackTo, null, contexts, output); } public void rollback(Date dateToRollBackTo, String rollbackScript, String contexts, Writer output) throws LiquibaseException { rollback(dateToRollBackTo, new Contexts(contexts), new LabelExpression(), output); } public void rollback(Date dateToRollBackTo, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { rollback(dateToRollBackTo, null, contexts, labelExpression, output); } public void rollback(Date dateToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); /* We have no other choice than to save the current Executer here. */ @SuppressWarnings("squid:S1941") Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database)); outputHeader("Rollback to " + dateToRollBackTo + " Script"); rollback(dateToRollBackTo, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(Date dateToRollBackTo, String contexts) throws LiquibaseException { rollback(dateToRollBackTo, null, contexts); } public void rollback(Date dateToRollBackTo, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { rollback(dateToRollBackTo, null, contexts, labelExpression); } public void rollback(Date dateToRollBackTo, String rollbackScript, String contexts) throws LiquibaseException { rollback(dateToRollBackTo, new Contexts(contexts), new LabelExpression()); } public void rollback(Date dateToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new ExecutedAfterChangeSetFilter(dateToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); if (rollbackScript == null) { logIterator.run(new RollbackVisitor(database, changeExecListener), new RuntimeEnvironment(database, contexts, labelExpression)); } else { executeRollbackScript(rollbackScript, contexts, labelExpression); removeRunStatus(logIterator, contexts, labelExpression); } } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } resetServices(); } public void changeLogSync(String contexts, Writer output) throws LiquibaseException { changeLogSync(new Contexts(contexts), new LabelExpression(), output); } public void changeLogSync(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor( ExecutorService.getInstance().getExecutor(database), output, database ); /* We have no other choice than to save the current Executer here. */ @SuppressWarnings("squid:S1941") Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to add all changesets to database history table"); changeLogSync(contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void changeLogSync(String contexts) throws LiquibaseException { changeLogSync(new Contexts(contexts), new LabelExpression()); } /** * @deprecated use version with LabelExpression */ @Deprecated public void changeLogSync(Contexts contexts) throws LiquibaseException { changeLogSync(contexts, new LabelExpression()); } public void changeLogSync(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); logIterator.run(new ChangeLogSyncVisitor(database, changeLogSyncListener), new RuntimeEnvironment(database, contexts, labelExpression) ); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } resetServices(); } } public void markNextChangeSetRan(String contexts, Writer output) throws LiquibaseException { markNextChangeSetRan(new Contexts(contexts), new LabelExpression(), output); } public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor( ExecutorService.getInstance().getExecutor(database), output, database ); /* We have no other choice than to save the current Executer here. */ @SuppressWarnings("squid:S1941") Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to add all changesets to database history table"); markNextChangeSetRan(contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void markNextChangeSetRan(String contexts) throws LiquibaseException { markNextChangeSetRan(new Contexts(contexts), new LabelExpression()); } public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(1)); logIterator.run(new ChangeLogSyncVisitor(database), new RuntimeEnvironment(database, contexts, labelExpression) ); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } resetServices(); } } public void futureRollbackSQL(String contexts, Writer output) throws LiquibaseException { futureRollbackSQL(null, contexts, output, true); } public void futureRollbackSQL(Writer output) throws LiquibaseException { futureRollbackSQL(null, null, new Contexts(), new LabelExpression(), output); } public void futureRollbackSQL(String contexts, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { futureRollbackSQL(null, contexts, output, checkLiquibaseTables); } public void futureRollbackSQL(Integer count, String contexts, Writer output) throws LiquibaseException { futureRollbackSQL(count, new Contexts(contexts), new LabelExpression(), output, true); } public void futureRollbackSQL(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { futureRollbackSQL(null, null, contexts, labelExpression, output); } public void futureRollbackSQL(Integer count, String contexts, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { futureRollbackSQL(count, new Contexts(contexts), new LabelExpression(), output, checkLiquibaseTables); } public void futureRollbackSQL(Integer count, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { futureRollbackSQL(count, contexts, labelExpression, output, true); } public void futureRollbackSQL(Integer count, Contexts contexts, LabelExpression labelExpression, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { futureRollbackSQL(count, null, contexts, labelExpression, output); } public void futureRollbackSQL(String tag, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { futureRollbackSQL(null, tag, contexts, labelExpression, output); } protected void futureRollbackSQL(Integer count, String tag, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { futureRollbackSQL(count, tag, contexts, labelExpression, output, true); } protected void futureRollbackSQL(Integer count, String tag, Contexts contexts, LabelExpression labelExpression, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to roll back currently unexecuted changes"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(false, changeLog, contexts, labelExpression); } ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator; if ((count == null) && (tag == null)) { logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); } else if (count != null) { ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(count)); final ListVisitor listVisitor = new ListVisitor(); forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression)); logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new ChangeSetFilter() { @Override public ChangeSetFilterResult accepts(ChangeSet changeSet) { return new ChangeSetFilterResult( listVisitor.getSeenChangeSets().contains(changeSet), null, null ); } }); } else { List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new UpToTagChangeSetFilter(tag, ranChangeSetList)); final ListVisitor listVisitor = new ListVisitor(); forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression)); logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new ChangeSetFilter() { @Override public ChangeSetFilterResult accepts(ChangeSet changeSet) { return new ChangeSetFilterResult( listVisitor.getSeenChangeSets().contains(changeSet), null, null ); } }); } logIterator.run(new RollbackVisitor(database, changeExecListener), new RuntimeEnvironment(database, contexts, labelExpression) ); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } protected void resetServices() { LockServiceFactory.getInstance().resetAll(); ChangeLogHistoryServiceFactory.getInstance().resetAll(); ExecutorService.getInstance().reset(); } /** * Drops all database objects in the default schema. */ public final void dropAll() throws DatabaseException { dropAll(new CatalogAndSchema(getDatabase().getDefaultCatalogName(), getDatabase().getDefaultSchemaName())); } /** * Drops all database objects in the passed schema(s). */ public final void dropAll(CatalogAndSchema... schemas) throws DatabaseException { if ((schemas == null) || (schemas.length == 0)) { schemas = new CatalogAndSchema[] { new CatalogAndSchema(getDatabase().getDefaultCatalogName(), getDatabase().getDefaultSchemaName()) }; } DropAllCommand dropAll = (DropAllCommand) CommandFactory.getInstance().getCommand("dropAll"); dropAll.setDatabase(this.getDatabase()); dropAll.setSchemas(schemas); try { dropAll.execute(); } catch (CommandExecutionException e) { throw new DatabaseException(e); } } /** * 'Tags' the database for future rollback */ public void tag(String tagString) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); getDatabase().tag(tagString); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } } public boolean tagExists(String tagString) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); return getDatabase().doesTagExist(tagString); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } } public void updateTestingRollback(String contexts) throws LiquibaseException { updateTestingRollback(new Contexts(contexts), new LabelExpression()); } public void updateTestingRollback(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { updateTestingRollback(null, contexts, labelExpression); } public void updateTestingRollback(String tag, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Date baseDate = new Date(); update(tag, contexts, labelExpression); rollback(baseDate, null, contexts, labelExpression); update(tag, contexts, labelExpression); } public void checkLiquibaseTables(boolean updateExistingNullChecksums, DatabaseChangeLog databaseChangeLog, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { ChangeLogHistoryService changeLogHistoryService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(getDatabase()); changeLogHistoryService.init(); if (updateExistingNullChecksums) { changeLogHistoryService.upgradeChecksums(databaseChangeLog, contexts, labelExpression); } LockServiceFactory.getInstance().getLockService(getDatabase()).init(); } /** * Returns true if it is "save" to migrate the database. * Currently, "safe" is defined as running in an output-sql mode or against a database on localhost. * It is fine to run Liquibase against a "non-safe" database, the method is mainly used to determine if the user * should be prompted before continuing. */ public boolean isSafeToRunUpdate() throws DatabaseException { return getDatabase().isSafeToRunUpdate(); } /** * Display change log lock information. */ public DatabaseChangeLogLock[] listLocks() throws LiquibaseException { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); return LockServiceFactory.getInstance().getLockService(database).listLocks(); } public void reportLocks(PrintStream out) throws LiquibaseException { DatabaseChangeLogLock[] locks = listLocks(); out.println("Database change log locks for " + getDatabase().getConnection().getConnectionUserName() + "@" + getDatabase().getConnection().getURL()); if (locks.length == 0) { out.println(" - No locks"); } for (DatabaseChangeLogLock lock : locks) { out.println(" - " + lock.getLockedBy() + " at " + DateFormat.getDateTimeInstance().format(lock.getLockGranted())); } } public void forceReleaseLocks() throws LiquibaseException { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); LockServiceFactory.getInstance().getLockService(database).forceReleaseLock(); } /** * @deprecated use version with LabelExpression */ @Deprecated public List<ChangeSet> listUnrunChangeSets(Contexts contexts) throws LiquibaseException { return listUnrunChangeSets(contexts, new LabelExpression()); } public List<ChangeSet> listUnrunChangeSets(Contexts contexts, LabelExpression labels) throws LiquibaseException { return listUnrunChangeSets(contexts, labels, true); } protected List<ChangeSet> listUnrunChangeSets(Contexts contexts, LabelExpression labels, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labels); DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(true, changeLog, contexts, labels); } changeLog.validate(database, contexts, labels); ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labels, changeLog); ListVisitor visitor = new ListVisitor(); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labels)); return visitor.getSeenChangeSets(); } /** * @deprecated use version with LabelExpression */ @Deprecated public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts) throws LiquibaseException { return getChangeSetStatuses(contexts, new LabelExpression()); } public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { return getChangeSetStatuses(contexts, labelExpression, true); } /** * Returns the ChangeSetStatuses of all changesets in the change log file and history in the order they * would be ran. */ public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(true, changeLog, contexts, labelExpression); } changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog); StatusVisitor visitor = new StatusVisitor(database); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); return visitor.getStatuses(); } public void reportStatus(boolean verbose, String contexts, Writer out) throws LiquibaseException { reportStatus(verbose, new Contexts(contexts), new LabelExpression(), out); } public void reportStatus(boolean verbose, Contexts contexts, Writer out) throws LiquibaseException { reportStatus(verbose, contexts, new LabelExpression(), out); } public void reportStatus(boolean verbose, Contexts contexts, LabelExpression labels, Writer out) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labels); try { List<ChangeSet> unrunChangeSets = listUnrunChangeSets(contexts, labels, false); if (unrunChangeSets.isEmpty()) { out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(" is up to date"); out.append(StreamUtil.getLineSeparator()); } else { out.append(String.valueOf(unrunChangeSets.size())); out.append(" change sets have not been applied to "); out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(StreamUtil.getLineSeparator()); if (verbose) { for (ChangeSet changeSet : unrunChangeSets) { out.append(" ").append(changeSet.toString(false)) .append(StreamUtil.getLineSeparator()); } } } out.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } public Collection<RanChangeSet> listUnexpectedChangeSets(String contexts) throws LiquibaseException { return listUnexpectedChangeSets(new Contexts(contexts), new LabelExpression()); } public Collection<RanChangeSet> listUnexpectedChangeSets(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); DatabaseChangeLog changeLog = getDatabaseChangeLog(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); ExpectedChangesVisitor visitor = new ExpectedChangesVisitor(database.getRanChangeSetList()); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); return visitor.getUnexpectedChangeSets(); } public void reportUnexpectedChangeSets(boolean verbose, String contexts, Writer out) throws LiquibaseException { reportUnexpectedChangeSets(verbose, new Contexts(contexts), new LabelExpression(), out); } public void reportUnexpectedChangeSets(boolean verbose, Contexts contexts, LabelExpression labelExpression, Writer out) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); try { Collection<RanChangeSet> unexpectedChangeSets = listUnexpectedChangeSets(contexts, labelExpression); if (unexpectedChangeSets.isEmpty()) { out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(" contains no unexpected changes!"); out.append(StreamUtil.getLineSeparator()); } else { out.append(String.valueOf(unexpectedChangeSets.size())); out.append(" unexpected changes were found in "); out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(StreamUtil.getLineSeparator()); if (verbose) { for (RanChangeSet ranChangeSet : unexpectedChangeSets) { out.append(" ").append(ranChangeSet.toString()).append(StreamUtil.getLineSeparator()); } } } out.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } /** * Sets checksums to null so they will be repopulated next run */ public void clearCheckSums() throws LiquibaseException { LOG.info(LogType.LOG, "Clearing database change log checksums"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); UpdateStatement updateStatement = new UpdateStatement( getDatabase().getLiquibaseCatalogName(), getDatabase().getLiquibaseSchemaName(), getDatabase().getDatabaseChangeLogTableName() ); updateStatement.addNewColumnValue("MD5SUM", null); ExecutorService.getInstance().getExecutor(database).execute(updateStatement); getDatabase().commit(); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } resetServices(); } public final CheckSum calculateCheckSum(final String changeSetIdentifier) throws LiquibaseException { if (changeSetIdentifier == null) { throw new LiquibaseException(new IllegalArgumentException("changeSetIdentifier")); } final List<String> parts = StringUtils.splitAndTrim(changeSetIdentifier, "::"); if ((parts == null) || (parts.size() < CHANGESET_ID_NUM_PARTS)) { throw new LiquibaseException( new IllegalArgumentException("Invalid changeSet identifier: " + changeSetIdentifier) ); } return this.calculateCheckSum(parts.get(CHANGESET_ID_CHANGELOG_PART), parts.get(CHANGESET_ID_CHANGESET_PART), parts.get(CHANGESET_ID_AUTHOR_PART)); } public CheckSum calculateCheckSum(final String filename, final String id, final String author) throws LiquibaseException { LOG.info(LogType.LOG, String.format("Calculating checksum for changeset %s::%s::%s", filename, id, author)); final ChangeLogParameters clParameters = this.getChangeLogParameters(); final ResourceAccessor resourceAccessor = this.getResourceAccessor(); final DatabaseChangeLog changeLog = ChangeLogParserFactory.getInstance().getParser( this.changeLogFile, resourceAccessor ).parse(this.changeLogFile, clParameters, resourceAccessor); // TODO: validate? final ChangeSet changeSet = changeLog.getChangeSet(filename, author, id); if (changeSet == null) { throw new LiquibaseException( new IllegalArgumentException("No such changeSet: " + filename + "::" + id + "::" + author) ); } return changeSet.generateCheckSum(); } public void generateDocumentation(String outputDirectory) throws LiquibaseException { // call without context generateDocumentation(outputDirectory, new Contexts(), new LabelExpression()); } public void generateDocumentation(String outputDirectory, String contexts) throws LiquibaseException { generateDocumentation(outputDirectory, new Contexts(contexts), new LabelExpression()); } public void generateDocumentation(String outputDirectory, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { LOG.info(LogType.LOG, "Generating Database Documentation"); changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, new Contexts(), new LabelExpression()); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new DbmsChangeSetFilter(database)); DBDocVisitor visitor = new DBDocVisitor(database); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); visitor.writeHTML(new File(outputDirectory), resourceAccessor); } catch (IOException e) { throw new LiquibaseException(e); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } } public DiffResult diff(Database referenceDatabase, Database targetDatabase, CompareControl compareControl) throws LiquibaseException { return DiffGeneratorFactory.getInstance().compare(referenceDatabase, targetDatabase, compareControl); } /** * Checks changelogs for bad MD5Sums and preconditions before attempting a migration */ public void validate() throws LiquibaseException { DatabaseChangeLog changeLog = getDatabaseChangeLog(); changeLog.validate(database); } public void setChangeLogParameter(String key, Object value) { this.changeLogParameters.set(key, value); } public void setChangeExecListener(ChangeExecListener listener) { this.changeExecListener = listener; } public void setChangeLogSyncListener(ChangeLogSyncListener changeLogSyncListener) { this.changeLogSyncListener = changeLogSyncListener; } public boolean isIgnoreClasspathPrefix() { return ignoreClasspathPrefix; } public void setIgnoreClasspathPrefix(boolean ignoreClasspathPrefix) { this.ignoreClasspathPrefix = ignoreClasspathPrefix; } public void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter, PrintStream outputStream, Class<? extends DatabaseObject>... snapshotTypes) throws DatabaseException, IOException, ParserConfigurationException { generateChangeLog(catalogAndSchema, changeLogWriter, outputStream, null, snapshotTypes); } public void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter, PrintStream outputStream, ChangeLogSerializer changeLogSerializer, Class<? extends DatabaseObject>... snapshotTypes) throws DatabaseException, IOException, ParserConfigurationException { Set<Class<? extends DatabaseObject>> finalCompareTypes = null; if ((snapshotTypes != null) && (snapshotTypes.length > 0)) { finalCompareTypes = new HashSet<>(Arrays.asList(snapshotTypes)); } SnapshotControl snapshotControl = new SnapshotControl(this.getDatabase(), snapshotTypes); CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison(catalogAndSchema, catalogAndSchema) }, finalCompareTypes); DatabaseSnapshot originalDatabaseSnapshot = null; try { originalDatabaseSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot( compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), getDatabase(), snapshotControl ); DiffResult diffResult = DiffGeneratorFactory.getInstance().compare( originalDatabaseSnapshot, SnapshotGeneratorFactory.getInstance().createSnapshot( compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), null, snapshotControl ), compareControl ); changeLogWriter.setDiffResult(diffResult); if(changeLogSerializer != null) { changeLogWriter.print(outputStream, changeLogSerializer); } else { changeLogWriter.print(outputStream); } } catch (InvalidExampleException e) { throw new UnexpectedLiquibaseException(e); } } }
package com.maddyhome.idea.vim.group; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.impl.EditorTabbedContainer; import com.intellij.openapi.fileEditor.impl.EditorWindow; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.VirtualFileSystem; import com.maddyhome.idea.vim.EventFacade; import com.maddyhome.idea.vim.KeyHandler; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.action.motion.MotionEditorAction; import com.maddyhome.idea.vim.action.motion.TextObjectAction; import com.maddyhome.idea.vim.command.*; import com.maddyhome.idea.vim.common.Jump; import com.maddyhome.idea.vim.common.Mark; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.ex.ExOutputModel; import com.maddyhome.idea.vim.handler.ExecuteMethodNotOverriddenException; import com.maddyhome.idea.vim.helper.CaretData; import com.maddyhome.idea.vim.helper.EditorData; import com.maddyhome.idea.vim.helper.EditorHelper; import com.maddyhome.idea.vim.helper.SearchHelper; import com.maddyhome.idea.vim.option.BoundStringOption; import com.maddyhome.idea.vim.option.NumberOption; import com.maddyhome.idea.vim.option.Options; import com.maddyhome.idea.vim.ui.ExEntryPanel; import kotlin.ranges.IntProgression; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.awt.event.MouseEvent; import java.io.File; import java.util.EnumSet; /** * This handles all motion related commands and marks */ public class MotionGroup { public static final int LAST_F = 1; public static final int LAST_f = 2; public static final int LAST_T = 3; public static final int LAST_t = 4; public static final int LAST_COLUMN = 9999; /** * Create the group */ public MotionGroup() { EventFacade.getInstance().addEditorFactoryListener(new EditorFactoryListener() { public void editorCreated(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); // This ridiculous code ensures that a lot of events are processed BEFORE we finally start listening // to visible area changes. The primary reason for this change is to fix the cursor position bug // using the gd and gD commands (Goto Declaration). This bug has been around since Idea 6.0.4? // Prior to this change the visible area code was moving the cursor around during file load and messing // with the cursor position of the Goto Declaration processing. ApplicationManager.getApplication().invokeLater( () -> ApplicationManager.getApplication().invokeLater( () -> ApplicationManager.getApplication().invokeLater( () -> { addEditorListener(editor); EditorData.setMotionGroup(editor, true); }) ) ); } public void editorReleased(@NotNull EditorFactoryEvent event) { Editor editor = event.getEditor(); if (EditorData.getMotionGroup(editor)) { removeEditorListener(editor); EditorData.setMotionGroup(editor, false); } } }, ApplicationManager.getApplication()); } public void turnOn() { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { if (!EditorData.getMotionGroup(editor)) { addEditorListener(editor); EditorData.setMotionGroup(editor, true); } } } public void turnOff() { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { if (EditorData.getMotionGroup(editor)) { removeEditorListener(editor); EditorData.setMotionGroup(editor, false); } } } private void addEditorListener(@NotNull Editor editor) { final EventFacade eventFacade = EventFacade.getInstance(); eventFacade.addEditorMouseListener(editor, mouseHandler); eventFacade.addEditorMouseMotionListener(editor, mouseHandler); eventFacade.addEditorSelectionListener(editor, selectionHandler); } private void removeEditorListener(@NotNull Editor editor) { final EventFacade eventFacade = EventFacade.getInstance(); eventFacade.removeEditorMouseListener(editor, mouseHandler); eventFacade.removeEditorMouseMotionListener(editor, mouseHandler); eventFacade.removeEditorSelectionListener(editor, selectionHandler); } /** * Process mouse clicks by setting/resetting visual mode. There are some strange scenarios to handle. * * @param editor The editor * @param event The mouse event */ private void processMouseClick(@NotNull Editor editor, @NotNull MouseEvent event) { if (ExEntryPanel.getInstance().isActive()) { VimPlugin.getProcess().cancelExEntry(editor, ExEntryPanel.getInstance().getEntry().getContext()); } ExOutputModel.getInstance(editor).clear(); CommandState.SubMode visualMode = CommandState.SubMode.NONE; switch (event.getClickCount()) { case 2: visualMode = CommandState.SubMode.VISUAL_CHARACTER; break; case 3: visualMode = CommandState.SubMode.VISUAL_LINE; // Pop state of being in Visual Char mode if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); editor.getSelectionModel().setSelection(start, Math.max(start, end - 1)); break; } setVisualMode(editor, visualMode); final CaretModel caretModel = editor.getCaretModel(); if (CommandState.getInstance(editor).getSubMode() != CommandState.SubMode.NONE) { caretModel.removeSecondaryCarets(); } switch (CommandState.getInstance(editor).getSubMode()) { case NONE: VisualPosition vp = caretModel.getVisualPosition(); int col = EditorHelper.normalizeVisualColumn(editor, vp.line, vp.column, CommandState.getInstance(editor).getMode() == CommandState.Mode.INSERT || CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE); if (col != vp.column) { caretModel.moveToVisualPosition(new VisualPosition(vp.line, col)); } MotionGroup.scrollCaretIntoView(editor); break; case VISUAL_CHARACTER: caretModel.moveToOffset(CaretData.getVisualEnd(caretModel.getPrimaryCaret())); break; case VISUAL_LINE: caretModel.moveToLogicalPosition(editor.xyToLogicalPosition(event.getPoint())); break; } CaretData.setVisualOffset(caretModel.getPrimaryCaret(), caretModel.getOffset()); CaretData.setLastColumn(editor, caretModel.getPrimaryCaret(), caretModel.getVisualPosition().column); } /** * Handles mouse drags by properly setting up visual mode based on the new selection. * * @param editor The editor the mouse drag occurred in. * @param update True if update, false if not. */ private void processLineSelection(@NotNull Editor editor, boolean update) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } ExOutputModel.getInstance(editor).clear(); if (update) { if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { for (@NotNull Caret caret : editor.getCaretModel().getAllCarets()) { updateSelection(editor, caret, caret.getOffset()); } } } else { if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); editor.getSelectionModel().setSelection(start, Math.max(start, end - 1)); setVisualMode(editor, CommandState.SubMode.VISUAL_LINE); final Caret primaryCaret = editor.getCaretModel().getPrimaryCaret(); VisualChange range = getVisualOperatorRange(editor, primaryCaret, EnumSet.of(CommandFlags.FLAG_MOT_LINEWISE)); if (range.getLines() > 1) { MotionGroup.moveCaret(editor, primaryCaret, moveCaretVertical(editor, primaryCaret, -1)); } } } private void processMouseReleased(@NotNull Editor editor, @NotNull CommandState.SubMode mode, int startOff, int endOff) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } ExOutputModel.getInstance(editor).clear(); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); if (start == end) return; if (mode == CommandState.SubMode.VISUAL_LINE) { end endOff } if (end == startOff || end == endOff) { int t = start; start = end; end = t; if (mode == CommandState.SubMode.VISUAL_CHARACTER) { start } } MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), start); toggleVisual(editor, 1, 0, mode); MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), end); KeyHandler.getInstance().reset(editor); } @NotNull public TextRange getWordRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter, boolean isBig) { int dir = 1; boolean selection = false; if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { if (CaretData.getVisualEnd(caret) < CaretData.getVisualStart(caret)) { dir = -1; } if (CaretData.getVisualStart(caret) != CaretData.getVisualEnd(caret)) { selection = true; } } return SearchHelper.findWordUnderCursor(editor, caret, count, dir, isOuter, isBig, selection); } @Nullable public TextRange getBlockQuoteRange(@NotNull Editor editor, @NotNull Caret caret, char quote, boolean isOuter) { return SearchHelper.findBlockQuoteInLineRange(editor, caret, quote, isOuter); } @Nullable public TextRange getBlockRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter, char type) { return SearchHelper.findBlockRange(editor, caret, type, count, isOuter); } @Nullable public TextRange getBlockTagRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) { return SearchHelper.findBlockTagRange(editor, caret, count, isOuter); } @NotNull public TextRange getSentenceRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) { return SearchHelper.findSentenceRange(editor, caret, count, isOuter); } @Nullable public TextRange getParagraphRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) { return SearchHelper.findParagraphRange(editor, caret, count, isOuter); } /** * This helper method calculates the complete range a motion will move over taking into account whether * the motion is FLAG_MOT_LINEWISE or FLAG_MOT_CHARACTERWISE (FLAG_MOT_INCLUSIVE or FLAG_MOT_EXCLUSIVE). * * @param editor The editor the motion takes place in * @param caret The caret the motion takes place on * @param context The data context * @param count The count applied to the motion * @param rawCount The actual count entered by the user * @param argument Any argument needed by the motion * @param incNewline True if to include newline * @return The motion's range */ @Nullable public static TextRange getMotionRange(@NotNull Editor editor, @NotNull Caret caret, DataContext context, int count, int rawCount, @NotNull Argument argument, boolean incNewline) { final Command cmd = argument.getMotion(); if (cmd == null) { return null; } // Normalize the counts between the command and the motion argument int cnt = cmd.getCount() * count; int raw = rawCount == 0 && cmd.getRawCount() == 0 ? 0 : cnt; int start = 0; int end = 0; if (cmd.getAction() instanceof MotionEditorAction) { MotionEditorAction action = (MotionEditorAction) cmd.getAction(); // This is where we are now start = caret.getOffset(); // Execute the motion (without moving the cursor) and get where we end try { end = action.getOffset(editor, caret, context, cnt, raw, cmd.getArgument()); } catch (ExecuteMethodNotOverriddenException e) { // This actually should have fallen even earlier. end = -1; VimPlugin.indicateError(); } // Invalid motion if (end == -1) { return null; } } else if (cmd.getAction() instanceof TextObjectAction) { TextObjectAction action = (TextObjectAction) cmd.getAction(); TextRange range = action.getRange(editor, caret, context, cnt, raw, cmd.getArgument()); if (range == null) { return null; } start = range.getStartOffset(); end = range.getEndOffset(); } // If we are a linewise motion we need to normalize the start and stop then move the start to the beginning // of the line and move the end to the end of the line. EnumSet<CommandFlags> flags = cmd.getFlags(); if (flags.contains(CommandFlags.FLAG_MOT_LINEWISE)) { if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.getLineStartForOffset(editor, start); end = Math .min(EditorHelper.getLineEndForOffset(editor, end) + (incNewline ? 1 : 0), EditorHelper.getFileSize(editor)); } // If characterwise and inclusive, add the last character to the range else if (flags.contains(CommandFlags.FLAG_MOT_INCLUSIVE)) { end++; } // Normalize the range if (start > end) { int t = start; start = end; end = t; } return new TextRange(start, end); } public int moveCaretToNthCharacter(@NotNull Editor editor, int count) { return Math.max(0, Math.min(count, EditorHelper.getFileSize(editor) - 1)); } public int moveCaretToFileMark(@NotNull Editor editor, char ch, boolean toLineStart) { final Mark mark = VimPlugin.getMark().getFileMark(editor, ch); if (mark == null) return -1; final int line = mark.getLogicalLine(); return toLineStart ? moveCaretToLineStartSkipLeading(editor, line) : editor.logicalPositionToOffset(new LogicalPosition(line, mark.getCol())); } public int moveCaretToMark(@NotNull Editor editor, char ch, boolean toLineStart) { final Mark mark = VimPlugin.getMark().getMark(editor, ch); if (mark == null) return -1; final VirtualFile vf = EditorData.getVirtualFile(editor); if (vf == null) return -1; final int line = mark.getLogicalLine(); if (vf.getPath().equals(mark.getFilename())) { return toLineStart ? moveCaretToLineStartSkipLeading(editor, line) : editor.logicalPositionToOffset(new LogicalPosition(line, mark.getCol())); } final Editor selectedEditor = selectEditor(editor, mark); if (selectedEditor != null) { for (Caret caret : selectedEditor.getCaretModel().getAllCarets()) { moveCaret(selectedEditor, caret, toLineStart ? moveCaretToLineStartSkipLeading(selectedEditor, line) : selectedEditor.logicalPositionToOffset( new LogicalPosition(line, mark.getCol()))); } } return -2; } public int moveCaretToJump(@NotNull Editor editor, @NotNull Caret caret, int count) { final int spot = VimPlugin.getMark().getJumpSpot(); final Jump jump = VimPlugin.getMark().getJump(count); if (jump == null) { return -1; } final VirtualFile vf = EditorData.getVirtualFile(editor); if (vf == null) { return -1; } final LogicalPosition lp = new LogicalPosition(jump.getLogicalLine(), jump.getCol()); final String fileName = jump.getFilename(); if (!vf.getPath().equals(fileName) && fileName != null) { final VirtualFile newFile = LocalFileSystem.getInstance().findFileByPath(fileName.replace(File.separatorChar, '/')); if (newFile == null) { return -2; } final Editor newEditor = selectEditor(editor, newFile); if (newEditor != null) { if (spot == -1) { VimPlugin.getMark().addJump(editor, false); } moveCaret(newEditor, caret, EditorHelper.normalizeOffset(newEditor, newEditor.logicalPositionToOffset(lp), false)); } return -2; } else { if (spot == -1) { VimPlugin.getMark().addJump(editor, false); } return editor.logicalPositionToOffset(lp); } } @Nullable private Editor selectEditor(@NotNull Editor editor, @NotNull Mark mark) { final VirtualFile virtualFile = markToVirtualFile(mark); if (virtualFile != null) { return selectEditor(editor, virtualFile); } else { return null; } } @Nullable private VirtualFile markToVirtualFile(@NotNull Mark mark) { String protocol = mark.getProtocol(); VirtualFileSystem fileSystem = VirtualFileManager.getInstance().getFileSystem(protocol); if (mark.getFilename() == null) { return null; } return fileSystem.findFileByPath(mark.getFilename()); } @Nullable private Editor selectEditor(@NotNull Editor editor, @NotNull VirtualFile file) { return VimPlugin.getFile().selectEditor(editor.getProject(), file); } public int moveCaretToMatchingPair(@NotNull Editor editor, @NotNull Caret caret) { int pos = SearchHelper.findMatchingPairOnCurrentLine(editor, caret); if (pos >= 0) { return pos; } else { return -1; } } /** * This moves the caret to the start of the next/previous camel word. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of words to skip * @return position */ public int moveCaretToNextCamel(@NotNull Editor editor, @NotNull Caret caret, int count) { if ((caret.getOffset() == 0 && count < 0) || (caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { return SearchHelper.findNextCamelStart(editor, caret, count); } } /** * This moves the caret to the start of the next/previous camel word. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of words to skip * @return position */ public int moveCaretToNextCamelEnd(@NotNull Editor editor, @NotNull Caret caret, int count) { if ((caret.getOffset() == 0 && count < 0) || (caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { return SearchHelper.findNextCamelEnd(editor, caret, count); } } /** * This moves the caret to the start of the next/previous word/WORD. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of words to skip * @param bigWord If true then find WORD, if false then find word * @return position */ public int moveCaretToNextWord(@NotNull Editor editor, @NotNull Caret caret, int count, boolean bigWord) { final int offset = caret.getOffset(); final int size = EditorHelper.getFileSize(editor); if ((offset == 0 && count < 0) || (offset >= size - 1 && count > 0)) { return -1; } return SearchHelper.findNextWord(editor, caret, count, bigWord); } /** * This moves the caret to the end of the next/previous word/WORD. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of words to skip * @param bigWord If true then find WORD, if false then find word * @return position */ public int moveCaretToNextWordEnd(@NotNull Editor editor, @NotNull Caret caret, int count, boolean bigWord) { if ((caret.getOffset() == 0 && count < 0) || (caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } // If we are doing this move as part of a change command (e.q. cw), we need to count the current end of // word if the cursor happens to be on the end of a word already. If this is a normal move, we don't count // the current word. int pos = SearchHelper.findNextWordEnd(editor, caret, count, bigWord); if (pos == -1) { if (count < 0) { return moveCaretToLineStart(editor, 0); } else { return moveCaretToLineEnd(editor, EditorHelper.getLineCount(editor) - 1, false); } } else { return pos; } } /** * This moves the caret to the start of the next/previous paragraph. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of paragraphs to skip * @return position */ public int moveCaretToNextParagraph(@NotNull Editor editor, @NotNull Caret caret, int count) { int res = SearchHelper.findNextParagraph(editor, caret, count, false); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, true); } else { res = -1; } return res; } public int moveCaretToNextSentenceStart(@NotNull Editor editor, @NotNull Caret caret, int count) { int res = SearchHelper.findNextSentenceStart(editor, caret, count, false, true); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, true); } else { res = -1; } return res; } public int moveCaretToNextSentenceEnd(@NotNull Editor editor, @NotNull Caret caret, int count) { int res = SearchHelper.findNextSentenceEnd(editor, caret, count, false, true); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, false); } else { res = -1; } return res; } public int moveCaretToUnmatchedBlock(@NotNull Editor editor, @NotNull Caret caret, int count, char type) { if ((editor.getCaretModel().getOffset() == 0 && count < 0) || (editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { int res = SearchHelper.findUnmatchedBlock(editor, caret, type, count); if (res != -1) { res = EditorHelper.normalizeOffset(editor, res, false); } return res; } } public int moveCaretToSection(@NotNull Editor editor, @NotNull Caret caret, char type, int dir, int count) { if ((caret.getOffset() == 0 && count < 0) || (caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { int res = SearchHelper.findSection(editor, caret, type, dir, count); if (res != -1) { res = EditorHelper.normalizeOffset(editor, res, false); } return res; } } public int moveCaretToMethodStart(@NotNull Editor editor, @NotNull Caret caret, int count) { return SearchHelper.findMethodStart(editor, caret, count); } public int moveCaretToMethodEnd(@NotNull Editor editor, @NotNull Caret caret, int count) { return SearchHelper.findMethodEnd(editor, caret, count); } public void setLastFTCmd(int lastFTCmd, char lastChar) { this.lastFTCmd = lastFTCmd; this.lastFTChar = lastChar; } public int repeatLastMatchChar(@NotNull Editor editor, @NotNull Caret caret, int count) { int res = -1; int startPos = editor.getCaretModel().getOffset(); switch (lastFTCmd) { case LAST_F: res = moveCaretToNextCharacterOnLine(editor, caret, -count, lastFTChar); break; case LAST_f: res = moveCaretToNextCharacterOnLine(editor, caret, count, lastFTChar); break; case LAST_T: res = moveCaretToBeforeNextCharacterOnLine(editor, caret, -count, lastFTChar); if (res == startPos && Math.abs(count) == 1) { res = moveCaretToBeforeNextCharacterOnLine(editor, caret, 2 * count, lastFTChar); } break; case LAST_t: res = moveCaretToBeforeNextCharacterOnLine(editor, caret, count, lastFTChar); if (res == startPos && Math.abs(count) == 1) { res = moveCaretToBeforeNextCharacterOnLine(editor, caret, 2 * count, lastFTChar); } break; } return res; } /** * This moves the caret to the next/previous matching character on the current line * * @param caret The caret to be moved * @param count The number of occurrences to move to * @param ch The character to search for * @param editor The editor to search in * @return True if [count] character matches were found, false if not */ public int moveCaretToNextCharacterOnLine(@NotNull Editor editor, @NotNull Caret caret, int count, char ch) { int pos = SearchHelper.findNextCharacterOnLine(editor, caret, count, ch); if (pos >= 0) { return pos; } else { return -1; } } /** * This moves the caret next to the next/previous matching character on the current line * * @param caret The caret to be moved * @param count The number of occurrences to move to * @param ch The character to search for * @param editor The editor to search in * @return True if [count] character matches were found, false if not */ public int moveCaretToBeforeNextCharacterOnLine(@NotNull Editor editor, @NotNull Caret caret, int count, char ch) { int pos = SearchHelper.findNextCharacterOnLine(editor, caret, count, ch); if (pos >= 0) { int step = count >= 0 ? 1 : -1; return pos - step; } else { return -1; } } public boolean scrollLineToFirstScreenLine(@NotNull Editor editor, int rawCount, boolean start) { scrollLineToScreenLocation(editor, ScreenLocation.TOP, rawCount, start); return true; } public boolean scrollLineToMiddleScreenLine(@NotNull Editor editor, int rawCount, boolean start) { scrollLineToScreenLocation(editor, ScreenLocation.MIDDLE, rawCount, start); return true; } public boolean scrollLineToLastScreenLine(@NotNull Editor editor, int rawCount, boolean start) { scrollLineToScreenLocation(editor, ScreenLocation.BOTTOM, rawCount, start); return true; } public boolean scrollColumnToFirstScreenColumn(@NotNull Editor editor) { scrollColumnToScreenColumn(editor, 0); return true; } public boolean scrollColumnToLastScreenColumn(@NotNull Editor editor) { scrollColumnToScreenColumn(editor, EditorHelper.getScreenWidth(editor)); return true; } private void scrollColumnToScreenColumn(@NotNull Editor editor, int column) { int scrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value(); int width = EditorHelper.getScreenWidth(editor); if (scrollOffset > width / 2) { scrollOffset = width / 2; } if (column <= width / 2) { if (column < scrollOffset + 1) { column = scrollOffset + 1; } } else { if (column > width - scrollOffset) { column = width - scrollOffset; } } int visualColumn = editor.getCaretModel().getVisualPosition().column; scrollColumnToLeftOfScreen(editor, EditorHelper .normalizeVisualColumn(editor, editor.getCaretModel().getVisualPosition().line, visualColumn - column + 1, false)); } // Scrolls current or [count] line to given screen location // In Vim, [count] refers to a file line, so it's a logical line private void scrollLineToScreenLocation(@NotNull Editor editor, @NotNull ScreenLocation screenLocation, int line, boolean start) { final int scrollOffset = getNormalizedScrollOffset(editor); line = EditorHelper.normalizeLine(editor, line); int visualLine = line == 0 ? editor.getCaretModel().getVisualPosition().line : EditorHelper.logicalLineToVisualLine(editor, line - 1); // This method moves the current (or [count]) line to the specified screen location // Scroll offset is applicable, but scroll jump isn't. Offset is applied to screen lines (visual lines) switch (screenLocation) { case TOP: EditorHelper.scrollVisualLineToTopOfScreen(editor, visualLine - scrollOffset); break; case MIDDLE: EditorHelper.scrollVisualLineToMiddleOfScreen(editor, visualLine); break; case BOTTOM: EditorHelper.scrollVisualLineToBottomOfScreen(editor, visualLine + scrollOffset); break; } if (visualLine != editor.getCaretModel().getVisualPosition().line || start) { int offset; if (start) { offset = moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, visualLine)); } else { offset = moveCaretVertical(editor, editor.getCaretModel().getPrimaryCaret(), EditorHelper.visualLineToLogicalLine(editor, visualLine) - editor.getCaretModel().getLogicalPosition().line); } moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset); } } public int moveCaretToFirstScreenLine(@NotNull Editor editor, int count) { return moveCaretToScreenLocation(editor, ScreenLocation.TOP, count); } public int moveCaretToLastScreenLine(@NotNull Editor editor, int count) { return moveCaretToScreenLocation(editor, ScreenLocation.BOTTOM, count); } public int moveCaretToMiddleScreenLine(@NotNull Editor editor) { return moveCaretToScreenLocation(editor, ScreenLocation.MIDDLE, 0); } // [count] is a visual line offset, which means it's 1 based. The value is ignored for ScreenLocation.MIDDLE private int moveCaretToScreenLocation(@NotNull Editor editor, @NotNull ScreenLocation screenLocation, int visualLineOffset) { final int scrollOffset = getNormalizedScrollOffset(editor); int topVisualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); int bottomVisualLine = EditorHelper.getVisualLineAtBottomOfScreen(editor); // Don't apply scrolloff if we're at the top or bottom of the file int offsetTopVisualLine = topVisualLine > 0 ? topVisualLine + scrollOffset : topVisualLine; int offsetBottomVisualLine = bottomVisualLine < EditorHelper.getVisualLineCount(editor) ? bottomVisualLine - scrollOffset : bottomVisualLine; // [count]H/[count]L moves caret to that screen line, bounded by top/bottom scroll offsets int targetVisualLine = 0; switch (screenLocation) { case TOP: targetVisualLine = Math.max(offsetTopVisualLine, topVisualLine + visualLineOffset - 1); targetVisualLine = Math.min(targetVisualLine, offsetBottomVisualLine); break; case MIDDLE: targetVisualLine = EditorHelper.getVisualLineAtMiddleOfScreen(editor); break; case BOTTOM: targetVisualLine = Math.min(offsetBottomVisualLine, bottomVisualLine - visualLineOffset + 1); targetVisualLine = Math.max(targetVisualLine, offsetTopVisualLine); break; } return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, targetVisualLine)); } public boolean scrollColumn(@NotNull Editor editor, int columns) { int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); visualColumn = EditorHelper .normalizeVisualColumn(editor, editor.getCaretModel().getVisualPosition().line, visualColumn + columns, false); scrollColumnToLeftOfScreen(editor, visualColumn); moveCaretToView(editor); return true; } public boolean scrollLine(@NotNull Editor editor, int lines) { assert lines != 0 : "lines cannot be 0"; if (lines > 0) { int visualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); visualLine = EditorHelper.normalizeVisualLine(editor, visualLine + lines); EditorHelper.scrollVisualLineToTopOfScreen(editor, visualLine); } else if (lines < 0) { int visualLine = EditorHelper.getVisualLineAtBottomOfScreen(editor); visualLine = EditorHelper.normalizeVisualLine(editor, visualLine + lines); EditorHelper.scrollVisualLineToBottomOfScreen(editor, visualLine); } moveCaretToView(editor); return true; } private static void moveCaretToView(@NotNull Editor editor) { final int scrollOffset = getNormalizedScrollOffset(editor); int topVisualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); int bottomVisualLine = EditorHelper.getVisualLineAtBottomOfScreen(editor); int caretVisualLine = editor.getCaretModel().getVisualPosition().line; int newline = caretVisualLine; if (caretVisualLine < topVisualLine + scrollOffset) { newline = EditorHelper.normalizeVisualLine(editor, topVisualLine + scrollOffset); } else if (caretVisualLine >= bottomVisualLine - scrollOffset) { newline = EditorHelper.normalizeVisualLine(editor, bottomVisualLine - scrollOffset); } int sideScrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value(); int width = EditorHelper.getScreenWidth(editor); if (sideScrollOffset > width / 2) { sideScrollOffset = width / 2; } int col = editor.getCaretModel().getVisualPosition().column; int oldColumn = col; if (col >= EditorHelper.getLineLength(editor) - 1) { col = CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()); } int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); int caretColumn = col; int newColumn = caretColumn; if (caretColumn < visualColumn + sideScrollOffset) { newColumn = visualColumn + sideScrollOffset; } else if (caretColumn >= visualColumn + width - sideScrollOffset) { newColumn = visualColumn + width - sideScrollOffset - 1; } if (newline == caretVisualLine && newColumn != caretColumn) { col = newColumn; } newColumn = EditorHelper.normalizeVisualColumn(editor, newline, newColumn, CommandState.inInsertMode(editor)); if (newline != caretVisualLine || newColumn != oldColumn) { int offset = EditorHelper.visualPositionToOffset(editor, new VisualPosition(newline, newColumn)); moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset); CaretData.setLastColumn(editor, editor.getCaretModel().getPrimaryCaret(), col); } } public boolean scrollFullPage(@NotNull Editor editor, int pages) { int caretVisualLine = EditorHelper.scrollFullPage(editor, pages); if (caretVisualLine != -1) { final int scrollOffset = getNormalizedScrollOffset(editor); boolean success = true; if (pages > 0) { // If the caret is ending up passed the end of the file, we need to beep if (caretVisualLine > EditorHelper.getVisualLineCount(editor) - 1) { success = false; } int topVisualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); if (caretVisualLine < topVisualLine + scrollOffset) { caretVisualLine = EditorHelper.normalizeVisualLine(editor, caretVisualLine + scrollOffset); } } else if (pages < 0) { int bottomVisualLine = EditorHelper.getVisualLineAtBottomOfScreen( editor); if (caretVisualLine > bottomVisualLine - scrollOffset) { caretVisualLine = EditorHelper.normalizeVisualLine(editor, caretVisualLine - scrollOffset); } } int offset = moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, caretVisualLine)); moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset); return success; } return false; } public boolean scrollScreen(@NotNull final Editor editor, int rawCount, boolean down) { final CaretModel caretModel = editor.getCaretModel(); final int currentLogicalLine = caretModel.getLogicalPosition().line; if ((!down && currentLogicalLine <= 0) || (down && currentLogicalLine >= EditorHelper.getLineCount(editor) - 1)) { return false; } final ScrollingModel scrollingModel = editor.getScrollingModel(); final Rectangle visibleArea = scrollingModel.getVisibleArea(); int targetCaretVisualLine = getScrollScreenTargetCaretVisualLine(editor, rawCount, down); // Scroll at most one screen height final int yInitialCaret = editor.visualLineToY(caretModel.getVisualPosition().line); final int yTargetVisualLine = editor.visualLineToY(targetCaretVisualLine); if (Math.abs(yTargetVisualLine - yInitialCaret) > visibleArea.height) { final int yPrevious = visibleArea.y; boolean moved; if (down) { targetCaretVisualLine = EditorHelper.getVisualLineAtBottomOfScreen(editor) + 1; moved = EditorHelper.scrollVisualLineToTopOfScreen(editor, targetCaretVisualLine); } else { targetCaretVisualLine = EditorHelper.getVisualLineAtTopOfScreen(editor) - 1; moved = EditorHelper.scrollVisualLineToBottomOfScreen(editor, targetCaretVisualLine); } if (moved) { // We'll keep the caret at the same position, although that might not be the same line offset as previously targetCaretVisualLine = editor.yToVisualLine(yInitialCaret + scrollingModel.getVisibleArea().y - yPrevious); } } else { EditorHelper.scrollVisualLineToCaretLocation(editor, targetCaretVisualLine); final int scrollOffset = getNormalizedScrollOffset(editor); final int visualTop = EditorHelper.getVisualLineAtTopOfScreen(editor) + scrollOffset; final int visualBottom = EditorHelper.getVisualLineAtBottomOfScreen(editor) - scrollOffset; targetCaretVisualLine = Math.max(visualTop, Math.min(visualBottom, targetCaretVisualLine)); } int logicalLine = EditorHelper.visualLineToLogicalLine(editor, targetCaretVisualLine); int caretOffset = moveCaretToLineStartSkipLeading(editor, logicalLine); moveCaret(editor, caretModel.getPrimaryCaret(), caretOffset); return true; } private static int getScrollScreenTargetCaretVisualLine(@NotNull final Editor editor, int rawCount, boolean down) { final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea(); final int caretVisualLine = editor.getCaretModel().getVisualPosition().line; final int scrollOption = getScrollOption(rawCount); int targetCaretVisualLine; if (scrollOption == 0) { // Scroll up/down half window size by default. We can't use line count here because of block inlays final int offset = down ? (visibleArea.height / 2) : editor.getLineHeight() - (visibleArea.height / 2); targetCaretVisualLine = editor.yToVisualLine(editor.visualLineToY(caretVisualLine) + offset); } else { targetCaretVisualLine = down ? caretVisualLine + scrollOption : caretVisualLine - scrollOption; } return targetCaretVisualLine; } private static int getScrollOption(int rawCount) { NumberOption scroll = (NumberOption) Options.getInstance().getOption("scroll"); if (rawCount == 0) { return scroll.value(); } // TODO: This needs to be reset whenever the window size changes scroll.set(rawCount); return rawCount; } private static int getNormalizedScrollOffset(@NotNull final Editor editor) { int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value(); return EditorHelper.normalizeScrollOffset(editor, scrollOffset); } private static void scrollColumnToLeftOfScreen(@NotNull Editor editor, int column) { editor.getScrollingModel().scrollHorizontally(column * EditorHelper.getColumnWidth(editor)); } public int moveCaretToMiddleColumn(@NotNull Editor editor, @NotNull Caret caret) { final int width = EditorHelper.getScreenWidth(editor) / 2; final int len = EditorHelper.getLineLength(editor); return moveCaretToColumn(editor, caret, Math.max(0, Math.min(len - 1, width)), false); } public int moveCaretToColumn(@NotNull Editor editor, @NotNull Caret caret, int count, boolean allowEnd) { int line = caret.getLogicalPosition().line; int pos = EditorHelper.normalizeColumn(editor, line, count, allowEnd); return editor.logicalPositionToOffset(new LogicalPosition(line, pos)); } /** * @deprecated To move the caret, use {@link #moveCaretToColumn(Editor, Caret, int, boolean)} */ public int moveCaretToColumn(@NotNull Editor editor, int count, boolean allowEnd) { return moveCaretToColumn(editor, editor.getCaretModel().getPrimaryCaret(), count, allowEnd); } public int moveCaretToLineStartSkipLeading(@NotNull Editor editor, @NotNull Caret caret) { int logicalLine = caret.getLogicalPosition().line; return moveCaretToLineStartSkipLeading(editor, logicalLine); } public int moveCaretToLineStartSkipLeading(@NotNull Editor editor, int line) { return EditorHelper.getLeadingCharacterOffset(editor, line); } /** * @deprecated To move the caret, use {@link #moveCaretToLineStartSkipLeading(Editor, Caret)} */ public int moveCaretToLineStartSkipLeading(@NotNull Editor editor) { return moveCaretToLineStartSkipLeading(editor, editor.getCaretModel().getPrimaryCaret()); } public int moveCaretToLineStartSkipLeadingOffset(@NotNull Editor editor, @NotNull Caret caret, int linesOffset) { int line = EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + linesOffset); return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line)); } /** * @deprecated To move the caret, use {@link #moveCaretToLineStartSkipLeadingOffset(Editor, Caret, int)} */ public int moveCaretToLineStartSkipLeadingOffset(@NotNull Editor editor, int linesOffset) { return moveCaretToLineStartSkipLeadingOffset(editor, editor.getCaretModel().getPrimaryCaret(), linesOffset); } public int moveCaretToLineEndSkipLeadingOffset(@NotNull Editor editor, @NotNull Caret caret, int linesOffset) { int line = EditorHelper.visualLineToLogicalLine(editor, EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + linesOffset)); int start = EditorHelper.getLineStartOffset(editor, line); int end = EditorHelper.getLineEndOffset(editor, line, true); CharSequence chars = editor.getDocument().getCharsSequence(); int pos = start; for (int offset = end; offset > start; offset if (offset >= chars.length()) { break; } if (!Character.isWhitespace(chars.charAt(offset))) { pos = offset; break; } } return pos; } /** * @deprecated Use {@link #moveCaretToLineEnd(Editor, Caret)} */ public int moveCaretToLineEnd(@NotNull Editor editor) { return moveCaretToLineEnd(editor, editor.getCaretModel().getPrimaryCaret()); } public int moveCaretToLineEnd(@NotNull Editor editor, @NotNull Caret caret) { final VisualPosition visualPosition = caret.getVisualPosition(); final int lastVisualLineColumn = EditorUtil.getLastVisualLineColumnNumber(editor, visualPosition.line); final VisualPosition visualEndOfLine = new VisualPosition(visualPosition.line, lastVisualLineColumn, true); return moveCaretToLineEnd(editor, editor.visualToLogicalPosition(visualEndOfLine).line, true); } public int moveCaretToLineEnd(@NotNull Editor editor, int line, boolean allowPastEnd) { return EditorHelper .normalizeOffset(editor, line, EditorHelper.getLineEndOffset(editor, line, allowPastEnd), allowPastEnd); } public int moveCaretToLineEndOffset(@NotNull Editor editor, @NotNull Caret caret, int cntForward, boolean allowPastEnd) { int line = EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + cntForward); if (line < 0) { return 0; } else { return moveCaretToLineEnd(editor, EditorHelper.visualLineToLogicalLine(editor, line), allowPastEnd); } } /** * @deprecated To move the caret, use {@link #moveCaretToLineEndOffset(Editor, Caret, int, boolean)} */ public int moveCaretToLineEndOffset(@NotNull Editor editor, int cntForward, boolean allowPastEnd) { return moveCaretToLineEndOffset(editor, editor.getCaretModel().getPrimaryCaret(), cntForward, allowPastEnd); } public int moveCaretToLineStart(@NotNull Editor editor, @NotNull Caret caret) { int logicalLine = caret.getLogicalPosition().line; return moveCaretToLineStart(editor, logicalLine); } /** * @deprecated To move the caret, use {@link #moveCaretToLineStart(Editor, Caret)} */ public int moveCaretToLineStart(@NotNull Editor editor) { return moveCaretToLineStart(editor, editor.getCaretModel().getPrimaryCaret()); } public int moveCaretToLineStart(@NotNull Editor editor, int line) { if (line >= EditorHelper.getLineCount(editor)) { return EditorHelper.getFileSize(editor); } return EditorHelper.getLineStartOffset(editor, line); } public int moveCaretToLineScreenStart(@NotNull Editor editor, @NotNull Caret caret) { final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor); return moveCaretToColumn(editor, caret, col, false); } public int moveCaretToLineScreenStartSkipLeading(@NotNull Editor editor, @NotNull Caret caret) { final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor); final int logicalLine = caret.getLogicalPosition().line; return EditorHelper.getLeadingCharacterOffset(editor, logicalLine, col); } public int moveCaretToLineScreenEnd(@NotNull Editor editor, @NotNull Caret caret, boolean allowEnd) { final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor) + EditorHelper.getScreenWidth(editor) - 1; return moveCaretToColumn(editor, caret, col, allowEnd); } public int moveCaretHorizontalWrap(@NotNull Editor editor, @NotNull Caret caret, int count) { // FIX - allows cursor over newlines int oldOffset = caret.getOffset(); int offset = Math.min(Math.max(0, caret.getOffset() + count), EditorHelper.getFileSize(editor)); if (offset == oldOffset) { return -1; } else { return offset; } } public int moveCaretHorizontal(@NotNull Editor editor, @NotNull Caret caret, int count, boolean allowPastEnd) { int oldOffset = caret.getOffset(); int diff = 0; String text = editor.getDocument().getText(); int sign = (int)Math.signum(count); for (Integer pointer : new IntProgression(0, count - sign, sign)) { int textPointer = oldOffset + pointer; if (textPointer < text.length() && textPointer >= 0) { // Actual char size can differ from 1 if unicode characters are used (like ) diff += Character.charCount(text.codePointAt(textPointer)); } else { diff += 1; } } int offset = EditorHelper.normalizeOffset(editor, caret.getLogicalPosition().line, oldOffset + (sign * diff), allowPastEnd); if (offset == oldOffset) { return -1; } else { return offset; } } public int moveCaretVertical(@NotNull Editor editor, @NotNull Caret caret, int count) { VisualPosition pos = caret.getVisualPosition(); if ((pos.line == 0 && count < 0) || (pos.line >= EditorHelper.getVisualLineCount(editor) - 1 && count > 0)) { return -1; } else { int col = CaretData.getLastColumn(caret); int line = EditorHelper.normalizeVisualLine(editor, pos.line + count); VisualPosition newPos = new VisualPosition(line, EditorHelper .normalizeVisualColumn(editor, line, col, CommandState.inInsertMode(editor))); return EditorHelper.visualPositionToOffset(editor, newPos); } } public int moveCaretToLine(@NotNull Editor editor, int logicalLine) { int col = CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()); int line = logicalLine; if (logicalLine < 0) { line = 0; col = 0; } else if (logicalLine >= EditorHelper.getLineCount(editor)) { line = EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1); col = EditorHelper.getLineLength(editor, line); } LogicalPosition newPos = new LogicalPosition(line, EditorHelper.normalizeColumn(editor, line, col, false)); return editor.logicalPositionToOffset(newPos); } public int moveCaretToLinePercent(@NotNull Editor editor, int count) { if (count > 100) count = 100; return moveCaretToLineStartSkipLeading(editor, EditorHelper .normalizeLine(editor, (EditorHelper.getLineCount(editor) * count + 99) / 100 - 1)); } public int moveCaretGotoLineLast(@NotNull Editor editor, int rawCount) { final int line = rawCount == 0 ? EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : rawCount - 1; return moveCaretToLineStartSkipLeading(editor, line); } public int moveCaretGotoLineLastEnd(@NotNull Editor editor, int rawCount, int line, boolean pastEnd) { return moveCaretToLineEnd(editor, rawCount == 0 ? EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : line, pastEnd); } public int moveCaretGotoLineFirst(@NotNull Editor editor, int line) { return moveCaretToLineStartSkipLeading(editor, line); } public static void moveCaret(@NotNull Editor editor, @NotNull Caret caret, int offset) { moveCaret(editor, caret, offset, false); } public static void moveCaret(@NotNull Editor editor, @NotNull Caret caret, int offset, boolean forceKeepVisual) { if (offset >= 0 && offset <= editor.getDocument().getTextLength()) { final boolean keepVisual = forceKeepVisual || keepVisual(editor); if (caret.getOffset() != offset) { caret.moveToOffset(offset); CaretData.setLastColumn(editor, caret, caret.getVisualPosition().column); if (caret == editor.getCaretModel().getPrimaryCaret()) { scrollCaretIntoView(editor); } } if (keepVisual) { VimPlugin.getMotion().updateSelection(editor, caret, offset); } else { editor.getSelectionModel().removeSelection(); } } } private static boolean keepVisual(Editor editor) { final CommandState commandState = CommandState.getInstance(editor); if (commandState.getMode() == CommandState.Mode.VISUAL) { final Command command = commandState.getCommand(); return command == null || !command.getFlags().contains(CommandFlags.FLAG_EXIT_VISUAL); } return false; } /** * If 'absolute' is true, then set tab index to 'value', otherwise add 'value' to tab index with wraparound. */ private void switchEditorTab(@Nullable EditorWindow editorWindow, int value, boolean absolute) { if (editorWindow != null) { final EditorTabbedContainer tabbedPane = editorWindow.getTabbedPane(); if (tabbedPane != null) { if (absolute) { tabbedPane.setSelectedIndex(value); } else { int tabIndex = (value + tabbedPane.getSelectedIndex()) % tabbedPane.getTabCount(); tabbedPane.setSelectedIndex(tabIndex < 0 ? tabIndex + tabbedPane.getTabCount() : tabIndex); } } } } public int moveCaretGotoPreviousTab(@NotNull Editor editor, @NotNull DataContext context, int rawCount) { switchEditorTab(EditorWindow.DATA_KEY.getData(context), rawCount >= 1 ? -rawCount : -1, false); return editor.getCaretModel().getOffset(); } public int moveCaretGotoNextTab(@NotNull Editor editor, @NotNull DataContext context, int rawCount) { final boolean absolute = rawCount >= 1; switchEditorTab(EditorWindow.DATA_KEY.getData(context), absolute ? rawCount - 1 : 1, absolute); return editor.getCaretModel().getOffset(); } private static void scrollCaretIntoView(@NotNull Editor editor) { final boolean scrollJump = !CommandState.getInstance(editor).getFlags().contains(CommandFlags.FLAG_IGNORE_SCROLL_JUMP); scrollPositionIntoView(editor, editor.getCaretModel().getVisualPosition(), scrollJump); } public static void scrollPositionIntoView(@NotNull Editor editor, @NotNull VisualPosition position, boolean scrollJump) { final int topVisualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); final int bottomVisualLine = EditorHelper.getVisualLineAtBottomOfScreen(editor); final int visualLine = position.line; final int column = position.column; // We need the non-normalised value here, so we can handle cases such as so=999 to keep the current line centred int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value(); int scrollJumpSize = 0; if (scrollJump) { scrollJumpSize = Math.max(0, ((NumberOption) Options.getInstance().getOption("scrolljump")).value() - 1); } int visualTop = topVisualLine + scrollOffset; int visualBottom = bottomVisualLine - scrollOffset + 1; if (visualTop == visualBottom) { visualBottom++; } int diff; if (visualLine < visualTop) { diff = visualLine - visualTop; scrollJumpSize = -scrollJumpSize; } else { diff = Math.max(0, visualLine - visualBottom + 1); } if (diff != 0) { // If we need to scroll the current line more than half a screen worth of lines then we just centre the new // current line. This mimics vim behaviour of e.g. 100G in a 300 line file with a screen size of 25 centering line // 100. It also handles so=999 keeping the current line centred. // It doesn't handle keeping the line centred when scroll offset is less than a full page height, as the new line // might be within e.g. top + scroll offset, so we test for that separately. // Note that block inlays means that the pixel height we are scrolling can be larger than half the screen, even if // the number of lines is less. I'm not sure what impact this has. int height = bottomVisualLine - topVisualLine + 1; if (Math.abs(diff) > height / 2 || scrollOffset > height / 2) { EditorHelper.scrollVisualLineToMiddleOfScreen(editor, visualLine); } else { // Put the new cursor line "scrolljump" lines from the top/bottom. Ensure that the line is fully visible, // including block inlays above/below the line if (diff > 0) { int resLine = bottomVisualLine + diff + scrollJumpSize; EditorHelper.scrollVisualLineToBottomOfScreen(editor, resLine); } else { int resLine = topVisualLine + diff + scrollJumpSize; resLine = Math.min(resLine, EditorHelper.getVisualLineCount(editor) - height); resLine = Math.max(0, resLine); EditorHelper.scrollVisualLineToTopOfScreen(editor, resLine); } } } int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); int width = EditorHelper.getScreenWidth(editor); scrollJump = !CommandState.getInstance(editor).getFlags().contains(CommandFlags.FLAG_IGNORE_SIDE_SCROLL_JUMP); scrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value(); scrollJumpSize = 0; if (scrollJump) { scrollJumpSize = Math.max(0, ((NumberOption) Options.getInstance().getOption("sidescroll")).value() - 1); if (scrollJumpSize == 0) { scrollJumpSize = width / 2; } } int visualLeft = visualColumn + scrollOffset; int visualRight = visualColumn + width - scrollOffset; if (scrollOffset >= width / 2) { scrollOffset = width / 2; visualLeft = visualColumn + scrollOffset; visualRight = visualColumn + width - scrollOffset; if (visualLeft == visualRight) { visualRight++; } } scrollJumpSize = Math.min(scrollJumpSize, width / 2 - scrollOffset); if (column < visualLeft) { diff = column - visualLeft + 1; scrollJumpSize = -scrollJumpSize; } else { diff = column - visualRight + 1; if (diff < 0) { diff = 0; } } if (diff != 0) { int col; if (Math.abs(diff) > width / 2) { col = column - width / 2 - 1; } else { col = visualColumn + diff + scrollJumpSize; } col = Math.max(0, col); scrollColumnToLeftOfScreen(editor, col); } } public boolean selectPreviousVisualMode(@NotNull Editor editor) { final SelectionType lastSelectionType = EditorData.getLastSelectionType(editor); if (lastSelectionType == null) { return false; } final TextRange visualMarks = VimPlugin.getMark().getVisualSelectionMarks(editor); if (visualMarks == null) { return false; } editor.getCaretModel().removeSecondaryCarets(); CommandState.getInstance(editor) .pushState(CommandState.Mode.VISUAL, lastSelectionType.toSubMode(), MappingMode.VISUAL); Caret primaryCaret = editor.getCaretModel().getPrimaryCaret(); CaretData.setVisualStart(primaryCaret, visualMarks.getStartOffset()); CaretData.setVisualEnd(primaryCaret, visualMarks.getEndOffset()); CaretData.setVisualOffset(primaryCaret, visualMarks.getEndOffset()); updateSelection(editor, primaryCaret, visualMarks.getEndOffset()); primaryCaret.moveToOffset(visualMarks.getEndOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); return true; } public boolean swapVisualSelections(@NotNull Editor editor) { final SelectionType lastSelectionType = EditorData.getLastSelectionType(editor); final TextRange lastVisualRange = EditorData.getLastVisualRange(editor); if (lastSelectionType == null || lastVisualRange == null) { return false; } final SelectionType selectionType = SelectionType.fromSubMode(CommandState.getInstance(editor).getSubMode()); EditorData.setLastSelectionType(editor, selectionType); editor.getCaretModel().removeSecondaryCarets(); Caret primaryCaret = editor.getCaretModel().getPrimaryCaret(); CaretData.setVisualStart(primaryCaret, lastVisualRange.getStartOffset()); CaretData.setVisualEnd(primaryCaret, lastVisualRange.getEndOffset()); CaretData.setVisualOffset(primaryCaret, lastVisualRange.getEndOffset()); CommandState.getInstance(editor).setSubMode(lastSelectionType.toSubMode()); updateSelection(editor, primaryCaret, lastVisualRange.getEndOffset()); primaryCaret.moveToOffset(lastVisualRange.getEndOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); return true; } public void setVisualMode(@NotNull Editor editor, @NotNull CommandState.SubMode mode) { CommandState.SubMode oldMode = CommandState.getInstance(editor).getSubMode(); if (mode == CommandState.SubMode.NONE) { int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); if (start != end) { int line = editor.offsetToLogicalPosition(start).line; int logicalStart = EditorHelper.getLineStartOffset(editor, line); int lend = EditorHelper.getLineEndOffset(editor, line, true); if (logicalStart == start && lend + 1 == end) { mode = CommandState.SubMode.VISUAL_LINE; } else { mode = CommandState.SubMode.VISUAL_CHARACTER; } } } if (oldMode == CommandState.SubMode.NONE && mode == CommandState.SubMode.NONE) { editor.getSelectionModel().removeSelection(); return; } if (mode == CommandState.SubMode.NONE) { exitVisual(editor); } else { CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL); } KeyHandler.getInstance().reset(editor); for (Caret caret : editor.getCaretModel().getAllCarets()) { CaretData.setVisualStart(caret, caret.getSelectionStart()); int visualEnd = caret.getSelectionEnd(); if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_CHARACTER) { BoundStringOption opt = (BoundStringOption) Options.getInstance().getOption("selection"); int adj = 1; if (opt.getValue().equals("exclusive")) { adj = 0; } visualEnd -= adj; } CaretData.setVisualEnd(caret, visualEnd); CaretData.setVisualOffset(caret, caret.getOffset()); } VimPlugin.getMark().setVisualSelectionMarks(editor, getRawVisualRange(editor.getCaretModel().getPrimaryCaret())); } public boolean toggleVisual(@NotNull Editor editor, int count, int rawCount, @NotNull CommandState.SubMode mode) { CommandState.SubMode currentMode = CommandState.getInstance(editor).getSubMode(); if (CommandState.getInstance(editor).getMode() != CommandState.Mode.VISUAL) { if (rawCount > 0) { if (editor.getCaretModel().getCaretCount() > 1) { return false; } VisualChange range = CaretData.getLastVisualOperatorRange(editor.getCaretModel().getPrimaryCaret()); if (range == null) { return false; } mode = range.getType().toSubMode(); int start = editor.getCaretModel().getOffset(); int end = calculateVisualRange(editor, range, count); Caret primaryCaret = editor.getCaretModel().getPrimaryCaret(); CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL); CaretData.setVisualStart(primaryCaret, start); updateSelection(editor, primaryCaret, end); MotionGroup.moveCaret(editor, primaryCaret, CaretData.getVisualEnd(primaryCaret), true); } else { CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL); if (mode == CommandState.SubMode.VISUAL_BLOCK) { EditorData.setVisualBlockStart(editor, editor.getSelectionModel().getSelectionStart()); updateBlockSelection(editor, editor.getSelectionModel().getSelectionEnd()); MotionGroup .moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), EditorData.getVisualBlockEnd(editor), true); } else { for (Caret caret : editor.getCaretModel().getAllCarets()) { CaretData.setVisualStart(caret, caret.getSelectionStart()); updateSelection(editor, caret, caret.getSelectionEnd()); MotionGroup.moveCaret(editor, caret, CaretData.getVisualEnd(caret), true); } } } } else if (mode == currentMode) { exitVisual(editor); } else if (mode == CommandState.SubMode.VISUAL_BLOCK) { CommandState.getInstance(editor).setSubMode(mode); updateBlockSelection(editor, EditorData.getVisualBlockEnd(editor)); } else { CommandState.getInstance(editor).setSubMode(mode); for (Caret caret : editor.getCaretModel().getAllCarets()) { updateSelection(editor, caret, CaretData.getVisualEnd(caret)); } } return true; } private int calculateVisualRange(@NotNull Editor editor, @NotNull VisualChange range, int count) { int lines = range.getLines(); int chars = range.getColumns(); if (range.getType() == SelectionType.LINE_WISE || range.getType() == SelectionType.BLOCK_WISE || lines > 1) { lines *= count; } if ((range.getType() == SelectionType.CHARACTER_WISE && lines == 1) || range.getType() == SelectionType.BLOCK_WISE) { chars *= count; } int start = editor.getCaretModel().getOffset(); LogicalPosition sp = editor.offsetToLogicalPosition(start); int endLine = sp.line + lines - 1; int res; if (range.getType() == SelectionType.LINE_WISE) { res = moveCaretToLine(editor, endLine); } else if (range.getType() == SelectionType.CHARACTER_WISE) { if (lines > 1) { res = moveCaretToLineStart(editor, endLine) + Math.min(EditorHelper.getLineLength(editor, endLine), chars); } else { res = EditorHelper.normalizeOffset(editor, sp.line, start + chars - 1, false); } } else { int endColumn = Math.min(EditorHelper.getLineLength(editor, endLine), sp.column + chars - 1); res = editor.logicalPositionToOffset(new LogicalPosition(endLine, endColumn)); } return res; } public void exitVisual(@NotNull final Editor editor) { resetVisual(editor, true); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } } public void resetVisual(@NotNull final Editor editor, final boolean removeSelection) { final boolean wasVisualBlock = CommandState.inVisualBlockMode(editor); final SelectionType selectionType = SelectionType.fromSubMode(CommandState.getInstance(editor).getSubMode()); EditorData.setLastSelectionType(editor, selectionType); final TextRange visualMarks = VimPlugin.getMark().getVisualSelectionMarks(editor); if (visualMarks != null) { EditorData.setLastVisualRange(editor, visualMarks); } if (removeSelection) { if (!EditorData.isKeepingVisualOperatorAction(editor)) { for (Caret caret : editor.getCaretModel().getAllCarets()) { caret.removeSelection(); } } if (wasVisualBlock) { editor.getCaretModel().removeSecondaryCarets(); } } CommandState.getInstance(editor).setSubMode(CommandState.SubMode.NONE); } @NotNull public VisualChange getVisualOperatorRange(@NotNull Editor editor, @NotNull Caret caret, EnumSet<CommandFlags> cmdFlags) { int start = CaretData.getVisualStart(caret); int end = CaretData.getVisualEnd(caret); if (CommandState.inVisualBlockMode(editor)) { start = EditorData.getVisualBlockStart(editor); end = EditorData.getVisualBlockEnd(editor); } if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.normalizeOffset(editor, start, false); end = EditorHelper.normalizeOffset(editor, end, false); LogicalPosition sp = editor.offsetToLogicalPosition(start); LogicalPosition ep = editor.offsetToLogicalPosition(end); int lines = ep.line - sp.line + 1; int chars; SelectionType type; if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_LINE || cmdFlags.contains(CommandFlags.FLAG_MOT_LINEWISE)) { chars = ep.column; type = SelectionType.LINE_WISE; } else if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_CHARACTER) { type = SelectionType.CHARACTER_WISE; if (lines > 1) { chars = ep.column; } else { chars = ep.column - sp.column + 1; } } else { chars = ep.column - sp.column + 1; if (CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()) == MotionGroup.LAST_COLUMN) { chars = MotionGroup.LAST_COLUMN; } type = SelectionType.BLOCK_WISE; } return new VisualChange(lines, chars, type); } @NotNull public TextRange getVisualRange(@NotNull Editor editor) { return new TextRange(editor.getSelectionModel().getBlockSelectionStarts(), editor.getSelectionModel().getBlockSelectionEnds()); } @NotNull public TextRange getVisualRange(@NotNull Caret caret) { return new TextRange(caret.getSelectionStart(), caret.getSelectionEnd()); } @NotNull public TextRange getRawVisualRange(@NotNull Caret caret) { return new TextRange(CaretData.getVisualStart(caret), CaretData.getVisualEnd(caret)); } public void updateBlockSelection(@NotNull Editor editor) { updateBlockSelection(editor, EditorData.getVisualBlockEnd(editor)); } private void updateBlockSelection(@NotNull Editor editor, int offset) { EditorData.setVisualBlockEnd(editor, offset); EditorData.setVisualBlockOffset(editor, offset); int start = EditorData.getVisualBlockStart(editor); int end = EditorData.getVisualBlockEnd(editor); LogicalPosition blockStart = editor.offsetToLogicalPosition(start); LogicalPosition blockEnd = editor.offsetToLogicalPosition(end); if (blockStart.column < blockEnd.column) { blockEnd = new LogicalPosition(blockEnd.line, blockEnd.column + 1); } else { blockStart = new LogicalPosition(blockStart.line, blockStart.column + 1); } editor.getSelectionModel().setBlockSelection(blockStart, blockEnd); for (Caret caret : editor.getCaretModel().getAllCarets()) { int line = caret.getLogicalPosition().line; int lineEndOffset = EditorHelper.getLineEndOffset(editor, line, true); if (CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()) >= MotionGroup.LAST_COLUMN) { caret.setSelection(caret.getSelectionStart(), lineEndOffset); } if (!EditorHelper.isLineEmpty(editor, line, false)) { caret.moveToOffset(caret.getSelectionEnd() - 1); } } editor.getCaretModel().getPrimaryCaret().moveToOffset(end); VimPlugin.getMark().setVisualSelectionMarks(editor, new TextRange(start, end)); } public void updateSelection(@NotNull Editor editor, @NotNull Caret caret, int offset) { if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_BLOCK) { updateBlockSelection(editor, offset); } else { CaretData.setVisualEnd(caret, offset); CaretData.setVisualOffset(caret, offset); int start = CaretData.getVisualStart(caret); int end = offset; final CommandState.SubMode subMode = CommandState.getInstance(editor).getSubMode(); if (subMode == CommandState.SubMode.VISUAL_CHARACTER) { if (start > end) { int t = start; start = end; end = t; } final BoundStringOption opt = (BoundStringOption) Options.getInstance().getOption("selection"); int lineEnd = EditorHelper.getLineEndForOffset(editor, end); final int adj = opt.getValue().equals("exclusive") || end == lineEnd ? 0 : 1; final int adjEnd = Math.min(EditorHelper.getFileSize(editor), end + adj); caret.setSelection(start, adjEnd); } else if (subMode == CommandState.SubMode.VISUAL_LINE) { if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.getLineStartForOffset(editor, start); end = EditorHelper.getLineEndForOffset(editor, end); caret.setSelection(start, end); } VimPlugin.getMark().setVisualSelectionMarks(editor, new TextRange(start, end)); } } public boolean swapVisualBlockEnds(@NotNull Editor editor) { if (!CommandState.inVisualBlockMode(editor)) return false; int t = EditorData.getVisualBlockEnd(editor); EditorData.setVisualBlockEnd(editor, EditorData.getVisualBlockStart(editor)); EditorData.setVisualBlockStart(editor, t); moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), EditorData.getVisualBlockEnd(editor)); return true; } public boolean swapVisualEnds(@NotNull Editor editor, @NotNull Caret caret) { int t = CaretData.getVisualEnd(caret); CaretData.setVisualEnd(caret, CaretData.getVisualStart(caret)); CaretData.setVisualStart(caret, t); moveCaret(editor, caret, CaretData.getVisualEnd(caret)); return true; } public void moveVisualStart(@NotNull Caret caret, int startOffset) { CaretData.setVisualStart(caret, startOffset); } public void processEscape(@NotNull Editor editor) { exitVisual(editor); } public static class MotionEditorChange implements FileEditorManagerListener { public void selectionChanged(@NotNull FileEditorManagerEvent event) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } final FileEditor fileEditor = event.getOldEditor(); if (fileEditor instanceof TextEditor) { final Editor editor = ((TextEditor) fileEditor).getEditor(); ExOutputModel.getInstance(editor).clear(); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { VimPlugin.getMotion().exitVisual(editor); } } } } private static class EditorSelectionHandler implements SelectionListener { private boolean myMakingChanges = false; public void selectionChanged(@NotNull SelectionEvent selectionEvent) { final Editor editor = selectionEvent.getEditor(); final Document document = editor.getDocument(); if (myMakingChanges || (document instanceof DocumentEx && ((DocumentEx) document).isInEventsHandling())) { return; } myMakingChanges = true; try { final com.intellij.openapi.util.TextRange newRange = selectionEvent.getNewRange(); for (Editor e : EditorFactory.getInstance().getEditors(document)) { if (!e.equals(editor)) { e.getSelectionModel().setSelection(newRange.getStartOffset(), newRange.getEndOffset()); } } } finally { myMakingChanges = false; } } } private static class EditorMouseHandler implements EditorMouseListener, EditorMouseMotionListener { public void mouseMoved(@NotNull EditorMouseEvent event) { } public void mouseDragged(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getArea() == EditorMouseEventArea.EDITING_AREA || event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) { if (dragEditor == null) { if (event.getArea() == EditorMouseEventArea.EDITING_AREA) { mode = CommandState.SubMode.VISUAL_CHARACTER; } else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) { mode = CommandState.SubMode.VISUAL_LINE; } startOff = event.getEditor().getSelectionModel().getSelectionStart(); endOff = event.getEditor().getSelectionModel().getSelectionEnd(); } dragEditor = event.getEditor(); } } public void mousePressed(@NotNull EditorMouseEvent event) { } public void mouseClicked(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getArea() == EditorMouseEventArea.EDITING_AREA) { VimPlugin.getMotion().processMouseClick(event.getEditor(), event.getMouseEvent()); } else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA && event.getArea() != EditorMouseEventArea.FOLDING_OUTLINE_AREA) { VimPlugin.getMotion() .processLineSelection(event.getEditor(), event.getMouseEvent().getButton() == MouseEvent.BUTTON3); } } public void mouseReleased(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getEditor().equals(dragEditor)) { VimPlugin.getMotion().processMouseReleased(event.getEditor(), mode, startOff, endOff); dragEditor = null; } } public void mouseEntered(@NotNull EditorMouseEvent event) { } public void mouseExited(@NotNull EditorMouseEvent event) { } @Nullable private Editor dragEditor = null; @NotNull private CommandState.SubMode mode = CommandState.SubMode.NONE; private int startOff; private int endOff; } private enum ScreenLocation { TOP, MIDDLE, BOTTOM } public int getLastFTCmd() { return lastFTCmd; } public char getLastFTChar() { return lastFTChar; } private int lastFTCmd = 0; private char lastFTChar; @NotNull private final EditorMouseHandler mouseHandler = new EditorMouseHandler(); @NotNull private final EditorSelectionHandler selectionHandler = new EditorSelectionHandler(); }
package com.thoughtworks.xstream.util; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import junit.framework.TestCase; public class XMLMapTest extends TestCase { private final File baseDir = new File("tmp-xstream-test"); protected void setUp() throws Exception { super.setUp(); if (baseDir.exists()) { clear(baseDir); } baseDir.mkdirs(); } protected void tearDown() throws Exception { super.tearDown(); clear(baseDir); } private void clear(File dir) { File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { boolean deleted = files[i].delete(); if (!deleted) { throw new RuntimeException( "Unable to continue testing: unable to remove file " + files[i].getAbsolutePath()); } } } dir.delete(); } public void testWritesASingleFile() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); File file = new File(baseDir, "guilherme.xml"); assertTrue(file.exists()); } public void testWritesTwoFiles() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); map.put("silveira", "anotherCuteString"); assertTrue(new File(baseDir, "guilherme.xml").exists()); assertTrue(new File(baseDir, "silveira.xml").exists()); } public void testRemovesAWrittenFile() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); assertTrue(new File(baseDir, "guilherme.xml").exists()); String aCuteString = (String) map.remove("guilherme"); assertEquals("aCuteString", aCuteString); assertFalse(new File(baseDir, "guilherme.xml").exists()); } public void testRemovesAnInvalidFile() { XMLMap map = new XMLMap(baseDir); String aCuteString = (String) map.remove("guilherme"); assertNull(aCuteString); } public void testHasZeroLength() { XMLMap map = new XMLMap(baseDir); assertEquals(map.size(), 0); } public void testHasOneItem() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); assertEquals(map.size(), 1); } public void testHasTwoItems() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); map.put("silveira", "anotherCuteString"); assertEquals(map.size(), 2); } public void testIsNotEmpty() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); assertFalse("Map should not be empty", map.isEmpty()); } public void testDoesNotContainKey() { XMLMap map = new XMLMap(baseDir); assertFalse(map.containsKey("guilherme")); } public void testContainsKey() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); assertTrue(map.containsKey("guilherme")); } public void testGetsAFile() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); assertTrue(new File(baseDir, "guilherme.xml").exists()); String aCuteString = (String) map.get("guilherme"); assertEquals("aCuteString", aCuteString); } public void testGetsAnInvalidFile() { XMLMap map = new XMLMap(baseDir); String aCuteString = (String) map.get("guilherme"); assertNull(aCuteString); } public void testRewritesASingleFile() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); File file = new File(baseDir, "guilherme.xml"); assertTrue(file.exists()); map.put("guilherme", "anotherCuteString"); assertEquals("anotherCuteString", map.get("guilherme")); } public void testIsEmpty() { XMLMap map = new XMLMap(baseDir); assertTrue("Map should be empty", map.isEmpty()); } public void testClearsItsFiles() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); map.put("silveira", "anotherCuteString"); map.clear(); assertEquals(0, map.size()); } public void testPutsAllAddsTwoItems() { Map original = new HashMap(); original.put("guilherme", "aCuteString"); original.put("silveira", "anotherCuteString"); XMLMap map = new XMLMap(baseDir); map.putAll(original); assertEquals(2, map.size()); } public void testContainsASpecificValue() { XMLMap map = new XMLMap(baseDir); String value = "aCuteString"; map.put("guilherme", value); assertTrue(map.containsValue(value)); } public void testDoesNotContainASpecificValue() { XMLMap map = new XMLMap(baseDir); assertFalse(map.containsValue("zzzz")); } public void testEntrySetContainsAllItems() { Map original = new HashMap(); original.put("guilherme", "aCuteString"); original.put("silveira", "anotherCuteString"); Set originalSet = original.entrySet(); XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); map.put("silveira", "anotherCuteString"); Set set = map.entrySet(); assertTrue(set.containsAll(originalSet)); } // actually an acceptance test? public void testIteratesOverEntryAndChecksItsKeyWithAnotherInstance() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); map.put("silveira", "anotherCuteString"); XMLMap built = new XMLMap(baseDir); for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); assertTrue(built.containsKey(entry.getKey())); } } // actually an acceptance test? public void testIteratesOverEntryAndChecksItsValueWithAnotherInstance() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); map.put("silveira", "anotherCuteString"); XMLMap built = new XMLMap(baseDir); for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); assertTrue(built.containsValue(entry.getValue())); } } public void testIteratesOverEntrySetContainingTwoItems() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); map.put("silveira", "anotherCuteString"); Map built = new HashMap(); for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); built.put(entry.getKey(), entry.getValue()); } assertEquals(map, built); } public void testRemovesAnItemThroughIteration() { XMLMap map = new XMLMap(baseDir); map.put("guilherme", "aCuteString"); map.put("silveira", "anotherCuteString"); for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); if(entry.getKey().equals("guilherme")) { iter.remove(); } } assertFalse(map.containsKey("guilherme")); } }
package org.zols.datastore; import java.util.HashMap; import java.util.*; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import static java.util.stream.Collectors.toList; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.zols.datastore.jsonschema.JSONSchema; import static org.zols.datastore.jsonschema.JSONSchema.jsonSchemaForSchema; import static org.zols.datastore.jsonschema.JSONSchema.jsonSchema; import org.zols.datastore.query.Filter; import static org.zols.datastore.query.Filter.Operator.EQUALS; import org.zols.datastore.query.Query; import org.zols.datastore.util.JsonUtil; import static org.zols.datastore.util.JsonUtil.asMap; import static org.zols.datastore.util.JsonUtil.asString; import org.zols.datastore.util.LocalitationUtil; import org.zols.datatore.exception.ConstraintViolationException; import org.zols.datatore.exception.DataStoreException; /** * Data Store is used to Store Static and Dynamic Objects using JSON Schema * * @author Sathish Kumar Thiyagarajan */ public abstract class DataStore { private final Validator validator; public DataStore() { validator = Validation.buildDefaultValidatorFactory().getValidator(); } public <T> T create(T object) throws DataStoreException { return create(object, null); } public <T> T create(T object, Locale locale) throws DataStoreException { T createdObject = null; if (object != null) { Set<ConstraintViolation<Object>> violations = validator.validate(object); if (violations.isEmpty()) { JSONSchema jsonSchema = jsonSchema(object.getClass()); createdObject = (T) readJsonDataAsObject(object.getClass(), create(jsonSchema, getImmutableJSONData(jsonSchema, object, locale)), locale); } else { throw new ConstraintViolationException(object, violations); } } return createdObject; } public <T> T read(Class<T> clazz, Locale locale, String idValue) throws DataStoreException { return (T) readJsonDataAsObject(clazz, read(jsonSchema(clazz), idValue), locale); } public <T> T read(Class<T> clazz, String idValue) throws DataStoreException { return read(clazz, null, idValue); } public Map<String, Object> getImmutableJSONData(JSONSchema jsonSchema, Object object, Locale locale) { return getImmutableJSONData(jsonSchema, asMap(object), locale); } public Map<String, Object> getImmutableJSONData(JSONSchema jsonSchema, Map<String, Object> jsonData, Locale locale) { Map linkedHashMap = new LinkedHashMap<>(jsonData); linkedHashMap.put("$type", jsonSchema.type()); if(locale != null && !Locale.getDefault().equals(locale)) { linkedHashMap = LocalitationUtil.prepareJSON(jsonSchema,linkedHashMap,locale); } return Collections.unmodifiableMap(linkedHashMap); } private <T> T readJsonDataAsObject(Class<T> clazz, Map<String, Object> map, Locale locale) { if (map != null) { map.remove("$type"); } return JsonUtil.asObject(clazz, readJsonData(jsonSchema(clazz),map, locale)); } private List<Map<String, Object>> readJsonData(JSONSchema jSONSchema,List<Map<String, Object>> listofData, Locale locale) { if (listofData != null) { listofData.parallelStream().forEach(jsonData -> readJsonData(jSONSchema,jsonData, locale)); } return listofData; } //TODO private Map<String, Object> readJsonData(JSONSchema jSONSchema,Map<String, Object> map, Locale locale) { if(locale != null && !Locale.getDefault().equals(locale)) { map = LocalitationUtil.readJSON(map, locale); }else { map = LocalitationUtil.readJSON(map); } return map; } public <T> T update(T object, String idValue) throws DataStoreException { return update(object, idValue, null); } public <T> T update(T object, String idValue, Locale locale) throws DataStoreException { T updatedObject = null; if (object != null) { Set<ConstraintViolation<Object>> violations = validator.validate(object); if (violations.isEmpty()) { JSONSchema jsonSchema = jsonSchema(object.getClass()); boolean updated = updatePartially(jsonSchema, getImmutableJSONData(jsonSchema, object, locale)); if (updated) { updatedObject = (T) read(object.getClass(), idValue); } } else { throw new ConstraintViolationException(object, violations); } } return updatedObject; } public boolean delete(Class clazz) throws DataStoreException { return delete(jsonSchema(clazz)); } public boolean delete(Class clazz, String idValue) throws DataStoreException { return delete(jsonSchema(clazz), idValue); } public boolean delete(Class clazz, Query query) throws DataStoreException { JSONSchema jsonSchema = jsonSchema(clazz); return delete(jsonSchema, getTypeFilteredQuery(jsonSchema, query)); } public <T> List<T> list(Class<T> clazz) throws DataStoreException { return list(clazz, (Locale) null); } public <T> List<T> list(Class<T> clazz, Locale locale) throws DataStoreException { List<T> objects = null; List<Map<String, Object>> maps = list(jsonSchema(clazz)); if (maps != null) { objects = maps.stream().map(map -> readJsonDataAsObject(clazz, map, locale)).collect(toList()); } return objects; } public <T> List<T> list(Class<T> clazz, Query query) throws DataStoreException { return list(clazz, (Locale) null, query); } public <T> List<T> list(Class<T> clazz, Locale locale, Query query) throws DataStoreException { List<T> objects = null; JSONSchema jsonSchema = jsonSchema(clazz); List<Map<String, Object>> maps = list(jsonSchema, getTypeFilteredQuery(jsonSchema, query)); if (maps != null) { objects = maps.stream().map(map -> readJsonDataAsObject(clazz, map, locale)).collect(toList()); } return objects; } public <T> Page<T> list(Class<T> clazz, Integer pageNumber, Integer pageSize) throws DataStoreException { return list(clazz, (Locale) null, pageNumber, pageSize); } public <T> Page<T> list(Class<T> clazz, Locale locale, Integer pageNumber, Integer pageSize) throws DataStoreException { Page<Map<String, Object>> page = list(jsonSchema(clazz), locale,pageNumber, pageSize); if (page != null) { return new Page(page.getPageNumber(), page.getPageSize(), page.getTotal(), page.getContent().stream().map(map -> readJsonDataAsObject(clazz, map, locale)).collect(toList())); } return null; } public <T> Page<T> list(Class<T> clazz, Query query, Integer pageNumber, Integer pageSize) throws DataStoreException { return list(clazz, (Locale) null, query, pageNumber, pageSize); } public <T> Page<T> list(Class<T> clazz, Locale locale, Query query, Integer pageNumber, Integer pageSize) throws DataStoreException { JSONSchema jsonSchema = jsonSchema(clazz); Page<Map<String, Object>> page = list(jsonSchema, getTypeFilteredQuery(jsonSchema, query), pageNumber, pageSize); if (page != null) { return new Page(page.getPageNumber(), page.getPageSize(), page.getTotal(), page.getContent().stream().map(map -> readJsonDataAsObject(clazz, map, locale)).collect(toList())); } return null; } /** * Data Related * */ /** * * @param schemaId * @param jsonData * @return * @throws DataStoreException */ public Map<String, Object> create(String schemaId, Map<String, Object> jsonData) throws DataStoreException { return create(schemaId, jsonData, null); } /** * * @param schemaId * @param jsonData * @param locale * @return * @throws DataStoreException */ public Map<String, Object> create(String schemaId, Map<String, Object> jsonData, Locale locale) throws DataStoreException { Map<String, Object> rawJsonSchema = getRawJsonSchema(schemaId); JSONSchema jsonSchema = jsonSchema(rawJsonSchema); Set<ConstraintViolation<Object>> violations = jsonSchema.validate(jsonData); if (violations == null) { return create(jsonSchema, getImmutableJSONData(jsonSchema, jsonData, locale)); } else { throw new ConstraintViolationException(jsonData, violations); } } public boolean update(String schemaId, Map<String, Object> jsonData) throws DataStoreException { return update(schemaId, jsonData, null); } public boolean update(String schemaId, Map<String, Object> jsonData, Locale locale) throws DataStoreException { JSONSchema jsonSchema = jsonSchema(getRawJsonSchema(schemaId)); Set<ConstraintViolation<Object>> violations = jsonSchema.validate(jsonData); if (violations == null) { return updatePartially(jsonSchema, getImmutableJSONData(jsonSchema, jsonData, locale)); } else { throw new ConstraintViolationException(jsonData, violations); } } public boolean updatePartial(String schemaId, String idValue, Map<String, Object> partialJsonData) throws DataStoreException { return updatePartial(schemaId, idValue, partialJsonData, null); } public boolean updatePartial(String schemaId, String idValue, Map<String, Object> partialJsonData, Locale locale) throws DataStoreException { JSONSchema jsonSchema = jsonSchema(getRawJsonSchema(schemaId)); Map<String, Object> jsonData = read(jsonSchema, idValue); jsonData.putAll(partialJsonData); Set<ConstraintViolation<Object>> violations = jsonSchema.validate(jsonData); if (violations == null) { return updatePartially(jsonSchema, getImmutableJSONData(jsonSchema, jsonData, locale)); } else { throw new ConstraintViolationException(jsonData, violations); } } public Map<String, Object> read(String schemaId, String name) throws DataStoreException { return read(schemaId, (Locale) null, name); } public Map<String, Object> read(String schemaId, Locale locale, String name) throws DataStoreException { JSONSchema jSONSchema = jsonSchema(getRawJsonSchema(schemaId)); return readJsonData(jSONSchema,read(jSONSchema, name), locale); } public boolean delete(String schemaId) throws DataStoreException { return delete(jsonSchema(getRawJsonSchema(schemaId))); } public boolean delete(String schemaId, String name) throws DataStoreException { return delete(jsonSchema(getRawJsonSchema(schemaId)), name); } public boolean delete(String schemaId, Query query) throws DataStoreException { JSONSchema jsonSchema = jsonSchema(getRawJsonSchema(schemaId)); return delete(jsonSchema, this.getTypeFilteredQuery(jsonSchema, query)); } public List<Map<String, Object>> list(String schemaId) throws DataStoreException { return list(jsonSchema(getRawJsonSchema(schemaId))); } public List<Map<String, Object>> list(String schemaId, Query query) throws DataStoreException { return list(schemaId,(Locale)null,query); } public List<Map<String, Object>> list(String schemaId, Locale locale,Query query) throws DataStoreException { JSONSchema jsonSchema = jsonSchema(getRawJsonSchema(schemaId)); return readJsonData(jsonSchema,list(jsonSchema, this.getTypeFilteredQuery(jsonSchema, query)),locale); } public Page<Map<String, Object>> list(String schemaId, Integer pageNumber, Integer pageSize) throws DataStoreException { return list(jsonSchema(getRawJsonSchema(schemaId)), (Locale)null, pageNumber, pageSize); } public Page<Map<String, Object>> list(String schemaId, Locale locale, Integer pageNumber, Integer pageSize) throws DataStoreException { return list(jsonSchema(getRawJsonSchema(schemaId)), locale, pageNumber, pageSize); } public Page<Map<String, Object>> list(String schemaId, Query query, Integer pageNumber, Integer pageSize) throws DataStoreException { JSONSchema jsonSchema = jsonSchema(getRawJsonSchema(schemaId)); return list(jsonSchema, getTypeFilteredQuery(jsonSchema, query), pageNumber, pageSize); } /** * * * Schema Related */ /** * * @param jsonSchemaTxt * @return * @throws DataStoreException */ public Map<String, Object> createSchema(String jsonSchemaTxt) throws DataStoreException { Map<String, Object> schema = asMap(jsonSchemaTxt); Map<String, Object> rawJsonSchema = getRawJsonSchema(schema); JSONSchema jsonSchema = jsonSchemaForSchema(); Set<ConstraintViolation<Object>> violations = jsonSchema.validate(rawJsonSchema); if (violations == null) { return create(jsonSchemaForSchema(), getImmutableJSONData(jsonSchema, schema, null)); } else { throw new ConstraintViolationException(schema, violations); } } public boolean updateSchema(String jsonSchemaTxt) throws DataStoreException { Map<String, Object> schema = asMap(jsonSchemaTxt); Map<String, Object> rawJsonSchema = getRawJsonSchema(asMap(jsonSchemaTxt)); JSONSchema jsonSchema = jsonSchemaForSchema(); Set<ConstraintViolation<Object>> violations = jsonSchema.validate(rawJsonSchema); if (violations == null) { return update(jsonSchema, getImmutableJSONData(jsonSchema, asMap(jsonSchemaTxt), null)); } else { throw new ConstraintViolationException(schema, violations); } } public Map<String, Object> getRawJsonSchema(String schemaId) throws DataStoreException { return getRawJsonSchema(read(jsonSchemaForSchema(), schemaId)); } public Map<String, Object> getSchema(String schemaId) throws DataStoreException { return read(jsonSchemaForSchema(), schemaId); } public Set<ConstraintViolation<Object>> validate(String schemaId, Map<String, Object> jsonData) throws DataStoreException { return jsonSchema(getRawJsonSchema(getSchema(schemaId))).validate(jsonData); } public Map<String, Object> getRawJsonSchema(final Map<String, Object> schema) throws DataStoreException { Map<String, Object> clonedSchema = asMap(asString(schema)); if (clonedSchema != null) { clonedSchema.remove("$type"); Map<String, Object> definitions = getDefinitions(clonedSchema); if (!definitions.isEmpty()) { definitions.entrySet().forEach((definition) -> { try { definition.setValue(getRawJsonSchema(getSchema(definition.getKey()))); } catch (DataStoreException ex) { Logger.getLogger(DataStore.class.getName()).log(Level.SEVERE, null, ex); } }); clonedSchema.put("definitions", definitions); JSONSchema jsonSchema = jsonSchema(clonedSchema); Map<String, Map<String, Object>> consolidatedDefinitions = jsonSchema.getConsolidatedDefinitions(); clonedSchema.put("definitions", consolidatedDefinitions); Map<String,Object> baseSchema = consolidatedDefinitions.get(jsonSchema.baseType()); if(baseSchema != null) { clonedSchema.put("idField", baseSchema.get("idField")); clonedSchema.put("labelField", baseSchema.get("labelField")); } } } return clonedSchema; } private Map<String, Object> getDefinitions(Map<String, Object> schema) { Map<String, Object> definitions = new HashMap(); schema.entrySet().forEach((schemaEntry) -> { if (schemaEntry.getKey().equals("$ref")) { definitions.put(schemaEntry.getValue().toString(), null); schemaEntry.setValue("#/definitions/" + schemaEntry.getValue()); } else if (schemaEntry.getKey().equals("properties")) { Map<String, Map<String, Object>> properties = (Map<String, Map<String, Object>>) schemaEntry.getValue(); properties.entrySet().forEach(propertyEntry -> { Object refValue; if ((refValue = propertyEntry.getValue().get("$ref")) != null) { definitions.put(refValue.toString(), null); propertyEntry.getValue().put("$ref", "#/definitions/" + refValue.toString()); } }); } }); return definitions; } public Boolean deleteSchema(String schemaId) throws DataStoreException { return delete(jsonSchemaForSchema(), schemaId); } public List<Map<String, Object>> listExtenstions(String schemaId) throws DataStoreException { List<Map<String, Object>> list = listChildSchema(schemaId); if(list != null && !list.isEmpty()) { List<Map<String, Object>> childrenOfChidrens = new ArrayList(); list.forEach(schema->{ try { List<Map<String, Object>> children = listExtenstions(schema.get("name").toString()); if(children != null) { childrenOfChidrens.addAll(children); } } catch (DataStoreException ex) { Logger.getLogger(DataStore.class.getName()).log(Level.SEVERE, null, ex); } }); list.addAll(childrenOfChidrens); } return list; } public List<String> listExtenstionTypes(String schemaId) throws DataStoreException { List<Map<String, Object>> list = listExtenstions(schemaId); if(list != null) { return list.stream().map(schema->schema.get("name").toString()).collect(toList()); } return null; } public List<Map<String, Object>> listChildSchema(String schemaId) throws DataStoreException { Query query = new Query(); query.addFilter(new Filter("$ref", EQUALS, schemaId)); return list(jsonSchemaForSchema(),query); } public List<Map<String, Object>> listSchema(Query query) throws DataStoreException { return list(jsonSchemaForSchema(),query); } public List<Map<String, Object>> listSchema() throws DataStoreException { return list(jsonSchemaForSchema()); } protected List<Map<String, Object>> list(JSONSchema jsonSchema) throws DataStoreException { return list(jsonSchema,(Locale)null); } /** * * @param jsonSchema schema of dynamic data * @param locale * @return list of dynamic objects * @throws org.zols.datatore.exception.DataStoreException */ protected List<Map<String, Object>> list(JSONSchema jsonSchema,Locale locale) throws DataStoreException { return readJsonData(jsonSchema,list(jsonSchema, getTypeFilteredQuery(jsonSchema)),locale); } public Query getTypeFilteredQuery(JSONSchema jsonSchema, Query query) throws DataStoreException { if(query == null) { query = new Query(); } List<String> implementations = listExtenstionTypes(jsonSchema.type()); if(implementations == null || implementations.isEmpty()) { query.addFilter(new Filter("$type", Filter.Operator.EQUALS, jsonSchema.type())); } else { implementations.add(jsonSchema.type()); query.addFilter(new Filter("$type", Filter.Operator.EXISTS_IN, implementations)); } return query; } public Query getTypeFilteredQuery(JSONSchema jsonSchema) throws DataStoreException { return getTypeFilteredQuery(jsonSchema, null); } private boolean delete(JSONSchema jsonSchema) throws DataStoreException { return delete(jsonSchema, getTypeFilteredQuery(jsonSchema)); } private Page<Map<String, Object>> list(JSONSchema jsonSchema,Locale locale, Integer pageNumber, Integer pageSize) throws DataStoreException { Page<Map<String, Object>> page = list(jsonSchema, getTypeFilteredQuery(jsonSchema), pageNumber, pageSize); if (page != null) { return new Page(page.getPageNumber(), page.getPageSize(), page.getTotal(), readJsonData(jsonSchema,page.getContent(),locale)); } return page; } /** * ALL ABSTRACT METHODS WILL COME HERE */ /** * * @param validatedDataObject validated object * @param jsonSchema schema of dynamic data * @return dynamic data as map * @throws org.zols.datatore.exception.DataStoreException */ protected abstract Map<String, Object> create( JSONSchema jsonSchema, Map<String, Object> validatedDataObject) throws DataStoreException; /** * * @param jsonSchema schema of dynamic data * @param idValue dynamic object name * @return dynamic data as map * @throws org.zols.datatore.exception.DataStoreException */ protected abstract Map<String, Object> read( JSONSchema jsonSchema, String idValue) throws DataStoreException; /** * * @param jsonSchema schema of dynamic data * @param idValue dynamic object name * @return status of the delete operation * @throws org.zols.datatore.exception.DataStoreException */ protected abstract boolean delete(JSONSchema jsonSchema, String idValue) throws DataStoreException; /** * * @param jsonSchema * @param query * @return * @throws DataStoreException */ protected abstract boolean delete(JSONSchema jsonSchema, Query query) throws DataStoreException; protected abstract boolean update(JSONSchema jsonSchema, Map<String, Object> validatedDataObject) throws DataStoreException; /** * * @param jsonSchema schema of dynamic data * @param validatedData validated Object * @return status of the update operation * @throws org.zols.datatore.exception.DataStoreException */ protected abstract boolean updatePartially(JSONSchema jsonSchema, Map<String, Object> validatedData) throws DataStoreException; /** * * @param jsonSchema schema of dynamic data * @param query query to consider * @return list of dynamic objects * @throws org.zols.datatore.exception.DataStoreException */ protected abstract List<Map<String, Object>> list(JSONSchema jsonSchema, Query query) throws DataStoreException; /** * * @param jsonSchema schema of dynamic data * @param query query to consider * @param pageNumber * @param pageSize * @return list of dynamic objects * @throws org.zols.datatore.exception.DataStoreException */ protected abstract Page<Map<String, Object>> list(JSONSchema jsonSchema, Query query, Integer pageNumber, Integer pageSize) throws DataStoreException; /** * Drops the DataStore * * @throws DataStoreException */ protected abstract void drop() throws DataStoreException; }
package org.elasticsearch.xpack.transform.integration.continuous; import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.client.transform.transforms.DestConfig; import org.elasticsearch.client.transform.transforms.SourceConfig; import org.elasticsearch.client.transform.transforms.TransformConfig; import org.elasticsearch.client.transform.transforms.pivot.GroupConfig; import org.elasticsearch.client.transform.transforms.pivot.HistogramGroupSource; import org.elasticsearch.client.transform.transforms.pivot.PivotConfig; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket; import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static org.hamcrest.Matchers.equalTo; @AwaitsFix(bugUrl="https://github.com/elastic/elasticsearch/issues/67887") public class HistogramGroupByIT extends ContinuousTestCase { private static final String NAME = "continuous-histogram-pivot-test"; private final String metricField; public HistogramGroupByIT() { metricField = randomFrom(METRIC_FIELDS); } @Override public String getName() { return NAME; } @Override public TransformConfig createConfig() { TransformConfig.Builder transformConfigBuilder = new TransformConfig.Builder(); addCommonBuilderParameters(transformConfigBuilder); transformConfigBuilder.setSource(new SourceConfig(CONTINUOUS_EVENTS_SOURCE_INDEX)); transformConfigBuilder.setDest(new DestConfig(NAME, INGEST_PIPELINE)); transformConfigBuilder.setId(NAME); PivotConfig.Builder pivotConfigBuilder = new PivotConfig.Builder(); pivotConfigBuilder.setGroups( new GroupConfig.Builder().groupBy("metric", new HistogramGroupSource.Builder().setField(metricField).setInterval(50.0).build()) .build() ); AggregatorFactories.Builder aggregations = new AggregatorFactories.Builder(); addCommonAggregations(aggregations); pivotConfigBuilder.setAggregations(aggregations); transformConfigBuilder.setPivotConfig(pivotConfigBuilder.build()); return transformConfigBuilder.build(); } @Override public void testIteration(int iteration, Set<String> modifiedEvents) throws IOException { SearchRequest searchRequestSource = new SearchRequest(CONTINUOUS_EVENTS_SOURCE_INDEX).allowPartialSearchResults(false) .indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN); SearchSourceBuilder sourceBuilderSource = new SearchSourceBuilder().size(0); HistogramAggregationBuilder metricBuckets = new HistogramAggregationBuilder("metric").field(metricField) .interval(50.0) .order(BucketOrder.key(true)); sourceBuilderSource.aggregation(metricBuckets); searchRequestSource.source(sourceBuilderSource); SearchResponse responseSource = search(searchRequestSource); SearchRequest searchRequestDest = new SearchRequest(NAME).allowPartialSearchResults(false) .indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN); SearchSourceBuilder sourceBuilderDest = new SearchSourceBuilder().size(10000).sort("metric"); searchRequestDest.source(sourceBuilderDest); SearchResponse responseDest = search(searchRequestDest); List<? extends Bucket> buckets = ((Histogram) responseSource.getAggregations().get("metric")).getBuckets(); Iterator<? extends Bucket> sourceIterator = buckets.iterator(); Iterator<SearchHit> destIterator = responseDest.getHits().iterator(); while (sourceIterator.hasNext() && destIterator.hasNext()) { Bucket bucket = sourceIterator.next(); SearchHit searchHit = destIterator.next(); Map<String, Object> source = searchHit.getSourceAsMap(); Long transformBucketKey = ((Integer) XContentMapValues.extractValue("metric", source)).longValue(); // aggs return buckets with 0 doc_count while composite aggs skip over them while (bucket.getDocCount() == 0L) { assertTrue(sourceIterator.hasNext()); bucket = sourceIterator.next(); } long bucketKey = ((Double) bucket.getKey()).longValue(); // test correctness, the results from the aggregation and the results from the transform should be the same assertThat( "Buckets did not match, source: " + source + ", expected: " + bucketKey + ", iteration: " + iteration, transformBucketKey, equalTo(bucketKey) ); assertThat( "Doc count did not match, source: " + source + ", expected: " + bucket.getDocCount() + ", iteration: " + iteration, ((Integer) XContentMapValues.extractValue("count", source)).longValue(), equalTo(bucket.getDocCount()) ); // TODO: gh#63801 transform is not optimized for histogram it, it should only rewrite documents that require it } assertFalse(sourceIterator.hasNext()); assertFalse(destIterator.hasNext()); } }
package com.travis.test.listeners; import com.mojang.authlib.GameProfile; import com.travis.test.Main; import com.travis.test.teamSetUP.teamManger.TeamSetUp; import com.travis.test.utilities.Commands; import net.minecraft.server.v1_8_R3.*; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.craftbukkit.v1_8_R3.CraftServer; import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.potion.PotionEffect; import java.util.UUID; public class PlayerListener implements Listener { public EntityPlayer npc; @EventHandler public void selectKit(PlayerInteractEvent player){ } @EventHandler public static void onPlayerQuit(PlayerQuitEvent e) { Player player = e.getPlayer(); TeamSetUp.blueTeam.remove(player.getName()); TeamSetUp.redTeam.remove(player.getName()); player.sendMessage("You have be removed"); //player.sendMessage("You have be removed form " + teamType.name()); } @EventHandler public void onPlayerJoin(PlayerJoinEvent e) { Player player = e.getPlayer(); player.getInventory().clear(); Commands.tpr(player); for (PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } //TODO Need to change to a banner on the screen player.sendMessage(ChatColor.GREEN + "Hello " + player.getName()); /* MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer(); WorldServer worldServer = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle(); npc = new EntityPlayer(server, worldServer, new GameProfile(UUID.randomUUID(), "NPC"), new PlayerInteractManager(worldServer)); npc.teleportTo(e.getPlayer().getLocation(), false); PlayerConnection connection = ((CraftPlayer) e.getPlayer()).getHandle().playerConnection; connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, npc)); connection.sendPacket(new PacketPlayOutNamedEntitySpawn(npc));*/ } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerDeath(PlayerDeathEvent e) { //TODO Need to add spawn point on death Player player = e.getEntity(); Commands.tpr(player); player.getInventory().clear(); Commands.tpr(player); } }
package org.xwiki.component.embed; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Provider; import org.apache.commons.lang3.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.component.annotation.ComponentAnnotationLoader; import org.xwiki.component.descriptor.ComponentDependency; import org.xwiki.component.descriptor.ComponentDescriptor; import org.xwiki.component.descriptor.ComponentInstantiationStrategy; import org.xwiki.component.descriptor.DefaultComponentDescriptor; import org.xwiki.component.internal.RoleHint; import org.xwiki.component.manager.ComponentEventManager; import org.xwiki.component.manager.ComponentLifecycleException; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.component.manager.ComponentManagerInitializer; import org.xwiki.component.manager.ComponentRepositoryException; import org.xwiki.component.phase.Disposable; import org.xwiki.component.util.ReflectionUtils; /** * Simple implementation of {@link ComponentManager} to be used when using some XWiki modules standalone. * * @version $Id$ * @since 2.0M1 */ public class EmbeddableComponentManager implements ComponentManager { private ComponentEventManager eventManager; /** * Used as fallback for lookup methods. */ private ComponentManager parent; private static class ComponentEntry<R> { /** * Descriptor of the component. */ public final ComponentDescriptor<R> descriptor; public volatile R instance; public ComponentEntry(ComponentDescriptor<R> descriptor, R instance) { this.descriptor = descriptor; this.instance = instance; } } private Map<RoleHint< ? >, ComponentEntry< ? >> componentEntries = new ConcurrentHashMap<RoleHint< ? >, ComponentEntry< ? >>(); private Logger logger = LoggerFactory.getLogger(EmbeddableComponentManager.class); /** * Finds all lifecycle handlers to use when instantiating a Component. */ private ServiceLoader<LifecycleHandler> lifecycleHandlers = ServiceLoader.load(LifecycleHandler.class); /** * Load all component annotations and register them as components. * * @param classLoader the class loader to use to look for component definitions */ public void initialize(ClassLoader classLoader) { ComponentAnnotationLoader loader = new ComponentAnnotationLoader(); loader.initialize(this, classLoader); // Extension point to allow component to manipulate ComponentManager initialized state. try { List<ComponentManagerInitializer> initializers = this.lookupList(ComponentManagerInitializer.class); Set keySet = this.componentEntries.keySet(); for (ComponentManagerInitializer initializer : initializers) { initializer.initialize(this); } } catch (ComponentLookupException e) { // Should never happen this.logger.error("Failed to lookup ComponentManagerInitializer components", e); } } @Override public boolean hasComponent(Type role) { return hasComponent(role, "default"); } @Override public boolean hasComponent(Type role, String hint) { if (this.componentEntries.containsKey(new RoleHint<Object>(role, hint))) { return true; } return getParent() != null ? getParent().hasComponent(role, hint) : false; } @Override public <T> T lookupComponent(Type roleType) throws ComponentLookupException { return getComponentInstance(new RoleHint<T>(roleType)); } @Override public <T> T lookupComponent(Type roleType, String roleHint) throws ComponentLookupException { return getComponentInstance(new RoleHint<T>(roleType, roleHint)); } @Override public <T> List<T> lookupList(Type role) throws ComponentLookupException { // Reuse lookupMap to make sure to not return components from parent Component Manager overridden by this // Component Manager Map<String, T> objects = lookupMap(role); return objects.isEmpty() ? Collections.<T> emptyList() : new ArrayList<T>(objects.values()); } @Override @SuppressWarnings("unchecked") public <T> Map<String, T> lookupMap(Type role) throws ComponentLookupException { Map<String, T> objects = new HashMap<String, T>(); for (Map.Entry<RoleHint< ? >, ComponentEntry< ? >> entry : this.componentEntries.entrySet()) { RoleHint< ? > roleHint = entry.getKey(); if (role.equals(roleHint.getRoleType())) { try { objects.put(roleHint.getHint(), getComponentInstance((ComponentEntry<T>) entry.getValue())); } catch (Exception e) { throw new ComponentLookupException("Failed to lookup component [" + roleHint + "]", e); } } } // Add parent's list of components if (getParent() != null) { // If the hint already exists in the children Component Manager then don't add the one from the parent. for (Map.Entry<String, T> entry : getParent().<T> lookupMap(role).entrySet()) { if (!objects.containsKey(entry.getKey())) { objects.put(entry.getKey(), entry.getValue()); } } } return objects; } @Override @SuppressWarnings("unchecked") public <T> ComponentDescriptor<T> getComponentDescriptor(Type role, String hint) { ComponentEntry<T> componentEntry = (ComponentEntry<T>) this.componentEntries.get(new RoleHint<T>(role, hint)); return componentEntry != null ? componentEntry.descriptor : null; } @Override @SuppressWarnings("unchecked") public <T> List<ComponentDescriptor<T>> getComponentDescriptorList(Type role) { List<ComponentDescriptor<T>> results = new ArrayList<ComponentDescriptor<T>>(); for (Map.Entry<RoleHint< ? >, ComponentEntry< ? >> entry : this.componentEntries.entrySet()) { // It's possible Class reference are not the same when it coming for different ClassLoader so we // compare class names if (entry.getKey().getRoleType().equals(role)) { results.add((ComponentDescriptor<T>) entry.getValue().descriptor); } } return results; } @Override @SuppressWarnings("unchecked") public <T> List<ComponentDescriptor<T>> getComponentDescriptorList(Class<T> role) { List<ComponentDescriptor<T>> results = new ArrayList<ComponentDescriptor<T>>(); for (Map.Entry<RoleHint< ? >, ComponentEntry< ? >> entry : this.componentEntries.entrySet()) { // It's possible Class reference are not the same when it coming for different ClassLoader so we // compare class names if (entry.getKey().getRoleClass() == role) { results.add((ComponentDescriptor<T>) entry.getValue().descriptor); } } return results; } @Override public ComponentEventManager getComponentEventManager() { return this.eventManager; } @Override public void setComponentEventManager(ComponentEventManager eventManager) { this.eventManager = eventManager; } @Override public ComponentManager getParent() { return this.parent; } @Override public void setParent(ComponentManager parentComponentManager) { this.parent = parentComponentManager; } private <T> T createInstance(ComponentDescriptor<T> descriptor) throws Exception { T instance = descriptor.getImplementation().newInstance(); // Set each dependency for (ComponentDependency< ? > dependency : descriptor.getComponentDependencies()) { // TODO: Handle dependency cycles // Handle different field types Object fieldValue; // Step 1: Verify if there's a Provider registered for the field type // - A Provider is a component like any other (except it cannot have a field produced by itself!) // - A Provider must implement the JSR330 Producer interface // Step 2: Handle Logger injection. // Step 3: No producer found, handle scalar and collection types by looking up standard component // implementations. Class< ? > dependencyRoleClass = ReflectionUtils.getTypeClass(dependency.getRoleType()); if (dependencyRoleClass.isAssignableFrom(Logger.class)) { fieldValue = LoggerFactory.getLogger(instance.getClass()); } else if (dependencyRoleClass.isAssignableFrom(List.class)) { fieldValue = lookupList(ReflectionUtils.getLastTypeGenericArgument(dependency.getRoleType())); } else if (dependencyRoleClass.isAssignableFrom(Map.class)) { fieldValue = lookupMap(ReflectionUtils.getLastTypeGenericArgument(dependency.getRoleType())); } else if (dependencyRoleClass.isAssignableFrom(Provider.class)) { try { fieldValue = lookupComponent(dependency.getRoleType(), dependency.getRoleHint()); } catch (ComponentLookupException e) { fieldValue = new GenericProvider<Object>(this, new RoleHint<Object>( ReflectionUtils.getLastTypeGenericArgument(dependency.getRoleType()), dependency.getRoleHint())); } } else { fieldValue = lookupComponent(dependency.getRoleType(), dependency.getRoleHint()); } // Set the field by introspection if (fieldValue != null) { ReflectionUtils.setFieldValue(instance, dependency.getName(), fieldValue); } } // Call Lifecycle Handlers for (LifecycleHandler lifecycleHandler : this.lifecycleHandlers) { lifecycleHandler.handle(instance, descriptor, this); } return instance; } @SuppressWarnings("unchecked") protected <T> T getComponentInstance(RoleHint<T> roleHint) throws ComponentLookupException { T instance; ComponentEntry<T> componentEntry = (ComponentEntry<T>) this.componentEntries.get(roleHint); if (componentEntry != null) { try { instance = getComponentInstance(componentEntry); } catch (Throwable e) { throw new ComponentLookupException(String.format("Failed to lookup component [%s] identifier by [%s]", componentEntry.descriptor.getImplementation().getName(), roleHint.toString()), e); } } else { if (getParent() != null) { instance = getParent().lookupComponent(roleHint.getRoleClass(), roleHint.getHint()); } else { throw new ComponentLookupException("Can't find descriptor for the component [" + roleHint + "]"); } } return instance; } private <T> T getComponentInstance(ComponentEntry<T> componentEntry) throws Exception { T instance; ComponentDescriptor<T> descriptor = componentEntry.descriptor; if (descriptor.getInstantiationStrategy() == ComponentInstantiationStrategy.SINGLETON) { if (componentEntry.instance != null) { // If the instance exists return it instance = componentEntry.instance; } else { synchronized (componentEntry) { // Recheck in case it has been created while we were waiting if (componentEntry.instance != null) { instance = componentEntry.instance; } else { componentEntry.instance = createInstance(descriptor); instance = componentEntry.instance; } } } } else { instance = createInstance(descriptor); } return instance; } // Add private <T> RoleHint<T> getRoleHint(ComponentDescriptor<T> componentDescriptor) { return new RoleHint<T>(componentDescriptor.getRoleType(), componentDescriptor.getRoleHint()); } @Override public <T> void registerComponent(ComponentDescriptor<T> componentDescriptor) throws ComponentRepositoryException { registerComponent(componentDescriptor, null); } @Override public <T> void registerComponent(ComponentDescriptor<T> componentDescriptor, T componentInstance) { RoleHint<T> roleHint = getRoleHint(componentDescriptor); // Remove any existing component associated to the provided roleHint removeComponentWithoutException(roleHint); // Register new component addComponent(roleHint, new DefaultComponentDescriptor<T>(componentDescriptor), componentInstance); } private <T> void addComponent(RoleHint<T> roleHint, ComponentDescriptor<T> descriptor, T instance) { ComponentEntry<T> componentEntry = new ComponentEntry<T>(descriptor, instance); // Register new component this.componentEntries.put(roleHint, componentEntry); // Send event about component registration if (this.eventManager != null) { this.eventManager.notifyComponentRegistered(descriptor, this); } } // Remove @Override public void unregisterComponent(Type role, String hint) { removeComponentWithoutException(new RoleHint<Object>(role, hint)); } @Override public void unregisterComponent(ComponentDescriptor< ? > componentDescriptor) { if (ObjectUtils.equals( getComponentDescriptor(componentDescriptor.getRoleType(), componentDescriptor.getRoleHint()), componentDescriptor)) { unregisterComponent(componentDescriptor.getRoleType(), componentDescriptor.getRoleHint()); } } @Override @SuppressWarnings("unchecked") public void release(Object component) throws ComponentLifecycleException { // First find the descriptor matching the passed component RoleHint< ? > key = null; ComponentDescriptor< ? > oldDescriptor = null; for (Map.Entry<RoleHint< ? >, ComponentEntry< ? >> entry : this.componentEntries.entrySet()) { if (entry.getValue().instance == component) { key = entry.getKey(); oldDescriptor = entry.getValue().descriptor; break; } } // Note that we're not removing inside the for loop above since it would cause a Concurrent // exception since we'd modify the map accessed by the iterator. if (key != null) { // We do the following: // - fire an unregistration event, to tell the world that this reference is now dead // - fire a registration event, to tell the world that it could get a new reference for this component // now // We need to do this since code holding a reference on the released component may need to know it's // been removed and thus discard its own reference to that component and look it up again. // Another solution would be to introduce a new event for Component creation/destruction (right now // we only send events for Component registration/unregistration). removeComponent(key); addComponent((RoleHint<Object>) key, (ComponentDescriptor<Object>) oldDescriptor, null); } } private void releaseInstance(ComponentEntry< ? > componentEntry) throws ComponentLifecycleException { // Make sure the singleton component instance can't be "lost" (impossible to dispose because returned but not // stored). synchronized (componentEntry) { Object instance = componentEntry.instance; // Give a chance to the component to clean up if (instance instanceof Disposable) { ((Disposable) instance).dispose(); } componentEntry.instance = null; } } private void releaseComponentEntry(ComponentEntry< ? > componentEntry) throws ComponentLifecycleException { // clean existing instance releaseInstance(componentEntry); } private void removeComponent(RoleHint< ? > roleHint) throws ComponentLifecycleException { // Make sure to remove the entry from the map before destroying it to reduce at the minimum the risk of // lookupping something invalid ComponentEntry< ? > componentEntry = this.componentEntries.remove(roleHint); if (componentEntry != null) { ComponentDescriptor< ? > oldDescriptor = componentEntry.descriptor; // clean any resource associated to the component instance and descriptor releaseComponentEntry(componentEntry); // Send event about component unregistration if (this.eventManager != null && oldDescriptor != null) { this.eventManager.notifyComponentUnregistered(oldDescriptor, this); } } } /** * Note: This method shouldn't exist but register/unregister methods should throw a * {@link ComponentLifecycleException} but that would break backward compatibility to add it. */ private <T> void removeComponentWithoutException(RoleHint<T> roleHint) { try { removeComponent(roleHint); } catch (Exception e) { logger.warn("Instance released but disposal failed. Some resources may not have been released.", e); } } // deprecated @Override @Deprecated public <T> boolean hasComponent(Class<T> role, String hint) { return hasComponent((Type) role, hint); } @Override @Deprecated public <T> boolean hasComponent(Class<T> role) { return hasComponent((Type) role); } @Override @Deprecated public <T> T lookup(Class<T> role) throws ComponentLookupException { return lookupComponent(role); } @Override @Deprecated public <T> T lookup(Class<T> role, String hint) throws ComponentLookupException { return lookupComponent(role, hint); } @Override @Deprecated public <T> List<T> lookupList(Class<T> role) throws ComponentLookupException { return lookupList((Type) role); } @Override @Deprecated public <T> Map<String, T> lookupMap(Class<T> role) throws ComponentLookupException { return lookupMap((Type) role); } @Override @Deprecated public <T> ComponentDescriptor<T> getComponentDescriptor(Class<T> role, String hint) { return getComponentDescriptor((Type) role, hint); } @Override @Deprecated public <T> void unregisterComponent(Class<T> role, String hint) { unregisterComponent((Type) role, hint); } }
package gov.nih.nci.cagrid.introduce.security.client; import gov.nih.nci.cagrid.introduce.security.common.ServiceSecurityI; import gov.nih.nci.cagrid.introduce.security.stubs.ServiceSecurityPortType; import gov.nih.nci.cagrid.introduce.security.stubs.service.ServiceSecurityServiceAddressingLocator; import gov.nih.nci.cagrid.metadata.security.CommunicationMechanism; import gov.nih.nci.cagrid.metadata.security.Operation; import gov.nih.nci.cagrid.metadata.security.ProtectionLevelType; import gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata; import gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadataOperations; import java.io.InputStream; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Map; import org.apache.axis.EngineConfiguration; import org.apache.axis.client.AxisClient; import org.apache.axis.client.Stub; import org.apache.axis.configuration.FileProvider; import org.apache.axis.message.addressing.Address; import org.apache.axis.message.addressing.EndpointReferenceType; import org.apache.axis.types.URI.MalformedURIException; import org.apache.axis.utils.ClassUtils; import org.globus.gsi.GlobusCredential; import org.globus.wsrf.impl.security.authorization.Authorization; import org.globus.wsrf.impl.security.authorization.NoAuthorization; public class ServiceSecurityClient implements ServiceSecurityI { private GlobusCredential proxy; private EndpointReferenceType epr; private ServiceSecurityMetadata securityMetadata; private Map operations; private Authorization authorization; private String delegationMode; static { org.globus.axis.util.Util.registerTransport(); } public ServiceSecurityClient(String url) throws MalformedURIException, RemoteException { this(url, null); } public ServiceSecurityClient(String url, GlobusCredential proxy) throws MalformedURIException, RemoteException { this.proxy = proxy; this.epr = new EndpointReferenceType(); this.epr.setAddress(new Address(url)); } public ServiceSecurityClient(EndpointReferenceType epr) throws MalformedURIException, RemoteException { this(epr, null); } public ServiceSecurityClient(EndpointReferenceType epr, GlobusCredential proxy) throws MalformedURIException, RemoteException { this.proxy = proxy; this.epr = epr; } public Authorization getAuthorization() { return authorization; } public void setAuthorization(Authorization authorization) { this.authorization = authorization; } public String getDelegationMode() { return delegationMode; } public void setDelegationMode(String delegationMode) { this.delegationMode = delegationMode; } public EndpointReferenceType getEndpointReference() { return this.epr; } public GlobusCredential getProxy() { return proxy; } public void setProxy(GlobusCredential proxy) { this.proxy = proxy; } private ServiceSecurityPortType getPortType() throws RemoteException { ServiceSecurityServiceAddressingLocator locator = new ServiceSecurityServiceAddressingLocator(); // attempt to load our context sensitive wsdd file InputStream resourceAsStream = ClassUtils.getResourceAsStream(getClass(), "client-config.wsdd"); if (resourceAsStream != null) { // we found it, so tell axis to configure an engine to use it EngineConfiguration engineConfig = new FileProvider(resourceAsStream); // set the engine of the locator locator.setEngine(new AxisClient(engineConfig)); } ServiceSecurityPortType port = null; try { port = locator.getServiceSecurityPortTypePort(this.epr); } catch (Exception e) { throw new RemoteException("Unable to configured porttype:" + e.getMessage(), e); } return port; } public static void usage() { System.out.println(ServiceSecurityClient.class.getName() + " -url <service url>"); } public static void main(String[] args) { System.out.println("Running the Grid Service Client"); try { if (!(args.length < 2)) { if (args[0].equals("-url")) { ServiceSecurityClient client = new ServiceSecurityClient(args[1]); // place client calls here if you want to use this main as a // test.... } else { usage(); System.exit(1); } } else { usage(); System.exit(1); } } catch (Exception e) { e.printStackTrace(); } } public void configureStubSecurity(Stub stub, String method) throws RemoteException { boolean https = false; if (epr.getAddress().getScheme().equals("https")) { https = true; } if (method.equals("getServiceSecurityMetadata")) { if (https) { resetStub(stub); stub._setProperty(org.globus.wsrf.security.Constants.GSI_TRANSPORT, org.globus.wsrf.security.Constants.SIGNATURE); stub._setProperty(org.globus.wsrf.security.Constants.GSI_ANONYMOUS, Boolean.TRUE); stub._setProperty(org.globus.wsrf.security.Constants.AUTHORIZATION, org.globus.wsrf.impl.security.authorization.NoAuthorization.getInstance()); } return; } if(this.securityMetadata == null){ operations = new HashMap(); this.authorization = NoAuthorization.getInstance(); this.securityMetadata = getServiceSecurityMetadata(); ServiceSecurityMetadataOperations ssmo = securityMetadata.getOperations(); if (ssmo != null) { Operation[] ops = ssmo.getOperation(); if (ops != null) { for (int i = 0; i < ops.length; i++) { operations.put(ops[i].getName(), ops[i]); } } } } resetStub(stub); CommunicationMechanism serviceDefault = securityMetadata.getDefaultCommunicationMechanism(); CommunicationMechanism mechanism = null; if (operations.containsKey(method)) { Operation o = (Operation) operations.get(method); mechanism = o.getCommunicationMechanism(); } else { mechanism = serviceDefault; } boolean anonymousAllowed = true; boolean authorizationAllowed = true; boolean delegationAllowed = true; boolean credentialsAllowed = true; if ((https) && (mechanism.getGSITransport() != null)) { ProtectionLevelType level = mechanism.getGSITransport().getProtectionLevel(); if (level != null) { if ((level.equals(ProtectionLevelType.privacy)) || (level.equals(ProtectionLevelType.either))) { stub._setProperty(org.globus.wsrf.security.Constants.GSI_TRANSPORT, org.globus.wsrf.security.Constants.ENCRYPTION); } else { stub._setProperty(org.globus.wsrf.security.Constants.GSI_TRANSPORT, org.globus.wsrf.security.Constants.SIGNATURE); } } else { stub._setProperty(org.globus.wsrf.security.Constants.GSI_TRANSPORT, org.globus.wsrf.security.Constants.SIGNATURE); } delegationAllowed = false; } else if (https) { stub._setProperty(org.globus.wsrf.security.Constants.GSI_TRANSPORT, org.globus.wsrf.security.Constants.SIGNATURE); delegationAllowed = false; } else if (mechanism.getGSISecureConversation() != null) { ProtectionLevelType level = mechanism.getGSISecureConversation().getProtectionLevel(); if (level != null) { if ((level.equals(ProtectionLevelType.privacy)) || (level.equals(ProtectionLevelType.either))) { stub._setProperty(org.globus.wsrf.security.Constants.GSI_SEC_CONV, org.globus.wsrf.security.Constants.ENCRYPTION); } else { stub._setProperty(org.globus.wsrf.security.Constants.GSI_SEC_CONV, org.globus.wsrf.security.Constants.SIGNATURE); } } else { stub._setProperty(org.globus.wsrf.security.Constants.GSI_SEC_CONV, org.globus.wsrf.security.Constants.ENCRYPTION); } } else if (mechanism.getGSISecureMessage() != null) { ProtectionLevelType level = mechanism.getGSISecureMessage().getProtectionLevel(); if (level != null) { if ((level.equals(ProtectionLevelType.privacy)) || (level.equals(ProtectionLevelType.either))) { stub._setProperty(org.globus.wsrf.security.Constants.GSI_SEC_MSG, org.globus.wsrf.security.Constants.ENCRYPTION); } else { stub._setProperty(org.globus.wsrf.security.Constants.GSI_SEC_MSG, org.globus.wsrf.security.Constants.SIGNATURE); } } else { stub._setProperty(org.globus.wsrf.security.Constants.GSI_SEC_MSG, org.globus.wsrf.security.Constants.ENCRYPTION); } delegationAllowed = false; anonymousAllowed = false; } else { anonymousAllowed = false; authorizationAllowed = false; delegationAllowed = false; credentialsAllowed = false; } if ((anonymousAllowed) && (mechanism.isAnonymousPermitted())) { stub._setProperty(org.globus.wsrf.security.Constants.GSI_ANONYMOUS, Boolean.TRUE); } else if ((credentialsAllowed) && (proxy != null)) { try { org.ietf.jgss.GSSCredential gss = new org.globus.gsi.gssapi.GlobusGSSCredentialImpl(proxy, org.ietf.jgss.GSSCredential.INITIATE_AND_ACCEPT); stub._setProperty(org.globus.axis.gsi.GSIConstants.GSI_CREDENTIALS, gss); } catch (org.ietf.jgss.GSSException ex) { throw new RemoteException(ex.getMessage()); } } if (authorizationAllowed) { if (authorization == null) { stub._setProperty(org.globus.wsrf.security.Constants.AUTHORIZATION, NoAuthorization.getInstance()); } else { stub._setProperty(org.globus.wsrf.security.Constants.AUTHORIZATION, getAuthorization()); } } if (delegationAllowed) { if (getDelegationMode() != null) { stub._setProperty(org.globus.axis.gsi.GSIConstants.GSI_MODE, getDelegationMode()); } } } private void resetStub(Stub stub) { stub.removeProperty(org.globus.wsrf.security.Constants.GSI_TRANSPORT); stub.removeProperty(org.globus.wsrf.security.Constants.GSI_ANONYMOUS); stub.removeProperty(org.globus.wsrf.security.Constants.AUTHORIZATION); stub.removeProperty(org.globus.axis.gsi.GSIConstants.GSI_CREDENTIALS); stub.removeProperty(org.globus.wsrf.security.Constants.GSI_SEC_CONV); stub.removeProperty(org.globus.wsrf.security.Constants.GSI_SEC_MSG); stub.removeProperty(org.globus.axis.gsi.GSIConstants.GSI_MODE); } public gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata getServiceSecurityMetadata() throws RemoteException { ServiceSecurityPortType port = this.getPortType(); this.configureStubSecurity((Stub)port,"getServiceSecurityMetadata"); gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataRequest params = new gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataRequest(); gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataResponse boxedResult = port .getServiceSecurityMetadata(params); return boxedResult.getServiceSecurityMetadata(); } }
package org.innovateuk.ifs.application.forms.sections.yourprojectcosts.form; import org.innovateuk.ifs.finance.resource.cost.FinanceRowItem; import org.innovateuk.ifs.finance.resource.cost.KtpTravelCost.KtpTravelCostType; import org.innovateuk.ifs.finance.resource.cost.LabourCost; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.stream.Stream; public class YourProjectCostsForm { public static final BigDecimal VAT_RATE = BigDecimal.valueOf(20); public final static BigDecimal INDIRECT_COST_PERCENTAGE = BigDecimal.valueOf(46); private LabourForm labour = new LabourForm(); private OverheadForm overhead = new OverheadForm(); private Map<String, ProcurementOverheadRowForm> procurementOverheadRows = new LinkedHashMap<>(); private Map<String, MaterialRowForm> materialRows = new LinkedHashMap<>(); private Map<String, CapitalUsageRowForm> capitalUsageRows = new LinkedHashMap<>(); private Map<String, SubcontractingRowForm> subcontractingRows = new LinkedHashMap<>(); private Map<String, TravelRowForm> travelRows = new LinkedHashMap<>(); private Map<String, OtherCostRowForm> otherRows = new LinkedHashMap<>(); private VatForm vatForm; private Map<String, AssociateSalaryCostRowForm> associateSalaryCostRows = new LinkedHashMap<>(); private Map<String, AssociateDevelopmentCostRowForm> associateDevelopmentCostRows = new LinkedHashMap<>(); private Map<String, ConsumablesRowForm> consumableCostRows = new LinkedHashMap<>(); private Map<String, KnowledgeBaseCostRowForm> knowledgeBaseCostRows = new LinkedHashMap<>(); private Map<String, AssociateSupportCostRowForm> associateSupportCostRows = new LinkedHashMap<>(); private Map<String, EstateCostRowForm> estateCostRows = new LinkedHashMap<>(); private Map<String, KtpTravelRowForm> ktpTravelCostRows = new LinkedHashMap<>(); private AdditionalCompanyCostForm additionalCompanyCostForm = new AdditionalCompanyCostForm(); private JustificationForm justificationForm = new JustificationForm(); private AcademicAndSecretarialSupportCostRowForm academicAndSecretarialSupportForm = new AcademicAndSecretarialSupportCostRowForm(); private Boolean eligibleAgreement; public VatForm getVatForm() { return vatForm; } public void setVatForm(VatForm vatForm) { this.vatForm = vatForm; } public OverheadForm getOverhead() { return overhead; } public void setOverhead(OverheadForm overhead) { this.overhead = overhead; } public Map<String, ProcurementOverheadRowForm> getProcurementOverheadRows() { return procurementOverheadRows; } public void setProcurementOverheadRows(Map<String, ProcurementOverheadRowForm> procurementOverheadRows) { this.procurementOverheadRows = procurementOverheadRows; } public Map<String, MaterialRowForm> getMaterialRows() { return materialRows; } public void setMaterialRows(Map<String, MaterialRowForm> materialRows) { this.materialRows = materialRows; } public Map<String, CapitalUsageRowForm> getCapitalUsageRows() { return capitalUsageRows; } public void setCapitalUsageRows(Map<String, CapitalUsageRowForm> capitalUsageRows) { this.capitalUsageRows = capitalUsageRows; } public Map<String, SubcontractingRowForm> getSubcontractingRows() { return subcontractingRows; } public void setSubcontractingRows(Map<String, SubcontractingRowForm> subcontractingRows) { this.subcontractingRows = subcontractingRows; } public Map<String, TravelRowForm> getTravelRows() { return travelRows; } public void setTravelRows(Map<String, TravelRowForm> travelRows) { this.travelRows = travelRows; } public Map<String, OtherCostRowForm> getOtherRows() { return otherRows; } public void setOtherRows(Map<String, OtherCostRowForm> otherRows) { this.otherRows = otherRows; } public Boolean getEligibleAgreement() { return eligibleAgreement; } public void setEligibleAgreement(Boolean eligibleAgreement) { this.eligibleAgreement = eligibleAgreement; } public LabourForm getLabour() { return labour; } public void setLabour(LabourForm labour) { this.labour = labour; } public Map<String, AssociateSalaryCostRowForm> getAssociateSalaryCostRows() { return associateSalaryCostRows; } public void setAssociateSalaryCostRows(Map<String, AssociateSalaryCostRowForm> associateSalaryCostRows) { this.associateSalaryCostRows = associateSalaryCostRows; } public Map<String, AssociateSupportCostRowForm> getAssociateSupportCostRows() { return associateSupportCostRows; } public void setAssociateSupportCostRows(Map<String, AssociateSupportCostRowForm> associateSupportCostRows) { this.associateSupportCostRows = associateSupportCostRows; } public Map<String, EstateCostRowForm> getEstateCostRows() { return estateCostRows; } public void setEstateCostRows(Map<String, EstateCostRowForm> estateCostRows) { this.estateCostRows = estateCostRows; } public AdditionalCompanyCostForm getAdditionalCompanyCostForm() { return additionalCompanyCostForm; } public void setAdditionalCompanyCostForm(AdditionalCompanyCostForm additionalCompanyCostForm) { this.additionalCompanyCostForm = additionalCompanyCostForm; } public Map<String, AssociateDevelopmentCostRowForm> getAssociateDevelopmentCostRows() { return associateDevelopmentCostRows; } public void setAssociateDevelopmentCostRows(Map<String, AssociateDevelopmentCostRowForm> associateDevelopmentCostRows) { this.associateDevelopmentCostRows = associateDevelopmentCostRows; } public Map<String, ConsumablesRowForm> getConsumableCostRows() { return consumableCostRows; } public void setConsumableCostRows(Map<String, ConsumablesRowForm> consumableCostRows) { this.consumableCostRows = consumableCostRows; } public Map<String, KnowledgeBaseCostRowForm> getKnowledgeBaseCostRows() { return knowledgeBaseCostRows; } public void setKnowledgeBaseCostRows(Map<String, KnowledgeBaseCostRowForm> knowledgeBaseCostRows) { this.knowledgeBaseCostRows = knowledgeBaseCostRows; } public Map<String, KtpTravelRowForm> getKtpTravelCostRows() { return ktpTravelCostRows; } public void setKtpTravelCostRows(Map<String, KtpTravelRowForm> ktpTravelCostRows) { this.ktpTravelCostRows = ktpTravelCostRows; } public JustificationForm getJustificationForm() { return justificationForm; } public void setJustificationForm(JustificationForm justificationForm) { this.justificationForm = justificationForm; } /* View methods. */ public BigDecimal getVatTotal() { return getOrganisationFinanceTotal().multiply(VAT_RATE).divide(BigDecimal.valueOf(100)); } public BigDecimal getProjectVatTotal() { return getOrganisationFinanceTotal().add(getVatTotal()); } public BigDecimal getTotalLabourCosts() { return labour == null ? BigDecimal.ZERO : calculateTotal(labour.getRows()); } public BigDecimal getTotalAssociateSalaryCosts() { return calculateTotal(associateSalaryCostRows); } public BigDecimal getTotalOverheadCosts() { if (overhead != null && overhead.getRateType() != null) { switch (overhead.getRateType()) { case NONE: return BigDecimal.ZERO; case DEFAULT_PERCENTAGE: return getTotalLabourCosts().multiply(new BigDecimal("0.2")); case TOTAL: return Optional.ofNullable(getOverhead().getTotalSpreadsheet()).map(BigDecimal::valueOf).orElse(BigDecimal.ZERO); default: return BigDecimal.ZERO; } } return BigDecimal.ZERO; } public BigDecimal getTotalMaterialCosts() { return calculateTotal(materialRows); } public BigDecimal getTotalProcurementOverheadCosts() { return calculateTotal(procurementOverheadRows); } public BigDecimal getTotalCapitalUsageCosts() { return calculateTotal(capitalUsageRows); } public BigDecimal getTotalSubcontractingCosts() { return calculateTotal(subcontractingRows); } public BigDecimal getTotalTravelCosts() { return calculateTotal(travelRows); } public BigDecimal getTotalOtherCosts() { return calculateTotal(otherRows); } public BigDecimal getTotalAssociateSupportCosts() { return calculateTotal(associateSupportCostRows); } public BigDecimal getTotalAssociateDevelopmentCosts() { return calculateTotal(associateDevelopmentCostRows); } public BigDecimal getTotalConsumableCosts() { return calculateTotal(consumableCostRows); } public BigDecimal getTotalKnowledgeBaseCosts() { return calculateTotal(knowledgeBaseCostRows); } public BigDecimal getTotalEstateCosts() { return calculateTotal(estateCostRows); } public BigDecimal getTotalKtpTravelCosts() { return calculateTotal(ktpTravelCostRows); } public BigDecimal getTotalAcademicAndSecretarialSupportCosts() { return new BigDecimal(Optional.ofNullable(academicAndSecretarialSupportForm.getCost()) .orElse(BigInteger.valueOf(0))); } public BigDecimal getIndirectCostsPercentage() { return INDIRECT_COST_PERCENTAGE; } public BigDecimal getTotalIndirectCosts() { return this.getTotalAssociateSalaryCosts().add(this.getTotalAcademicAndSecretarialSupportCosts()) .multiply(INDIRECT_COST_PERCENTAGE).divide(new BigDecimal(100)); } public BigDecimal getOrganisationFinanceTotal() { return getTotalLabourCosts() .add(getTotalOverheadCosts()) .add(getTotalMaterialCosts()) .add(getTotalProcurementOverheadCosts()) .add(getTotalCapitalUsageCosts()) .add(getTotalSubcontractingCosts()) .add(getTotalTravelCosts()) .add(getTotalOtherCosts()) .add(getTotalAssociateSalaryCosts()) .add(getTotalAssociateDevelopmentCosts()) .add(getTotalAssociateSupportCosts()) .add(getTotalConsumableCosts()) .add(getTotalKnowledgeBaseCosts()) .add(getTotalEstateCosts()) .add(getTotalKtpTravelCosts()) .add(getTotalAcademicAndSecretarialSupportCosts()) .add(getTotalIndirectCosts()); } private BigDecimal calculateTotal(Map<String, ? extends AbstractCostRowForm> costRows) { return calculateTotal(costRows.values()); } private BigDecimal calculateTotal(Collection<? extends AbstractCostRowForm> costRows) { return calculateTotal(costRows.stream()); } private BigDecimal calculateTotal(Stream<? extends AbstractCostRowForm> costRows) { return costRows .map(AbstractCostRowForm::getTotal) .filter(Objects::nonNull) .reduce(BigDecimal::add) .orElse(BigDecimal.ZERO) .setScale(0, RoundingMode.HALF_UP); } public void recalculateTotals() { getLabour().getRows().forEach((id, row) -> { LabourCost cost = row.toCost(null); row.setTotal(cost.getTotal(getLabour().getWorkingDaysPerYear())); row.setRate(cost.getRate(getLabour().getWorkingDaysPerYear())); }); getOverhead().setTotal(getOverhead().getTotal()); recalculateTotal(getMaterialRows()); recalculateTotal(getCapitalUsageRows()); recalculateTotal(getSubcontractingRows()); recalculateTotal(getTravelRows()); recalculateTotal(getOtherRows()); recalculateTotal(getProcurementOverheadRows()); recalculateTotal(getAssociateSalaryCostRows()); recalculateTotal(getAssociateDevelopmentCostRows()); recalculateTotal(getConsumableCostRows()); recalculateTotal(getKnowledgeBaseCostRows()); recalculateTotal(getEstateCostRows()); recalculateTotal(getAssociateSupportCostRows()); recalculateTotal(getKtpTravelCostRows()); } private void recalculateTotal(Map<String, ? extends AbstractCostRowForm> rows) { rows.forEach((id, row) -> { FinanceRowItem cost = row.toCost(null); row.setTotal(cost.getTotal()); }); } public BigDecimal getTotalKtpTravelAssociateCosts() { return calculateTotal(ktpTravelCostRows .values() .stream() .filter(cost -> cost.getType() != null && cost.getType() == KtpTravelCostType.ASSOCIATE)); } public BigDecimal getTotalKtpTravelSupervisorCosts() { return calculateTotal(ktpTravelCostRows .values() .stream() .filter(cost -> cost.getType() != null && cost.getType() == KtpTravelCostType.SUPERVISOR)); } public AcademicAndSecretarialSupportCostRowForm getAcademicAndSecretarialSupportForm() { return academicAndSecretarialSupportForm; } public void setAcademicAndSecretarialSupportForm(AcademicAndSecretarialSupportCostRowForm academicAndSecretarialSupportForm) { this.academicAndSecretarialSupportForm = academicAndSecretarialSupportForm; } }
package org.innovateuk.ifs.competitionsetup.controller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.innovateuk.ifs.application.service.CompetitionService; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.resource.*; import org.innovateuk.ifs.competition.resource.CompetitionSetupSubsection; import org.innovateuk.ifs.competitionsetup.form.CompetitionSetupForm; import org.innovateuk.ifs.competitionsetup.form.LandingPageForm; import org.innovateuk.ifs.competitionsetup.form.application.ApplicationDetailsForm; import org.innovateuk.ifs.competitionsetup.form.application.ApplicationFinanceForm; import org.innovateuk.ifs.competitionsetup.form.application.ApplicationProjectForm; import org.innovateuk.ifs.competitionsetup.form.application.ApplicationQuestionForm; import org.innovateuk.ifs.competitionsetup.service.CompetitionSetupQuestionService; import org.innovateuk.ifs.competitionsetup.service.CompetitionSetupService; import org.innovateuk.ifs.competitionsetup.viewmodel.GuidanceRowForm; import org.innovateuk.ifs.controller.ValidationHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid; import java.util.Optional; import java.util.function.Supplier; import static org.innovateuk.ifs.competition.resource.CompetitionSetupSection.APPLICATION_FORM; import static org.innovateuk.ifs.competition.resource.CompetitionSetupSubsection.*; import static org.innovateuk.ifs.competitionsetup.controller.CompetitionSetupController.*; /** * Controller to manage the Application Questions and it's sub-sections in the * competition setup process */ @Controller @RequestMapping("/competition/setup/{competitionId}/section/application") public class CompetitionSetupApplicationController { private static final Log LOG = LogFactory.getLog(CompetitionSetupApplicationController.class); public static final String APPLICATION_LANDING_REDIRECT = "redirect:/competition/setup/%d/section/application/landing-page"; private static final String questionView = "competition/setup/question"; @Autowired private CompetitionSetupService competitionSetupService; @Autowired private CompetitionService competitionService; @Autowired private CompetitionSetupQuestionService competitionSetupQuestionService; @Autowired @Qualifier("mvcValidator") private Validator validator; @RequestMapping(value = "/landing-page", method = RequestMethod.GET) public String applicationProcessLandingPage(Model model, @PathVariable(COMPETITION_ID_KEY) Long competitionId) { CompetitionResource competitionResource = competitionService.getById(competitionId); competitionSetupService.populateCompetitionSectionModelAttributes(model, competitionResource, APPLICATION_FORM); model.addAttribute(COMPETITION_SETUP_FORM_KEY, new LandingPageForm()); return "competition/setup"; } @RequestMapping(value = "/landing-page", method = RequestMethod.POST) public String setApplicationProcessAsComplete(Model model, @PathVariable(COMPETITION_ID_KEY) Long competitionId, @ModelAttribute(COMPETITION_SETUP_FORM_KEY) LandingPageForm form, BindingResult bindingResult, ValidationHandler validationHandler) { CompetitionResource competitionResource = competitionService.getById(competitionId); Supplier<String> failureView = () -> { competitionSetupService.populateCompetitionSectionModelAttributes(model, competitionResource, APPLICATION_FORM); model.addAttribute(COMPETITION_SETUP_FORM_KEY, form); return "competition/setup"; }; Supplier<String> successView = () -> String.format(APPLICATION_LANDING_REDIRECT, competitionId); return validationHandler.performActionOrBindErrorsToField("", failureView, successView, () -> competitionSetupQuestionService.validateApplicationQuestions(competitionResource, form, bindingResult)); } @RequestMapping(value = "/question/finance", method = RequestMethod.GET) public String seeApplicationFinances(@PathVariable(COMPETITION_ID_KEY) Long competitionId, Model model) { CompetitionResource competitionResource = competitionService.getById(competitionId); return getFinancePage(model, competitionResource, false, null); } @RequestMapping(value = "/question/finance/edit", method = RequestMethod.GET) public String editApplicationFinances(@PathVariable(COMPETITION_ID_KEY) Long competitionId, Model model) { CompetitionResource competitionResource = competitionService.getById(competitionId); return getFinancePage(model, competitionResource, true, null); } @RequestMapping(value = "/question/finance/edit", method = RequestMethod.POST) public String submitApplicationFinances(@ModelAttribute(COMPETITION_SETUP_FORM_KEY) ApplicationFinanceForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable(COMPETITION_ID_KEY) Long competitionId, Model model) { CompetitionResource competitionResource = competitionService.getById(competitionId); Supplier<String> failureView = () -> getFinancePage(model, competitionResource, true, form); Supplier<String> successView = () -> String.format(APPLICATION_LANDING_REDIRECT, competitionId); return validationHandler.performActionOrBindErrorsToField("", failureView, successView, () -> competitionSetupService.saveCompetitionSetupSubsection(form, competitionResource, APPLICATION_FORM, FINANCES)); } @RequestMapping(value = "/question/{questionId}", method = RequestMethod.GET) public String seeQuestionInCompSetup(@PathVariable(COMPETITION_ID_KEY) Long competitionId, @PathVariable("questionId") Long questionId, Model model) { CompetitionResource competitionResource = competitionService.getById(competitionId); return getQuestionPage(model, competitionResource, questionId, false, null); } @RequestMapping(value = "/question/{questionId}/edit", method = RequestMethod.GET) public String editQuestionInCompSetup(@PathVariable(COMPETITION_ID_KEY) Long competitionId, @PathVariable("questionId") Long questionId, Model model) { CompetitionResource competitionResource = competitionService.getById(competitionId); return getQuestionPage(model, competitionResource, questionId, true, null); } @RequestMapping(value = "/question", method = RequestMethod.POST, params = "question.type=ASSESSED_QUESTION") public String submitAssessedQuestion(@Valid @ModelAttribute(COMPETITION_SETUP_FORM_KEY) ApplicationQuestionForm competitionSetupForm, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable(COMPETITION_ID_KEY) Long competitionId, Model model) { validateAssessmentGuidanceRows(competitionSetupForm, bindingResult); CompetitionResource competitionResource = competitionService.getById(competitionId); Supplier<String> failureView = () -> getQuestionPage(model, competitionResource, competitionSetupForm.getQuestion().getQuestionId(), true, competitionSetupForm); Supplier<String> successView = () -> "redirect:/competition/setup/" + competitionId + "/section/application"; return validationHandler.performActionOrBindErrorsToField("", failureView, successView, () -> competitionSetupService.saveCompetitionSetupSubsection(competitionSetupForm, competitionResource, APPLICATION_FORM, QUESTIONS)); } @RequestMapping(value = "/question", method = RequestMethod.POST) public String submitProjectDetailsQuestion(@Valid @ModelAttribute(COMPETITION_SETUP_FORM_KEY) ApplicationProjectForm competitionSetupForm, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable(COMPETITION_ID_KEY) Long competitionId, Model model) { validateScopeGuidanceRows(competitionSetupForm, bindingResult); CompetitionResource competitionResource = competitionService.getById(competitionId); Supplier<String> failureView = () -> getQuestionPage(model, competitionResource, competitionSetupForm.getQuestion().getQuestionId(), true, competitionSetupForm); Supplier<String> successView = () -> "redirect:/competition/setup/" + competitionId + "/section/application"; return validationHandler.performActionOrBindErrorsToField("", failureView, successView, () -> competitionSetupService.saveCompetitionSetupSubsection(competitionSetupForm, competitionResource, APPLICATION_FORM, PROJECT_DETAILS)); } @RequestMapping(value = "/detail", method = RequestMethod.GET) public String viewApplicationDetails(@PathVariable(COMPETITION_ID_KEY) Long competitionId, Model model) { CompetitionResource competitionResource = competitionService.getById(competitionId); return getDetailsPage(model, competitionResource, false, null); } @RequestMapping(value = "/detail/edit", method = RequestMethod.GET) public String getEditApplicationDetails(@PathVariable(COMPETITION_ID_KEY) Long competitionId, Model model) { CompetitionResource competitionResource = competitionService.getById(competitionId); return getDetailsPage(model, competitionResource, true, null); } @RequestMapping(value = "/detail/edit", method = RequestMethod.POST) public String submitApplicationDetails(@ModelAttribute(COMPETITION_SETUP_FORM_KEY) ApplicationDetailsForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable(COMPETITION_ID_KEY) Long competitionId, Model model) { CompetitionResource competitionResource = competitionService.getById(competitionId); Supplier<String> failureView = () -> getDetailsPage(model, competitionResource, true, form); Supplier<String> successView = () -> String.format(APPLICATION_LANDING_REDIRECT, competitionId); return validationHandler.performActionOrBindErrorsToField("", failureView, successView, () -> competitionSetupService.saveCompetitionSetupSubsection(form, competitionResource, APPLICATION_FORM, APPLICATION_DETAILS)); } private void validateAssessmentGuidanceRows(ApplicationQuestionForm applicationQuestionForm, BindingResult bindingResult) { if (Boolean.TRUE.equals(applicationQuestionForm.getQuestion().getWrittenFeedback())) { ValidationUtils.invokeValidator(validator, applicationQuestionForm, bindingResult, GuidanceRowForm.GuidanceRowViewGroup.class); } } private void validateScopeGuidanceRows(ApplicationProjectForm applicationProjectForm, BindingResult bindingResult) { if (Boolean.TRUE.equals(applicationProjectForm.getQuestion().getWrittenFeedback())) { ValidationUtils.invokeValidator(validator, applicationProjectForm, bindingResult, GuidanceRowResource.GuidanceRowGroup.class); } } private String getFinancePage(Model model, CompetitionResource competitionResource, boolean isEditable, CompetitionSetupForm form) { setupQuestionToModel(competitionResource, Optional.empty(), model, FINANCES, isEditable, form); return "competition/finances"; } private String getDetailsPage(Model model, CompetitionResource competitionResource, boolean isEditable, CompetitionSetupForm form) { setupQuestionToModel(competitionResource, Optional.empty(), model, APPLICATION_DETAILS, isEditable, form); return "competition/application-details"; } private String getQuestionPage(Model model, CompetitionResource competitionResource, Long questionId, boolean isEditable, CompetitionSetupForm form) { ServiceResult<CompetitionSetupQuestionResource> questionResource = competitionSetupQuestionService.getQuestion(questionId); CompetitionSetupQuestionType type = questionResource.getSuccessObjectOrThrowException().getType(); CompetitionSetupSubsection setupSubsection; if (type.equals(CompetitionSetupQuestionType.ASSESSED_QUESTION)) { setupSubsection = CompetitionSetupSubsection.QUESTIONS; } else { setupSubsection = CompetitionSetupSubsection.PROJECT_DETAILS; } setupQuestionToModel(competitionResource, Optional.of(questionId), model, setupSubsection, isEditable, form); return questionView; } private void setupQuestionToModel(final CompetitionResource competition, final Optional<Long> questionId, Model model, CompetitionSetupSubsection subsection, boolean isEditable, CompetitionSetupForm form) { CompetitionSetupSection section = APPLICATION_FORM; competitionSetupService.populateCompetitionSubsectionModelAttributes(model, competition, section, subsection, questionId); CompetitionSetupForm competitionSetupForm = form; if (form == null) { competitionSetupForm = competitionSetupService.getSubsectionFormData( competition, section, subsection, questionId); } model.addAttribute(COMPETITION_NAME_KEY, competition.getName()); model.addAttribute(COMPETITION_SETUP_FORM_KEY, competitionSetupForm); model.addAttribute("editable", isEditable); } }
package org.innovateuk.ifs.management.competition.setup.projectimpact.form; import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupForm; import javax.validation.constraints.NotNull; import static java.util.Objects.isNull; /** * Form for the Project Impact competition setup section. */ public class ProjectImpactForm extends CompetitionSetupForm { @NotNull(message = "{validation.projectImpactForm.projectImpactSurveyApplicable.required}") private Boolean projectImpactSurveyApplicable; public Boolean getProjectImpactSurveyApplicable() { return projectImpactSurveyApplicable; } public void setProjectImpactSurveyApplicable(Boolean projectImpactSurveyApplicable) { this.projectImpactSurveyApplicable = projectImpactSurveyApplicable; } }