lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
error: pathspec 'ohmdb-test/src/test/java/com/ohmdb/basic/ShortyTest.java' did not match any file(s) known to git
73eee6ececa13df84795a9eb9802cb9b21e4b5c3
1
ohmdb/ohmdb,gitblit/ohmdb,ohmdb/ohmdb,gitblit/ohmdb
package com.ohmdb.basic; /* * #%L * ohmdb-test * %% * Copyright (C) 2013 - 2014 Nikolche Mihajlovski * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.testng.annotations.Test; import com.ohmdb.api.Ohm; import com.ohmdb.api.Table; import com.ohmdb.test.Person; import com.ohmdb.test.TestCommons; public class ShortyTest extends TestCommons { @Test public void shouldHaveShortAPI() { Table<Person> persons = Ohm.db().table(Person.class); persons.insert(new Person("john", 29)); eq(persons.size(), 1); persons.print(); } }
ohmdb-test/src/test/java/com/ohmdb/basic/ShortyTest.java
Initial commit: ShortyTest.java
ohmdb-test/src/test/java/com/ohmdb/basic/ShortyTest.java
Initial commit: ShortyTest.java
<ide><path>hmdb-test/src/test/java/com/ohmdb/basic/ShortyTest.java <add>package com.ohmdb.basic; <add> <add>/* <add> * #%L <add> * ohmdb-test <add> * %% <add> * Copyright (C) 2013 - 2014 Nikolche Mihajlovski <add> * %% <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> * #L% <add> */ <add> <add>import org.testng.annotations.Test; <add> <add>import com.ohmdb.api.Ohm; <add>import com.ohmdb.api.Table; <add>import com.ohmdb.test.Person; <add>import com.ohmdb.test.TestCommons; <add> <add>public class ShortyTest extends TestCommons { <add> <add> @Test <add> public void shouldHaveShortAPI() { <add> Table<Person> persons = Ohm.db().table(Person.class); <add> <add> persons.insert(new Person("john", 29)); <add> <add> eq(persons.size(), 1); <add> <add> persons.print(); <add> } <add> <add>}
JavaScript
bsd-3-clause
da398f875f30373b153b525485d2e35d23c24918
0
cedricpinson/WebGL-Inspector,benvanik/WebGL-Inspector,greggman/WebGL-Inspector,greggman/WebGL-Inspector,cedricpinson/WebGL-Inspector,mcanthony/WebGL-Inspector,mcanthony/WebGL-Inspector,cedricpinson/WebGL-Inspector,mcanthony/WebGL-Inspector,benvanik/WebGL-Inspector,TheKK/WebGL-Inspector,benvanik/WebGL-Inspector,TheKK/WebGL-Inspector,TheKK/WebGL-Inspector,greggman/WebGL-Inspector
(function () { var TraceMinibar = function (view, w) { var self = this; this.view = view; this.window = w; this.elements = { bar: w.root.getElementsByClassName("trace-minibar")[0] }; this.buttons = {}; // Pull out the canvas from the OutputHUD and set up the replay controller var canvas = w.outputHUD.canvas; var replaygl = null; try { replaygl = canvas.getContext("experimental-webgl"); } catch (e) { } this.replaygl = replaygl; this.replay = new gli.Replay(w.context, replaygl); this.replay.onStep = function (replay, frame, callIndex) { self.lastCallIndex = callIndex; }; function addButton(bar, name, tip, callback) { var el = document.createElement("div"); el.className = "trace-minibar-button trace-minibar-button-disabled trace-minibar-command-" + name; el.title = tip; el.innerHTML = "&nbsp;"; el.onclick = function () { callback.apply(self); }; bar.appendChild(el); self.buttons[name] = el; }; addButton(this.elements.bar, "run", "Playback entire frame", function () { this.replay.stepUntilEnd(); this.refreshState(); }); addButton(this.elements.bar, "step-forward", "Step forward one call", function () { if (this.replay.step() == false) { this.replay.reset(); this.replay.beginFrame(this.view.frame); } this.refreshState(); }); addButton(this.elements.bar, "step-back", "Step backward one call", function () { this.replay.stepBack(); this.refreshState(); }); addButton(this.elements.bar, "step-until-error", "Run until an error occurs", function () { alert("step-until-error"); this.replay.stepUntilError(); this.refreshState(); }); addButton(this.elements.bar, "step-until-draw", "Run until the next draw call", function () { alert("step-until-draw"); this.replay.stepUntilDraw(); this.refreshState(); }); addButton(this.elements.bar, "restart", "Restart from the beginning of the frame", function () { this.replay.beginFrame(this.view.frame); this.refreshState(); }); this.update(); }; TraceMinibar.prototype.refreshState = function () { var newState = new gli.StateCapture(this.replaygl); this.view.traceListing.setActiveCall(this.lastCallIndex); this.window.stateHUD.showState(newState); this.window.outputHUD.refresh(); }; TraceMinibar.prototype.stepUntil = function (callIndex) { if (this.replay.callIndex > callIndex) { this.replay.reset(); this.replay.beginFrame(this.view.frame); this.replay.stepUntil(callIndex); } else { this.replay.stepUntil(callIndex); } this.refreshState(); }; TraceMinibar.prototype.update = function () { var self = this; if (this.view.frame) { this.replay.reset(); this.replay.runFrame(this.view.frame); } else { this.replay.reset(); // TODO: clear canvas console.log("would clear canvas"); } function toggleButton(name, enabled) { var el = self.buttons[name]; if (enabled) { el.className = el.className.replace("trace-minibar-button-disabled", "trace-minibar-button-enabled"); } else { el.className = el.className.replace("trace-minibar-button-enabled", "trace-minibar-button-disabled"); } }; for (var n in this.buttons) { toggleButton(n, false); } toggleButton("run", true); toggleButton("step-forward", true); toggleButton("step-back", true); toggleButton("step-until-error", true); toggleButton("step-until-draw", true); toggleButton("restart", true); this.window.outputHUD.refresh(); }; var TraceView = function (w) { var self = this; this.window = w; this.elements = {}; this.minibar = new TraceMinibar(this, w); this.traceListing = new gli.ui.TraceListing(this, w); this.inspector = new gli.ui.TraceInspector(this, w); this.frame = null; }; TraceView.prototype.reset = function () { this.minibar.update(); this.traceListing.reset(); this.inspector.reset(); this.frame = null; }; TraceView.prototype.setFrame = function (frame) { this.reset(); this.frame = frame; this.traceListing.setFrame(frame); this.minibar.update(); this.traceListing.scrollToCall(0); }; gli = gli || {}; gli.ui = gli.ui || {}; gli.ui.TraceView = TraceView; })();
core/ui/traceview.js
(function () { var TraceMinibar = function (view, w) { var self = this; this.view = view; this.window = w; this.elements = { bar: w.root.getElementsByClassName("trace-minibar")[0] }; this.buttons = {}; // Pull out the canvas from the OutputHUD and set up the replay controller var canvas = w.outputHUD.canvas; var replaygl = null; try { replaygl = canvas.getContext("experimental-webgl"); } catch (e) { } this.replaygl = replaygl; this.replay = new gli.Replay(w.context, replaygl); this.replay.onStep = function (replay, frame, callIndex) { self.view.traceListing.setActiveCall(callIndex); }; function addButton(bar, name, tip, callback) { var el = document.createElement("div"); el.className = "trace-minibar-button trace-minibar-button-disabled trace-minibar-command-" + name; el.title = tip; el.innerHTML = "&nbsp;"; el.onclick = function () { callback.apply(self); }; bar.appendChild(el); self.buttons[name] = el; }; addButton(this.elements.bar, "run", "Playback entire frame", function () { this.replay.stepUntilEnd(); this.refreshState(); }); addButton(this.elements.bar, "step-forward", "Step forward one call", function () { if (this.replay.step() == false) { this.replay.reset(); this.replay.beginFrame(this.view.frame); } this.refreshState(); }); addButton(this.elements.bar, "step-back", "Step backward one call", function () { this.replay.stepBack(); this.refreshState(); }); addButton(this.elements.bar, "step-until-error", "Run until an error occurs", function () { alert("step-until-error"); this.replay.stepUntilError(); this.refreshState(); }); addButton(this.elements.bar, "step-until-draw", "Run until the next draw call", function () { alert("step-until-draw"); this.replay.stepUntilDraw(); this.refreshState(); }); addButton(this.elements.bar, "restart", "Restart from the beginning of the frame", function () { this.replay.beginFrame(this.view.frame); this.refreshState(); }); this.update(); }; TraceMinibar.prototype.refreshState = function () { var newState = new gli.StateCapture(this.replaygl); this.window.stateHUD.showState(newState); this.window.outputHUD.refresh(); }; TraceMinibar.prototype.stepUntil = function (callIndex) { if (this.replay.callIndex > callIndex) { this.replay.reset(); this.replay.beginFrame(this.view.frame); this.replay.stepUntil(callIndex); } else { this.replay.stepUntil(callIndex); } this.refreshState(); }; TraceMinibar.prototype.update = function () { var self = this; if (this.view.frame) { this.replay.reset(); this.replay.runFrame(this.view.frame); } else { this.replay.reset(); // TODO: clear canvas console.log("would clear canvas"); } function toggleButton(name, enabled) { var el = self.buttons[name]; if (enabled) { el.className = el.className.replace("trace-minibar-button-disabled", "trace-minibar-button-enabled"); } else { el.className = el.className.replace("trace-minibar-button-enabled", "trace-minibar-button-disabled"); } }; for (var n in this.buttons) { toggleButton(n, false); } toggleButton("run", true); toggleButton("step-forward", true); toggleButton("step-back", true); toggleButton("step-until-error", true); toggleButton("step-until-draw", true); toggleButton("restart", true); this.window.outputHUD.refresh(); }; var TraceView = function (w) { var self = this; this.window = w; this.elements = {}; this.minibar = new TraceMinibar(this, w); this.traceListing = new gli.ui.TraceListing(this, w); this.inspector = new gli.ui.TraceInspector(this, w); this.frame = null; }; TraceView.prototype.reset = function () { this.minibar.update(); this.traceListing.reset(); this.inspector.reset(); this.frame = null; }; TraceView.prototype.setFrame = function (frame) { this.reset(); this.frame = frame; this.traceListing.setFrame(frame); this.minibar.update(); this.traceListing.scrollToCall(0); }; gli = gli || {}; gli.ui = gli.ui || {}; gli.ui.TraceView = TraceView; })();
avoid heavy work on each replay step until the end
core/ui/traceview.js
avoid heavy work on each replay step until the end
<ide><path>ore/ui/traceview.js <ide> this.replay = new gli.Replay(w.context, replaygl); <ide> <ide> this.replay.onStep = function (replay, frame, callIndex) { <del> self.view.traceListing.setActiveCall(callIndex); <add> self.lastCallIndex = callIndex; <ide> }; <ide> <ide> function addButton(bar, name, tip, callback) { <ide> }; <ide> TraceMinibar.prototype.refreshState = function () { <ide> var newState = new gli.StateCapture(this.replaygl); <add> this.view.traceListing.setActiveCall(this.lastCallIndex); <ide> this.window.stateHUD.showState(newState); <ide> this.window.outputHUD.refresh(); <ide> };
Java
apache-2.0
97fb3779440636c9cf202c3a63f2a6bd4b350400
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing.contentQueue; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.InvalidVirtualFileAccessException; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem; import com.intellij.util.PathUtil; import com.intellij.util.indexing.FileBasedIndexImpl; import com.intellij.util.indexing.diagnostic.FileIndexingStatistics; import com.intellij.util.indexing.diagnostic.IndexingJobStatistics; import com.intellij.util.progress.SubTaskProgressIndicator; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.FileNotFoundException; import java.util.Collection; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @ApiStatus.Internal public final class IndexUpdateRunner { private static final long SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY = 20 * FileUtilRt.MEGABYTE; private static final CopyOnWriteArrayList<IndexingJob> ourIndexingJobs = new CopyOnWriteArrayList<>(); private final FileBasedIndexImpl myFileBasedIndex; private final ExecutorService myIndexingExecutor; private final int myNumberOfIndexingThreads; /** * Memory optimization to prevent OutOfMemory on loading file contents. * <p> * "Soft" total limit of bytes loaded into memory in the whole application is {@link #SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY}. * It is "soft" because one (and only one) "indexable" file can exceed this limit. * <p> * "Indexable" file is any file for which {@link FileBasedIndexImpl#isTooLarge(VirtualFile)} returns {@code false}. * Note that this method may return {@code false} even for relatively big files with size greater than {@link #SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY}. * This is because for some files (or file types) the size limit is ignored. * <p> * So in its maximum we will load {@code SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY + <size of not "too large" file>}, which seems acceptable, * because we have to index this "not too large" file anyway (even if its size is 4 Gb), and {@code SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY} * additional bytes are insignificant. */ private static long ourTotalBytesLoadedIntoMemory = 0; private static final Lock ourLoadedBytesLimitLock = new ReentrantLock(); private static final Condition ourLoadedBytesAreReleasedCondition = ourLoadedBytesLimitLock.newCondition(); public IndexUpdateRunner(@NotNull FileBasedIndexImpl fileBasedIndex, @NotNull ExecutorService indexingExecutor, int numberOfIndexingThreads) { myFileBasedIndex = fileBasedIndex; myIndexingExecutor = indexingExecutor; myNumberOfIndexingThreads = numberOfIndexingThreads; } @NotNull public IndexingJobStatistics indexFiles(@NotNull Project project, @NotNull Collection<VirtualFile> files, @NotNull ProgressIndicator indicator) { indicator.checkCanceled(); indicator.setIndeterminate(false); CachedFileContentLoader contentLoader = new CurrentProjectHintedCachedFileContentLoader(project); IndexingJob indexingJob = new IndexingJob(project, indicator, contentLoader, files); if (ApplicationManager.getApplication().isWriteAccessAllowed()) { // If the current thread has acquired the write lock, we can't grant it to worker threads, so we must do the work in the current thread. while (!indexingJob.areAllFilesProcessed()) { indexOneFileOfJob(indexingJob); } } else { ourIndexingJobs.add(indexingJob); try { AtomicInteger numberOfRunningWorkers = new AtomicInteger(); Runnable worker = () -> { try { indexJobsFairly(); } finally { numberOfRunningWorkers.decrementAndGet(); } }; while (!project.isDisposed() && !indexingJob.areAllFilesProcessed() && indexingJob.myError.get() == null) { if (numberOfRunningWorkers.get() < myNumberOfIndexingThreads) { numberOfRunningWorkers.incrementAndGet(); myIndexingExecutor.execute(worker); } indicator.checkCanceled(); try { //noinspection BusyWait Thread.sleep(10); } catch (InterruptedException e) { throw new ProcessCanceledException(e); } } Throwable error = indexingJob.myError.get(); if (error instanceof ProcessCanceledException) { throw (ProcessCanceledException) error; } if (error != null) { throw new RuntimeException("Indexing of " + project.getName() + " has failed", error); } } finally { ourIndexingJobs.remove(indexingJob); } } return indexingJob.myStatistics; } // Index jobs one by one while there are some. Jobs may belong to different projects, and we index them fairly. // Drops finished, cancelled and failed jobs from {@code ourIndexingJobs}. Does not throw exceptions. private void indexJobsFairly() { while (!ourIndexingJobs.isEmpty()) { for (IndexingJob job : ourIndexingJobs) { if (job.myProject.isDisposed() || job.myNoMoreFilesToProcess.get() || job.myIndicator.isCanceled() || job.myError.get() != null) { ourIndexingJobs.remove(job); continue; } try { indexOneFileOfJob(job); } catch (Throwable e) { job.myError.compareAndSet(null, e); ourIndexingJobs.remove(job); } } } } private void indexOneFileOfJob(@NotNull IndexingJob indexingJob) throws ProcessCanceledException { long contentLoadingTime = System.nanoTime(); ContentLoadingResult loadingResult; try { loadingResult = loadNextContent(indexingJob, indexingJob.myIndicator); } catch (TooLargeContentException e) { indexingJob.oneMoreFileProcessed(); indexingJob.myStatistics.getNumberOfTooLargeFiles().incrementAndGet(); FileBasedIndexImpl.LOG.info("File: " + e.getFile().getUrl() + " is too large for indexing"); return; } catch (FailedToLoadContentException e) { indexingJob.oneMoreFileProcessed(); indexingJob.myStatistics.getNumberOfFailedToLoadFiles().incrementAndGet(); logFailedToLoadContentException(e); return; } finally { contentLoadingTime = System.nanoTime() - contentLoadingTime; } if (loadingResult == null) { indexingJob.myNoMoreFilesToProcess.set(true); return; } CachedFileContent fileContent = loadingResult.cachedFileContent; VirtualFile file = fileContent.getVirtualFile(); try { indexingJob.setLocationBeingIndexed(file); if (!file.isDirectory()) { FileIndexingStatistics fileIndexingStatistics = ReadAction .nonBlocking(() -> myFileBasedIndex.indexFileContent(indexingJob.myProject, fileContent)) .expireWith(indexingJob.myProject) .wrapProgress(indexingJob.myIndicator) .executeSynchronously(); indexingJob.myStatistics.addFileStatistics(fileIndexingStatistics, contentLoadingTime, loadingResult.fileLength); } indexingJob.oneMoreFileProcessed(); } catch (ProcessCanceledException e) { // Push back the file. indexingJob.myQueueOfFiles.add(file); throw e; } catch (Throwable e) { indexingJob.oneMoreFileProcessed(); indexingJob.myStatistics.getNumberOfFailedToIndexFiles().incrementAndGet(); FileBasedIndexImpl.LOG.error("Error while indexing " + file.getPresentableUrl() + "\n" + "To reindex this file IDEA has to be restarted", e); } finally { signalThatFileIsUnloaded(loadingResult.fileLength); } } @Nullable private IndexUpdateRunner.ContentLoadingResult loadNextContent(@NotNull IndexingJob indexingJob, @NotNull ProgressIndicator indicator) throws FailedToLoadContentException, TooLargeContentException, ProcessCanceledException { VirtualFile file = indexingJob.myQueueOfFiles.poll(); if (file == null) { return null; } if (myFileBasedIndex.isTooLarge(file)) { throw new TooLargeContentException(file); } try { long fileLength = file.getLength(); waitForFreeMemoryToLoadFileContent(indicator, fileLength); CachedFileContent fileContent = indexingJob.myContentLoader.loadContent(file); return new ContentLoadingResult(fileContent, fileLength); } catch (ProcessCanceledException e) { indexingJob.myQueueOfFiles.add(file); throw e; } } private static class ContentLoadingResult { final @NotNull CachedFileContent cachedFileContent; final long fileLength; private ContentLoadingResult(@NotNull CachedFileContent cachedFileContent, long fileLength) { this.cachedFileContent = cachedFileContent; this.fileLength = fileLength; } } private static void waitForFreeMemoryToLoadFileContent(@NotNull ProgressIndicator indicator, long fileLength) { ourLoadedBytesLimitLock.lock(); try { while (ourTotalBytesLoadedIntoMemory >= SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY) { indicator.checkCanceled(); try { ourLoadedBytesAreReleasedCondition.await(100, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new ProcessCanceledException(e); } } ourTotalBytesLoadedIntoMemory += fileLength; } finally { ourLoadedBytesLimitLock.unlock(); } } private static void signalThatFileIsUnloaded(long fileLength) { ourLoadedBytesLimitLock.lock(); try { assert ourTotalBytesLoadedIntoMemory >= fileLength; ourTotalBytesLoadedIntoMemory -= fileLength; if (ourTotalBytesLoadedIntoMemory < SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY) { ourLoadedBytesAreReleasedCondition.signalAll(); } } finally { ourLoadedBytesLimitLock.unlock(); } } private static void logFailedToLoadContentException(@NotNull FailedToLoadContentException e) { Throwable cause = e.getCause(); VirtualFile file = e.getFile(); String fileUrl = "File: " + file.getUrl(); if (cause instanceof FileNotFoundException) { // It is possible to not observe file system change until refresh finish, we handle missed file properly anyway. FileBasedIndexImpl.LOG.debug(fileUrl, e); } else if (cause instanceof IndexOutOfBoundsException || cause instanceof InvalidVirtualFileAccessException) { FileBasedIndexImpl.LOG.info(fileUrl, e); } else { FileBasedIndexImpl.LOG.error(fileUrl, e); } } @NotNull public static String getPresentableLocationBeingIndexed(@NotNull Project project, @NotNull VirtualFile file) { VirtualFile actualFile = file; if (actualFile.getFileSystem() instanceof ArchiveFileSystem) { actualFile = VfsUtil.getLocalFile(actualFile); } return FileUtil.toSystemDependentName(getProjectRelativeOrAbsolutePath(project, actualFile)); } @NotNull private static String getProjectRelativeOrAbsolutePath(@NotNull Project project, @NotNull VirtualFile file) { String projectBase = project.getBasePath(); if (StringUtil.isNotEmpty(projectBase)) { String filePath = file.getPath(); if (FileUtil.isAncestor(projectBase, filePath, true)) { String projectDirName = PathUtil.getFileName(projectBase); String relativePath = FileUtil.getRelativePath(projectBase, filePath, '/'); if (StringUtil.isNotEmpty(projectDirName) && StringUtil.isNotEmpty(relativePath)) { return projectDirName + "/" + relativePath; } } } return file.getPath(); } private static class IndexingJob { final Project myProject; final CachedFileContentLoader myContentLoader; final BlockingQueue<VirtualFile> myQueueOfFiles; final ProgressIndicator myIndicator; final AtomicInteger myNumberOfProcessedFiles = new AtomicInteger(); final int myTotalFiles; final AtomicBoolean myNoMoreFilesToProcess = new AtomicBoolean(); final IndexingJobStatistics myStatistics = new IndexingJobStatistics(); final AtomicReference<Throwable> myError = new AtomicReference<>(); IndexingJob(@NotNull Project project, @NotNull ProgressIndicator indicator, @NotNull CachedFileContentLoader contentLoader, @NotNull Collection<VirtualFile> files) { myProject = project; myIndicator = indicator; myTotalFiles = files.size(); myContentLoader = contentLoader; myQueueOfFiles = new ArrayBlockingQueue<>(files.size(), false, files); } public void oneMoreFileProcessed() { double newFraction = myNumberOfProcessedFiles.incrementAndGet() / (double)myTotalFiles; try { myIndicator.setFraction(newFraction); } catch (Exception ignored) { //Unexpected here. A misbehaved progress indicator must not break our code flow. } } boolean areAllFilesProcessed() { return myNumberOfProcessedFiles.get() == myTotalFiles; } public void setLocationBeingIndexed(@NotNull VirtualFile virtualFile) { String presentableLocation = getPresentableLocationBeingIndexed(myProject, virtualFile); if (myIndicator instanceof SubTaskProgressIndicator) { myIndicator.setText(presentableLocation); } else { myIndicator.setText2(presentableLocation); } } } }
platform/lang-impl/src/com/intellij/util/indexing/contentQueue/IndexUpdateRunner.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing.contentQueue; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.InvalidVirtualFileAccessException; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem; import com.intellij.util.PathUtil; import com.intellij.util.indexing.FileBasedIndexImpl; import com.intellij.util.indexing.diagnostic.FileIndexingStatistics; import com.intellij.util.indexing.diagnostic.IndexingJobStatistics; import com.intellij.util.progress.SubTaskProgressIndicator; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.FileNotFoundException; import java.util.Collection; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @ApiStatus.Internal public final class IndexUpdateRunner { private static final long SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY = 20 * FileUtilRt.MEGABYTE; private static final CopyOnWriteArrayList<IndexingJob> ourIndexingJobs = new CopyOnWriteArrayList<>(); private final FileBasedIndexImpl myFileBasedIndex; private final ExecutorService myIndexingExecutor; private final int myNumberOfIndexingThreads; /** * Memory optimization to prevent OutOfMemory on loading file contents. * <p> * "Soft" total limit of bytes loaded into memory in the whole application is {@link #SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY}. * It is "soft" because one (and only one) "indexable" file can exceed this limit. * <p> * "Indexable" file is any file for which {@link FileBasedIndexImpl#isTooLarge(VirtualFile)} returns {@code false}. * Note that this method may return {@code false} even for relatively big files with size greater than {@link #SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY}. * This is because for some files (or file types) the size limit is ignored. * <p> * So in its maximum we will load {@code SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY + <size of not "too large" file>}, which seems acceptable, * because we have to index this "not too large" file anyway (even if its size is 4 Gb), and {@code SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY} * additional bytes are insignificant. */ private static long ourTotalBytesLoadedIntoMemory = 0; private static final Lock ourLoadedBytesLimitLock = new ReentrantLock(); private static final Condition ourLoadedBytesAreReleasedCondition = ourLoadedBytesLimitLock.newCondition(); public IndexUpdateRunner(@NotNull FileBasedIndexImpl fileBasedIndex, @NotNull ExecutorService indexingExecutor, int numberOfIndexingThreads) { myFileBasedIndex = fileBasedIndex; myIndexingExecutor = indexingExecutor; myNumberOfIndexingThreads = numberOfIndexingThreads; } @NotNull public IndexingJobStatistics indexFiles(@NotNull Project project, @NotNull Collection<VirtualFile> files, @NotNull ProgressIndicator indicator) { indicator.checkCanceled(); indicator.setIndeterminate(false); CachedFileContentLoader contentLoader = new CurrentProjectHintedCachedFileContentLoader(project); IndexingJob indexingJob = new IndexingJob(project, indicator, contentLoader, files); if (ApplicationManager.getApplication().isWriteAccessAllowed()) { // If the current thread has acquired the write lock, we can't grant it to worker threads, so we must do the work in the current thread. while (!indexingJob.areAllFilesProcessed()) { indexOneFileOfJob(indexingJob); } } else { ourIndexingJobs.add(indexingJob); try { for (int i = 0; i < myNumberOfIndexingThreads; i++) { myIndexingExecutor.execute(() -> indexJobsFairly()); } while (!project.isDisposed() && !indexingJob.areAllFilesProcessed() && indexingJob.myError.get() == null) { indicator.checkCanceled(); try { //noinspection BusyWait Thread.sleep(10); } catch (InterruptedException e) { throw new ProcessCanceledException(e); } } Throwable error = indexingJob.myError.get(); if (error instanceof ProcessCanceledException) { throw (ProcessCanceledException) error; } if (error != null) { throw new RuntimeException("Indexing of " + project.getName() + " has failed", error); } } finally { ourIndexingJobs.remove(indexingJob); } } return indexingJob.myStatistics; } // Index jobs one by one while there are some. Jobs may belong to different projects, and we index them fairly. // Drops finished, cancelled and failed jobs from {@code ourIndexingJobs}. Does not throw exceptions. private void indexJobsFairly() { while (!ourIndexingJobs.isEmpty()) { for (IndexingJob job : ourIndexingJobs) { if (job.myProject.isDisposed() || job.myNoMoreFilesToProcess.get() || job.myIndicator.isCanceled() || job.myError.get() != null) { ourIndexingJobs.remove(job); continue; } try { indexOneFileOfJob(job); } catch (Throwable e) { job.myError.compareAndSet(null, e); ourIndexingJobs.remove(job); } } } } private void indexOneFileOfJob(@NotNull IndexingJob indexingJob) throws ProcessCanceledException { long contentLoadingTime = System.nanoTime(); ContentLoadingResult loadingResult; try { loadingResult = loadNextContent(indexingJob, indexingJob.myIndicator); } catch (TooLargeContentException e) { indexingJob.oneMoreFileProcessed(); indexingJob.myStatistics.getNumberOfTooLargeFiles().incrementAndGet(); FileBasedIndexImpl.LOG.info("File: " + e.getFile().getUrl() + " is too large for indexing"); return; } catch (FailedToLoadContentException e) { indexingJob.oneMoreFileProcessed(); indexingJob.myStatistics.getNumberOfFailedToLoadFiles().incrementAndGet(); logFailedToLoadContentException(e); return; } finally { contentLoadingTime = System.nanoTime() - contentLoadingTime; } if (loadingResult == null) { indexingJob.myNoMoreFilesToProcess.set(true); return; } CachedFileContent fileContent = loadingResult.cachedFileContent; VirtualFile file = fileContent.getVirtualFile(); try { indexingJob.setLocationBeingIndexed(file); if (!file.isDirectory()) { FileIndexingStatistics fileIndexingStatistics = ReadAction .nonBlocking(() -> myFileBasedIndex.indexFileContent(indexingJob.myProject, fileContent)) .expireWith(indexingJob.myProject) .wrapProgress(indexingJob.myIndicator) .executeSynchronously(); indexingJob.myStatistics.addFileStatistics(fileIndexingStatistics, contentLoadingTime, loadingResult.fileLength); } indexingJob.oneMoreFileProcessed(); } catch (ProcessCanceledException e) { // Push back the file. indexingJob.myQueueOfFiles.add(file); throw e; } catch (Throwable e) { indexingJob.oneMoreFileProcessed(); indexingJob.myStatistics.getNumberOfFailedToIndexFiles().incrementAndGet(); FileBasedIndexImpl.LOG.error("Error while indexing " + file.getPresentableUrl() + "\n" + "To reindex this file IDEA has to be restarted", e); } finally { signalThatFileIsUnloaded(loadingResult.fileLength); } } @Nullable private IndexUpdateRunner.ContentLoadingResult loadNextContent(@NotNull IndexingJob indexingJob, @NotNull ProgressIndicator indicator) throws FailedToLoadContentException, TooLargeContentException, ProcessCanceledException { VirtualFile file = indexingJob.myQueueOfFiles.poll(); if (file == null) { return null; } if (myFileBasedIndex.isTooLarge(file)) { throw new TooLargeContentException(file); } try { long fileLength = file.getLength(); waitForFreeMemoryToLoadFileContent(indicator, fileLength); CachedFileContent fileContent = indexingJob.myContentLoader.loadContent(file); return new ContentLoadingResult(fileContent, fileLength); } catch (ProcessCanceledException e) { indexingJob.myQueueOfFiles.add(file); throw e; } } private static class ContentLoadingResult { final @NotNull CachedFileContent cachedFileContent; final long fileLength; private ContentLoadingResult(@NotNull CachedFileContent cachedFileContent, long fileLength) { this.cachedFileContent = cachedFileContent; this.fileLength = fileLength; } } private static void waitForFreeMemoryToLoadFileContent(@NotNull ProgressIndicator indicator, long fileLength) { ourLoadedBytesLimitLock.lock(); try { while (ourTotalBytesLoadedIntoMemory >= SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY) { indicator.checkCanceled(); try { ourLoadedBytesAreReleasedCondition.await(100, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new ProcessCanceledException(e); } } ourTotalBytesLoadedIntoMemory += fileLength; } finally { ourLoadedBytesLimitLock.unlock(); } } private static void signalThatFileIsUnloaded(long fileLength) { ourLoadedBytesLimitLock.lock(); try { assert ourTotalBytesLoadedIntoMemory >= fileLength; ourTotalBytesLoadedIntoMemory -= fileLength; if (ourTotalBytesLoadedIntoMemory < SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY) { ourLoadedBytesAreReleasedCondition.signalAll(); } } finally { ourLoadedBytesLimitLock.unlock(); } } private static void logFailedToLoadContentException(@NotNull FailedToLoadContentException e) { Throwable cause = e.getCause(); VirtualFile file = e.getFile(); String fileUrl = "File: " + file.getUrl(); if (cause instanceof FileNotFoundException) { // It is possible to not observe file system change until refresh finish, we handle missed file properly anyway. FileBasedIndexImpl.LOG.debug(fileUrl, e); } else if (cause instanceof IndexOutOfBoundsException || cause instanceof InvalidVirtualFileAccessException) { FileBasedIndexImpl.LOG.info(fileUrl, e); } else { FileBasedIndexImpl.LOG.error(fileUrl, e); } } @NotNull public static String getPresentableLocationBeingIndexed(@NotNull Project project, @NotNull VirtualFile file) { VirtualFile actualFile = file; if (actualFile.getFileSystem() instanceof ArchiveFileSystem) { actualFile = VfsUtil.getLocalFile(actualFile); } return FileUtil.toSystemDependentName(getProjectRelativeOrAbsolutePath(project, actualFile)); } @NotNull private static String getProjectRelativeOrAbsolutePath(@NotNull Project project, @NotNull VirtualFile file) { String projectBase = project.getBasePath(); if (StringUtil.isNotEmpty(projectBase)) { String filePath = file.getPath(); if (FileUtil.isAncestor(projectBase, filePath, true)) { String projectDirName = PathUtil.getFileName(projectBase); String relativePath = FileUtil.getRelativePath(projectBase, filePath, '/'); if (StringUtil.isNotEmpty(projectDirName) && StringUtil.isNotEmpty(relativePath)) { return projectDirName + "/" + relativePath; } } } return file.getPath(); } private static class IndexingJob { final Project myProject; final CachedFileContentLoader myContentLoader; final BlockingQueue<VirtualFile> myQueueOfFiles; final ProgressIndicator myIndicator; final AtomicInteger myNumberOfProcessedFiles = new AtomicInteger(); final int myTotalFiles; final AtomicBoolean myNoMoreFilesToProcess = new AtomicBoolean(); final IndexingJobStatistics myStatistics = new IndexingJobStatistics(); final AtomicReference<Throwable> myError = new AtomicReference<>(); IndexingJob(@NotNull Project project, @NotNull ProgressIndicator indicator, @NotNull CachedFileContentLoader contentLoader, @NotNull Collection<VirtualFile> files) { myProject = project; myIndicator = indicator; myTotalFiles = files.size(); myContentLoader = contentLoader; myQueueOfFiles = new ArrayBlockingQueue<>(files.size(), false, files); } public void oneMoreFileProcessed() { double newFraction = myNumberOfProcessedFiles.incrementAndGet() / (double)myTotalFiles; try { myIndicator.setFraction(newFraction); } catch (Exception ignored) { //Unexpected here. A misbehaved progress indicator must not break our code flow. } } boolean areAllFilesProcessed() { return myNumberOfProcessedFiles.get() == myTotalFiles; } public void setLocationBeingIndexed(@NotNull VirtualFile virtualFile) { String presentableLocation = getPresentableLocationBeingIndexed(myProject, virtualFile); if (myIndicator instanceof SubTaskProgressIndicator) { myIndicator.setText(presentableLocation); } else { myIndicator.setText2(presentableLocation); } } } }
Indexing: track number of running workers and add new workers if necessary. If worker threads die for whatever reason, we don't want indexing to stop (we used to have some bugs when indexing worker would finish with an exception and indexing wouldn't make progress). Let's guarantee there are enough workers running. GitOrigin-RevId: 9e99abb3e51838e5bd4c624239aa336963de4b0c
platform/lang-impl/src/com/intellij/util/indexing/contentQueue/IndexUpdateRunner.java
Indexing: track number of running workers and add new workers if necessary.
<ide><path>latform/lang-impl/src/com/intellij/util/indexing/contentQueue/IndexUpdateRunner.java <ide> else { <ide> ourIndexingJobs.add(indexingJob); <ide> try { <del> for (int i = 0; i < myNumberOfIndexingThreads; i++) { <del> myIndexingExecutor.execute(() -> indexJobsFairly()); <del> } <add> AtomicInteger numberOfRunningWorkers = new AtomicInteger(); <add> Runnable worker = () -> { <add> try { <add> indexJobsFairly(); <add> } <add> finally { <add> numberOfRunningWorkers.decrementAndGet(); <add> } <add> }; <ide> while (!project.isDisposed() && !indexingJob.areAllFilesProcessed() && indexingJob.myError.get() == null) { <add> if (numberOfRunningWorkers.get() < myNumberOfIndexingThreads) { <add> numberOfRunningWorkers.incrementAndGet(); <add> myIndexingExecutor.execute(worker); <add> } <ide> indicator.checkCanceled(); <ide> try { <ide> //noinspection BusyWait
Java
apache-2.0
error: pathspec 'src/test/com/google/inject/BindingTypesTest.java' did not match any file(s) known to git
0fdae330d8a1d5b69d85bf9da97f4571f1764999
1
mikosik/deguicifier
package com.google.inject; import static org.hamcrest.Matchers.instanceOf; import static org.testory.Testory.given; import static org.testory.Testory.thenReturned; import static org.testory.Testory.when; import org.junit.Test; import com.google.inject.spi.ConstructorBinding; import com.google.inject.spi.InstanceBinding; import com.google.inject.spi.LinkedKeyBinding; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderKeyBinding; public class BindingTypesTest { private Module module; private Injector injector; @Test public void binds_constructor() { given(module = new AbstractModule() { @Override protected void configure() { bind(Implementation.class); } }); given(injector = Guice.createInjector(module)); when(injector.getBinding(Implementation.class)); thenReturned(instanceOf(ConstructorBinding.class)); } @Test public void binds_linked_key() { given(module = new AbstractModule() { @Override protected void configure() { bind(Interface.class).to(Implementation.class); } }); given(injector = Guice.createInjector(module)); when(injector.getBinding(Interface.class)); thenReturned(instanceOf(LinkedKeyBinding.class)); } @Test public void binds_provider_key() { given(module = new AbstractModule() { @Override protected void configure() { bind(Interface.class).toProvider(InterfaceProvider.class); } }); given(injector = Guice.createInjector(module)); when(injector.getBinding(Interface.class)); thenReturned(instanceOf(ProviderKeyBinding.class)); } @Test public void binds_provider_instance() { given(module = new AbstractModule() { @Override protected void configure() { bind(Interface.class).toProvider(new InterfaceProvider()); } }); given(injector = Guice.createInjector(module)); when(injector.getBinding(Interface.class)); thenReturned(instanceOf(ProviderInstanceBinding.class)); } @Test public void binds_provider_instance_from_method() { given(module = new AbstractModule() { @Override protected void configure() {} @Provides public Interface provide() { return new Implementation(); } }); given(injector = Guice.createInjector(module)); when(injector.getBinding(Interface.class)); thenReturned(instanceOf(ProviderInstanceBinding.class)); } @Test public void binds_instance() { given(module = new AbstractModule() { @Override protected void configure() { bind(Interface.class).toInstance(new Implementation()); } }); given(injector = Guice.createInjector(module)); when(injector.getBinding(Interface.class)); thenReturned(instanceOf(InstanceBinding.class)); } private static interface Interface {} private static class Implementation implements Interface {} private static class InterfaceProvider implements Provider<Interface> { @Override public Interface get() { return null; } } }
src/test/com/google/inject/BindingTypesTest.java
created learning test explaining Binding types
src/test/com/google/inject/BindingTypesTest.java
created learning test explaining Binding types
<ide><path>rc/test/com/google/inject/BindingTypesTest.java <add>package com.google.inject; <add> <add>import static org.hamcrest.Matchers.instanceOf; <add>import static org.testory.Testory.given; <add>import static org.testory.Testory.thenReturned; <add>import static org.testory.Testory.when; <add> <add>import org.junit.Test; <add> <add>import com.google.inject.spi.ConstructorBinding; <add>import com.google.inject.spi.InstanceBinding; <add>import com.google.inject.spi.LinkedKeyBinding; <add>import com.google.inject.spi.ProviderInstanceBinding; <add>import com.google.inject.spi.ProviderKeyBinding; <add> <add>public class BindingTypesTest { <add> private Module module; <add> private Injector injector; <add> <add> @Test <add> public void binds_constructor() { <add> given(module = new AbstractModule() { <add> @Override <add> protected void configure() { <add> bind(Implementation.class); <add> } <add> }); <add> given(injector = Guice.createInjector(module)); <add> when(injector.getBinding(Implementation.class)); <add> thenReturned(instanceOf(ConstructorBinding.class)); <add> } <add> <add> @Test <add> public void binds_linked_key() { <add> given(module = new AbstractModule() { <add> @Override <add> protected void configure() { <add> bind(Interface.class).to(Implementation.class); <add> } <add> }); <add> given(injector = Guice.createInjector(module)); <add> when(injector.getBinding(Interface.class)); <add> thenReturned(instanceOf(LinkedKeyBinding.class)); <add> } <add> <add> @Test <add> public void binds_provider_key() { <add> given(module = new AbstractModule() { <add> @Override <add> protected void configure() { <add> bind(Interface.class).toProvider(InterfaceProvider.class); <add> } <add> }); <add> given(injector = Guice.createInjector(module)); <add> when(injector.getBinding(Interface.class)); <add> thenReturned(instanceOf(ProviderKeyBinding.class)); <add> } <add> <add> @Test <add> public void binds_provider_instance() { <add> given(module = new AbstractModule() { <add> @Override <add> protected void configure() { <add> bind(Interface.class).toProvider(new InterfaceProvider()); <add> } <add> }); <add> given(injector = Guice.createInjector(module)); <add> when(injector.getBinding(Interface.class)); <add> thenReturned(instanceOf(ProviderInstanceBinding.class)); <add> } <add> <add> @Test <add> public void binds_provider_instance_from_method() { <add> given(module = new AbstractModule() { <add> @Override <add> protected void configure() {} <add> <add> @Provides <add> public Interface provide() { <add> return new Implementation(); <add> } <add> }); <add> given(injector = Guice.createInjector(module)); <add> when(injector.getBinding(Interface.class)); <add> thenReturned(instanceOf(ProviderInstanceBinding.class)); <add> } <add> <add> @Test <add> public void binds_instance() { <add> given(module = new AbstractModule() { <add> @Override <add> protected void configure() { <add> bind(Interface.class).toInstance(new Implementation()); <add> } <add> }); <add> given(injector = Guice.createInjector(module)); <add> when(injector.getBinding(Interface.class)); <add> thenReturned(instanceOf(InstanceBinding.class)); <add> } <add> <add> private static interface Interface {} <add> <add> private static class Implementation implements Interface {} <add> <add> private static class InterfaceProvider implements Provider<Interface> { <add> @Override <add> public Interface get() { <add> return null; <add> } <add> } <add>}
Java
apache-2.0
8ae1f8e24a7156c189bab50d30b794587809a6ca
0
romy-khetan/hydrator-plugins,ananya-bhattacharya/hydrator-plugins
/* * Copyright © 2015-2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.hydrator.plugin.db.batch.sink; import co.cask.cdap.api.annotation.Description; import co.cask.cdap.api.annotation.Name; import co.cask.cdap.api.annotation.Plugin; import co.cask.cdap.api.data.batch.OutputFormatProvider; import co.cask.cdap.api.data.format.StructuredRecord; import co.cask.cdap.api.data.schema.Schema; import co.cask.cdap.api.dataset.lib.KeyValue; import co.cask.cdap.api.plugin.PluginConfig; import co.cask.cdap.etl.api.Emitter; import co.cask.cdap.etl.api.PipelineConfigurer; import co.cask.cdap.etl.api.batch.BatchRuntimeContext; import co.cask.cdap.etl.api.batch.BatchSink; import co.cask.cdap.etl.api.batch.BatchSinkContext; import co.cask.hydrator.plugin.DBConfig; import co.cask.hydrator.plugin.DBManager; import co.cask.hydrator.plugin.DBRecord; import co.cask.hydrator.plugin.DBUtils; import co.cask.hydrator.plugin.ETLDBOutputFormat; import co.cask.hydrator.plugin.FieldCase; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapred.lib.db.DBConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Sink that can be configured to export data to a database table. */ @Plugin(type = "batchsink") @Name("Database") @Description("Writes records to a database table. Each record will be written to a row in the table.") public class DBSink extends BatchSink<StructuredRecord, DBRecord, NullWritable> { private static final Logger LOG = LoggerFactory.getLogger(DBSink.class); private final DBSinkConfig dbSinkConfig; private final DBManager dbManager; private Class<? extends Driver> driverClass; private int [] columnTypes; private List<String> columns; public DBSink(DBSinkConfig dbSinkConfig) { this.dbSinkConfig = dbSinkConfig; this.dbManager = new DBManager(dbSinkConfig); } private String getJDBCPluginId() { return String.format("%s.%s.%s", "sink", dbSinkConfig.jdbcPluginType, dbSinkConfig.jdbcPluginName); } @Override public void configurePipeline(PipelineConfigurer pipelineConfigurer) { dbManager.validateJDBCPluginPipeline(pipelineConfigurer, getJDBCPluginId()); } @Override public void prepareRun(BatchSinkContext context) { LOG.debug("tableName = {}; pluginType = {}; pluginName = {}; connectionString = {}; columns = {}", dbSinkConfig.tableName, dbSinkConfig.jdbcPluginType, dbSinkConfig.jdbcPluginName, dbSinkConfig.connectionString, dbSinkConfig.columns); // Load the plugin class to make sure it is available. Class<? extends Driver> driverClass = context.loadPluginClass(getJDBCPluginId()); // make sure that the table exists try { Preconditions.checkArgument( dbManager.tableExists(driverClass, dbSinkConfig.tableName), "Table %s does not exist. Please check that the 'tableName' property " + "has been set correctly, and that the connection string %s points to a valid database.", dbSinkConfig.tableName, dbSinkConfig.connectionString); } finally { DBUtils.cleanup(driverClass); } context.addOutput(dbSinkConfig.tableName, new DBOutputFormatProvider(dbSinkConfig, driverClass)); } @Override public void initialize(BatchRuntimeContext context) throws Exception { super.initialize(context); driverClass = context.loadPluginClass(getJDBCPluginId()); setResultSetMetadata(); } @Override public void transform(StructuredRecord input, Emitter<KeyValue<DBRecord, NullWritable>> emitter) throws Exception { // Create StructuredRecord that only has the columns in this.columns List<Schema.Field> outputFields = new ArrayList<>(); for (String column : columns) { Schema.Field field = input.getSchema().getField(column); Preconditions.checkNotNull(field, "Missing schema field for column '%s'", column); outputFields.add(field); } StructuredRecord.Builder output = StructuredRecord.builder( Schema.recordOf(input.getSchema().getRecordName(), outputFields)); for (String column : columns) { output.set(column, input.get(column)); } emitter.emit(new KeyValue<DBRecord, NullWritable>(new DBRecord(output.build(), columnTypes), null)); } @Override public void destroy() { DBUtils.cleanup(driverClass); dbManager.destroy(); } @VisibleForTesting void setColumns(List<String> columns) { this.columns = ImmutableList.copyOf(columns); } private void setResultSetMetadata() throws Exception { dbManager.ensureJDBCDriverIsAvailable(driverClass); Map<String, Integer> columnToType = new HashMap<>(); Connection connection; if (dbSinkConfig.user == null) { connection = DriverManager.getConnection(dbSinkConfig.connectionString); } else { connection = DriverManager.getConnection(dbSinkConfig.connectionString, dbSinkConfig.user, dbSinkConfig.password); } try { try (Statement statement = connection.createStatement(); // Run a query against the DB table that returns 0 records, but returns valid ResultSetMetadata // that can be used to construct DBRecord objects to sink to the database table. ResultSet rs = statement.executeQuery(String.format("SELECT %s FROM %s WHERE 1 = 0", dbSinkConfig.columns, dbSinkConfig.tableName)) ) { ResultSetMetaData resultSetMetadata = rs.getMetaData(); FieldCase fieldCase = FieldCase.toFieldCase(dbSinkConfig.columnNameCase); // JDBC driver column indices start with 1 for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { String name = resultSetMetadata.getColumnName(i + 1); int type = resultSetMetadata.getColumnType(i + 1); if (fieldCase == FieldCase.LOWER) { name = name.toLowerCase(); } else if (fieldCase == FieldCase.UPPER) { name = name.toUpperCase(); } columnToType.put(name, type); } } } finally { connection.close(); } columns = ImmutableList.copyOf(Splitter.on(",").omitEmptyStrings().trimResults().split(dbSinkConfig.columns)); columnTypes = new int[columns.size()]; for (int i = 0; i < columnTypes.length; i++) { String name = columns.get(i); Preconditions.checkArgument(columnToType.containsKey(name), "Missing column '%s' in SQL table", name); columnTypes[i] = columnToType.get(name); } } /** * {@link PluginConfig} for {@link DBSink} */ public static class DBSinkConfig extends DBConfig { @Description("Comma-separated list of columns in the specified table to export to.") public String columns; @Description("Name of the database table to write to.") public String tableName; } private static class DBOutputFormatProvider implements OutputFormatProvider { private final Map<String, String> conf; public DBOutputFormatProvider(DBSinkConfig dbSinkConfig, Class<? extends Driver> driverClass) { this.conf = new HashMap<>(); conf.put(DBConfiguration.DRIVER_CLASS_PROPERTY, driverClass.getName()); conf.put(DBConfiguration.URL_PROPERTY, dbSinkConfig.connectionString); if (dbSinkConfig.user != null && dbSinkConfig.password != null) { conf.put(DBConfiguration.USERNAME_PROPERTY, dbSinkConfig.user); conf.put(DBConfiguration.PASSWORD_PROPERTY, dbSinkConfig.password); } conf.put(DBConfiguration.OUTPUT_TABLE_NAME_PROPERTY, dbSinkConfig.tableName); conf.put(DBConfiguration.OUTPUT_FIELD_NAMES_PROPERTY, dbSinkConfig.columns); } @Override public String getOutputFormatClassName() { return ETLDBOutputFormat.class.getName(); } @Override public Map<String, String> getOutputFormatConfiguration() { return conf; } } }
database-plugins/src/main/java/co/cask/hydrator/plugin/db/batch/sink/DBSink.java
/* * Copyright © 2015-2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.hydrator.plugin.db.batch.sink; import co.cask.cdap.api.annotation.Description; import co.cask.cdap.api.annotation.Name; import co.cask.cdap.api.annotation.Plugin; import co.cask.cdap.api.data.batch.OutputFormatProvider; import co.cask.cdap.api.data.format.StructuredRecord; import co.cask.cdap.api.data.schema.Schema; import co.cask.cdap.api.dataset.lib.KeyValue; import co.cask.cdap.api.plugin.PluginConfig; import co.cask.cdap.etl.api.Emitter; import co.cask.cdap.etl.api.PipelineConfigurer; import co.cask.cdap.etl.api.batch.BatchRuntimeContext; import co.cask.cdap.etl.api.batch.BatchSink; import co.cask.cdap.etl.api.batch.BatchSinkContext; import co.cask.hydrator.plugin.DBConfig; import co.cask.hydrator.plugin.DBManager; import co.cask.hydrator.plugin.DBRecord; import co.cask.hydrator.plugin.DBUtils; import co.cask.hydrator.plugin.ETLDBOutputFormat; import co.cask.hydrator.plugin.FieldCase; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapred.lib.db.DBConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Sink that can be configured to export data to a database table. */ @Plugin(type = "batchsink") @Name("Database") @Description("Writes records to a database table. Each record will be written to a row in the table.") public class DBSink extends BatchSink<StructuredRecord, DBRecord, NullWritable> { private static final Logger LOG = LoggerFactory.getLogger(DBSink.class); private final DBSinkConfig dbSinkConfig; private final DBManager dbManager; private Class<? extends Driver> driverClass; private int [] columnTypes; private List<String> columns; public DBSink(DBSinkConfig dbSinkConfig) { this.dbSinkConfig = dbSinkConfig; this.dbManager = new DBManager(dbSinkConfig); } private String getJDBCPluginId() { return String.format("%s.%s.%s", "sink", dbSinkConfig.jdbcPluginType, dbSinkConfig.jdbcPluginName); } @Override public void configurePipeline(PipelineConfigurer pipelineConfigurer) { dbManager.validateJDBCPluginPipeline(pipelineConfigurer, getJDBCPluginId()); } @Override public void prepareRun(BatchSinkContext context) { LOG.debug("tableName = {}; pluginType = {}; pluginName = {}; connectionString = {}; columns = {}", dbSinkConfig.tableName, dbSinkConfig.jdbcPluginType, dbSinkConfig.jdbcPluginName, dbSinkConfig.connectionString, dbSinkConfig.columns); // Load the plugin class to make sure it is available. Class<? extends Driver> driverClass = context.loadPluginClass(getJDBCPluginId()); // make sure that the table exists try { Preconditions.checkArgument( dbManager.tableExists(driverClass, dbSinkConfig.tableName), "Table %s does not exist. Please check that the 'tableName' property " + "has been set correctly, and that the connection string %s points to a valid database.", dbSinkConfig.tableName, dbSinkConfig.connectionString); } finally { DBUtils.cleanup(driverClass); } context.addOutput(dbSinkConfig.tableName, new DBOutputFormatProvider(dbSinkConfig, driverClass)); } @Override public void initialize(BatchRuntimeContext context) throws Exception { super.initialize(context); driverClass = context.loadPluginClass(getJDBCPluginId()); setResultSetMetadata(); } @Override public void transform(StructuredRecord input, Emitter<KeyValue<DBRecord, NullWritable>> emitter) throws Exception { // Create StructuredRecord that only has the columns in this.columns List<Schema.Field> outputFields = new ArrayList<>(); for (String column : columns) { Schema.Field field = input.getSchema().getField(column); Preconditions.checkNotNull(field, "Missing schema field for column '%s'", column); outputFields.add(field); } StructuredRecord.Builder output = StructuredRecord.builder( Schema.recordOf(input.getSchema().getRecordName(), outputFields)); for (String column : columns) { output.set(column, input.get(column)); } emitter.emit(new KeyValue<DBRecord, NullWritable>(new DBRecord(output.build(), columnTypes), null)); } @Override public void destroy() { DBUtils.cleanup(driverClass); dbManager.destroy(); } @VisibleForTesting void setColumns(List<String> columns) { this.columns = ImmutableList.copyOf(columns); } private void setResultSetMetadata() throws Exception { dbManager.ensureJDBCDriverIsAvailable(driverClass); Map<String, Integer> columnToType = new HashMap<>(); Connection connection; if (dbSinkConfig.user == null) { connection = DriverManager.getConnection(dbSinkConfig.connectionString); } else { connection = DriverManager.getConnection(dbSinkConfig.connectionString, dbSinkConfig.user, dbSinkConfig.password); } try { try (Statement statement = connection.createStatement(); // Run a query against the DB table that returns 0 records, but returns valid ResultSetMetadata // that can be used to construct DBRecord objects to sink to the database table. ResultSet rs = statement.executeQuery(String.format("SELECT %s FROM %s WHERE 1 = 0", dbSinkConfig.columns, dbSinkConfig.tableName)) ) { ResultSetMetaData resultSetMetadata = rs.getMetaData(); FieldCase fieldCase = FieldCase.toFieldCase(dbSinkConfig.columnNameCase); // JDBC driver column indices start with 1 for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { String name = resultSetMetadata.getColumnName(i + 1); int type = resultSetMetadata.getColumnType(i + 1); if (fieldCase == FieldCase.LOWER) { name = name.toLowerCase(); } else if (fieldCase == FieldCase.UPPER) { name = name.toUpperCase(); } columnToType.put(name, type); } } } finally { connection.close(); } columns = ImmutableList.copyOf(Splitter.on(",").omitEmptyStrings().trimResults().split(dbSinkConfig.columns)); columnTypes = new int[columns.size()]; for (int i = 0; i < columnTypes.length; i++) { String name = columns.get(i); Preconditions.checkArgument(columnToType.containsKey(name), "Missing column '%s' in SQL table", name); columnTypes[i] = columnToType.get(name); } } /** * {@link PluginConfig} for {@link DBSink} */ public static class DBSinkConfig extends DBConfig { @Description("Comma-separated list of columns in the specified table to export to.") public String columns; @Description("Name of the database table to use as a source or a sink.") public String tableName; } private static class DBOutputFormatProvider implements OutputFormatProvider { private final Map<String, String> conf; public DBOutputFormatProvider(DBSinkConfig dbSinkConfig, Class<? extends Driver> driverClass) { this.conf = new HashMap<>(); conf.put(DBConfiguration.DRIVER_CLASS_PROPERTY, driverClass.getName()); conf.put(DBConfiguration.URL_PROPERTY, dbSinkConfig.connectionString); if (dbSinkConfig.user != null && dbSinkConfig.password != null) { conf.put(DBConfiguration.USERNAME_PROPERTY, dbSinkConfig.user); conf.put(DBConfiguration.PASSWORD_PROPERTY, dbSinkConfig.password); } conf.put(DBConfiguration.OUTPUT_TABLE_NAME_PROPERTY, dbSinkConfig.tableName); conf.put(DBConfiguration.OUTPUT_FIELD_NAMES_PROPERTY, dbSinkConfig.columns); } @Override public String getOutputFormatClassName() { return ETLDBOutputFormat.class.getName(); } @Override public Map<String, String> getOutputFormatConfiguration() { return conf; } } }
CDAP-4908 fix tablename description.
database-plugins/src/main/java/co/cask/hydrator/plugin/db/batch/sink/DBSink.java
CDAP-4908 fix tablename description.
<ide><path>atabase-plugins/src/main/java/co/cask/hydrator/plugin/db/batch/sink/DBSink.java <ide> @Description("Comma-separated list of columns in the specified table to export to.") <ide> public String columns; <ide> <del> @Description("Name of the database table to use as a source or a sink.") <add> @Description("Name of the database table to write to.") <ide> public String tableName; <ide> } <ide>
Java
apache-2.0
29d0b7e3b4ec4378caa6f501c5904b30a4ccdfd5
0
gpolitis/jitsi-videobridge,gpolitis/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,gpolitis/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,davidertel/jitsi-videobridge,davidertel/jitsi-videobridge,jitsi/jitsi-videobridge,davidertel/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge
/* * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge; import org.jitsi.impl.neomedia.*; import org.jitsi.impl.neomedia.rtp.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; import java.lang.ref.*; import java.util.*; import java.util.concurrent.*; /** * Implements a hack for * https://bugs.chromium.org/p/chromium/issues/detail?id=403710. The hack * injects black video key frames to unstuck the playback of audio for composite * media streams. * * @author George Politis */ public class LipSyncHack { /** * A byte array holding a black key frame. */ private static final byte[] KEY_FRAME_BUFFER = new byte[]{ -112, -28, 64, 52, -92, -96, 115, -79, -5, -111, 32, 79, -66, -34, 0, 1, 50, -63, 45, -124, -112, -32, -3, 48, -17, 32, 16, 18, 0, -99, 1, 42, 64, 1, -76, 0, 57, 75, 0, 27, 28, 36, 12, 44, 44, 68, -52, 36, 65, 36, 1, 18, 76, 28, -95, -109, 56, 60, 9, -105, 79, 38, -65, -37, -38, 32, -43, 37, -111, 4, -93, 68, 49, -67, -94, 13, -115, -45, 44, -110, 95, -61, 27, -38, 32, -40, -35, -104, 123, -13, -109, 95, -19, -19, 16, 108, 110, -48, 63, 34, 13, -115, -38, 18, -105, 63, 68, 49, -67, -95, -26, -101, 48, -9, -25, 38, -19, 9, 75, -98, -86, -35, 50, -23, -31, 37, -111, 11, 39, -110, 82, -108, 54, -115, -115, -38, 17, -60, 104, -122, 55, -79, 13, 55, 104, 74, 92, -3, 16, -58, -10, -120, 54, 55, 104, 74, 92, -4, 122, 109, 9, 75, -98, -86, -35, 50, -55, -103, -126, 82, -105, 63, 68, 49, -68, 89, -55, -69, 46, 0, -2, -78, 38, 50, -16, 47, -126, -99, -32, 50, 32, 67, 100, 0}; /** * A constant defining the maximum number of black key frames to send. */ private static final int MAX_KEY_FRAMES = 20; /** * The rate (in ms) at which we are to send black key frames. */ private static final long KEY_FRAME_RATE_MS = 33; /** * Wait for media for WAIT_MS before sending frames. */ private static final long WAIT_MS = 1000; /** * The <tt>Logger</tt> used by the <tt>LipSyncHack</tt> class and * its instances to print debug information. */ private static final Logger logger = Logger.getLogger(LipSyncHack.class); /** * The owner of this hack. */ private final Endpoint endpoint; /** * The executor service that takes care of black key frame scheduling * and injection. */ private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); /** * The remote audio SSRCs that have been accepted by the translator and * forwarded to the endpoint associated to this instance. */ private final List<Long> acceptedAudioSSRCs = new ArrayList<>(); /** * The remote video SSRCs that have been accepted by the translator and * forwarded to the endpoint associated to this instance. */ private final List<Long> acceptedVideoSSRCs = new ArrayList<>(); /** * A map that holds all the inject states. */ private final Map<Long, InjectState> states = new HashMap<>(); /** * Ctor. * * @param endpoint */ public LipSyncHack(Endpoint endpoint) { this.endpoint = endpoint; } /** * Notifies this instance that an audio packet is about to be written. * * @param data * @param buffer * @param offset * @param length * @param source */ public void onRTPTranslatorWillWriteAudio( boolean data, byte[] buffer, int offset, int length, Channel source) { if (!data) { return; } // Decide whether to trigger the hack or not. Long acceptedAudioSSRC = RawPacket.getSSRCAsLong(buffer, offset, length); // In order to minimize the synchronization overhead, we process // only the first data packet of a given RTP stream. // // XXX No synchronization is required to r/w the acceptedAudioSSRCs // because in the current architecture this method is called by a single // thread at the time. if (acceptedAudioSSRCs.contains(acceptedAudioSSRC)) { // We've already triggered the hack for this audio stream and its // associated video streams. return; } acceptedAudioSSRCs.add(acceptedAudioSSRC); // New audio stream. Trigger the hack for the associated video stream. List<RtpChannel> targetVideoChannels = endpoint.getChannels(MediaType.VIDEO); if (targetVideoChannels == null || targetVideoChannels.size() == 0) { return; } VideoChannel targetVC = (VideoChannel) targetVideoChannels.get(0); if (targetVC == null) { return; } List<RtpChannel> sourceVideoChannels = source.getEndpoint().getChannels(MediaType.VIDEO); if (sourceVideoChannels == null || sourceVideoChannels.size() == 0) { return; } VideoChannel sourceVC = (VideoChannel) sourceVideoChannels.get(0); if (sourceVC == null) { return; } // FIXME this will include rtx ssrcs and whatnot. for (int ssrc : sourceVC.getReceiveSSRCs()) { Long receiveVideoSSRC = ssrc & 0xffffffffl; synchronized (states) { if (states.containsKey(receiveVideoSSRC)) { // This receive video SSRC has already been processed. continue; } InjectState injectState = new InjectState( receiveVideoSSRC, targetVC.getStream(), true); states.put(receiveVideoSSRC, injectState); InjectTask injectTask = new InjectTask(injectState); injectTask.schedule(); } } } /** * Notifies this instance that a video packet is about to be written. */ public void onRTPTranslatorWillWriteVideo( boolean accept, boolean data, byte[] buffer, int offset, int length, Channel target) { if (!accept || !data) { return; } Long acceptedVideoSSRC = RawPacket.getSSRCAsLong(buffer, offset, length); // In order to minimize the synchronization overhead, we process // only the first data packet of a given RTP stream. // // XXX No synchronization is required to r/w the acceptedVideoSSRCs // because in the current architecture this method is called by a single // thread at the time. if (acceptedVideoSSRCs.contains(acceptedVideoSSRC)) { return; } acceptedVideoSSRCs.add(acceptedVideoSSRC); InjectState state; synchronized (states) { state = states.get(acceptedVideoSSRC); if (state == null) { // The hack has never been triggered for this stream. states.put(acceptedVideoSSRC, new InjectState(acceptedVideoSSRC, ((RtpChannel) target).getStream(), false)); return; } } synchronized (state) { // If we reached this point => state.active = true. state.active = false; if (state.numOfKeyframesSent == 0) { // No key frames have been sent for this SSRC => No need to // rewrite anything. return; } StreamRTPManager streamRTPManager = ((VideoChannel) target).getStream().getStreamRTPManager(); ResumableStreamRewriter rewriter = streamRTPManager.ssrcToRewriter.get(acceptedVideoSSRC); if (rewriter == null) { int seqnum = RawPacket.getSequenceNumber(buffer, offset, length); // Pretend we have dropped all the packets prior to the one // that's about to be written by the translator. int lastSeqnumDropped = RTPUtils.subtractNumber(seqnum, 1); int seqnumDelta = RTPUtils.subtractNumber( lastSeqnumDropped, state.numOfKeyframesSent); long timestamp = RawPacket.getTimestamp(buffer, offset, length); // Timestamps are calculated. long highestTimestampSent = state.numOfKeyframesSent * 3000; // Pretend we have dropped all the packets prior to the one // that's about to be written by the translator. long lastTimestampDropped = (timestamp - 3000) & 0xffffffffl; long timestampDelta = (lastTimestampDropped - highestTimestampSent) & 0xffffffff; rewriter = new ResumableStreamRewriter( state.numOfKeyframesSent, seqnumDelta, highestTimestampSent, timestampDelta); streamRTPManager.ssrcToRewriter.put(acceptedVideoSSRC, rewriter); } else { logger.warn("Could not initialize a sequence number rewriter" + "because one is already there."); } } } /** * */ class InjectTask implements Runnable { /** * The state for this injector. */ private final InjectState injectState; /** * The {@link ScheduledFuture} for this task. */ private ScheduledFuture<?> scheduledFuture; /** * Ctor. * * @param injectState */ public InjectTask(InjectState injectState) { this.injectState = injectState; } /** * {@inheritDoc} */ @Override public void run() { synchronized (injectState) { if (!injectState.active || injectState.numOfKeyframesSent >= MAX_KEY_FRAMES) { scheduledFuture.cancel(true); return; } MediaStream mediaStream = injectState.target.get(); if (mediaStream == null || !mediaStream.isStarted()) { logger.debug("Waiting for the media stream to become" + "available."); return; } try { injectState.numOfKeyframesSent++; // FIXME maybe grab from the write pool and copy the array? byte[] buf = KEY_FRAME_BUFFER.clone(); RawPacket keyframe = new RawPacket(buf, 0, buf.length); long timestamp = injectState.numOfKeyframesSent * 3000; keyframe.setSSRC(injectState.ssrc.intValue()); keyframe.setSequenceNumber( injectState.numOfKeyframesSent); keyframe.setTimestamp(timestamp); logger.debug("Injecting black key frame ssrc=" + injectState.ssrc + ", seqnum=" + injectState.numOfKeyframesSent + ", timestamp=" + timestamp); mediaStream.injectPacket(keyframe, true, null); } catch (TransmissionFailedException e) { injectState.numOfKeyframesSent--; logger.error(e); } } } /** * */ public void schedule() { this.scheduledFuture = scheduler.scheduleAtFixedRate( this, WAIT_MS , KEY_FRAME_RATE_MS, TimeUnit.MILLISECONDS); } } /** * */ static class InjectState { /** * The SSRC to send black key frames with. */ private final Long ssrc; /** * The */ private final WeakReference<MediaStream> target; /** * */ private boolean active; /** * The number of key frames that have already been sent. */ private int numOfKeyframesSent = 0; /** * Ctor. * * @param ssrc * @param target */ public InjectState(Long ssrc, MediaStream target, boolean active) { this.ssrc = ssrc; this.active = active; this.target = new WeakReference<>(target); } } }
src/main/java/org/jitsi/videobridge/LipSyncHack.java
/* * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge; import org.jitsi.impl.neomedia.*; import org.jitsi.impl.neomedia.rtp.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; import java.lang.ref.*; import java.util.*; import java.util.concurrent.*; /** * Implements a hack for * https://bugs.chromium.org/p/chromium/issues/detail?id=403710. The hack * injects black video key frames to unstuck the playback of audio for composite * media streams. * * @author George Politis */ public class LipSyncHack { /** * A byte array holding a black key frame. */ private static final byte[] KEY_FRAME_BUFFER = new byte[]{ -112, -28, 64, 52, -92, -96, 115, -79, -5, -111, 32, 79, -66, -34, 0, 1, 50, -63, 45, -124, -112, -32, -3, 48, -17, 32, 16, 18, 0, -99, 1, 42, 64, 1, -76, 0, 57, 75, 0, 27, 28, 36, 12, 44, 44, 68, -52, 36, 65, 36, 1, 18, 76, 28, -95, -109, 56, 60, 9, -105, 79, 38, -65, -37, -38, 32, -43, 37, -111, 4, -93, 68, 49, -67, -94, 13, -115, -45, 44, -110, 95, -61, 27, -38, 32, -40, -35, -104, 123, -13, -109, 95, -19, -19, 16, 108, 110, -48, 63, 34, 13, -115, -38, 18, -105, 63, 68, 49, -67, -95, -26, -101, 48, -9, -25, 38, -19, 9, 75, -98, -86, -35, 50, -23, -31, 37, -111, 11, 39, -110, 82, -108, 54, -115, -115, -38, 17, -60, 104, -122, 55, -79, 13, 55, 104, 74, 92, -3, 16, -58, -10, -120, 54, 55, 104, 74, 92, -4, 122, 109, 9, 75, -98, -86, -35, 50, -55, -103, -126, 82, -105, 63, 68, 49, -68, 89, -55, -69, 46, 0, -2, -78, 38, 50, -16, 47, -126, -99, -32, 50, 32, 67, 100, 0}; /** * A constant defining the maximum number of black key frames to send. */ private static final int MAX_KEY_FRAMES = 20; /** * The rate (in ms) at which we are to send black key frames. */ private static final long KEY_FRAME_RATE_MS = 33; /** * Wait for media for WAIT_MS before sending frames. */ private static final long WAIT_MS = 1000; /** * The <tt>Logger</tt> used by the <tt>LipSyncHack</tt> class and * its instances to print debug information. */ private static final Logger logger = Logger.getLogger(LipSyncHack.class); /** * The owner of this hack. */ private final Endpoint endpoint; /** * The executor service that takes care of black key frame scheduling * and injection. */ private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); /** * The remote audio SSRCs that have been accepted by the translator and * forwarded to the endpoint associated to this instance. */ private final List<Long> acceptedAudioSSRCs = new ArrayList<>(); /** * The remote video SSRCs that have been accepted by the translator and * forwarded to the endpoint associated to this instance. */ private final List<Long> acceptedVideoSSRCs = new ArrayList<>(); /** * A map that holds all the inject states. */ private final Map<Long, InjectState> states = new HashMap<>(); /** * Ctor. * * @param endpoint */ public LipSyncHack(Endpoint endpoint) { this.endpoint = endpoint; } /** * Notifies this instance that an audio packet is about to be written. * * @param data * @param buffer * @param offset * @param length * @param source */ public void onRTPTranslatorWillWriteAudio( boolean data, byte[] buffer, int offset, int length, Channel source) { if (!data) { return; } // Decide whether to trigger the hack or not. Long acceptedAudioSSRC = RawPacket.getSSRCAsLong(buffer, offset, length); // In order to minimize the synchronization overhead, we process // only the first data packet of a given RTP stream. // // XXX No synchronization is required to r/w the acceptedAudioSSRCs // because in the current architecture this method is called by a single // thread at the time. if (acceptedAudioSSRCs.contains(acceptedAudioSSRC)) { // We've already triggered the hack for this audio stream and its // associated video streams. return; } acceptedAudioSSRCs.add(acceptedAudioSSRC); // New audio stream. Trigger the hack for the associated video stream. List<RtpChannel> targetVideoChannels = endpoint.getChannels(MediaType.VIDEO); if (targetVideoChannels == null || targetVideoChannels.size() == 0) { return; } VideoChannel targetVC = (VideoChannel) targetVideoChannels.get(0); if (targetVC == null) { return; } List<RtpChannel> sourceVideoChannels = source.getEndpoint().getChannels(MediaType.VIDEO); if (sourceVideoChannels == null || sourceVideoChannels.size() == 0) { return; } VideoChannel sourceVC = (VideoChannel) sourceVideoChannels.get(0); if (sourceVC == null) { return; } // FIXME this will include rtx ssrcs and whatnot. for (int ssrc : sourceVC.getReceiveSSRCs()) { Long receiveVideoSSRC = ssrc & 0xffffffffl; synchronized (states) { if (states.containsKey(receiveVideoSSRC)) { // This receive video SSRC has already been processed. continue; } InjectState injectState = new InjectState( receiveVideoSSRC, targetVC.getStream(), true); states.put(receiveVideoSSRC, injectState); InjectTask injectTask = new InjectTask(injectState); injectTask.schedule(); } } } /** * Notifies this instance that a video packet is about to be written. */ public void onRTPTranslatorWillWriteVideo( boolean accept, boolean data, byte[] buffer, int offset, int length, Channel target) { if (!accept || !data) { return; } Long acceptedVideoSSRC = RawPacket.getSSRCAsLong(buffer, offset, length); // In order to minimize the synchronization overhead, we process // only the first data packet of a given RTP stream. // // XXX No synchronization is required to r/w the acceptedVideoSSRCs // because in the current architecture this method is called by a single // thread at the time. if (acceptedVideoSSRCs.contains(acceptedVideoSSRC)) { return; } acceptedVideoSSRCs.add(acceptedVideoSSRC); InjectState state; synchronized (states) { state = states.get(acceptedVideoSSRC); if (state == null) { // The hack has never been triggered for this stream. states.put(acceptedVideoSSRC, new InjectState(acceptedVideoSSRC, ((RtpChannel) target).getStream(), false)); return; } } synchronized (state) { // If we reached this point => state.active = true. state.active = false; if (state.numOfKeyframesSent == 0) { // No key frames have been sent for this SSRC => No need to // rewrite anything. return; } StreamRTPManager streamRTPManager = ((VideoChannel) target).getStream().getStreamRTPManager(); ResumableStreamRewriter rewriter = streamRTPManager.ssrcToRewriter.get(acceptedVideoSSRC); if (rewriter == null) { int seqnum = RawPacket.getSequenceNumber(buffer, offset, length); // Pretend we have dropped all the packets prior to the one // that's about to be written by the translator. int lastSeqnumDropped = RTPUtils.subtractNumber(seqnum, 1); int seqnumDelta = RTPUtils.subtractNumber( lastSeqnumDropped, state.numOfKeyframesSent); long timestamp = RawPacket.getTimestamp(buffer, offset, length); // Timestamps are calculated. long highestTimestampSent = state.numOfKeyframesSent * 3000; // Pretend we have dropped all the packets prior to the one // that's about to be written by the translator. long lastTimestampDropped = (timestamp - 3000) & 0xffffffffl; long timestampDelta = (lastTimestampDropped - highestTimestampSent) & 0xffffffff; rewriter = new ResumableStreamRewriter( state.numOfKeyframesSent, seqnumDelta, highestTimestampSent, timestampDelta); streamRTPManager.ssrcToRewriter.put(acceptedVideoSSRC, rewriter); } else { logger.warn("Could not initialize a sequence number rewriter" + "because one is already there."); } } } /** * */ class InjectTask implements Runnable { /** * The state for this injector. */ private final InjectState injectState; /** * The {@link ScheduledFuture} for this task. */ private ScheduledFuture<?> scheduledFuture; /** * Ctor. * * @param injectState */ public InjectTask(InjectState injectState) { this.injectState = injectState; } /** * {@inheritDoc} */ @Override public void run() { synchronized (injectState) { if (!injectState.active || injectState.numOfKeyframesSent++ >= MAX_KEY_FRAMES) { scheduledFuture.cancel(true); return; } MediaStream mediaStream = injectState.target.get(); if (mediaStream == null || !mediaStream.isStarted()) { logger.debug("Waiting for the media stream to become" + "available."); return; } try { // FIXME maybe grab from the write pool and copy the array? byte[] buf = KEY_FRAME_BUFFER.clone(); RawPacket keyframe = new RawPacket(buf, 0, buf.length); long timestamp = injectState.numOfKeyframesSent * 3000; keyframe.setSSRC(injectState.ssrc.intValue()); keyframe.setSequenceNumber( injectState.numOfKeyframesSent); keyframe.setTimestamp(timestamp); logger.debug("Injecting black key frame ssrc=" + injectState.ssrc + ", seqnum=" + injectState.numOfKeyframesSent + ", timestamp=" + timestamp); mediaStream.injectPacket(keyframe, true, null); } catch (TransmissionFailedException e) { injectState.numOfKeyframesSent--; logger.error(e); } } } /** * */ public void schedule() { this.scheduledFuture = scheduler.scheduleAtFixedRate( this, WAIT_MS , KEY_FRAME_RATE_MS, TimeUnit.MILLISECONDS); } } /** * */ static class InjectState { /** * The SSRC to send black key frames with. */ private final Long ssrc; /** * The */ private final WeakReference<MediaStream> target; /** * */ private boolean active; /** * The number of key frames that have already been sent. */ private int numOfKeyframesSent = 0; /** * Ctor. * * @param ssrc * @param target */ public InjectState(Long ssrc, MediaStream target, boolean active) { this.ssrc = ssrc; this.active = active; this.target = new WeakReference<>(target); } } }
Fixes a counter increment bug.
src/main/java/org/jitsi/videobridge/LipSyncHack.java
Fixes a counter increment bug.
<ide><path>rc/main/java/org/jitsi/videobridge/LipSyncHack.java <ide> synchronized (injectState) <ide> { <ide> if (!injectState.active <del> || injectState.numOfKeyframesSent++ >= MAX_KEY_FRAMES) <add> || injectState.numOfKeyframesSent >= MAX_KEY_FRAMES) <ide> { <ide> scheduledFuture.cancel(true); <ide> return; <ide> <ide> try <ide> { <add> injectState.numOfKeyframesSent++; <add> <ide> // FIXME maybe grab from the write pool and copy the array? <ide> byte[] buf = KEY_FRAME_BUFFER.clone(); <ide> RawPacket keyframe = new RawPacket(buf, 0, buf.length);
Java
bsd-3-clause
5836cab33f9dc728122144268a857eb79587e4b0
0
eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j
package org.eclipse.rdf4j.validation; import org.eclipse.rdf4j.IsolationLevel; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.impl.TreeModel; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.SailConnectionListener; import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.helpers.NotifyingSailConnectionWrapper; /** * Created by heshanjayasinghe on 4/23/17. */ public class SHACLSailConnection extends NotifyingSailConnectionWrapper implements SailConnectionListener { private SHACLSail sail; private boolean statementsRemoved; private Model newStatements; public SHACLSailConnection(SHACLSail shaclSail, NotifyingSailConnection connection) { super(connection); this.sail = shaclSail; } @Override public void begin(IsolationLevel level) throws SailException { super.begin(level); } @Override public void statementAdded(Statement statement) { if (statementsRemoved) { return; } if (newStatements == null) { newStatements = createModel(); } newStatements.add(statement); } @Override public void statementRemoved(Statement statement) { boolean removed = (newStatements != null) ? newStatements.remove(statement) : false; if (!removed) { statementsRemoved = true; newStatements = null; } } @Override public void commit() throws SailException { super.commit(); } protected Model createModel(){ return new TreeModel(); }; }
core/shacl/src/main/java/org/eclipse/rdf4j/validation/SHACLSailConnection.java
package org.eclipse.rdf4j.validation; import org.eclipse.rdf4j.IsolationLevel; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.SailConnectionListener; import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.helpers.NotifyingSailConnectionWrapper; import java.util.ArrayList; import java.util.List; /** * Created by heshanjayasinghe on 4/23/17. */ public class SHACLSailConnection extends NotifyingSailConnectionWrapper implements SailConnectionListener { private SHACLSail sail; List<Statement> addedStatement = new ArrayList<Statement>(); /** * Creates a new {@link org.eclipse.rdf4j.sail.helpers.NotifyingSailConnectionWrapper} object that wraps the supplied connection. * * @param wrappedCon */ public SHACLSailConnection(NotifyingSailConnection wrappedCon) { super(wrappedCon); } public SHACLSailConnection(SHACLSail shaclSail) { super(null); this.sail = shaclSail; } @Override public void begin(IsolationLevel level) throws SailException { super.begin(level); } @Override public void statementAdded(Statement statement) { addedStatement.add(statement); } @Override public void statementRemoved(Statement st) { } @Override public void commit() throws SailException { super.commit(); MoreDataCacheLayer getMoreDataCacheLayer = new MoreDataCacheLayer(this); sail.shapes.forEach(shape -> shape.validate(addedStatement, getMoreDataCacheLayer)); } public void addShaclViolationListener(ShaclViolationListener shaclViolationListener) { } }
add statement added and statement removed Signed-off-by: Heshan Jayasinghe <heshanjse> Signed-off-by: Håvard Ottestad <[email protected]>
core/shacl/src/main/java/org/eclipse/rdf4j/validation/SHACLSailConnection.java
add statement added and statement removed
<ide><path>ore/shacl/src/main/java/org/eclipse/rdf4j/validation/SHACLSailConnection.java <ide> package org.eclipse.rdf4j.validation; <ide> <del> <ide> import org.eclipse.rdf4j.IsolationLevel; <add>import org.eclipse.rdf4j.model.Model; <ide> import org.eclipse.rdf4j.model.Statement; <add>import org.eclipse.rdf4j.model.impl.TreeModel; <ide> import org.eclipse.rdf4j.sail.NotifyingSailConnection; <ide> import org.eclipse.rdf4j.sail.SailConnectionListener; <ide> import org.eclipse.rdf4j.sail.SailException; <ide> import org.eclipse.rdf4j.sail.helpers.NotifyingSailConnectionWrapper; <ide> <del>import java.util.ArrayList; <del>import java.util.List; <del> <ide> /** <ide> * Created by heshanjayasinghe on 4/23/17. <ide> */ <del>public class SHACLSailConnection extends NotifyingSailConnectionWrapper implements SailConnectionListener { <add>public class SHACLSailConnection extends NotifyingSailConnectionWrapper <add> implements SailConnectionListener { <ide> <del> private SHACLSail sail; <del> List<Statement> addedStatement = new ArrayList<Statement>(); <del> <del> /** <del> * Creates a new {@link org.eclipse.rdf4j.sail.helpers.NotifyingSailConnectionWrapper} object that wraps the supplied connection. <del> * <del> * @param wrappedCon <del> */ <add> private SHACLSail sail; <add> private boolean statementsRemoved; <add> private Model newStatements; <ide> <ide> <del> public SHACLSailConnection(NotifyingSailConnection wrappedCon) { <del> super(wrappedCon); <del> } <ide> <del> public SHACLSailConnection(SHACLSail shaclSail) { <del> super(null); <del> this.sail = shaclSail; <del> } <add> public SHACLSailConnection(SHACLSail shaclSail, NotifyingSailConnection connection) { <add> super(connection); <add> this.sail = shaclSail; <ide> <del> @Override <del> public void begin(IsolationLevel level) throws SailException { <del> super.begin(level); <del> } <add> } <ide> <del> @Override <del> public void statementAdded(Statement statement) { <del> addedStatement.add(statement); <del> } <add> @Override <add> public void begin(IsolationLevel level) throws SailException { <add> super.begin(level); <add> } <ide> <del> @Override <del> public void statementRemoved(Statement st) { <add> @Override <add> public void statementAdded(Statement statement) { <add> if (statementsRemoved) { <add> return; <add> } <ide> <del> } <add> if (newStatements == null) { <add> newStatements = createModel(); <add> } <add> newStatements.add(statement); <add> } <ide> <del> @Override <del> public void commit() throws SailException { <del> super.commit(); <del> MoreDataCacheLayer getMoreDataCacheLayer = new MoreDataCacheLayer(this); <del> sail.shapes.forEach(shape -> shape.validate(addedStatement, getMoreDataCacheLayer)); <del> } <ide> <del> public void addShaclViolationListener(ShaclViolationListener shaclViolationListener) { <add> @Override <add> public void statementRemoved(Statement statement) { <add> boolean removed = (newStatements != null) ? newStatements.remove(statement) : false; <add> if (!removed) { <add> statementsRemoved = true; <add> newStatements = null; <add> } <add> } <ide> <del> } <add> <add> <add> @Override <add> public void commit() throws SailException { <add> super.commit(); <add> <add> } <add> <add> protected Model createModel(){ <add> return new TreeModel(); <add> }; <add> <add> <ide> }
Java
agpl-3.0
ef77e4fbf46029a15a85241b308e2c2689f35004
0
smith750/kfs,quikkian-ua-devops/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,kuali/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,ua-eas/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,bhutchinson/kfs,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,smith750/kfs,kuali/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs
/* * Copyright 2005-2006 The Kuali Foundation. * * $Source: /opt/cvs/kfs/work/src/org/kuali/kfs/module/purap/businessobject/PurchaseOrderStatus.java,v $ * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.module.purap.bo; import java.util.LinkedHashMap; import org.kuali.core.bo.BusinessObjectBase; /** * @author Kuali Nervous System Team ([email protected]) */ public class PurchaseOrderStatus extends BusinessObjectBase { private String purchaseOrderStatusCode; private String purchaseOrderStatusDescription; private boolean dataObjectMaintenanceCodeActiveIndicator; /** * Default constructor. */ public PurchaseOrderStatus() { } /** * Gets the purchaseOrderStatusCode attribute. * * @return - Returns the purchaseOrderStatusCode * */ public String getPurchaseOrderStatusCode() { return purchaseOrderStatusCode; } /** * Sets the purchaseOrderStatusCode attribute. * * @param - purchaseOrderStatusCode The purchaseOrderStatusCode to set. * */ public void setPurchaseOrderStatusCode(String purchaseOrderStatusCode) { this.purchaseOrderStatusCode = purchaseOrderStatusCode; } /** * Gets the purchaseOrderStatusDescription attribute. * * @return - Returns the purchaseOrderStatusDescription * */ public String getPurchaseOrderStatusDescription() { return purchaseOrderStatusDescription; } /** * Sets the purchaseOrderStatusDescription attribute. * * @param - purchaseOrderStatusDescription The purchaseOrderStatusDescription to set. * */ public void setPurchaseOrderStatusDescription(String purchaseOrderStatusDescription) { this.purchaseOrderStatusDescription = purchaseOrderStatusDescription; } /** * Gets the dataObjectMaintenanceCodeActiveIndicator attribute. * * @return - Returns the dataObjectMaintenanceCodeActiveIndicator * */ public boolean getDataObjectMaintenanceCodeActiveIndicator() { return dataObjectMaintenanceCodeActiveIndicator; } /** * Sets the dataObjectMaintenanceCodeActiveIndicator attribute. * * @param - dataObjectMaintenanceCodeActiveIndicator The dataObjectMaintenanceCodeActiveIndicator to set. * */ public void setDataObjectMaintenanceCodeActiveIndicator(boolean dataObjectMaintenanceCodeActiveIndicator) { this.dataObjectMaintenanceCodeActiveIndicator = dataObjectMaintenanceCodeActiveIndicator; } /** * @see org.kuali.bo.BusinessObjectBase#toStringMapper() */ protected LinkedHashMap toStringMapper() { LinkedHashMap m = new LinkedHashMap(); m.put("purchaseOrderStatusCode", this.purchaseOrderStatusCode); return m; } }
work/src/org/kuali/kfs/module/purap/businessobject/PurchaseOrderStatus.java
/* * Copyright 2005-2006 The Kuali Foundation. * * $Source: /opt/cvs/kfs/work/src/org/kuali/kfs/module/purap/businessobject/PurchaseOrderStatus.java,v $ * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.module.purap.bo; import java.util.LinkedHashMap; import org.kuali.core.bo.BusinessObjectBase; /** * @author Kuali Nervous System Team ([email protected]) */ public class PurchaseOrderStatus extends BusinessObjectBase { private String purchaseOrderStatusCode; private String purchaseOrderStatusDescription; private String dataObjectMaintenanceCodeActiveIndicator; /** * Default constructor. */ public PurchaseOrderStatus() { } /** * Gets the purchaseOrderStatusCode attribute. * * @return - Returns the purchaseOrderStatusCode * */ public String getPurchaseOrderStatusCode() { return purchaseOrderStatusCode; } /** * Sets the purchaseOrderStatusCode attribute. * * @param - purchaseOrderStatusCode The purchaseOrderStatusCode to set. * */ public void setPurchaseOrderStatusCode(String purchaseOrderStatusCode) { this.purchaseOrderStatusCode = purchaseOrderStatusCode; } /** * Gets the purchaseOrderStatusDescription attribute. * * @return - Returns the purchaseOrderStatusDescription * */ public String getPurchaseOrderStatusDescription() { return purchaseOrderStatusDescription; } /** * Sets the purchaseOrderStatusDescription attribute. * * @param - purchaseOrderStatusDescription The purchaseOrderStatusDescription to set. * */ public void setPurchaseOrderStatusDescription(String purchaseOrderStatusDescription) { this.purchaseOrderStatusDescription = purchaseOrderStatusDescription; } /** * Gets the dataObjectMaintenanceCodeActiveIndicator attribute. * * @return - Returns the dataObjectMaintenanceCodeActiveIndicator * */ public String getDataObjectMaintenanceCodeActiveIndicator() { return dataObjectMaintenanceCodeActiveIndicator; } /** * Sets the dataObjectMaintenanceCodeActiveIndicator attribute. * * @param - dataObjectMaintenanceCodeActiveIndicator The dataObjectMaintenanceCodeActiveIndicator to set. * */ public void setDataObjectMaintenanceCodeActiveIndicator(String dataObjectMaintenanceCodeActiveIndicator) { this.dataObjectMaintenanceCodeActiveIndicator = dataObjectMaintenanceCodeActiveIndicator; } /** * @see org.kuali.bo.BusinessObjectBase#toStringMapper() */ protected LinkedHashMap toStringMapper() { LinkedHashMap m = new LinkedHashMap(); m.put("purchaseOrderStatusCode", this.purchaseOrderStatusCode); return m; } }
KULPURAP-251: Fixing the bug for search
work/src/org/kuali/kfs/module/purap/businessobject/PurchaseOrderStatus.java
KULPURAP-251: Fixing the bug for search
<ide><path>ork/src/org/kuali/kfs/module/purap/businessobject/PurchaseOrderStatus.java <ide> <ide> private String purchaseOrderStatusCode; <ide> private String purchaseOrderStatusDescription; <del> private String dataObjectMaintenanceCodeActiveIndicator; <add> private boolean dataObjectMaintenanceCodeActiveIndicator; <ide> <ide> /** <ide> * Default constructor. <ide> * @return - Returns the dataObjectMaintenanceCodeActiveIndicator <ide> * <ide> */ <del> public String getDataObjectMaintenanceCodeActiveIndicator() { <add> public boolean getDataObjectMaintenanceCodeActiveIndicator() { <ide> return dataObjectMaintenanceCodeActiveIndicator; <ide> } <ide> <ide> * @param - dataObjectMaintenanceCodeActiveIndicator The dataObjectMaintenanceCodeActiveIndicator to set. <ide> * <ide> */ <del> public void setDataObjectMaintenanceCodeActiveIndicator(String dataObjectMaintenanceCodeActiveIndicator) { <add> public void setDataObjectMaintenanceCodeActiveIndicator(boolean dataObjectMaintenanceCodeActiveIndicator) { <ide> this.dataObjectMaintenanceCodeActiveIndicator = dataObjectMaintenanceCodeActiveIndicator; <ide> } <ide>
Java
mit
eb8a1422b48c0ea5fa41d39475ab4ee4ca5f739b
0
chriskearney/creeper,Syncleus/AetherMUD,chriskearney/creeper,Dibasic/creeper,Syncleus/AetherMUD
package com.comandante.creeper.room; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.UnmodifiableIterator; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class MapMatrix { private final List<List<Integer>> matrix; private final Coords max; public MapMatrix(List<List<Integer>> matrix) { this.matrix = matrix; this.max = new Coords(matrix.size(), getMaxColumn()); } public int getMaxRow() { return max.row; } public int getMaxCol() { return max.column; } public java.util.Iterator<List<Integer>> getRows() { return matrix.iterator(); } public Coords getCoords(Integer roomId) { int row = 0; int column = 0; for (List<Integer> r : matrix) { for (Integer id : r) { if (id.equals(roomId)) { return new Coords(row, column); } else { column++; } } row++; column = 0; } return null; } public void setCoordsValue(Coords coords, Integer roomId) { if (coords.row < 0 || coords.column < 0 || coords.row >= max.row || coords.column >= max.column) { return; } matrix.get(coords.row).set(coords.column, roomId); } public Integer getNorth(Integer sourceId) { Coords coords = getCoords(sourceId); int rowNorth = coords.row - 1; int columnNorth = coords.column; return getId(rowNorth, columnNorth); } public Integer getSouth(Integer sourceId) { Coords coords = getCoords(sourceId); int rowSouth = coords.row + 1; int columnSouth = coords.column; return getId(rowSouth, columnSouth); } public Integer getEast(Integer sourceId) { Coords coords = getCoords(sourceId); int rowEast = coords.row; int columnEast = coords.column + 1; return getId(rowEast, columnEast); } public Integer getWest(Integer sourceId) { Coords coords = getCoords(sourceId); int rowWest = coords.row; int columnWest = coords.column - 1; return getId(rowWest, columnWest); } private Integer getId(int row, int column) { if (row < 0 || column < 0 || row >= max.row || column >= max.column) { return 0; } List<Integer> integers = matrix.get(row); return integers.get(column); } private int getMaxColumn() { int max = 0; for (List<Integer> list : matrix) { if (list.size() > max) { max = list.size(); } } return max; } public MapMatrix extractMatrix(Integer roomId, Coords newMax) { MapMatrix destinationMatrix = getBlankMatrix(newMax.row, newMax.column); Coords coords = getCoords(roomId); int rowDifference = destinationMatrix.getMaxRow() / 2 - coords.row; int columnDifference = destinationMatrix.getMaxCol() / 2 - coords.column; Iterator<List<Integer>> rows = getRows(); while (rows.hasNext()) { UnmodifiableIterator<Integer> ids = Iterators.filter(rows.next().iterator(), removeZeros()); while (ids.hasNext()) { Integer id = ids.next(); Coords currentMatrixCoords = getCoords(id); Coords destinationMatrixCoords = new Coords(currentMatrixCoords.row + rowDifference, currentMatrixCoords.column + columnDifference); destinationMatrix.setCoordsValue(destinationMatrixCoords, id); } } return destinationMatrix; } private Predicate<Integer> removeZeros(){ return new Predicate<Integer>() { @Override public boolean apply(Integer integer) { if (integer > 0) { return true; } return false; } }; } public static MapMatrix createMatrixFromCsv(String mapCSV) { List<String> rows = Arrays.asList(mapCSV.split("\n")); ArrayList<List<Integer>> rowsList = Lists.newArrayList(); for (String row : rows) { List<String> strings = Arrays.asList(row.split(",", -1)); List<Integer> data = Lists.newArrayList(); for (String string : strings) { if (!string.isEmpty()) { data.add(Integer.parseInt(string)); } else { data.add(0); } } rowsList.add(data); } return new MapMatrix(rowsList); } private static MapMatrix getBlankMatrix(int maxRows, int maxColumns) { List<List<Integer>> lists = Lists.newArrayList(); for (int i = 0; i <= maxRows; i++) { lists.add(Lists.<Integer>newArrayList()); } for (List<Integer> roomOpts : lists) { for (int i = 0; i <= maxColumns; i++) { roomOpts.add(0); } } return new MapMatrix(lists); } public String renderMap(Integer roomId) { StringBuilder sb = new StringBuilder(); Iterator<List<Integer>> rows = getRows(); while (rows.hasNext()) { List<Integer> next = rows.next(); Iterator<String> transform = Iterators.transform(next.iterator(), MapsManager.render(roomId)); while (transform.hasNext()) { String s = transform.next(); sb.append(s); } sb.append("\r\n"); } return sb.toString(); } }
src/main/java/com/comandante/creeper/room/MapMatrix.java
package com.comandante.creeper.room; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.UnmodifiableIterator; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class MapMatrix { private final List<List<Integer>> matrix; private final Coords max; public MapMatrix(List<List<Integer>> matrix) { this.matrix = matrix; this.max = new Coords(matrix.size(), getMaxColumn()); } public int getMaxRow() { return max.row; } public int getMaxCol() { return max.column; } public java.util.Iterator<List<Integer>> getRows() { return matrix.iterator(); } public Coords getCoords(Integer roomId) { int row = 0; int column = 0; for (List<Integer> r : matrix) { for (Integer id : r) { if (id.equals(roomId)) { return new Coords(row, column); } else { column++; } } row++; column = 0; } return null; } public void setCoordsValue(Coords coords, Integer roomId) { if (coords.row < 0 || coords.column < 0 || coords.row >= max.row || coords.column >= max.column) { return; } matrix.get(coords.row).set(coords.column, roomId); } public Integer getNorth(Integer sourceId) { Coords coords = getCoords(sourceId); int rowNorth = coords.row - 1; int columnNorth = coords.column; return getId(rowNorth, columnNorth); } public Integer getSouth(Integer sourceId) { Coords coords = getCoords(sourceId); int rowSouth = coords.row + 1; int columnSouth = coords.column; return getId(rowSouth, columnSouth); } public Integer getEast(Integer sourceId) { Coords coords = getCoords(sourceId); int rowEast = coords.row; int columnEast = coords.column + 1; return getId(rowEast, columnEast); } public Integer getWest(Integer sourceId) { Coords coords = getCoords(sourceId); int rowWest = coords.row; int columnWest = coords.column - 1; return getId(rowWest, columnWest); } private Integer getId(int row, int column) { if (row < 0 || column < 0 || row >= max.row || column >= max.column) { return 0; } List<Integer> integers = matrix.get(row); return integers.get(column); } private int getMaxColumn() { int max = 0; for (List<Integer> list : matrix) { if (list.size() > max) { max = list.size(); } } return max; } public MapMatrix extractMatrix(Integer roomId, Coords newMax) { MapMatrix destinationMatrix = getBlankMatrix(newMax.row, newMax.column); Coords coords = getCoords(roomId); int rowDifference = destinationMatrix.getMaxRow() / 2 - coords.row; int columnDifference = destinationMatrix.getMaxCol() / 2 - coords.column; Iterator<List<Integer>> rows = getRows(); while (rows.hasNext()) { Iterator<Integer> row = rows.next().iterator(); UnmodifiableIterator<Integer> filter = Iterators.filter(row, removeZeros()); while (filter.hasNext()) { Integer id = filter.next(); Coords currentMatrixCoords = getCoords(id); Coords destinationMatrixCoords = new Coords(currentMatrixCoords.row + rowDifference, currentMatrixCoords.column + columnDifference); destinationMatrix.setCoordsValue(destinationMatrixCoords, id); } } return destinationMatrix; } private Predicate<Integer> removeZeros(){ return new Predicate<Integer>() { @Override public boolean apply(Integer integer) { if (integer > 0) { return true; } return false; } }; } public static MapMatrix createMatrixFromCsv(String mapCSV) { List<String> rows = Arrays.asList(mapCSV.split("\n")); ArrayList<List<Integer>> rowsList = Lists.newArrayList(); for (String row : rows) { List<String> strings = Arrays.asList(row.split(",", -1)); List<Integer> data = Lists.newArrayList(); for (String string : strings) { if (!string.isEmpty()) { data.add(Integer.parseInt(string)); } else { data.add(0); } } rowsList.add(data); } return new MapMatrix(rowsList); } private static MapMatrix getBlankMatrix(int maxRows, int maxColumns) { List<List<Integer>> lists = Lists.newArrayList(); for (int i = 0; i <= maxRows; i++) { lists.add(Lists.<Integer>newArrayList()); } for (List<Integer> roomOpts : lists) { for (int i = 0; i <= maxColumns; i++) { roomOpts.add(0); } } return new MapMatrix(lists); } public String renderMap(Integer roomId) { StringBuilder sb = new StringBuilder(); Iterator<List<Integer>> rows = getRows(); while (rows.hasNext()) { List<Integer> next = rows.next(); Iterator<String> transform = Iterators.transform(next.iterator(), MapsManager.render(roomId)); while (transform.hasNext()) { String s = transform.next(); sb.append(s); } sb.append("\r\n"); } return sb.toString(); } }
done for real
src/main/java/com/comandante/creeper/room/MapMatrix.java
done for real
<ide><path>rc/main/java/com/comandante/creeper/room/MapMatrix.java <ide> int columnDifference = destinationMatrix.getMaxCol() / 2 - coords.column; <ide> Iterator<List<Integer>> rows = getRows(); <ide> while (rows.hasNext()) { <del> Iterator<Integer> row = rows.next().iterator(); <del> UnmodifiableIterator<Integer> filter = Iterators.filter(row, removeZeros()); <del> while (filter.hasNext()) { <del> Integer id = filter.next(); <add> UnmodifiableIterator<Integer> ids = Iterators.filter(rows.next().iterator(), removeZeros()); <add> while (ids.hasNext()) { <add> Integer id = ids.next(); <ide> Coords currentMatrixCoords = getCoords(id); <ide> Coords destinationMatrixCoords = new Coords(currentMatrixCoords.row + rowDifference, <ide> currentMatrixCoords.column + columnDifference);
Java
apache-2.0
d3de62f6a158231696d7a628b2e6bc9eef807012
0
pyamsoft/power-manager,pyamsoft/power-manager
/* * Copyright 2016 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.powermanager.app.main; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.databinding.DataBindingUtil; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.CheckResult; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.support.v7.preference.PreferenceManager; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.pyamsoft.powermanager.BuildConfig; import com.pyamsoft.powermanager.R; import com.pyamsoft.powermanager.app.airplane.AirplaneFragment; import com.pyamsoft.powermanager.app.bluetooth.BluetoothFragment; import com.pyamsoft.powermanager.app.data.DataFragment; import com.pyamsoft.powermanager.app.doze.DozeFragment; import com.pyamsoft.powermanager.app.logger.LoggerDialog; import com.pyamsoft.powermanager.app.overview.OverviewFragment; import com.pyamsoft.powermanager.app.service.ForegroundService; import com.pyamsoft.powermanager.app.settings.SettingsFragment; import com.pyamsoft.powermanager.app.sync.SyncFragment; import com.pyamsoft.powermanager.app.trigger.PowerTriggerFragment; import com.pyamsoft.powermanager.app.wifi.WifiFragment; import com.pyamsoft.powermanager.databinding.ActivityMainBinding; import com.pyamsoft.pydroid.about.AboutLibrariesFragment; import com.pyamsoft.pydroid.app.PersistLoader; import com.pyamsoft.pydroid.sec.TamperActivity; import com.pyamsoft.pydroid.rating.RatingDialog; import com.pyamsoft.pydroid.util.AppUtil; import com.pyamsoft.pydroid.util.PersistentCache; import java.util.HashMap; import java.util.Map; import timber.log.Timber; public class MainActivity extends TamperActivity implements MainPresenter.View { @NonNull private static final String KEY_PRESENTER = "key_main_presenter"; @NonNull private final Map<String, View> addedViewMap = new HashMap<>(); @Nullable private final Runnable longPressBackRunnable = Build.VERSION.SDK_INT < Build.VERSION_CODES.N ? null : this::handleBackLongPress; @Nullable private final Handler mainHandler = Build.VERSION.SDK_INT < Build.VERSION_CODES.N ? null : new Handler(Looper.getMainLooper()); @SuppressWarnings("WeakerAccess") MainPresenter presenter; private ActivityMainBinding binding; @ColorInt private int oldAppBarColor; @ColorInt private int oldStatusBarColor; @Nullable private ValueAnimator appBarAnimator; @Nullable private ValueAnimator statusBarAnimator; private long loadedKey; @SuppressWarnings("WeakerAccess") @CheckResult @ColorInt static int blendColors(@ColorInt int from, @ColorInt int to, float ratio) { final float inverseRatio = 1f - ratio; final float r = Color.red(to) * ratio + Color.red(from) * inverseRatio; final float g = Color.green(to) * ratio + Color.green(from) * inverseRatio; final float b = Color.blue(to) * ratio + Color.blue(from) * inverseRatio; return Color.rgb((int) r, (int) g, (int) b); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { setTheme(R.style.Theme_PowerManager_Light); super.onCreate(savedInstanceState); oldAppBarColor = ContextCompat.getColor(this, R.color.amber500); oldStatusBarColor = ContextCompat.getColor(this, R.color.amber700); setupPreferenceDefaults(); setupAppBar(); if (hasNoActiveFragment()) { loadOverviewFragment(); } loadedKey = PersistentCache.get() .load(KEY_PRESENTER, savedInstanceState, new PersistLoader.Callback<MainPresenter>() { @NonNull @Override public PersistLoader<MainPresenter> createLoader() { return new MainPresenterLoader(); } @Override public void onPersistentLoaded(@NonNull MainPresenter persist) { presenter = persist; } }); } @Override protected int bindActivityToView() { binding = DataBindingUtil.setContentView(this, R.layout.activity_main); return R.id.ad_view; } @Override protected void onDestroy() { super.onDestroy(); if (statusBarAnimator != null) { statusBarAnimator.cancel(); } if (appBarAnimator != null) { appBarAnimator.cancel(); } //noinspection Convert2streamapi for (final String key : addedViewMap.keySet()) { removeViewFromAppBar(key); } if (!isChangingConfigurations()) { PersistentCache.get().unload(loadedKey); } addedViewMap.clear(); binding.unbind(); } @Override public void onBackPressed() { final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStackImmediate(); } else { super.onBackPressed(); } } private void setupPreferenceDefaults() { PreferenceManager.setDefaultValues(this, R.xml.preferences, false); PreferenceManager.setDefaultValues(this, R.xml.manage_wifi, false); PreferenceManager.setDefaultValues(this, R.xml.manage_data, false); PreferenceManager.setDefaultValues(this, R.xml.manage_bluetooth, false); PreferenceManager.setDefaultValues(this, R.xml.manage_sync, false); PreferenceManager.setDefaultValues(this, R.xml.periodic_wifi, false); PreferenceManager.setDefaultValues(this, R.xml.periodic_data, false); PreferenceManager.setDefaultValues(this, R.xml.periodic_bluetooth, false); PreferenceManager.setDefaultValues(this, R.xml.periodic_sync, false); PreferenceManager.setDefaultValues(this, R.xml.manage_doze, false); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { boolean handled; switch (item.getItemId()) { case android.R.id.home: onBackPressed(); handled = true; break; default: handled = false; } return handled || super.onOptionsItemSelected(item); } private void setupAppBar() { setSupportActionBar(binding.mainToolbar); binding.mainToolbar.setTitle(getString(R.string.app_name)); } @CheckResult private boolean hasNoActiveFragment() { final FragmentManager fragmentManager = getSupportFragmentManager(); return fragmentManager.findFragmentByTag(OverviewFragment.TAG) == null && fragmentManager.findFragmentByTag(WifiFragment.TAG) == null && fragmentManager.findFragmentByTag(DataFragment.TAG) == null && fragmentManager.findFragmentByTag(BluetoothFragment.TAG) == null && fragmentManager.findFragmentByTag(SyncFragment.TAG) == null && fragmentManager.findFragmentByTag(PowerTriggerFragment.TAG) == null && fragmentManager.findFragmentByTag(DozeFragment.TAG) == null && fragmentManager.findFragmentByTag(AirplaneFragment.TAG) == null && fragmentManager.findFragmentByTag(SettingsFragment.TAG) == null && fragmentManager.findFragmentByTag(AboutLibrariesFragment.TAG) == null; } private void loadOverviewFragment() { final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag(OverviewFragment.TAG) == null) { fragmentManager.beginTransaction() .replace(R.id.main_container, new OverviewFragment(), OverviewFragment.TAG) .commitNow(); } } @Override protected void onPostResume() { super.onPostResume(); RatingDialog.showRatingDialog(this, this); } @NonNull @Override protected String getSafePackageName() { return "com.pyamsoft.powermanager"; } public void addViewToAppBar(@NonNull String tag, @NonNull View view) { if (addedViewMap.containsKey(tag)) { Timber.w("AppBar already has view with this tag: %s", tag); removeViewFromAppBar(tag); } Timber.d("Add view to map with tag: %s", tag); addedViewMap.put(tag, view); binding.mainAppbar.addView(view); } public void removeViewFromAppBar(@NonNull String tag) { if (addedViewMap.containsKey(tag)) { Timber.d("Remove tag from map: %s", tag); final View viewToRemove = addedViewMap.remove(tag); if (viewToRemove == null) { Timber.e("View to remove was NULL for tag: %s", tag); } else { binding.mainAppbar.removeView(viewToRemove); } } else { Timber.e("Viewmap does not contain a view for tag: %s", tag); } } @NonNull @Override protected String[] getChangeLogLines() { final String line1 = "BUGFIX: General stability improvements"; final String line2 = "BUGFIX: Power Trigger improvements"; return new String[] { line1, line2 }; } @NonNull @Override protected String getVersionName() { return BuildConfig.VERSION_NAME; } @Override public int getApplicationIcon() { return R.mipmap.ic_launcher; } @NonNull @Override public String provideApplicationName() { return "Power Manager"; } @Override public int getCurrentApplicationVersion() { return BuildConfig.VERSION_CODE; } /** * Color the app bar using a nice blending animation */ public void colorAppBar(@ColorRes int color, long duration) { final int newColor = ContextCompat.getColor(this, color); Timber.d("Blend appbar color"); blendAppBar(oldAppBarColor, newColor, duration); oldAppBarColor = newColor; } /** * Runs a blending animation on the app bar color */ private void blendAppBar(int fromColor, int toColor, long duration) { if (appBarAnimator != null) { appBarAnimator.cancel(); } appBarAnimator = ValueAnimator.ofFloat(0, 1); appBarAnimator.addUpdateListener(animation -> { // Use animation position to blend colors. final float position = animation.getAnimatedFraction(); // Apply blended color to the status bar. final int blended = blendColors(fromColor, toColor, position); // To color the entire app bar binding.mainAppbar.setBackgroundColor(blended); }); appBarAnimator.setDuration(duration).start(); } /** * Colors the status bar using a nice blending animation */ public void colorStatusBar(@ColorRes int colorDark, long duration) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { final int newColor = ContextCompat.getColor(this, colorDark); Timber.d("Blend statusbar color"); blendStatusBar(oldStatusBarColor, newColor, duration); oldStatusBarColor = newColor; } } /** * Runs a blending animation on the status bar color */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void blendStatusBar(@ColorInt int fromColor, @ColorInt int toColor, long duration) { if (statusBarAnimator != null) { statusBarAnimator.cancel(); } statusBarAnimator = ValueAnimator.ofFloat(0, 1); statusBarAnimator.addUpdateListener(animation -> { // Use animation position to blend colors. final float position = animation.getAnimatedFraction(); // Apply blended color to the status bar. final int blended = blendColors(fromColor, toColor, position); getWindow().setStatusBarColor(blended); }); statusBarAnimator.setDuration(duration).start(); } @Override public void onServiceEnabledWhenOpen() { Timber.d("Should refresh service when opened"); ForegroundService.start(getApplicationContext()); } @Override public void explainRootRequirement() { // TODO explain with dialog Toast.makeText(getApplicationContext(), "Root is required for certain functions like Doze and Airplane mode", Toast.LENGTH_SHORT) .show(); } @Override protected void onStart() { super.onStart(); presenter.bindView(this); } @Override protected void onStop() { super.onStop(); presenter.unbindView(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); PersistentCache.get().saveKey(outState, KEY_PRESENTER, loadedKey); } // https://github.com/mozilla/gecko-dev/blob/master/mobile/android/base/java/org/mozilla/gecko/BrowserApp.java @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && keyCode == KeyEvent.KEYCODE_BACK) { if (mainHandler != null && longPressBackRunnable != null) { mainHandler.removeCallbacksAndMessages(null); mainHandler.postDelayed(longPressBackRunnable, 1400L); } } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N && keyCode == KeyEvent.KEYCODE_BACK) { if (handleBackLongPress()) { return true; } } return super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && keyCode == KeyEvent.KEYCODE_BACK) { if (mainHandler != null) { mainHandler.removeCallbacksAndMessages(null); } } return super.onKeyUp(keyCode, event); } @SuppressWarnings("WeakerAccess") boolean handleBackLongPress() { final String tag = "logger_dialog"; final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag(tag) == null) { Timber.d("Show logger dialog"); AppUtil.guaranteeSingleDialogFragment(getSupportFragmentManager(), new LoggerDialog(), tag); return true; } else { Timber.w("Logger dialog is already shown"); return false; } } }
src/main/java/com/pyamsoft/powermanager/app/main/MainActivity.java
/* * Copyright 2016 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.powermanager.app.main; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.databinding.DataBindingUtil; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.CheckResult; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.support.v7.preference.PreferenceManager; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.pyamsoft.powermanager.BuildConfig; import com.pyamsoft.powermanager.R; import com.pyamsoft.powermanager.app.airplane.AirplaneFragment; import com.pyamsoft.powermanager.app.bluetooth.BluetoothFragment; import com.pyamsoft.powermanager.app.data.DataFragment; import com.pyamsoft.powermanager.app.doze.DozeFragment; import com.pyamsoft.powermanager.app.logger.LoggerDialog; import com.pyamsoft.powermanager.app.overview.OverviewFragment; import com.pyamsoft.powermanager.app.service.ForegroundService; import com.pyamsoft.powermanager.app.settings.SettingsFragment; import com.pyamsoft.powermanager.app.sync.SyncFragment; import com.pyamsoft.powermanager.app.trigger.PowerTriggerFragment; import com.pyamsoft.powermanager.app.wifi.WifiFragment; import com.pyamsoft.powermanager.databinding.ActivityMainBinding; import com.pyamsoft.pydroid.about.AboutLibrariesFragment; import com.pyamsoft.pydroid.app.PersistLoader; import com.pyamsoft.pydroid.sec.TamperActivity; import com.pyamsoft.pydroid.support.RatingDialog; import com.pyamsoft.pydroid.util.AppUtil; import com.pyamsoft.pydroid.util.PersistentCache; import java.util.HashMap; import java.util.Map; import timber.log.Timber; public class MainActivity extends TamperActivity implements MainPresenter.View { @NonNull private static final String KEY_PRESENTER = "key_main_presenter"; @NonNull private final Map<String, View> addedViewMap = new HashMap<>(); @Nullable private final Runnable longPressBackRunnable = Build.VERSION.SDK_INT < Build.VERSION_CODES.N ? null : this::handleBackLongPress; @Nullable private final Handler mainHandler = Build.VERSION.SDK_INT < Build.VERSION_CODES.N ? null : new Handler(Looper.getMainLooper()); @SuppressWarnings("WeakerAccess") MainPresenter presenter; private ActivityMainBinding binding; @ColorInt private int oldAppBarColor; @ColorInt private int oldStatusBarColor; @Nullable private ValueAnimator appBarAnimator; @Nullable private ValueAnimator statusBarAnimator; private long loadedKey; @SuppressWarnings("WeakerAccess") @CheckResult @ColorInt static int blendColors(@ColorInt int from, @ColorInt int to, float ratio) { final float inverseRatio = 1f - ratio; final float r = Color.red(to) * ratio + Color.red(from) * inverseRatio; final float g = Color.green(to) * ratio + Color.green(from) * inverseRatio; final float b = Color.blue(to) * ratio + Color.blue(from) * inverseRatio; return Color.rgb((int) r, (int) g, (int) b); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { setTheme(R.style.Theme_PowerManager_Light); super.onCreate(savedInstanceState); oldAppBarColor = ContextCompat.getColor(this, R.color.amber500); oldStatusBarColor = ContextCompat.getColor(this, R.color.amber700); setupPreferenceDefaults(); setupAppBar(); if (hasNoActiveFragment()) { loadOverviewFragment(); } loadedKey = PersistentCache.get() .load(KEY_PRESENTER, savedInstanceState, new PersistLoader.Callback<MainPresenter>() { @NonNull @Override public PersistLoader<MainPresenter> createLoader() { return new MainPresenterLoader(); } @Override public void onPersistentLoaded(@NonNull MainPresenter persist) { presenter = persist; } }); } @Override protected int bindActivityToView() { binding = DataBindingUtil.setContentView(this, R.layout.activity_main); return R.id.ad_view; } @Override protected void onDestroy() { super.onDestroy(); if (statusBarAnimator != null) { statusBarAnimator.cancel(); } if (appBarAnimator != null) { appBarAnimator.cancel(); } //noinspection Convert2streamapi for (final String key : addedViewMap.keySet()) { removeViewFromAppBar(key); } if (!isChangingConfigurations()) { PersistentCache.get().unload(loadedKey); } addedViewMap.clear(); binding.unbind(); } @Override public void onBackPressed() { final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStackImmediate(); } else { super.onBackPressed(); } } private void setupPreferenceDefaults() { PreferenceManager.setDefaultValues(this, R.xml.preferences, false); PreferenceManager.setDefaultValues(this, R.xml.manage_wifi, false); PreferenceManager.setDefaultValues(this, R.xml.manage_data, false); PreferenceManager.setDefaultValues(this, R.xml.manage_bluetooth, false); PreferenceManager.setDefaultValues(this, R.xml.manage_sync, false); PreferenceManager.setDefaultValues(this, R.xml.periodic_wifi, false); PreferenceManager.setDefaultValues(this, R.xml.periodic_data, false); PreferenceManager.setDefaultValues(this, R.xml.periodic_bluetooth, false); PreferenceManager.setDefaultValues(this, R.xml.periodic_sync, false); PreferenceManager.setDefaultValues(this, R.xml.manage_doze, false); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { boolean handled; switch (item.getItemId()) { case android.R.id.home: onBackPressed(); handled = true; break; default: handled = false; } return handled || super.onOptionsItemSelected(item); } private void setupAppBar() { setSupportActionBar(binding.mainToolbar); binding.mainToolbar.setTitle(getString(R.string.app_name)); } @CheckResult private boolean hasNoActiveFragment() { final FragmentManager fragmentManager = getSupportFragmentManager(); return fragmentManager.findFragmentByTag(OverviewFragment.TAG) == null && fragmentManager.findFragmentByTag(WifiFragment.TAG) == null && fragmentManager.findFragmentByTag(DataFragment.TAG) == null && fragmentManager.findFragmentByTag(BluetoothFragment.TAG) == null && fragmentManager.findFragmentByTag(SyncFragment.TAG) == null && fragmentManager.findFragmentByTag(PowerTriggerFragment.TAG) == null && fragmentManager.findFragmentByTag(DozeFragment.TAG) == null && fragmentManager.findFragmentByTag(AirplaneFragment.TAG) == null && fragmentManager.findFragmentByTag(SettingsFragment.TAG) == null && fragmentManager.findFragmentByTag(AboutLibrariesFragment.TAG) == null; } private void loadOverviewFragment() { final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag(OverviewFragment.TAG) == null) { fragmentManager.beginTransaction() .replace(R.id.main_container, new OverviewFragment(), OverviewFragment.TAG) .commitNow(); } } @Override protected void onPostResume() { super.onPostResume(); RatingDialog.showRatingDialog(this, this); } @NonNull @Override protected String getSafePackageName() { return "com.pyamsoft.powermanager"; } public void addViewToAppBar(@NonNull String tag, @NonNull View view) { if (addedViewMap.containsKey(tag)) { Timber.w("AppBar already has view with this tag: %s", tag); removeViewFromAppBar(tag); } Timber.d("Add view to map with tag: %s", tag); addedViewMap.put(tag, view); binding.mainAppbar.addView(view); } public void removeViewFromAppBar(@NonNull String tag) { if (addedViewMap.containsKey(tag)) { Timber.d("Remove tag from map: %s", tag); final View viewToRemove = addedViewMap.remove(tag); if (viewToRemove == null) { Timber.e("View to remove was NULL for tag: %s", tag); } else { binding.mainAppbar.removeView(viewToRemove); } } else { Timber.e("Viewmap does not contain a view for tag: %s", tag); } } @NonNull @Override protected String[] getChangeLogLines() { final String line1 = "BUGFIX: General stability improvements"; final String line2 = "BUGFIX: Power Trigger improvements"; return new String[] { line1, line2 }; } @NonNull @Override protected String getVersionName() { return BuildConfig.VERSION_NAME; } @Override public int getApplicationIcon() { return R.mipmap.ic_launcher; } @NonNull @Override public String provideApplicationName() { return "Power Manager"; } @Override public int getCurrentApplicationVersion() { return BuildConfig.VERSION_CODE; } /** * Color the app bar using a nice blending animation */ public void colorAppBar(@ColorRes int color, long duration) { final int newColor = ContextCompat.getColor(this, color); Timber.d("Blend appbar color"); blendAppBar(oldAppBarColor, newColor, duration); oldAppBarColor = newColor; } /** * Runs a blending animation on the app bar color */ private void blendAppBar(int fromColor, int toColor, long duration) { if (appBarAnimator != null) { appBarAnimator.cancel(); } appBarAnimator = ValueAnimator.ofFloat(0, 1); appBarAnimator.addUpdateListener(animation -> { // Use animation position to blend colors. final float position = animation.getAnimatedFraction(); // Apply blended color to the status bar. final int blended = blendColors(fromColor, toColor, position); // To color the entire app bar binding.mainAppbar.setBackgroundColor(blended); }); appBarAnimator.setDuration(duration).start(); } /** * Colors the status bar using a nice blending animation */ public void colorStatusBar(@ColorRes int colorDark, long duration) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { final int newColor = ContextCompat.getColor(this, colorDark); Timber.d("Blend statusbar color"); blendStatusBar(oldStatusBarColor, newColor, duration); oldStatusBarColor = newColor; } } /** * Runs a blending animation on the status bar color */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void blendStatusBar(@ColorInt int fromColor, @ColorInt int toColor, long duration) { if (statusBarAnimator != null) { statusBarAnimator.cancel(); } statusBarAnimator = ValueAnimator.ofFloat(0, 1); statusBarAnimator.addUpdateListener(animation -> { // Use animation position to blend colors. final float position = animation.getAnimatedFraction(); // Apply blended color to the status bar. final int blended = blendColors(fromColor, toColor, position); getWindow().setStatusBarColor(blended); }); statusBarAnimator.setDuration(duration).start(); } @Override public void onServiceEnabledWhenOpen() { Timber.d("Should refresh service when opened"); ForegroundService.start(getApplicationContext()); } @Override public void explainRootRequirement() { // TODO explain with dialog Toast.makeText(getApplicationContext(), "Root is required for certain functions like Doze and Airplane mode", Toast.LENGTH_SHORT) .show(); } @Override protected void onStart() { super.onStart(); presenter.bindView(this); } @Override protected void onStop() { super.onStop(); presenter.unbindView(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); PersistentCache.get().saveKey(outState, KEY_PRESENTER, loadedKey); } // https://github.com/mozilla/gecko-dev/blob/master/mobile/android/base/java/org/mozilla/gecko/BrowserApp.java @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && keyCode == KeyEvent.KEYCODE_BACK) { if (mainHandler != null && longPressBackRunnable != null) { mainHandler.removeCallbacksAndMessages(null); mainHandler.postDelayed(longPressBackRunnable, 1400L); } } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N && keyCode == KeyEvent.KEYCODE_BACK) { if (handleBackLongPress()) { return true; } } return super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && keyCode == KeyEvent.KEYCODE_BACK) { if (mainHandler != null) { mainHandler.removeCallbacksAndMessages(null); } } return super.onKeyUp(keyCode, event); } @SuppressWarnings("WeakerAccess") boolean handleBackLongPress() { final String tag = "logger_dialog"; final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag(tag) == null) { Timber.d("Show logger dialog"); AppUtil.guaranteeSingleDialogFragment(getSupportFragmentManager(), new LoggerDialog(), tag); return true; } else { Timber.w("Logger dialog is already shown"); return false; } } }
Update to latest pydroid
src/main/java/com/pyamsoft/powermanager/app/main/MainActivity.java
Update to latest pydroid
<ide><path>rc/main/java/com/pyamsoft/powermanager/app/main/MainActivity.java <ide> import com.pyamsoft.pydroid.about.AboutLibrariesFragment; <ide> import com.pyamsoft.pydroid.app.PersistLoader; <ide> import com.pyamsoft.pydroid.sec.TamperActivity; <del>import com.pyamsoft.pydroid.support.RatingDialog; <add>import com.pyamsoft.pydroid.rating.RatingDialog; <ide> import com.pyamsoft.pydroid.util.AppUtil; <ide> import com.pyamsoft.pydroid.util.PersistentCache; <ide> import java.util.HashMap;
Java
apache-2.0
45ac4cec61b79977c14179309b9a4d7737c373c1
0
sebastiansokolowski/ReservationSystem-BJ,sebastiansokolowski/ReservationSystem-BJ
package bj.pranie.controller; import bj.pranie.dao.RoomDao; import bj.pranie.service.UserAuthenticatedService; import bj.pranie.service.UserServiceImpl; import bj.pranie.entity.Room; import bj.pranie.entity.User; import bj.pranie.model.UserRegistrationModel; import bj.pranie.model.UserSettingsModel; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; /** * Created by Sebastian Sokolowski on 10.08.16. */ @Controller @RequestMapping("/user") public class UserController { private final static int TOKENS_AT_START = 2; @Autowired private RoomDao roomDao; @Autowired private UserServiceImpl userService; @Autowired private UserAuthenticatedService userAuthenticatedService; @RequestMapping(value = "/settings", method = RequestMethod.GET) public String userSettings(Model model) { model.addAttribute("userSettingsModel", new UserSettingsModel()); model.addAttribute("user", userAuthenticatedService.getAuthenticatedUser()); return "user/settings"; } @RequestMapping(value = "/settings", method = RequestMethod.POST) public ModelAndView saveUserSettings(@ModelAttribute("userSettingsModel") @Valid UserSettingsModel userSettingsModel, BindingResult bindingResult) { ModelAndView modelAndView = new ModelAndView(); User user = (User) userAuthenticatedService.getAuthenticatedUser(); if (!userSettingsModel.getPassword().equals(user.getPassword())) { bindingResult.rejectValue("password", "error.userRegistrationModel", "Podane hasło jest nieprawidłowe."); } User userExist; if (userSettingsModel.isSetNewUsername()) { userExist = userService.findByUsername(userSettingsModel.getNewUsername()); if (userExist != null) { bindingResult.rejectValue("newUsername", "error.userSettingsModel", "Podana nazwa użytkownika istnieje już w bazie."); } } if (userSettingsModel.isSetNewEmail()) { userExist = userService.findByEmail(userSettingsModel.getNewEmail()); if (userExist != null) { bindingResult.rejectValue("newEmail", "error.userSettingsModel", "Podany adres email istnieje już w bazie."); } } if (userSettingsModel.isSetNewPassword()) { if (!userSettingsModel.getNewPassword().equals(userSettingsModel.getNewPasswordRepeat())) { bindingResult.rejectValue("newPasswordRepeat", "error.userRegistrationModel", "Powtórzone hasło jest różne od wpisanego."); } } if (!bindingResult.hasErrors()) { if (userSettingsModel.isSetNewUsername()) { user.setUsername(userSettingsModel.getNewUsername()); } if (userSettingsModel.isSetNewEmail()) { user.setEmail(userSettingsModel.getNewEmail()); } if (userSettingsModel.isSetNewName()) { user.setName(userSettingsModel.getNewName()); } if (userSettingsModel.isSetNewPassword()) { user.setPassword(userSettingsModel.getNewPassword()); } userService.save(user); modelAndView.addObject("successMessage", "Zmiany zostały zachowane pomyślnie."); } modelAndView.addObject("user", userAuthenticatedService.getAuthenticatedUser()); modelAndView.setViewName("user/settings"); return modelAndView; } @RequestMapping(value = "/registration", method = RequestMethod.GET) public String registrationForm(Model model) { model.addAttribute("userRegistrationModel", new UserRegistrationModel()); model.addAttribute("rooms", roomDao.findAll()); return "user/registration"; } @RequestMapping(value = "/registration", method = RequestMethod.POST) public ModelAndView createUser(@ModelAttribute("userRegistrationModel") @Valid UserRegistrationModel userRegistrationModel, BindingResult bindingResult) { ModelAndView modelAndView = new ModelAndView(); User userExist = userService.findByEmail(userRegistrationModel.getEmail()); if (userExist != null) { bindingResult.rejectValue("email", "error.userRegistrationModel", "Podany adres email istnieje już w bazie."); } userExist = userService.findByUsername(userRegistrationModel.getUsername()); if (userExist != null) { bindingResult.rejectValue("username", "error.userRegistrationModel", "Podana nazwa użytkownika istnieje już w bazie."); } if (!userRegistrationModel.getPassword().equals(userRegistrationModel.getPasswordRepeat())) { bindingResult.rejectValue("passwordRepeat", "error.userRegistrationModel", "Powtórzone hasło jest różne od wpisanego."); } Room room = roomDao.findOne(userRegistrationModel.getRoomId()); if (room == null) { bindingResult.rejectValue("roomId", "error.userRegistrationModel", "Wybierz pokój z listy."); } else if (userService.findByRoom(room).size() >= room.getPeoples()) { bindingResult.rejectValue("roomId", "error.userRegistrationModel", "Brak miejsca w wybranym pokoju."); } if (!bindingResult.hasErrors()) { ModelMapper modelMapper = new ModelMapper(); User user = modelMapper.map(userRegistrationModel, User.class); user.setTokens(TOKENS_AT_START); userService.save(user); modelAndView.addObject("successMessage", "Rejestracja przebiegła pomyślnie."); } modelAndView.addObject("rooms", roomDao.findAll()); modelAndView.setViewName("user/registration"); return modelAndView; } }
src/main/java/bj/pranie/controller/UserController.java
package bj.pranie.controller; import bj.pranie.dao.RoomDao; import bj.pranie.service.UserAuthenticatedService; import bj.pranie.service.UserServiceImpl; import bj.pranie.entity.Room; import bj.pranie.entity.User; import bj.pranie.model.UserRegistrationModel; import bj.pranie.model.UserSettingsModel; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; /** * Created by Sebastian Sokolowski on 10.08.16. */ @Controller @RequestMapping("/user") public class UserController { @Autowired private RoomDao roomDao; @Autowired private UserServiceImpl userService; @Autowired private UserAuthenticatedService userAuthenticatedService; @RequestMapping(value = "/settings", method = RequestMethod.GET) public String userSettings(Model model) { model.addAttribute("userSettingsModel", new UserSettingsModel()); model.addAttribute("user", userAuthenticatedService.getAuthenticatedUser()); return "user/settings"; } @RequestMapping(value = "/settings", method = RequestMethod.POST) public ModelAndView saveUserSettings(@ModelAttribute("userSettingsModel") @Valid UserSettingsModel userSettingsModel, BindingResult bindingResult) { ModelAndView modelAndView = new ModelAndView(); User user = (User) userAuthenticatedService.getAuthenticatedUser(); if (!userSettingsModel.getPassword().equals(user.getPassword())) { bindingResult.rejectValue("password", "error.userRegistrationModel", "Podane hasło jest nieprawidłowe."); } User userExist; if (userSettingsModel.isSetNewUsername()) { userExist = userService.findByUsername(userSettingsModel.getNewUsername()); if (userExist != null) { bindingResult.rejectValue("newUsername", "error.userSettingsModel", "Podana nazwa użytkownika istnieje już w bazie."); } } if (userSettingsModel.isSetNewEmail()) { userExist = userService.findByEmail(userSettingsModel.getNewEmail()); if (userExist != null) { bindingResult.rejectValue("newEmail", "error.userSettingsModel", "Podany adres email istnieje już w bazie."); } } if (userSettingsModel.isSetNewPassword()) { if (!userSettingsModel.getNewPassword().equals(userSettingsModel.getNewPasswordRepeat())) { bindingResult.rejectValue("newPasswordRepeat", "error.userRegistrationModel", "Powtórzone hasło jest różne od wpisanego."); } } if (!bindingResult.hasErrors()) { if (userSettingsModel.isSetNewUsername()) { user.setUsername(userSettingsModel.getNewUsername()); } if (userSettingsModel.isSetNewEmail()) { user.setEmail(userSettingsModel.getNewEmail()); } if (userSettingsModel.isSetNewName()) { user.setName(userSettingsModel.getNewName()); } if (userSettingsModel.isSetNewPassword()) { user.setPassword(userSettingsModel.getNewPassword()); } userService.save(user); modelAndView.addObject("successMessage", "Zmiany zostały zachowane pomyślnie."); } modelAndView.addObject("user", userAuthenticatedService.getAuthenticatedUser()); modelAndView.setViewName("user/settings"); return modelAndView; } @RequestMapping(value = "/registration", method = RequestMethod.GET) public String registrationForm(Model model) { model.addAttribute("userRegistrationModel", new UserRegistrationModel()); model.addAttribute("rooms", roomDao.findAll()); return "user/registration"; } @RequestMapping(value = "/registration", method = RequestMethod.POST) public ModelAndView createUser(@ModelAttribute("userRegistrationModel") @Valid UserRegistrationModel userRegistrationModel, BindingResult bindingResult) { ModelAndView modelAndView = new ModelAndView(); User userExist = userService.findByEmail(userRegistrationModel.getEmail()); if (userExist != null) { bindingResult.rejectValue("email", "error.userRegistrationModel", "Podany adres email istnieje już w bazie."); } userExist = userService.findByUsername(userRegistrationModel.getUsername()); if (userExist != null) { bindingResult.rejectValue("username", "error.userRegistrationModel", "Podana nazwa użytkownika istnieje już w bazie."); } if (!userRegistrationModel.getPassword().equals(userRegistrationModel.getPasswordRepeat())) { bindingResult.rejectValue("passwordRepeat", "error.userRegistrationModel", "Powtórzone hasło jest różne od wpisanego."); } Room room = roomDao.findOne(userRegistrationModel.getRoomId()); if (room == null) { bindingResult.rejectValue("roomId", "error.userRegistrationModel", "Wybierz pokój z listy."); } else if (userService.findByRoom(room).size() >= room.getPeoples()) { bindingResult.rejectValue("roomId", "error.userRegistrationModel", "Brak miejsca w wybranym pokoju."); } if (!bindingResult.hasErrors()) { ModelMapper modelMapper = new ModelMapper(); User user = modelMapper.map(userRegistrationModel, User.class); userService.save(user); modelAndView.addObject("successMessage", "Rejestracja przebiegła pomyślnie."); } modelAndView.addObject("rooms", roomDao.findAll()); modelAndView.setViewName("user/registration"); return modelAndView; } }
Fix no give user tokens at start.
src/main/java/bj/pranie/controller/UserController.java
Fix no give user tokens at start.
<ide><path>rc/main/java/bj/pranie/controller/UserController.java <ide> @Controller <ide> @RequestMapping("/user") <ide> public class UserController { <add> <add> private final static int TOKENS_AT_START = 2; <ide> <ide> @Autowired <ide> private RoomDao roomDao; <ide> ModelMapper modelMapper = new ModelMapper(); <ide> User user = modelMapper.map(userRegistrationModel, User.class); <ide> <add> user.setTokens(TOKENS_AT_START); <ide> userService.save(user); <ide> <ide> modelAndView.addObject("successMessage", "Rejestracja przebiegła pomyślnie.");
Java
apache-2.0
34f4be73dbce33a3cebce95363c6a6b4a136a74f
0
Grasia/swellrt,P2Pvalue/swellrt,P2Pvalue/swellrt,P2Pvalue/swellrt,Grasia/swellrt,Grasia/swellrt,Grasia/swellrt,P2Pvalue/swellrt
package org.swellrt.model.js; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArrayMixed; import com.google.gwt.core.client.JsArrayString; import org.swellrt.model.generic.BooleanType; import org.swellrt.model.generic.ListType; import org.swellrt.model.generic.MapType; import org.swellrt.model.generic.Model; import org.swellrt.model.generic.NumberType; import org.swellrt.model.generic.StringType; import org.swellrt.model.generic.Type; import org.waveprotocol.wave.model.wave.ParticipantId; import java.util.Set; /** * * Adapt SwellRT objects from/to JavaScript proxy objects. * * @author [email protected] (Pablo Ojanguren) * */ public class ProxyAdapter { /** * Converts a Java iterable of strings to a Javascript array. * * @param [email protected] * @return */ private static JsArrayString iterableToArray(Iterable<String> strings) { JsArrayString array = (JsArrayString) JavaScriptObject.createArray(); for (String s : strings) array.push(s); return array; } /** * Converts a Java set of ParticipantId objects to a Javascript array of * strings. * * @param participants * @return */ private static JsArrayString participantsToArray(Set<ParticipantId> participants) { JsArrayString array = (JsArrayString) JavaScriptObject.createArray(); for (ParticipantId p : participants) array.push(p.getAddress()); return array; } private native static boolean isJsArray(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "object") && (jso.constructor == Array)); }-*/; private native static boolean isJsObject(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "object")); }-*/; private native static boolean isJsNumber(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "number")); }-*/; private native static boolean isJsBoolean(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "boolean")); }-*/; private native static boolean isJsString(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "string")); }-*/; private native static boolean isJsFile(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "object") && (jso.constructor == File)); }-*/; private native static boolean isJsText(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "object") && (jso.constructor == Text)); }-*/; private native static boolean isJsFunction(JavaScriptObject jso) /*-{ return jso != null && (typeof jso == "function"); }-*/; private native static String asString(JavaScriptObject jso) /*-{ return ""+jso; }-*/; private native static Integer asInteger(JavaScriptObject value) /*-{ var x; if (isNaN(value)) { return null; } x = parseFloat(value); if ((x | 0) === x) { return value; } return null; }-*/; private native static Double asDouble(JavaScriptObject value) /*-{ return value; }-*/; private native static boolean asBoolean(JavaScriptObject value) /*-{ return value; }-*/; private native static JsArrayMixed asArray(JavaScriptObject jso) /*-{ return jso; }-*/; private native static void log(String m, JavaScriptObject obj) /*-{ if (!$wnd._traces) { $wnd._traces = new Array(); } $wnd._traces.push({ trace: m, data: obj }); console.log(m); }-*/; private final Model model; public ProxyAdapter(Model model) { this.model = model; } /** * Generate a {@link Type} instance for a Javascript value. The new object is * NOT attached to a collaborative object. * * @param value * @return */ protected Type fromJs(JavaScriptObject value) { Type t = null; if (isJsNumber(value)) { // Using the string representation of the number to avoid // issues converting JS number to Java number with toString() methods t = model.createNumber(asString(value)); } else if (isJsString(value)) { t = model.createString(asString(value)); } else if (isJsBoolean(value)) { t = model.createBoolean(asString(value)); } else if (isJsArray(value)) { t = model.createList(); } else if (isJsText(value)) { t = model.createText(); } else if (isJsFile(value)) { t = model.createList(); } else if (isJsObject(value)) { t = model.createMap(); } return t; } /** * Populate the content of a native Javascript object into its counterpart of * the collaborative object. Hence, types of both 'tObject' and 'jsObject' * arguments must be similar. * * If they are primitive values, values are not populated. * * * @param tObject * @param jsObject * @return */ protected boolean populateValues(Type tObject, JavaScriptObject jsObject) { if (isJsNumber(jsObject)) { // Nothing to do return true; } else if (isJsString(jsObject)) { // Nothing to do return true; } else if (isJsBoolean(jsObject)) { // Nothing to do return true; } else if (isJsArray(jsObject)) { JsArrayMixed jsArray = asArray(jsObject); for (int i = 0; i < jsArray.length(); i++) { if (!add((ListType) tObject, jsArray.getObject(i))) { return false; } } } else if (isJsText(jsObject)) { // TODO add support for Text objects return true; } else if (isJsFile(jsObject)) { // TODO add support for File objects return true; } else if (isJsObject(jsObject)) { JsMap jsMap = JsMap.of(jsObject); JsArrayString keys = jsMap.keys(); for (int i = 0; i < keys.length(); i++) { String key = keys.get(i); if (!put((MapType) tObject, key, jsMap.get(key))) { return false; } } } return false; } /** * Put a Javascript object into a {@MapType} instance. This can * trigger a recursive process to attach a new subtree of Javascript objects * into the collaborative object. * * @param map * @param key * @param value */ protected boolean put(MapType map, String key, JavaScriptObject value) { Type tvalue = fromJs(value); if (tvalue == null) return false; tvalue = map.put(key, tvalue); return populateValues(tvalue, value); } /** * Add a Javascript object into a {@ListType} instance in the * specified index. This can trigger a recursive process to attach a new * subtree of Javascript objects into the collaborative object. * * Collaborative list semantics differs from javascript's, provided index must * be in the bounds of the list. * * @param list * @param value * @return */ protected boolean add(ListType list, int index, JavaScriptObject value) { Type tvalue = fromJs(value); if (tvalue == null) return false; tvalue = list.add(index, tvalue); return populateValues(tvalue, value); } /** * Add a Javascript object into a {@ListType} instance. This can * trigger a recursive process to attach a new subtree of Javascript objects * into the collaborative object. * * @param list * @param value * @return */ protected boolean add(ListType list, JavaScriptObject value) { Type tvalue = fromJs(value); if (tvalue == null) return false; tvalue = list.add(tvalue); return populateValues(tvalue, value); } /** * Sets an event handler in a node of the collaborative object. Handler must * be a function. * * @param handler * @param target * @return the listener */ protected ProxyListener setListener(Type target, JavaScriptObject handler) { if (!isJsFunction(handler)) return null; if (target instanceof MapType) { ProxyMapListener listener = ProxyMapListener.create(handler); listener.setAdapter(this); ((MapType) target).addListener(listener); return listener; } else if (target instanceof ListType) { ProxyListListener listener = ProxyListListener.create(handler); listener.setAdapter(this); ((ListType) target).addListener(listener); return listener; } else if (target instanceof StringType) { ProxyPrimitiveListener listener = ProxyPrimitiveListener.create(handler); listener.setAdapter(this); ((StringType) target).addListener(listener); return listener; } return null; } /** * Remove an event handler from a node of the collaborative object. * * TODO verify that this implementation works * * @param target * @param handler */ protected boolean removeListener(Type target, ProxyListener handler) { if (handler instanceof ProxyMapListener) { ((MapType) target).removeListener((ProxyMapListener) handler); } else if (handler instanceof ProxyListListener) { ((ListType) target).removeListener((ProxyListListener) handler); } else if (handler instanceof ProxyPrimitiveListener) { ((StringType) target).removeListener((ProxyPrimitiveListener) handler); } return true; } /** * Creates a Javascript object proxing a collaborative object. The create * object allows a native JS syntax to work with the collab. object. * * It also provide syntax sugar to inner properties by path: <br> * * "object[listprop.3.field]" is equivalent to "object.listprop[3].field" * * * <br> * but the first expression is more efficient. * * @param delegate * @param root * @return */ public native JavaScriptObject getJSObject(Model delegate, MapType root) /*-{ var _this = this; var target = [email protected]::of(Lorg/swellrt/model/generic/Type;)(root); target._object = delegate; var proxy = new $wnd.Proxy(target, { get: function(target, propKey) { if (typeof propKey == "string" && propKey.indexOf(".") > 0) { var value = [email protected]::fromPath(Ljava/lang/String;)(propKey); if (value) { return [email protected]::of(Lorg/swellrt/model/generic/Type;)(value); } } else if (propKey == "addCollaborator") { return function(c) { [email protected]::addParticipant(Ljava/lang/String;)(c); }; } else if (propKey == "removeCollaborator") { return function(c) { [email protected]::removeParticipant(Ljava/lang/String;)(c); }; } else if (propKey == "collaborators") { var collaboratorSet = [email protected]::getParticipants()(); return @org.swellrt.model.js.ProxyAdapter::participantsToArray(Ljava/util/Set;)(collaboratorSet); } else if (propKey == "_nodes") { // // For debug purposes: list of Wavelet documents storing collaborative object's nodes // var parts = [email protected]::getModelDocuments()(); return @org.swellrt.model.js.ProxyAdapter::iterableToArray(Ljava/lang/Iterable;)(parts); } else if (propKey == "_node") { // // For debug purposes: return a Wavelet document storing a collaborative object's node // return function(node) { return [email protected]::getModelDocument(Ljava/lang/String;)(node); }; } else if (propKey == "_oid") { // TODO make _id property read-only return [email protected]::getId()(); } else { return target[propKey]; } } }); return proxy; }-*/; public JavaScriptObject of(Type delegate) { if (delegate instanceof MapType) return ofMap((MapType) delegate); if (delegate instanceof ListType) return ofList((ListType) delegate); if (delegate instanceof StringType) return ofString((StringType) delegate); if (delegate instanceof NumberType) return ofNumber((NumberType) delegate); if (delegate instanceof BooleanType) return ofBoolean((BooleanType) delegate); return null; } /** * Generate a JavaScript proxy object for an underlying collaborative map * * @param delegate * @return */ public native JavaScriptObject ofMap(MapType delegate) /*-{ var _this = this; var proxy = new $wnd.Proxy( { _delegate: delegate }, { get: function(target, propKey, receiver) { if (propKey == 'addListener' || propKey == 'on' || propKey == 'onEvent') { return function(listener, property) { if (!listener) return false; var eventTarget = target._delegate; if (property != null && typeof property == 'string') { eventTarget = [email protected]::get(Ljava/lang/String;)(propKey); if (!eventTarget) return false; } var proxyListener = [email protected]::setListener(Lorg/swellrt/model/generic/Type;Lcom/google/gwt/core/client/JavaScriptObject;)(eventTarget, listener); // Return an object which can remove the listener return { dispose: function() { [email protected]::removeListener(Lorg/swellrt/model/generic/Type;Lorg/swellrt/model/js/ProxyListener;)(eventTarget, proxyListener); } }; }; } else if (propKey == '_object') { // bypass the _object property return target[propKey]; } else { var value = [email protected]::get(Ljava/lang/String;)(propKey); if (!value) return undefined; var proxy = [email protected]::of(Lorg/swellrt/model/generic/Type;)(value); return proxy; } }, has: function(target, propKey) { return [email protected]::hasKey(Ljava/lang/String;)(propKey); }, ownKeys: function(target) { var nativeKeys = [email protected]::keySet()(); var keys = @org.swellrt.model.js.ProxyAdapter::iterableToArray(Ljava/lang/Iterable;)(nativeKeys); return keys; }, getOwnPropertyDescriptor: function(target, propKey) { var hasPropKey = [email protected]::hasKey(Ljava/lang/String;)(propKey); if (hasPropKey) { var descriptor = { value: this.get(target, propKey), writable: true, enumerable: true, configurable: true }; return descriptor; } else { return Reflect.getOwnPropertyDescriptor(target, propKey); } }, set: function(target, propKey, value, receiver) { // bypass a special property _object if (propKey == '_object') { return target[propKey] = value; } return [email protected]::put(Lorg/swellrt/model/generic/MapType;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(target._delegate, propKey, value); }, defineProperty: function(target, propKey, propDesc) { var value = propDesc.value; if (!value) return false; return [email protected]::put(Lorg/swellrt/model/generic/MapType;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(target._delegate, propKey, value); }, deleteProperty: function(target, propKey) { [email protected]::remove(Ljava/lang/String;)(propKey); var hasPropKey = [email protected]::hasKey(Ljava/lang/String;)(propKey); return !hasPropKey; } }); return proxy; }-*/; public native JavaScriptObject ofList(ListType delegate) /*-{ var _this = this; var _array = new Array(); _array._delegate = delegate; var proxy = new $wnd.Proxy(_array,{ get: function(target, propKey, receiver) { var length = [email protected]::size()(); var index = Number(propKey); if (index >=0 && index < length) { // // get // var value = [email protected]::get(I)(index); if (!value) { return undefined; } else { return [email protected]::of(Lorg/swellrt/model/generic/Type;)(value); } } else if (propKey == "length") { // // length // return [email protected]::size()(); } else if (propKey == "push") { // // push // return function() { for(var i in arguments) { [email protected]::add(Lorg/swellrt/model/generic/ListType;Lcom/google/gwt/core/client/JavaScriptObject;)(target._delegate, arguments[i]); } return [email protected]::size()(); } } else if (propKey == "pop") { // // pop // return function() { var length = [email protected]::size()(); if (length > 0) { var value = [email protected]::get(I)(length-1); var proxy = null; if (!value) { return undefined; } else { proxy = [email protected]::of(Lorg/swellrt/model/generic/Type;)(value); } [email protected]::remove(I)(length-1); return proxy; } } } else if (propKey == 'addListener' || propKey == 'on' || propKey == 'onEvent') { return function(listener, index) { if (!listener) return false; var eventTarget = target._delegate; index = Number(index); if (index >=0 && index < length) eventTarget = [email protected]::get(I)(index); if (!eventTarget) return false; var proxyListener = [email protected]::setListener(Lorg/swellrt/model/generic/Type;Lcom/google/gwt/core/client/JavaScriptObject;)(eventTarget, listener); // Return an object which can remove the listener return { dispose: function() { [email protected]::removeListener(Lorg/swellrt/model/generic/Type;Lorg/swellrt/model/js/ProxyListener;)(eventTarget, proxyListener); } }; }; } }, set: function(target, propKey, value, receiver) { var length = [email protected]::size()(); var index = Number(propKey); // Should check here index out of bounds? // Collaborative list doesn't support inserting out of bounds if (index >=0 && index <= length) { if (value === undefined || value === null) { var deletedValue = [email protected]::remove(I)(index); if (deletedValue) return [email protected]::of(Lorg/swellrt/model/generic/Type;)(deletedValue); else return false; } else { return [email protected]::add(Lorg/swellrt/model/generic/ListType;ILcom/google/gwt/core/client/JavaScriptObject;)(target._delegate, propKey, value); } } else { // Should reflect non array properties set? return Reflect.set(target, propKey, value); } }, has: function(target, propKey) { var length = [email protected]::size()(); var index = Number(propKey); if (index >=0 && index < length) return true; else if (propKey === 'length') return true; else Reflect.has(target, propKey); }, ownKeys: function(target) { // keys is just a contiguos list of indexes, because collaborative lists doesn't allow gaps on indexes var length = [email protected]::size()(); var keys = new Array(); for (var i = 0; i < length; i++) keys.push(""+i); keys.push("length"); return keys; }, getOwnPropertyDescriptor: function(target, propKey) { var length = [email protected]::size()(); var index = Number(propKey); if (index >=0 && index < length) { var descriptor = { value: this.get(target, propKey), writable: true, enumerable: true, configurable: true }; return descriptor; } else if (propKey == 'length') { return { value: this.get(target, 'length'), writable: true, enumerable: false, configurable: false }; } else { return Reflect.getOwnPropertyDescriptor(target, propKey); } }, deleteProperty: function(target, propKey) { var length = [email protected]::size()(); var index = Number(propKey); if (index >=0 && index < length) { var deletedValue = [email protected]::remove(I)(index); if (deletedValue) return [email protected]::of(Lorg/swellrt/model/generic/Type;)(deletedValue); else return false; } else { return Reflect.deleteProperty(target, propKey); } } }); return proxy; }-*/; public native JavaScriptObject ofString(StringType delegate) /*-{ return [email protected]::getValue()(); }-*/; public native JavaScriptObject ofNumber(NumberType delegate) /*-{ var value = [email protected]::getValueDouble()(); if (value != null) { return [email protected]::doubleValue()(); } return null; }-*/; public native JavaScriptObject ofBoolean(BooleanType delegate) /*-{ return [email protected]::getValue()(); }-*/; public final native JavaScriptObject ofParticipant(ParticipantId participant) /*-{ return [email protected]::getAddress()() }-*/; public final native JavaScriptObject ofPrimitive(String value) /*-{ return value; }-*/; }
src/org/swellrt/model/js/ProxyAdapter.java
package org.swellrt.model.js; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArrayMixed; import com.google.gwt.core.client.JsArrayString; import org.swellrt.model.generic.BooleanType; import org.swellrt.model.generic.ListType; import org.swellrt.model.generic.MapType; import org.swellrt.model.generic.Model; import org.swellrt.model.generic.NumberType; import org.swellrt.model.generic.StringType; import org.swellrt.model.generic.Type; import org.waveprotocol.wave.model.wave.ParticipantId; import java.util.Set; /** * * Adapt SwellRT objects from/to JavaScript proxy objects. * * @author [email protected] (Pablo Ojanguren) * */ public class ProxyAdapter { /** * Converts a Java iterable of strings to a Javascript array. * * @param [email protected] * @return */ private static JsArrayString iterableToArray(Iterable<String> strings) { JsArrayString array = (JsArrayString) JavaScriptObject.createArray(); for (String s : strings) array.push(s); return array; } /** * Converts a Java set of ParticipantId objects to a Javascript array of * strings. * * @param participants * @return */ private static JsArrayString participantsToArray(Set<ParticipantId> participants) { JsArrayString array = (JsArrayString) JavaScriptObject.createArray(); for (ParticipantId p : participants) array.push(p.getAddress()); return array; } private native static boolean isJsArray(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "object") && (jso.constructor == Array)); }-*/; private native static boolean isJsObject(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "object")); }-*/; private native static boolean isJsNumber(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "number")); }-*/; private native static boolean isJsBoolean(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "boolean")); }-*/; private native static boolean isJsString(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "string")); }-*/; private native static boolean isJsFile(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "object") && (jso.constructor == File)); }-*/; private native static boolean isJsText(JavaScriptObject jso) /*-{ return jso != null && ((typeof jso == "object") && (jso.constructor == Text)); }-*/; private native static boolean isJsFunction(JavaScriptObject jso) /*-{ return jso != null && (typeof jso == "function"); }-*/; private native static String asString(JavaScriptObject jso) /*-{ return ""+jso; }-*/; private native static Integer asInteger(JavaScriptObject value) /*-{ var x; if (isNaN(value)) { return null; } x = parseFloat(value); if ((x | 0) === x) { return value; } return null; }-*/; private native static Double asDouble(JavaScriptObject value) /*-{ return value; }-*/; private native static boolean asBoolean(JavaScriptObject value) /*-{ return value; }-*/; private native static JsArrayMixed asArray(JavaScriptObject jso) /*-{ return jso; }-*/; private native static void log(String m, JavaScriptObject obj) /*-{ if (!$wnd._traces) { $wnd._traces = new Array(); } $wnd._traces.push({ trace: m, data: obj }); console.log(m); }-*/; private final Model model; public ProxyAdapter(Model model) { this.model = model; } /** * Generate a {@link Type} instance for a Javascript value. The new object is * NOT attached to a collaborative object. * * @param value * @return */ protected Type fromJs(JavaScriptObject value) { Type t = null; if (isJsNumber(value)) { // Using the string representation of the number to avoid // issues converting JS number to Java number with toString() methods t = model.createNumber(asString(value)); } else if (isJsString(value)) { t = model.createString(asString(value)); } else if (isJsBoolean(value)) { t = model.createBoolean(asString(value)); } else if (isJsArray(value)) { t = model.createList(); } else if (isJsText(value)) { t = model.createText(); } else if (isJsFile(value)) { t = model.createList(); } else if (isJsObject(value)) { t = model.createMap(); } return t; } /** * Populate the content of a native Javascript object into its counterpart of * the collaborative object. Hence, types of both 'tObject' and 'jsObject' * arguments must be similar. * * If they are primitive values, values are not populated. * * * @param tObject * @param jsObject * @return */ protected boolean populateValues(Type tObject, JavaScriptObject jsObject) { if (isJsNumber(jsObject)) { // Nothing to do return true; } else if (isJsString(jsObject)) { // Nothing to do return true; } else if (isJsBoolean(jsObject)) { // Nothing to do return true; } else if (isJsArray(jsObject)) { JsArrayMixed jsArray = asArray(jsObject); for (int i = 0; i < jsArray.length(); i++) { if (!add((ListType) tObject, jsArray.getObject(i))) { return false; } } } else if (isJsText(jsObject)) { // TODO add support for Text objects return true; } else if (isJsFile(jsObject)) { // TODO add support for File objects return true; } else if (isJsObject(jsObject)) { JsMap jsMap = JsMap.of(jsObject); JsArrayString keys = jsMap.keys(); for (int i = 0; i < keys.length(); i++) { String key = keys.get(i); if (!put((MapType) tObject, key, jsMap.get(key))) { return false; } } } return false; } /** * Put a Javascript object into a {@MapType} instance. This can * trigger a recursive process to attach a new subtree of Javascript objects * into the collaborative object. * * @param map * @param key * @param value */ protected boolean put(MapType map, String key, JavaScriptObject value) { Type tvalue = fromJs(value); if (tvalue == null) return false; tvalue = map.put(key, tvalue); return populateValues(tvalue, value); } /** * Add a Javascript object into a {@ListType} instance in the * specified index. This can trigger a recursive process to attach a new * subtree of Javascript objects into the collaborative object. * * Collaborative list semantics differs from javascript's, provided index must * be in the bounds of the list. * * @param list * @param value * @return */ protected boolean add(ListType list, int index, JavaScriptObject value) { Type tvalue = fromJs(value); if (tvalue == null) return false; tvalue = list.add(index, tvalue); return populateValues(tvalue, value); } /** * Add a Javascript object into a {@ListType} instance. This can * trigger a recursive process to attach a new subtree of Javascript objects * into the collaborative object. * * @param list * @param value * @return */ protected boolean add(ListType list, JavaScriptObject value) { Type tvalue = fromJs(value); if (tvalue == null) return false; tvalue = list.add(tvalue); return populateValues(tvalue, value); } /** * Sets an event handler in a node of the collaborative object. Handler must * be a function. * * @param handler * @param target * @return the listener */ protected ProxyListener setListener(Type target, JavaScriptObject handler) { if (!isJsFunction(handler)) return null; if (target instanceof MapType) { ProxyMapListener listener = ProxyMapListener.create(handler); listener.setAdapter(this); ((MapType) target).addListener(listener); return listener; } else if (target instanceof ListType) { ProxyListListener listener = ProxyListListener.create(handler); listener.setAdapter(this); ((ListType) target).addListener(listener); return listener; } else if (target instanceof StringType) { ProxyPrimitiveListener listener = ProxyPrimitiveListener.create(handler); listener.setAdapter(this); ((StringType) target).addListener(listener); return listener; } return null; } /** * Remove an event handler from a node of the collaborative object. * * TODO verify that this implementation works * * @param target * @param handler */ protected boolean removeListener(Type target, ProxyListener handler) { if (handler instanceof ProxyMapListener) { ((MapType) target).removeListener((ProxyMapListener) handler); } else if (handler instanceof ProxyListListener) { ((ListType) target).removeListener((ProxyListListener) handler); } else if (handler instanceof ProxyPrimitiveListener) { ((StringType) target).removeListener((ProxyPrimitiveListener) handler); } return true; } /** * Creates a Javascript object proxing a collaborative object. The create * object allows a native JS syntax to work with the collab. object. * * It also provide syntax sugar to inner properties by path: <br> * * "object[listprop.3.field]" is equivalent to "object.listprop[3].field" * * * <br> * but the first expression is more efficient. * * @param delegate * @param root * @return */ public native JavaScriptObject getJSObject(Model delegate, MapType root) /*-{ var _this = this; var target = [email protected]::of(Lorg/swellrt/model/generic/Type;)(root); target._object = delegate; var proxy = new $wnd.Proxy(target, { get: function(target, propKey) { if (typeof propKey == "string" && propKey.indexOf(".") > 0) { var value = [email protected]::fromPath(Ljava/lang/String;)(propKey); if (value) { return [email protected]::of(Lorg/swellrt/model/generic/Type;)(value); } } else if (propKey == "addCollaborator") { return function(c) { [email protected]::addParticipant(Ljava/lang/String;)(c); }; } else if (propKey == "removeCollaborator") { return function(c) { [email protected]::removeParticipant(Ljava/lang/String;)(c); }; } else if (propKey == "collaborators") { var collaboratorSet = [email protected]::getParticipants()(); return @org.swellrt.model.js.ProxyAdapter::participantsToArray(Ljava/util/Set;)(collaboratorSet); } else if (propKey == "_nodes") { // // For debug purposes: list of Wavelet documents storing collaborative object's nodes // var parts = [email protected]::getModelDocuments()(); return @org.swellrt.model.js.ProxyAdapter::iterableToArray(Ljava/lang/Iterable;)(parts); } else if (propKey == "_node") { // // For debug purposes: return a Wavelet document storing a collaborative object's node // return function(node) { return [email protected]::getModelDocument(Ljava/lang/String;)(node); }; } else { return target[propKey]; } } }); return proxy; }-*/; public JavaScriptObject of(Type delegate) { if (delegate instanceof MapType) return ofMap((MapType) delegate); if (delegate instanceof ListType) return ofList((ListType) delegate); if (delegate instanceof StringType) return ofString((StringType) delegate); if (delegate instanceof NumberType) return ofNumber((NumberType) delegate); if (delegate instanceof BooleanType) return ofBoolean((BooleanType) delegate); return null; } /** * Generate a JavaScript proxy object for an underlying collaborative map * * @param delegate * @return */ public native JavaScriptObject ofMap(MapType delegate) /*-{ var _this = this; var proxy = new $wnd.Proxy( { _delegate: delegate }, { get: function(target, propKey, receiver) { if (propKey == 'addListener' || propKey == 'on' || propKey == 'onEvent') { return function(listener, property) { if (!listener) return false; var eventTarget = target._delegate; if (property != null && typeof property == 'string') { eventTarget = [email protected]::get(Ljava/lang/String;)(propKey); if (!eventTarget) return false; } var proxyListener = [email protected]::setListener(Lorg/swellrt/model/generic/Type;Lcom/google/gwt/core/client/JavaScriptObject;)(eventTarget, listener); // Return an object which can remove the listener return { dispose: function() { [email protected]::removeListener(Lorg/swellrt/model/generic/Type;Lorg/swellrt/model/js/ProxyListener;)(eventTarget, proxyListener); } }; }; } else if (propKey == '_object') { // bypass the _object property return target[propKey]; } else { var value = [email protected]::get(Ljava/lang/String;)(propKey); if (!value) return undefined; var proxy = [email protected]::of(Lorg/swellrt/model/generic/Type;)(value); return proxy; } }, has: function(target, propKey) { return [email protected]::hasKey(Ljava/lang/String;)(propKey); }, ownKeys: function(target) { var nativeKeys = [email protected]::keySet()(); var keys = @org.swellrt.model.js.ProxyAdapter::iterableToArray(Ljava/lang/Iterable;)(nativeKeys); return keys; }, getOwnPropertyDescriptor: function(target, propKey) { var hasPropKey = [email protected]::hasKey(Ljava/lang/String;)(propKey); if (hasPropKey) { var descriptor = { value: this.get(target, propKey), writable: true, enumerable: true, configurable: true }; return descriptor; } else { return Reflect.getOwnPropertyDescriptor(target, propKey); } }, set: function(target, propKey, value, receiver) { // bypass a special property _object if (propKey == '_object') { return target[propKey] = value; } return [email protected]::put(Lorg/swellrt/model/generic/MapType;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(target._delegate, propKey, value); }, defineProperty: function(target, propKey, propDesc) { var value = propDesc.value; if (!value) return false; return [email protected]::put(Lorg/swellrt/model/generic/MapType;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(target._delegate, propKey, value); }, deleteProperty: function(target, propKey) { [email protected]::remove(Ljava/lang/String;)(propKey); var hasPropKey = [email protected]::hasKey(Ljava/lang/String;)(propKey); return !hasPropKey; } }); return proxy; }-*/; public native JavaScriptObject ofList(ListType delegate) /*-{ var _this = this; var _array = new Array(); _array._delegate = delegate; var proxy = new $wnd.Proxy(_array,{ get: function(target, propKey, receiver) { var length = [email protected]::size()(); var index = Number(propKey); if (index >=0 && index < length) { // // get // var value = [email protected]::get(I)(index); if (!value) { return undefined; } else { return [email protected]::of(Lorg/swellrt/model/generic/Type;)(value); } } else if (propKey == "length") { // // length // return [email protected]::size()(); } else if (propKey == "push") { // // push // return function() { for(var i in arguments) { [email protected]::add(Lorg/swellrt/model/generic/ListType;Lcom/google/gwt/core/client/JavaScriptObject;)(target._delegate, arguments[i]); } return [email protected]::size()(); } } else if (propKey == "pop") { // // pop // return function() { var length = [email protected]::size()(); if (length > 0) { var value = [email protected]::get(I)(length-1); var proxy = null; if (!value) { return undefined; } else { proxy = [email protected]::of(Lorg/swellrt/model/generic/Type;)(value); } [email protected]::remove(I)(length-1); return proxy; } } } else if (propKey == 'addListener' || propKey == 'on' || propKey == 'onEvent') { return function(listener, index) { if (!listener) return false; var eventTarget = target._delegate; index = Number(index); if (index >=0 && index < length) eventTarget = [email protected]::get(I)(index); if (!eventTarget) return false; var proxyListener = [email protected]::setListener(Lorg/swellrt/model/generic/Type;Lcom/google/gwt/core/client/JavaScriptObject;)(eventTarget, listener); // Return an object which can remove the listener return { dispose: function() { [email protected]::removeListener(Lorg/swellrt/model/generic/Type;Lorg/swellrt/model/js/ProxyListener;)(eventTarget, proxyListener); } }; }; } }, set: function(target, propKey, value, receiver) { var length = [email protected]::size()(); var index = Number(propKey); // Should check here index out of bounds? // Collaborative list doesn't support inserting out of bounds if (index >=0 && index <= length) { if (value === undefined || value === null) { var deletedValue = [email protected]::remove(I)(index); if (deletedValue) return [email protected]::of(Lorg/swellrt/model/generic/Type;)(deletedValue); else return false; } else { return [email protected]::add(Lorg/swellrt/model/generic/ListType;ILcom/google/gwt/core/client/JavaScriptObject;)(target._delegate, propKey, value); } } else { // Should reflect non array properties set? return Reflect.set(target, propKey, value); } }, has: function(target, propKey) { var length = [email protected]::size()(); var index = Number(propKey); if (index >=0 && index < length) return true; else if (propKey === 'length') return true; else Reflect.has(target, propKey); }, ownKeys: function(target) { // keys is just a contiguos list of indexes, because collaborative lists doesn't allow gaps on indexes var length = [email protected]::size()(); var keys = new Array(); for (var i = 0; i < length; i++) keys.push(""+i); keys.push("length"); return keys; }, getOwnPropertyDescriptor: function(target, propKey) { var length = [email protected]::size()(); var index = Number(propKey); if (index >=0 && index < length) { var descriptor = { value: this.get(target, propKey), writable: true, enumerable: true, configurable: true }; return descriptor; } else if (propKey == 'length') { return { value: this.get(target, 'length'), writable: true, enumerable: false, configurable: false }; } else { return Reflect.getOwnPropertyDescriptor(target, propKey); } }, deleteProperty: function(target, propKey) { var length = [email protected]::size()(); var index = Number(propKey); if (index >=0 && index < length) { var deletedValue = [email protected]::remove(I)(index); if (deletedValue) return [email protected]::of(Lorg/swellrt/model/generic/Type;)(deletedValue); else return false; } else { return Reflect.deleteProperty(target, propKey); } } }); return proxy; }-*/; public native JavaScriptObject ofString(StringType delegate) /*-{ return [email protected]::getValue()(); }-*/; public native JavaScriptObject ofNumber(NumberType delegate) /*-{ var value = [email protected]::getValueDouble()(); if (value != null) { return [email protected]::doubleValue()(); } return null; }-*/; public native JavaScriptObject ofBoolean(BooleanType delegate) /*-{ return [email protected]::getValue()(); }-*/; public final native JavaScriptObject ofParticipant(ParticipantId participant) /*-{ return [email protected]::getAddress()() }-*/; public final native JavaScriptObject ofPrimitive(String value) /*-{ return value; }-*/; }
New js api. Get object id.
src/org/swellrt/model/js/ProxyAdapter.java
New js api. Get object id.
<ide><path>rc/org/swellrt/model/js/ProxyAdapter.java <ide> return [email protected]::getModelDocument(Ljava/lang/String;)(node); <ide> }; <ide> <add> } else if (propKey == "_oid") { <add> <add> // TODO make _id property read-only <add> return [email protected]::getId()(); <add> <ide> } else { <ide> return target[propKey]; <ide> }
Java
apache-2.0
b5612456c47f917a4202b121bb2c0615cfd17122
0
sizebay/Sizebay-Catalog-API-Client,sizebay/Sizebay-Catalog-API-Client
package sizebay.catalog.client.model.filters; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) public class ProductFilter extends Filter { private String page; private String id; private String name; private String permalink; private String ageGroup; private String feedAgeGroup; private String gender; private String feedGender; private String feedProductId; private String brandId; private String brandName; private String feedBrandId; private String feedBrandName; private String categoryId; private String categoryName; private String modelingId; private String modelingName; private String sizeType; private String modelingSizeType; private String strongBrandId; private String strongBrandName; private String strongCategoryType; private String strongCategoryId; private String strongCategoryName; private String strongSubcategoryId; private String strongSubcategoryName; private String strongModelId; private String strongModelName; private String slugId; private String onlyShoes; private String status; private String productsThatShouldBeFixed; private String productsAvailable; private String productsAvailableWithError; private String groupIds; private String groupAgeGroup; public void setPermalink(String permalink) { this.permalink = URLEncoder.encode(permalink, StandardCharsets.UTF_8); } public String getDecodePermalink() { return URLDecoder.decode(this.permalink, StandardCharsets.UTF_8); } }
src/main/java/sizebay/catalog/client/model/filters/ProductFilter.java
package sizebay.catalog.client.model.filters; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) public class ProductFilter extends Filter { private String page; private String id; private String name; private String permalink; private String ageGroup; private String feedAgeGroup; private String gender; private String feedGender; private String feedProductId; private String brandId; private String brandName; private String feedBrandId; private String feedBrandName; private String categoryId; private String categoryName; private String modelingId; private String modelingName; private String sizeType; private String modelingSizeType; private String strongBrandId; private String strongBrandName; private String strongCategoryType; private String strongCategoryId; private String strongCategoryName; private String strongSubcategoryId; private String strongSubcategoryName; private String strongModelId; private String strongModelName; private String slugId; private String onlyShoes; private String status; private String productsThatShouldBeFixed; private String productsAvailable; private String productsAvailableWithError; private String groupIds; private String groupAgeGroup; }
feat: added enconder on set permalink and create get decode permalink
src/main/java/sizebay/catalog/client/model/filters/ProductFilter.java
feat: added enconder on set permalink and create get decode permalink
<ide><path>rc/main/java/sizebay/catalog/client/model/filters/ProductFilter.java <ide> import lombok.NoArgsConstructor; <ide> import lombok.Setter; <ide> import lombok.experimental.Accessors; <add> <add>import java.net.URLDecoder; <add>import java.net.URLEncoder; <add>import java.nio.charset.StandardCharsets; <ide> <ide> @Getter <ide> @Setter <ide> private String productsAvailableWithError; <ide> private String groupIds; <ide> private String groupAgeGroup; <add> <add> public void setPermalink(String permalink) { <add> this.permalink = URLEncoder.encode(permalink, StandardCharsets.UTF_8); <add> } <add> <add> public String getDecodePermalink() { <add> return URLDecoder.decode(this.permalink, StandardCharsets.UTF_8); <add> } <ide> }
Java
apache-2.0
e2ebcafaae9dffaea6ae3c17ebd62dbc2abbbb1f
0
tascape/thx-ios,tascape/thx-ios
/* * Copyright 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tascape.qa.th.ios.driver; import com.tascape.qa.th.ios.comm.JavaScriptServer; import com.tascape.qa.th.Utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecuteResultHandler; import org.apache.commons.exec.ExecuteStreamHandler; import org.apache.commons.exec.ExecuteWatchdog; import org.apache.commons.exec.Executor; import org.apache.commons.io.FileUtils; import org.libimobiledevice.ios.driver.binding.exceptions.SDKException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.martiansoftware.nailgun.NGServer; import com.tascape.qa.th.SystemConfiguration; import com.tascape.qa.th.exception.EntityDriverException; import net.sf.lipermi.exception.LipeRMIException; import net.sf.lipermi.handler.CallHandler; import net.sf.lipermi.net.Server; import com.tascape.qa.th.ios.comm.JavaScriptNail; import com.tascape.qa.th.ios.model.UIAElement; import com.tascape.qa.th.libx.DefaultExecutor; import java.awt.Dimension; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; /** * * @author linsong wang */ public class UiAutomationDevice extends LibIMobileDevice implements JavaScriptServer, Observer { private static final Logger LOG = LoggerFactory.getLogger(UiAutomationDevice.class); public static final String SYSPROP_TIMEOUT_SECOND = "qa.th.driver.ios.TIMEOUT_SECOND"; public static final String FAIL = "Fail: The target application appears to have died"; public static final String TRACE_TEMPLATE = "/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents" + "/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate"; public static final int JAVASCRIPT_TIMEOUT_SECOND = SystemConfiguration.getInstance().getIntProperty(SYSPROP_TIMEOUT_SECOND, 30); private final SynchronousQueue<String> javaScriptQueue = new SynchronousQueue<>(); private final BlockingQueue<String> responseQueue = new ArrayBlockingQueue<>(5000); private int ngPort; private int rmiPort; private NGServer ngServer; private Server rmiServer; private ExecuteWatchdog instrumentsDog; private ESH instrumentsStreamHandler; public UiAutomationDevice(String uuid) throws SDKException, IOException { super(uuid); } public void start(String appName) throws Exception { LOG.info("Start server"); ngServer = this.startNailGunServer(); rmiServer = this.startRmiServer(); instrumentsDog = this.startInstrumentsServer(appName); addInstrumentsStreamObserver(this); sendJavaScript("window.logElement();").forEach(l -> LOG.debug(l)); } public void stop() { LOG.info("Stop server"); if (ngServer != null) { ngServer.shutdown(false); } if (rmiServer != null) { rmiServer.close(); } if (instrumentsDog != null) { instrumentsDog.stop(); instrumentsDog.killedProcess(); } } public void delay(int second) throws InterruptedException, EntityDriverException { this.sendJavaScript("target.delay(" + second + ")"); } /** * Gets the screen size in points. * http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions * * @return the screen size in points * * @throws InterruptedException in case of any issue * @throws EntityDriverException in case of any issue */ public Dimension getDisplaySize() throws InterruptedException, EntityDriverException { List<String> lines = this.sendJavaScript("window.logElement();"); Dimension dimension = new Dimension(); String line = lines.stream().filter((l) -> (l.startsWith("UIAWindow"))).findFirst().get(); if (StringUtils.isNotEmpty(line)) { String s = line.split("\\{", 2)[1].replaceAll("\\{", "").replaceAll("\\}", ""); String[] ds = s.split(","); dimension.setSize(Integer.parseInt(ds[2].trim()), Integer.parseInt(ds[3].trim())); } return dimension; } public List<String> logElementTree() throws InterruptedException, EntityDriverException { return this.sendJavaScript("window.logElementTree();"); } /** * Checks if an element exists on current UI, based on element type. * * @param <T> sub-class of UIAElement * @param javaScript such as "window.tabBars()['MainTabBar'].logElement();" * @param type type of uia element, such as UIATabBar * * @return true if element identified by javascript exists * * @throws InterruptedException in case of any issue * @throws EntityDriverException in case of any issue */ public <T extends UIAElement> boolean doesElementExist(String javaScript, Class<T> type) throws InterruptedException, EntityDriverException { return doesElementExist(javaScript, type, null); } /** * Checks if an element exists on current UI, based on element type and text. * * @param <T> sub-class of UIAElement * @param javaScript the javascript that uniquely identify the element, such as "window.tabBars()['MainTabBar'];", * or "window.elements()[1].buttons()[0];" * @param type type of uia element, such as UIATabBar * @param text text of an element, such as "MainTabBar" * * @return true if element identified by javascript exists * * @throws InterruptedException in case of any issue * @throws EntityDriverException in case of any issue */ public <T extends UIAElement> boolean doesElementExist(String javaScript, Class<T> type, String text) throws InterruptedException, EntityDriverException { String js = "var e = " + javaScript + "\n" + "e.logElement()"; return sendJavaScript(js).stream() .filter(line -> line.contains(type.getSimpleName())) .filter(line -> StringUtils.isEmpty(text) ? true : line.contains(text)) .findFirst().isPresent(); } public List<String> sendJavaScript(String javaScript) throws InterruptedException, EntityDriverException { String reqId = UUID.randomUUID().toString(); LOG.trace("sending js {}", javaScript); javaScriptQueue.offer("UIALogger.logMessage('" + reqId + " start');", JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); javaScriptQueue.offer(javaScript, JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); javaScriptQueue .offer("UIALogger.logMessage('" + reqId + " stop');", JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); while (true) { String res = this.responseQueue.poll(JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); if (res == null) { throw new EntityDriverException("no response from device"); } LOG.trace(res); if (res.contains(FAIL)) { throw new EntityDriverException(res); } if (res.contains(reqId + " start")) { break; } } List<String> lines = new ArrayList<>(); while (true) { String res = this.responseQueue.poll(JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); if (res == null) { throw new EntityDriverException("no response from device"); } LOG.trace(res); if (res.contains(FAIL)) { throw new EntityDriverException(res); } if (res.contains(reqId + " start")) { continue; } if (res.contains(reqId + " stop")) { break; } else { lines.add(res); } } javaScriptQueue.clear(); return lines; } @Override public String retrieveJavaScript() throws InterruptedException { String js = javaScriptQueue.take(); LOG.trace("got js {}", js); return js; } public boolean addInstrumentsStreamObserver(Observer observer) { if (this.instrumentsStreamHandler != null) { this.instrumentsStreamHandler.addObserver(observer); return true; } return false; } @Override public void update(Observable o, Object arg) { String res = arg.toString(); try { responseQueue.put(res); } catch (InterruptedException ex) { LOG.error("Cannot save instruments response"); } } private NGServer startNailGunServer() throws InterruptedException { NGServer ngs = new NGServer(null, 0); new Thread(ngs).start(); Utils.sleep(2000, ""); this.ngPort = ngs.getPort(); LOG.trace("ng port {}", this.ngPort); return ngs; } private Server startRmiServer() throws IOException, LipeRMIException { Server rmis = new Server(); CallHandler callHandler = new CallHandler(); this.rmiPort = 8000; while (true) { try { rmis.bind(rmiPort, callHandler); break; } catch (IOException ex) { LOG.trace("rmi port {} - {}", this.rmiPort, ex.getMessage()); this.rmiPort += 7; } } LOG.trace("rmi port {}", this.rmiPort); callHandler.registerGlobal(JavaScriptServer.class, this); return rmis; } private ExecuteWatchdog startInstrumentsServer(String appName) throws IOException { StringBuilder sb = new StringBuilder() .append("while (1) {\n") .append(" var target = UIATarget.localTarget();\n") .append(" var host = target.host();\n") .append(" var app = target.frontMostApp();\n") .append(" var window = app.mainWindow();\n") .append(" var js = host.performTaskWithPathArgumentsTimeout('").append(JavaScriptNail.NG_CLIENT) .append("', ['--nailgun-port', '").append(ngPort).append("', '").append(JavaScriptNail.class.getName()) .append("', '").append(rmiPort).append("'], 10000);\n") .append(" UIALogger.logDebug(js.stdout);\n") .append(" try {\n") .append(" var res = eval(js.stdout);\n") .append(" } catch(err) {\n") .append(" UIALogger.logError(err);\n") .append(" }\n") .append("}\n"); File js = File.createTempFile("instruments-", ".js"); FileUtils.write(js, sb); LOG.trace("{}\n{}", js, sb); CommandLine cmdLine = new CommandLine("instruments"); cmdLine.addArgument("-t"); cmdLine.addArgument(TRACE_TEMPLATE); cmdLine.addArgument("-w"); cmdLine.addArgument(this.getIosDevice().getUUID()); cmdLine.addArgument(appName); cmdLine.addArgument("-e"); cmdLine.addArgument("UIASCRIPT"); cmdLine.addArgument(js.getAbsolutePath()); cmdLine.addArgument("-e"); cmdLine.addArgument("UIARESULTSPATH"); cmdLine.addArgument(Paths.get(System.getProperty("java.io.tmpdir")).toFile().getAbsolutePath()); LOG.trace("{}", cmdLine.toString()); ExecuteWatchdog watchdog = new ExecuteWatchdog(Long.MAX_VALUE); Executor executor = new DefaultExecutor(); executor.setWatchdog(watchdog); instrumentsStreamHandler = new ESH(); instrumentsStreamHandler.addObserver(this); executor.setStreamHandler(instrumentsStreamHandler); executor.execute(cmdLine, new DefaultExecuteResultHandler()); return watchdog; } private class ESH extends Observable implements ExecuteStreamHandler { @Override public void setProcessInputStream(OutputStream out) throws IOException { LOG.trace("setProcessInputStream"); } @Override public void setProcessErrorStream(InputStream in) throws IOException { BufferedReader bis = new BufferedReader(new InputStreamReader(in)); do { String line = bis.readLine(); if (line == null) { break; } LOG.error(line); this.notifyObserversX("ERROR " + line); } while (true); } @Override public void setProcessOutputStream(InputStream in) throws IOException { BufferedReader bis = new BufferedReader(new InputStreamReader(in)); while (true) { String line = bis.readLine(); if (line == null) { break; } LOG.debug(line); this.notifyObserversX(line); } } @Override public void start() throws IOException { LOG.trace("start"); } @Override public void stop() { LOG.trace("stop"); } private void notifyObserversX(String line) { this.setChanged(); this.notifyObservers(line); this.clearChanged(); } } public static void main(String[] args) throws Exception { UiAutomationDevice d = new UiAutomationDevice(LibIMobileDevice.getAllUuids().get(0)); d.start("Xinkaishi"); LOG.debug("{}", d.getDisplaySize()); d.stop(); System.exit(0); } }
uia-test/src/main/java/com/tascape/qa/th/ios/driver/UiAutomationDevice.java
/* * Copyright 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tascape.qa.th.ios.driver; import com.tascape.qa.th.ios.comm.JavaScriptServer; import com.tascape.qa.th.Utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecuteResultHandler; import org.apache.commons.exec.ExecuteStreamHandler; import org.apache.commons.exec.ExecuteWatchdog; import org.apache.commons.exec.Executor; import org.apache.commons.io.FileUtils; import org.libimobiledevice.ios.driver.binding.exceptions.SDKException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.martiansoftware.nailgun.NGServer; import com.tascape.qa.th.exception.EntityDriverException; import net.sf.lipermi.exception.LipeRMIException; import net.sf.lipermi.handler.CallHandler; import net.sf.lipermi.net.Server; import com.tascape.qa.th.ios.comm.JavaScriptNail; import com.tascape.qa.th.ios.model.UIAElement; import com.tascape.qa.th.libx.DefaultExecutor; import java.awt.Dimension; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; /** * * @author linsong wang */ public class UiAutomationDevice extends LibIMobileDevice implements JavaScriptServer, Observer { private static final Logger LOG = LoggerFactory.getLogger(UiAutomationDevice.class); public static final String FAIL = "Fail: The target application appears to have died"; public static final String TRACE_TEMPLATE = "/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents" + "/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate"; public static final int JAVASCRIPT_TIMEOUT_SECOND = 10; private final SynchronousQueue<String> javaScriptQueue = new SynchronousQueue<>(); private final BlockingQueue<String> responseQueue = new ArrayBlockingQueue<>(5000); private int ngPort; private int rmiPort; private NGServer ngServer; private Server rmiServer; private ExecuteWatchdog instrumentsDog; private ESH instrumentsStreamHandler; public UiAutomationDevice(String uuid) throws SDKException, IOException { super(uuid); } public void start(String appName) throws Exception { LOG.info("Start server"); ngServer = this.startNailGunServer(); rmiServer = this.startRmiServer(); instrumentsDog = this.startInstrumentsServer(appName); addInstrumentsStreamObserver(this); sendJavaScript("window.logElement();").forEach(l -> LOG.debug(l)); } public void stop() { LOG.info("Stop server"); if (ngServer != null) { ngServer.shutdown(false); } if (rmiServer != null) { rmiServer.close(); } if (instrumentsDog != null) { instrumentsDog.stop(); instrumentsDog.killedProcess(); } } public void delay(int second) throws InterruptedException, EntityDriverException { this.sendJavaScript("target.delay(" + second + ")"); } /** * Gets the screen size in points. * http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions * * @return the screen size in points * * @throws InterruptedException in case of any issue * @throws EntityDriverException in case of any issue */ public Dimension getDisplaySize() throws InterruptedException, EntityDriverException { List<String> lines = this.sendJavaScript("window.logElement();"); Dimension dimension = new Dimension(); String line = lines.stream().filter((l) -> (l.startsWith("UIAWindow"))).findFirst().get(); if (StringUtils.isNotEmpty(line)) { String s = line.split("\\{", 2)[1].replaceAll("\\{", "").replaceAll("\\}", ""); String[] ds = s.split(","); dimension.setSize(Integer.parseInt(ds[2].trim()), Integer.parseInt(ds[3].trim())); } return dimension; } public List<String> logElementTree() throws InterruptedException, EntityDriverException { return this.sendJavaScript("window.logElementTree();"); } /** * Checks if an element exists on current UI, based on element type. * * @param <T> sub-class of UIAElement * @param javaScript such as "window.tabBars()['MainTabBar'].logElement();" * @param type type of uia element, such as UIATabBar * * @return true if element identified by javascript exists * * @throws InterruptedException in case of any issue * @throws EntityDriverException in case of any issue */ public <T extends UIAElement> boolean doesElementExist(String javaScript, Class<T> type) throws InterruptedException, EntityDriverException { return doesElementExist(javaScript, type, null); } /** * Checks if an element exists on current UI, based on element type and text. * * @param <T> sub-class of UIAElement * @param javaScript the javascript that uniquely identify the element, such as "window.tabBars()['MainTabBar'];", * or "window.elements()[1].buttons()[0];" * @param type type of uia element, such as UIATabBar * @param text text of an element, such as "MainTabBar" * * @return true if element identified by javascript exists * * @throws InterruptedException in case of any issue * @throws EntityDriverException in case of any issue */ public <T extends UIAElement> boolean doesElementExist(String javaScript, Class<T> type, String text) throws InterruptedException, EntityDriverException { String js = "var e = " + javaScript + "\n" + "e.logElement()"; return sendJavaScript(js).stream() .filter(line -> line.contains(type.getSimpleName())) .filter(line -> StringUtils.isEmpty(text) ? true : line.contains(text)) .findFirst().isPresent(); } public List<String> sendJavaScript(String javaScript) throws InterruptedException, EntityDriverException { String reqId = UUID.randomUUID().toString(); LOG.trace("sending js {}", javaScript); javaScriptQueue.offer("UIALogger.logMessage('" + reqId + " start');", JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); javaScriptQueue.offer(javaScript, JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); javaScriptQueue.offer("UIALogger.logMessage('" + reqId + " stop');", JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); while (true) { String res = this.responseQueue.poll(JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); if (res == null) { throw new EntityDriverException("no response from device"); } LOG.trace(res); if (res.contains(FAIL)) { throw new EntityDriverException(res); } if (res.contains(reqId + " start")) { break; } } List<String> lines = new ArrayList<>(); while (true) { String res = this.responseQueue.poll(JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); if (res == null) { throw new EntityDriverException("no response from device"); } LOG.trace(res); if (res.contains(FAIL)) { throw new EntityDriverException(res); } if (res.contains(reqId + " start")) { continue; } if (res.contains(reqId + " stop")) { break; } else { lines.add(res); } } javaScriptQueue.clear(); return lines; } @Override public String retrieveJavaScript() throws InterruptedException { String js = javaScriptQueue.take(); LOG.trace("got js {}", js); return js; } public boolean addInstrumentsStreamObserver(Observer observer) { if (this.instrumentsStreamHandler != null) { this.instrumentsStreamHandler.addObserver(observer); return true; } return false; } @Override public void update(Observable o, Object arg) { String res = arg.toString(); try { responseQueue.put(res); } catch (InterruptedException ex) { LOG.error("Cannot save instruments response"); } } private NGServer startNailGunServer() throws InterruptedException { NGServer ngs = new NGServer(null, 0); new Thread(ngs).start(); Utils.sleep(2000, ""); this.ngPort = ngs.getPort(); LOG.trace("ng port {}", this.ngPort); return ngs; } private Server startRmiServer() throws IOException, LipeRMIException { Server rmis = new Server(); CallHandler callHandler = new CallHandler(); this.rmiPort = 8000; while (true) { try { rmis.bind(rmiPort, callHandler); break; } catch (IOException ex) { LOG.trace("rmi port {} - {}", this.rmiPort, ex.getMessage()); this.rmiPort += 7; } } LOG.trace("rmi port {}", this.rmiPort); callHandler.registerGlobal(JavaScriptServer.class, this); return rmis; } private ExecuteWatchdog startInstrumentsServer(String appName) throws IOException { StringBuilder sb = new StringBuilder() .append("while (1) {\n") .append(" var target = UIATarget.localTarget();\n") .append(" var host = target.host();\n") .append(" var app = target.frontMostApp();\n") .append(" var window = app.mainWindow();\n") .append(" var js = host.performTaskWithPathArgumentsTimeout('").append(JavaScriptNail.NG_CLIENT) .append("', ['--nailgun-port', '").append(ngPort).append("', '").append(JavaScriptNail.class.getName()) .append("', '").append(rmiPort).append("'], 10000);\n") .append(" UIALogger.logDebug(js.stdout);\n") .append(" try {\n") .append(" var res = eval(js.stdout);\n") .append(" } catch(err) {\n") .append(" UIALogger.logError(err);\n") .append(" }\n") .append("}\n"); File js = File.createTempFile("instruments-", ".js"); FileUtils.write(js, sb); LOG.trace("{}\n{}", js, sb); CommandLine cmdLine = new CommandLine("instruments"); cmdLine.addArgument("-t"); cmdLine.addArgument(TRACE_TEMPLATE); cmdLine.addArgument("-w"); cmdLine.addArgument(this.getIosDevice().getUUID()); cmdLine.addArgument(appName); cmdLine.addArgument("-e"); cmdLine.addArgument("UIASCRIPT"); cmdLine.addArgument(js.getAbsolutePath()); cmdLine.addArgument("-e"); cmdLine.addArgument("UIARESULTSPATH"); cmdLine.addArgument(Paths.get(System.getProperty("java.io.tmpdir")).toFile().getAbsolutePath()); LOG.trace("{}", cmdLine.toString()); ExecuteWatchdog watchdog = new ExecuteWatchdog(Long.MAX_VALUE); Executor executor = new DefaultExecutor(); executor.setWatchdog(watchdog); instrumentsStreamHandler = new ESH(); instrumentsStreamHandler.addObserver(this); executor.setStreamHandler(instrumentsStreamHandler); executor.execute(cmdLine, new DefaultExecuteResultHandler()); return watchdog; } private class ESH extends Observable implements ExecuteStreamHandler { @Override public void setProcessInputStream(OutputStream out) throws IOException { LOG.trace("setProcessInputStream"); } @Override public void setProcessErrorStream(InputStream in) throws IOException { BufferedReader bis = new BufferedReader(new InputStreamReader(in)); do { String line = bis.readLine(); if (line == null) { break; } LOG.error(line); this.notifyObserversX("ERROR " + line); } while (true); } @Override public void setProcessOutputStream(InputStream in) throws IOException { BufferedReader bis = new BufferedReader(new InputStreamReader(in)); while (true) { String line = bis.readLine(); if (line == null) { break; } LOG.debug(line); this.notifyObserversX(line); } } @Override public void start() throws IOException { LOG.trace("start"); } @Override public void stop() { LOG.trace("stop"); } private void notifyObserversX(String line) { this.setChanged(); this.notifyObservers(line); this.clearChanged(); } } public static void main(String[] args) throws Exception { UiAutomationDevice d = new UiAutomationDevice(LibIMobileDevice.getAllUuids().get(0)); d.start("Xinkaishi"); LOG.debug("{}", d.getDisplaySize()); d.stop(); System.exit(0); } }
add send js timeout
uia-test/src/main/java/com/tascape/qa/th/ios/driver/UiAutomationDevice.java
add send js timeout
<ide><path>ia-test/src/main/java/com/tascape/qa/th/ios/driver/UiAutomationDevice.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> import com.martiansoftware.nailgun.NGServer; <add>import com.tascape.qa.th.SystemConfiguration; <ide> import com.tascape.qa.th.exception.EntityDriverException; <ide> import net.sf.lipermi.exception.LipeRMIException; <ide> import net.sf.lipermi.handler.CallHandler; <ide> public class UiAutomationDevice extends LibIMobileDevice implements JavaScriptServer, Observer { <ide> private static final Logger LOG = LoggerFactory.getLogger(UiAutomationDevice.class); <ide> <add> public static final String SYSPROP_TIMEOUT_SECOND = "qa.th.driver.ios.TIMEOUT_SECOND"; <add> <ide> public static final String FAIL = "Fail: The target application appears to have died"; <ide> <ide> public static final String TRACE_TEMPLATE = "/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents" <ide> + "/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate"; <ide> <del> public static final int JAVASCRIPT_TIMEOUT_SECOND = 10; <add> public static final int JAVASCRIPT_TIMEOUT_SECOND <add> = SystemConfiguration.getInstance().getIntProperty(SYSPROP_TIMEOUT_SECOND, 30); <ide> <ide> private final SynchronousQueue<String> javaScriptQueue = new SynchronousQueue<>(); <ide> <ide> public List<String> sendJavaScript(String javaScript) throws InterruptedException, EntityDriverException { <ide> String reqId = UUID.randomUUID().toString(); <ide> LOG.trace("sending js {}", javaScript); <del> javaScriptQueue.offer("UIALogger.logMessage('" + reqId + " start');", JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); <add> javaScriptQueue.offer("UIALogger.logMessage('" + reqId + " start');", JAVASCRIPT_TIMEOUT_SECOND, <add> TimeUnit.SECONDS); <ide> javaScriptQueue.offer(javaScript, JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); <del> javaScriptQueue.offer("UIALogger.logMessage('" + reqId + " stop');", JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); <add> javaScriptQueue <add> .offer("UIALogger.logMessage('" + reqId + " stop');", JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); <ide> while (true) { <ide> String res = this.responseQueue.poll(JAVASCRIPT_TIMEOUT_SECOND, TimeUnit.SECONDS); <ide> if (res == null) {
Java
mit
f40c8296eb4558ddef29be5bdc759027c6b4bcc9
0
thandomy/foodie
package com.team3009.foodie; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.Espresso.pressBack; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.replaceText; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; @LargeTest @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void mainActivityTest() { // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html onView(withId(R.id.txt_email)) .perform(typeText("[email protected]"), closeSoftKeyboard()); onView(withId(R.id.txt_email)) .perform(typeText("12345678"), closeSoftKeyboard()); ViewInteraction appCompatButton = onView( allOf(withId(R.id.butn_login), withText("Login"), isDisplayed())); appCompatButton.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction floatingActionButton = onView( allOf(withId(R.id.list), isDisplayed())); floatingActionButton.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } pressBack(); ViewInteraction floatingActionButton3 = onView( allOf(withId(R.id.fab), isDisplayed())); floatingActionButton3.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction appCompatEditText6 = onView( allOf(withId(R.id.mealtitle), isDisplayed())); appCompatEditText6.perform(typeText("tf"), closeSoftKeyboard()); ViewInteraction appCompatEditText7 = onView( allOf(withId(R.id.mealDescription), isDisplayed())); appCompatEditText7.perform(typeText("ggg"), closeSoftKeyboard()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction appCompatButton2 = onView( allOf(withId(R.id.getPic), withText("Select Image"), isDisplayed())); appCompatButton2.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction appCompatButton3 = onView( allOf(withId(R.id.subImage), withText("Upload"), isDisplayed())); appCompatButton3.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } pressBack(); } }
app/src/androidTest/java/com/team3009/foodie/MainActivityTest.java
package com.team3009.foodie; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.Espresso.pressBack; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.replaceText; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; @LargeTest @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void mainActivityTest() { // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction appCompatEditText = onView( allOf(withId(R.id.txt_email), isDisplayed())); appCompatEditText.perform(click()); ViewInteraction appCompatEditText2 = onView( allOf(withId(R.id.txt_email), isDisplayed())); appCompatEditText2.perform(replaceText("thandom"), closeSoftKeyboard()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html ViewInteraction appCompatEditText4 = onView( allOf(withId(R.id.txt_email), withText("thandomy"), isDisplayed())); appCompatEditText4.perform(replaceText("[email protected]"), closeSoftKeyboard()); ViewInteraction appCompatEditText5 = onView( allOf(withId(R.id.txt_pass), isDisplayed())); appCompatEditText5.perform(replaceText("12345678"), closeSoftKeyboard()); pressBack(); ViewInteraction appCompatButton = onView( allOf(withId(R.id.butn_login), withText("Login"), isDisplayed())); appCompatButton.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction appCompatCheckedTextView = onView( allOf(withId(R.id.design_menu_item_text), withText("List All"), isDisplayed())); appCompatCheckedTextView.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction floatingActionButton = onView( allOf(withId(R.id.list), isDisplayed())); floatingActionButton.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } pressBack(); ViewInteraction floatingActionButton3 = onView( allOf(withId(R.id.fab), isDisplayed())); floatingActionButton3.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction appCompatEditText6 = onView( allOf(withId(R.id.mealtitle), isDisplayed())); appCompatEditText6.perform(replaceText("tf"), closeSoftKeyboard()); ViewInteraction appCompatEditText7 = onView( allOf(withId(R.id.mealDescription), isDisplayed())); appCompatEditText7.perform(replaceText("ggg"), closeSoftKeyboard()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction appCompatButton2 = onView( allOf(withId(R.id.getPic), withText("Select Image"), isDisplayed())); appCompatButton2.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } ViewInteraction appCompatButton3 = onView( allOf(withId(R.id.subImage), withText("Upload"), isDisplayed())); appCompatButton3.perform(click()); // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } pressBack(); } }
testing
app/src/androidTest/java/com/team3009/foodie/MainActivityTest.java
testing
<ide><path>pp/src/androidTest/java/com/team3009/foodie/MainActivityTest.java <ide> import static android.support.test.espresso.action.ViewActions.click; <ide> import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; <ide> import static android.support.test.espresso.action.ViewActions.replaceText; <add>import static android.support.test.espresso.action.ViewActions.typeText; <ide> import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; <ide> import static android.support.test.espresso.matcher.ViewMatchers.withId; <ide> import static android.support.test.espresso.matcher.ViewMatchers.withText; <ide> e.printStackTrace(); <ide> } <ide> <del> ViewInteraction appCompatEditText = onView( <del> allOf(withId(R.id.txt_email), isDisplayed())); <del> appCompatEditText.perform(click()); <del> <del> ViewInteraction appCompatEditText2 = onView( <del> allOf(withId(R.id.txt_email), isDisplayed())); <del> appCompatEditText2.perform(replaceText("thandom"), closeSoftKeyboard()); <del> <del> // Added a sleep statement to match the app's execution delay. <del> // The recommended way to handle such scenarios is to use Espresso idling resources: <del> // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html <del> try { <del> Thread.sleep(5000); <del> } catch (InterruptedException e) { <del> e.printStackTrace(); <del> } <del> <ide> // Added a sleep statement to match the app's execution delay. <ide> // The recommended way to handle such scenarios is to use Espresso idling resources: <ide> // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html <ide> <del> ViewInteraction appCompatEditText4 = onView( <del> allOf(withId(R.id.txt_email), withText("thandomy"), isDisplayed())); <del> appCompatEditText4.perform(replaceText("[email protected]"), closeSoftKeyboard()); <add> onView(withId(R.id.txt_email)) <add> .perform(typeText("[email protected]"), closeSoftKeyboard()); <ide> <del> ViewInteraction appCompatEditText5 = onView( <del> allOf(withId(R.id.txt_pass), isDisplayed())); <del> appCompatEditText5.perform(replaceText("12345678"), closeSoftKeyboard()); <del> <del> pressBack(); <add> onView(withId(R.id.txt_email)) <add> .perform(typeText("12345678"), closeSoftKeyboard()); <ide> <ide> ViewInteraction appCompatButton = onView( <ide> allOf(withId(R.id.butn_login), withText("Login"), isDisplayed())); <ide> // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html <ide> try { <ide> Thread.sleep(10000); <del> } catch (InterruptedException e) { <del> e.printStackTrace(); <del> } <del> <del> ViewInteraction appCompatCheckedTextView = onView( <del> allOf(withId(R.id.design_menu_item_text), withText("List All"), isDisplayed())); <del> appCompatCheckedTextView.perform(click()); <del> <del> // Added a sleep statement to match the app's execution delay. <del> // The recommended way to handle such scenarios is to use Espresso idling resources: <del> // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html <del> try { <del> Thread.sleep(5000); <ide> } catch (InterruptedException e) { <ide> e.printStackTrace(); <ide> } <ide> <ide> ViewInteraction appCompatEditText6 = onView( <ide> allOf(withId(R.id.mealtitle), isDisplayed())); <del> appCompatEditText6.perform(replaceText("tf"), closeSoftKeyboard()); <add> appCompatEditText6.perform(typeText("tf"), closeSoftKeyboard()); <add> <add> <ide> <ide> ViewInteraction appCompatEditText7 = onView( <ide> allOf(withId(R.id.mealDescription), isDisplayed())); <del> appCompatEditText7.perform(replaceText("ggg"), closeSoftKeyboard()); <add> appCompatEditText7.perform(typeText("ggg"), closeSoftKeyboard()); <ide> <ide> // Added a sleep statement to match the app's execution delay. <ide> // The recommended way to handle such scenarios is to use Espresso idling resources:
Java
apache-2.0
10b2cd98f6cdd1eefa4308c32d958eee0fcbd11f
0
lijiangdong/News
/* * Copyright (C) 2016 Li Jiangdong Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ljd.news.presentation; import android.app.Application; import android.os.Environment; import com.alipay.euler.andfix.patch.PatchManager; import com.ljd.news.presentation.internal.di.components.ApplicationComponent; import com.ljd.news.presentation.internal.di.components.DaggerApplicationComponent; import com.ljd.news.presentation.internal.di.modules.ApplicationModule; import com.ljd.news.utils.ToastUtils; import java.io.IOException; import javax.inject.Inject; import cn.sharesdk.framework.ShareSDK; import timber.log.Timber; import static timber.log.Timber.DebugTree; public class NewsApplication extends Application { private ApplicationComponent applicationComponent; @Inject PatchManager patchManager; @Override public void onCreate() { super.onCreate(); initializeInjector(); getApplicationComponent().inject(this); initToastUtils(); initTimber(); initShare(); initAndFix(); } private void initAndFix(){ patchManager.init(NewsConfig.VERSION_NAME); patchManager.loadPatch(); String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hack.apatch"; try { patchManager.addPatch(path); } catch (IOException e) { e.printStackTrace(); } } public PatchManager getPatchManager() { return patchManager; } private void initToastUtils(){ ToastUtils.register(this); } private void initTimber(){ if (NewsConfig.IS_DEBUG){ Timber.plant(new DebugTree()); } } private void initializeInjector() { this.applicationComponent = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .build(); } private void initShare(){ ShareSDK.initSDK(this); } public ApplicationComponent getApplicationComponent() { return this.applicationComponent; } }
app/src/main/java/com/ljd/news/presentation/NewsApplication.java
/* * Copyright (C) 2016 Li Jiangdong Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ljd.news.presentation; import android.app.Application; import android.os.Environment; import com.alipay.euler.andfix.patch.PatchManager; import com.ljd.news.presentation.internal.di.components.ApplicationComponent; import com.ljd.news.presentation.internal.di.components.DaggerApplicationComponent; import com.ljd.news.presentation.internal.di.modules.ApplicationModule; import com.ljd.news.utils.ToastUtils; import java.io.IOException; import javax.inject.Inject; import cn.sharesdk.framework.ShareSDK; import timber.log.Timber; import static timber.log.Timber.DebugTree; public class NewsApplication extends Application { private ApplicationComponent applicationComponent; @Inject PatchManager patchManager; @Override public void onCreate() { super.onCreate(); initializeInjector(); initToastUtils(); // initLeakCanary(); initTimber(); // initStetho(); initShare(); initAndFix(); } private void initAndFix(){ patchManager.init(NewsConfig.VERSION_NAME); patchManager.loadPatch(); String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hack.apatch"; try { patchManager.addPatch(path); } catch (IOException e) { e.printStackTrace(); } // patchManager.addPatch(); // Intent patchDownloadIntent = new Intent(this, PatchDownloadIntentService.class); // patchDownloadIntent.putExtra("url", "http://xxx/patch/app-release-fix-shine.apatch"); // startService(patchDownloadIntent); } public PatchManager getPatchManager() { return patchManager; } private void initToastUtils(){ ToastUtils.register(this); } // private void initLeakCanary(){ // LeakCanary.install(this); // } private void initTimber(){ if (NewsConfig.IS_DEBUG){ Timber.plant(new DebugTree()); } } private void initializeInjector() { this.applicationComponent = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .build(); } // private void initStetho(){ // Stetho.initializeWithDefaults(this); // } private void initShare(){ ShareSDK.initSDK(this); } public ApplicationComponent getApplicationComponent() { return this.applicationComponent; } }
commit
app/src/main/java/com/ljd/news/presentation/NewsApplication.java
commit
<ide><path>pp/src/main/java/com/ljd/news/presentation/NewsApplication.java <ide> public void onCreate() { <ide> super.onCreate(); <ide> initializeInjector(); <add> getApplicationComponent().inject(this); <ide> initToastUtils(); <del>// initLeakCanary(); <ide> initTimber(); <del>// initStetho(); <ide> initShare(); <ide> initAndFix(); <ide> } <ide> } catch (IOException e) { <ide> e.printStackTrace(); <ide> } <del>// patchManager.addPatch(); <del>// Intent patchDownloadIntent = new Intent(this, PatchDownloadIntentService.class); <del>// patchDownloadIntent.putExtra("url", "http://xxx/patch/app-release-fix-shine.apatch"); <del>// startService(patchDownloadIntent); <ide> } <ide> <ide> public PatchManager getPatchManager() { <ide> ToastUtils.register(this); <ide> } <ide> <del>// private void initLeakCanary(){ <del>// LeakCanary.install(this); <del>// } <ide> <ide> private void initTimber(){ <ide> if (NewsConfig.IS_DEBUG){ <ide> .build(); <ide> } <ide> <del>// private void initStetho(){ <del>// Stetho.initializeWithDefaults(this); <del>// } <del> <ide> private void initShare(){ <ide> ShareSDK.initSDK(this); <ide> }
Java
apache-2.0
17098e8da84347c88c8cce60d54e0d8bf4ecce24
0
tylerparsons/surfdep
/* ###################################### SurfaceGrowth.java @author Tyler Parsons @created 7 May 2014 A runnable class that manages instant- iation of models, visualization, data analysis, UI and I/O of parameters. ###################################### */ package ch13; import org.opensourcephysics.controls.AbstractSimulation; import org.opensourcephysics.controls.SimulationControl; import org.opensourcephysics.frames.PlotFrame; import org.opensourcephysics.frames.LatticeFrame; import java.awt.Color; import ch13.Parameter; import ch13.LinearRegression.Function; import java.util.ArrayList; import java.util.Scanner; public class SurfaceGrowth extends AbstractSimulation { private LatticeFrame lattice; private PlotFrame width_vs_time, width_vs_length; private LinearRegression lnw_vs_lnL; private ArrayList<Deposition> models; private Deposition model; private DepositionDataManager dataManager; /************************** * Initialization Methods * **************************/ public SurfaceGrowth() { //set up visualizations model = new BallisticDeposition(); models = new ArrayList<Deposition>(); lattice = new LatticeFrame(model.getClass().getName()); width_vs_time = new PlotFrame("ln t (t in steps)", "ln w", "ln w = b*ln t + C"); width_vs_time.setAutoscaleX(true); width_vs_time.setAutoscaleY(true); width_vs_length = new PlotFrame("ln L", "ln w_avg", "ln w = a*ln L + C (After Saturation)"); width_vs_length.setAutoscaleX(true); width_vs_length.setAutoscaleY(true); dataManager = new DepositionDataManager( "C:\\Users\\Tyler\\Documents\\Classes\\CurrentClasses\\PHYS436\\workspace\\csm\\data\\id_log.txt", "C:\\Users\\Tyler\\Documents\\Classes\\CurrentClasses\\PHYS436\\workspace\\csm\\data\\deposition_data.txt", "C:\\Users\\Tyler\\Documents\\Classes\\CurrentClasses\\PHYS436\\workspace\\csm\\data\\deposition_data.csv" ); dataManager.startTrial(); } public void initialize() { //Create a new model for each simulation model = new BallisticDeposition(); lattice.clearDrawables(); lattice.setVisible(false); width_vs_length.setVisible(false); //Set Parameters ArrayList<Parameter> params = model.parameters(); Parameter p; for (int i = 0; i < params.size(); i++) { p = params.get(i); p.value = control.getDouble(p.name); } model.init(); if (control.getBoolean("Enable Visualizations")) { lattice.addDrawable(model); lattice.setVisible(true); lattice.setPreferredMinMax( 0, model.getLength()*model.getXSpacing(), 0, model.getHeight()*model.getYSpacing() ); } } /***************** * Control Setup * *****************/ public void reset() { //Add Parameters to control ArrayList<Parameter> params = model.parameters(); Parameter p; for (int i = 0; i < params.size(); i++) { p = params.get(i); control.setValue(p.name, p.defaultValue); } //Control Values control.setValue("Save Data", true); control.setValue("Plot All", false); control.setValue("Enable Visualizations", false); enableStepsPerDisplay(true); } /**************** * Calculations * ****************/ protected void doStep() { if(model.getAverageHeight() > 0.9*model.getHeight()) { stopSimulation(); return; } try { model.step(); } catch(ArrayIndexOutOfBoundsException e) { stopSimulation(); return; } int time = model.getTime(); if(time%pointModulus(time) == 0) { width_vs_time.append(model.getLength(), Math.log(time), Math.log(model.getWidth(time))); } } public void stopRunning() { //Save model for later use, avoiding duplicate entries in model set if (!exists(model)) models.add(model); //Estimate t_cross Scanner in = new Scanner(System.in); System.out.println("Define regions over which to run the regression:"); System.out.print("ln(t_0) = "); int t_0 = (int)Math.exp(in.nextDouble()); System.out.print("ln(t_cross1) = "); int t_cross1 = (int)Math.exp(in.nextDouble()); System.out.print("ln(t_cross2) = "); int t_cross2 = (int)Math.exp(in.nextDouble()); //Run calculations model.calculateBeta(t_0, t_cross1); model.calculatelnw_avg(t_cross2); double beta_avg = calculateAverageBeta(); double alpha = calculateAlpha(); //Wrap data in Parameters to pass to dataManager as list ArrayList<Parameter> addlParams = new ArrayList<Parameter>(); addlParams.add(new Parameter("averageHeight", model.getAverageHeight())); addlParams.add(new Parameter("width", model.getWidth(model.getTime()))); addlParams.add(new Parameter("numsteps", model.getTime())); addlParams.add(new Parameter("t_cross1", t_cross1)); addlParams.add(new Parameter("t_cross2", t_cross2)); addlParams.add(new Parameter("lnw_avg", model.getlnw_avg())); addlParams.add(new Parameter("beta", model.getBeta())); addlParams.add(new Parameter("beta_avg", beta_avg)); addlParams.add(new Parameter("alpha", alpha)); addlParams.add(new Parameter("R2", lnw_vs_lnL.R2())); //Print params to control for(Parameter p: model.parameters()) control.println(p.name + " = " + p.value); for(Parameter p: addlParams) control.println(p.name + " = " + p.value); //Save, display data if (control.getBoolean("Save Data")) { dataManager.saveToTxt(model, addlParams); dataManager.saveToCSV(model, addlParams); String fileName = "L"+model.getLength()+"H"+model.getHeight(); dataManager.saveImage(lattice, "lattices", fileName + ".jpeg"); dataManager.saveImage(width_vs_time, "plots", fileName + ".jpeg"); } if (control.getBoolean("Plot All")) { plotAll(); dataManager.saveImage(width_vs_time, ".", "masterPlot.jpeg"); dataManager.saveImage(width_vs_length, ".", "alphaPlot.jpeg"); } } private double calculateAverageBeta() { double sum = 0; for(Deposition m: models) { sum += m.getBeta(); } return sum/(double)models.size(); } // Runs regression of lnw_avg vs lnL private double calculateAlpha() { //wrap lnL, lnw_avg in Functions Function lnw_avg = new Function() { public double val(double x) { return models.get((int)x).getlnw_avg(); } }; Function lnL = new Function() { public double val(double x) { return Math.log(models.get((int)x).getLength()); } }; //Pass functions to regression lnw_vs_lnL = new LinearRegression(lnL, lnw_avg, 0, (double)models.size()-1, 1); return lnw_vs_lnL.m(); } public boolean exists(Deposition m) { for (Deposition mod: models) if (m.equals(mod)) return true; return false; } /*************************** * Visualization Functions * ***************************/ /* * Point Density Calculator * - Determines density of plotted points * based on time elapsed and N_max, the * plot's point capacity. * - Density decays such that lim t->inf- * inity N(t) = N_max * - Returns a max of 1000 to continue p- * lotting for very large t * */ final static int N_max = 10000; final static int mod_max = 10000; private int pointModulus(int t) { if (t > N_max*((int)(Math.log(mod_max)))) return mod_max; return (int)(Math.exp(((double)t)/((double)N_max))) + 1; } /* * Plots all models on two different plots * - width_vs_time * -> used to measure beta * -> plots entire width array up to * total run time for each model * - lnw_vs_lnA * -> plots ln of avgerage width ag- * ainst ln L * -> runs linear regression for alpha * * */ private void plotAll() { // width_vs_time width_vs_time.clearDrawables(); for (int i = 0; i < models.size(); i++) { Deposition m = models.get(i); //plot entire width array, set color width_vs_time.setMarkerColor(i, colors[i%colors.length]); int time = m.getTime(); for (int t = 1; t <= time; t++) { long mod = pointModulus(t)*models.size(); if (t % mod == 0) { width_vs_time.append(i, Math.log(t), Math.log(m.getWidth(t))); } } } // width_vs_length width_vs_length.clearDrawables(); for (int i = 0; i < models.size(); i++) { Deposition m = models.get(i); width_vs_length.append(i, Math.log(m.getLength()), m.getlnw_avg()); } // Draw linear regression width_vs_length.addDrawable(lnw_vs_lnL); } // Color palette for plotting models private Color[] colors = {Color.CYAN, Color.ORANGE, Color.MAGENTA, Color.PINK, Color.YELLOW, Color.RED, Color.GREEN, Color.BLUE}; /******** * Main * ********/ public static void main(String[] args) { SimulationControl.createApp(new SurfaceGrowth()); } }
SurfaceGrowth.java
/* ###################################### SurfaceGrowth.java @author Tyler Parsons @created 7 May 2014 A runnable class that manages instant- iation of models, visualization, data analysis, UI and I/O of parameters. ###################################### */ package ch13; import org.opensourcephysics.controls.AbstractSimulation; import org.opensourcephysics.controls.SimulationControl; import org.opensourcephysics.frames.PlotFrame; import org.opensourcephysics.frames.LatticeFrame; import java.awt.Color; import ch13.Parameter; import ch13.LinearRegression.Function; import java.util.ArrayList; import java.util.Scanner; public class SurfaceGrowth extends AbstractSimulation { private LatticeFrame lattice; private PlotFrame width_vs_time, width_vs_length; private LinearRegression lnw_vs_lnL; private ArrayList<Deposition> models; private Deposition model; private DepositionDataManager dataManager; /************************** * Initialization Methods * **************************/ public SurfaceGrowth() { //set up visualizations model = new BallisticDiffusionModel(); models = new ArrayList<Deposition>(); lattice = new LatticeFrame(model.getClass().getName()); width_vs_time = new PlotFrame("ln t (t in steps)", "ln w", "ln w = b*ln t + C"); width_vs_time.setAutoscaleX(true); width_vs_time.setAutoscaleY(true); width_vs_length = new PlotFrame("ln L", "ln w_avg", "ln w = a*ln L + C (After Saturation)"); width_vs_length.setAutoscaleX(true); width_vs_length.setAutoscaleY(true); dataManager = new DepositionDataManager( "C:\\Users\\Tyler\\Documents\\Classes\\CurrentClasses\\PHYS436\\workspace\\csm\\data\\id_log.txt", "C:\\Users\\Tyler\\Documents\\Classes\\CurrentClasses\\PHYS436\\workspace\\csm\\data\\deposition_data.txt", "C:\\Users\\Tyler\\Documents\\Classes\\CurrentClasses\\PHYS436\\workspace\\csm\\data\\deposition_data.csv" ); dataManager.startTrial(); } public void initialize() { //Create a new model for each simulation model = new BallisticDiffusionModel(); lattice.clearDrawables(); lattice.setVisible(false); width_vs_length.setVisible(false); //Set Parameters ArrayList<Parameter> params = model.parameters(); Parameter p; for (int i = 0; i < params.size(); i++) { p = params.get(i); p.value = control.getDouble(p.name); } model.init(); if (control.getBoolean("Enable Visualizations")) { lattice.addDrawable(model); lattice.setVisible(true); lattice.setPreferredMinMax( 0, model.getLength()*model.getXSpacing(), 0, model.getHeight()*model.getYSpacing() ); } } /***************** * Control Setup * *****************/ public void reset() { //Add Parameters to control ArrayList<Parameter> params = model.parameters(); Parameter p; for (int i = 0; i < params.size(); i++) { p = params.get(i); control.setValue(p.name, p.defaultValue); } //Control Values control.setValue("Save Data", true); control.setValue("Plot All", false); control.setValue("Enable Visualizations", false); enableStepsPerDisplay(true); } /**************** * Calculations * ****************/ protected void doStep() { if(model.getAverageHeight() > 0.9*model.getHeight()) { stopSimulation(); return; } try { model.step(); } catch(ArrayIndexOutOfBoundsException e) { stopSimulation(); return; } int time = model.getTime(); if(time%pointModulus(time) == 0) { width_vs_time.append(model.getLength(), Math.log(time), Math.log(model.getWidth(time))); } } public void stopRunning() { //Save model for later use, avoiding duplicate entries in model set if (!exists(model)) models.add(model); //Estimate t_cross Scanner in = new Scanner(System.in); System.out.println("Define regions over which to run the regression:"); System.out.print("ln(t_0) = "); int t_0 = (int)Math.exp(in.nextDouble()); System.out.print("ln(t_cross1) = "); int t_cross1 = (int)Math.exp(in.nextDouble()); System.out.print("ln(t_cross2) = "); int t_cross2 = (int)Math.exp(in.nextDouble()); //Run calculations model.calculateBeta(t_0, t_cross1); model.calculatelnw_avg(t_cross2); double beta_avg = calculateAverageBeta(); double alpha = calculateAlpha(); //Wrap data in Parameters to pass to dataManager as list ArrayList<Parameter> addlParams = new ArrayList<Parameter>(); addlParams.add(new Parameter("averageHeight", model.getAverageHeight())); addlParams.add(new Parameter("width", model.getWidth(model.getTime()))); addlParams.add(new Parameter("numsteps", model.getTime())); addlParams.add(new Parameter("t_cross1", t_cross1)); addlParams.add(new Parameter("t_cross2", t_cross2)); addlParams.add(new Parameter("lnw_avg", model.getlnw_avg())); addlParams.add(new Parameter("beta", model.getBeta())); addlParams.add(new Parameter("beta_avg", beta_avg)); addlParams.add(new Parameter("alpha", alpha)); addlParams.add(new Parameter("R2", lnw_vs_lnL.R2())); //Print params to control for(Parameter p: model.parameters()) control.println(p.name + " = " + p.value); for(Parameter p: addlParams) control.println(p.name + " = " + p.value); //Save, display data if (control.getBoolean("Save Data")) { dataManager.saveToTxt(model, addlParams); dataManager.saveToCSV(model, addlParams); String fileName = "L"+model.getLength()+"H"+model.getHeight(); dataManager.saveImage(lattice, "lattices", fileName + ".jpeg"); dataManager.saveImage(width_vs_time, "plots", fileName + ".jpeg"); } if (control.getBoolean("Plot All")) { plotAll(); dataManager.saveImage(width_vs_time, ".", "masterPlot.jpeg"); dataManager.saveImage(width_vs_length, ".", "alphaPlot.jpeg"); } } private double calculateAverageBeta() { double sum = 0; for(Deposition m: models) { sum += m.getBeta(); } return sum/(double)models.size(); } // Runs regression of lnw_avg vs lnL private double calculateAlpha() { //wrap lnL, lnw_avg in Functions Function lnw_avg = new Function() { public double val(double x) { return models.get((int)x).getlnw_avg(); } }; Function lnL = new Function() { public double val(double x) { return Math.log(models.get((int)x).getLength()); } }; //Pass functions to regression lnw_vs_lnL = new LinearRegression(lnL, lnw_avg, 0, (double)models.size()-1, 1); return lnw_vs_lnL.m(); } public boolean exists(Deposition m) { for (Deposition mod: models) if (m.equals(mod)) return true; return false; } /*************************** * Visualization Functions * ***************************/ /* * Point Density Calculator * - Determines density of plotted points * based on time elapsed and N_max, the * plot's point capacity. * - Density decays such that lim t->inf- * inity N(t) = N_max * - Returns a max of 1000 to continue p- * lotting for very large t * */ final static int N_max = 10000; final static int mod_max = 10000; private int pointModulus(int t) { if (t > N_max*((int)(Math.log(mod_max)))) return mod_max; return (int)(Math.exp(((double)t)/((double)N_max))) + 1; } /* * Plots all models on two different plots * - width_vs_time * -> used to measure beta * -> plots entire width array up to * total run time for each model * - lnw_vs_lnA * -> plots ln of avgerage width ag- * ainst ln L * -> runs linear regression for alpha * * */ private void plotAll() { // width_vs_time width_vs_time.clearDrawables(); for (int i = 0; i < models.size(); i++) { Deposition m = models.get(i); //plot entire width array, set color width_vs_time.setMarkerColor(i, colors[i%colors.length]); int time = m.getTime(); for (int t = 1; t <= time; t++) { long mod = pointModulus(t)*models.size(); if (t % mod == 0) { width_vs_time.append(i, Math.log(t), Math.log(m.getWidth(t))); } } } // width_vs_length width_vs_length.clearDrawables(); for (int i = 0; i < models.size(); i++) { Deposition m = models.get(i); width_vs_length.append(i, Math.log(m.getLength()), m.getlnw_avg()); } // Draw linear regression width_vs_length.addDrawable(lnw_vs_lnL); } // Color palette for plotting models private Color[] colors = {Color.CYAN, Color.ORANGE, Color.MAGENTA, Color.PINK, Color.YELLOW, Color.RED, Color.GREEN, Color.BLUE}; /******** * Main * ********/ public static void main(String[] args) { SimulationControl.createApp(new SurfaceGrowth()); } }
Obscuring implementation of Ballistic Diffusion Model
SurfaceGrowth.java
Obscuring implementation of Ballistic Diffusion Model
<ide><path>urfaceGrowth.java <ide> public SurfaceGrowth() { <ide> <ide> //set up visualizations <del> model = new BallisticDiffusionModel(); <add> model = new BallisticDeposition(); <ide> models = new ArrayList<Deposition>(); <ide> lattice = new LatticeFrame(model.getClass().getName()); <ide> <ide> <ide> public void initialize() { <ide> //Create a new model for each simulation <del> model = new BallisticDiffusionModel(); <add> model = new BallisticDeposition(); <ide> lattice.clearDrawables(); <ide> lattice.setVisible(false); <ide> width_vs_length.setVisible(false);
JavaScript
mit
c774dcdcaf1a5cec9d87aac2ddbbfbe14f713275
0
nilenso/ashoka-survey-mobile,nilenso/ashoka-survey-mobile
var _ = require('lib/underscore')._; var Answer = require('models/answer'); var Choice = require('models/choice'); var Response = new Ti.App.joli.model({ table : 'responses', columns : { id : 'INTEGER PRIMARY KEY', survey_id : 'INTEGER', web_id : 'INTEGER', status : 'TEXT', updated_at : 'TEXT' }, methods : { createRecord : function(surveyID, status, answersData) { var record = this.newRecord({ survey_id : surveyID, status : status, updated_at : (new Date()).toString() }); record.save(); _(answersData).each(function(answer) { Answer.createRecord(answer, record.id); }); Ti.API.info("Resp ID is " + record.id); return true; }, validate : function(answersData, status) { var errors = {}; _(answersData).each(function(answerData) { var answerErrors = Answer.validate(answerData, status); if (!_.isEmpty(answerErrors)) { errors[answerData.question_id] = answerErrors; } }); return errors; } }, objectMethods : { prepRailsParams : function() { var answer_attributes = {} _(this.answers()).each(function(answer, index) { answer_attributes[index] = {}; answer_attributes[index]['question_id'] = answer.question_id; answer_attributes[index]['updated_at'] = answer.updated_at; if (answer.web_id) answer_attributes[index]['id'] = answer.web_id; if (answer.hasChoices()) answer_attributes[index]['option_ids'] = answer.optionIDs(); else answer_attributes[index]['content'] = answer.content; }); return answer_attributes; }, update : function(status, answersData) { Ti.API.info("updating response"); this.fromArray({ 'id' : this.id, 'survey_id' : this.survey_id, 'web_id' : this.web_id, 'status' : status, 'updated_at' : (new Date()).toString() }); var self = this; _(answersData).each(function(answerData) { var answer = Answer.findOneById(answerData.id); if (answer) answer.update(answerData.content); else Answer.createRecord(answerData, self.id); }); this.deleteObsoleteAnswers(answersData); this.save(); Ti.App.fireEvent('updatedResponse'); Ti.API.info("response updated at" + this.updated_at); }, deleteObsoleteAnswers : function(answersData) { var answerIDs = _(answersData).map(function(answerData) { if(answerData.id) return answerData.id; }); var obsoleteAnswers = _(this.answers()).select(function(answer) { Ti.API.info("answer id " + answer.id); return !_(answerIDs).include(answer.id); }); _(obsoleteAnswers).each(function(answer) { answer.destroy_choices(); answer.destroy(); }); }, sync : function() { //TODO: REFACTOR THIS. var url = Ti.App.Properties.getString('server_url') + '/api/responses'; var self = this; this.synced = false; var params = {}; params['answers_attributes'] = this.prepRailsParams(); params['status'] = this.status; params['survey_id'] = this.survey_id; params['updated_at'] = this.updated_at; var client = Ti.Network.createHTTPClient({ // function called when the response data is available onload : function(e) { Ti.API.info("Synced response successfully: " + this.responseText); self.has_error = false; self.synced = true; Ti.App.fireEvent('response.sync', { survey_id : self.survey_id }); var received_response = JSON.parse(this.responseText); if (received_response['status'] == "complete") { self.destroy_answers(); self.destroy(); } else { self.fromArray({ 'id' : self.id, 'survey_id' : self.survey_id, 'web_id' : received_response['id'], 'status' : received_response['status'], 'updated_at' : (new Date()).toString() }); _(self.answers()).each(function(answer, index) { answer.destroy_choices(); answer.destroy(); var new_answer = Answer.newRecord({ 'response_id' : self.id, 'question_id' : received_response.answers[index].question_id, 'web_id' : received_response.answers[index].id, 'content' : received_response.answers[index].content, 'updated_at' : (new Date()).toString(), }); new_answer.save(); _(received_response.answers[index].choices).each(function(choice) { choice.answer_id = new_answer.id; Choice.newRecord(choice).save(); }) }); Ti.API.info("before save response WEB ID: " + self.web_id); self.save(); Ti.API.info("after save response WEB ID: " + self.web_id); } }, // function called when an error occurs, including a timeout onerror : function(e) { if(this.status == '410') { // Response deleted on server Ti.API.info("Response deleted on server: " + this.responseText); self.destroy_answers(); self.destroy(); } else { Ti.API.info("Erroneous Response: " + this.responseText); self.has_error = true; } self.synced = true; Ti.App.fireEvent('response.sync', { survey_id : self.survey_id }); }, timeout : 5000 // in milliseconds }); var method = self.web_id ? "PUT" : "POST"; url += self.web_id ? "/" + self.web_id : ""; url += ".json"; Ti.API.info("method: " + method); client.open(method, url); client.setRequestHeader("Content-Type", "application/json"); client.send(JSON.stringify(params)); }, answers : function() { return Answer.findBy('response_id', this.id) }, destroy_answers : function() { _(this.answers()).each(function(answer){ answer.destroy(); }) } } }); Ti.App.joli.models.initialize(); module.exports = Response;
Resources/models/response.js
var _ = require('lib/underscore')._; var Answer = require('models/answer'); var Choice = require('models/choice'); var Response = new Ti.App.joli.model({ table : 'responses', columns : { id : 'INTEGER PRIMARY KEY', survey_id : 'INTEGER', web_id : 'INTEGER', status : 'TEXT', updated_at : 'TEXT' }, methods : { createRecord : function(surveyID, status, answersData) { var record = this.newRecord({ survey_id : surveyID, status : status, updated_at : (new Date()).toString() }); record.save(); _(answersData).each(function(answer) { Answer.createRecord(answer, record.id); }); Ti.API.info("Resp ID is " + record.id); return true; }, validate : function(answersData, status) { var errors = {}; _(answersData).each(function(answerData) { var answerErrors = Answer.validate(answerData, status); if (!_.isEmpty(answerErrors)) { errors[answerData.question_id] = answerErrors; } }); return errors; } }, objectMethods : { prepRailsParams : function() { var answer_attributes = {} _(this.answers()).each(function(answer, index) { answer_attributes[index] = {}; answer_attributes[index]['question_id'] = answer.question_id; answer_attributes[index]['updated_at'] = answer.updated_at; if (answer.web_id) answer_attributes[index]['id'] = answer.web_id; if (answer.hasChoices()) answer_attributes[index]['option_ids'] = answer.optionIDs(); else answer_attributes[index]['content'] = answer.content; }); return answer_attributes; }, update : function(status, answersData) { Ti.API.info("updating response"); this.fromArray({ 'id' : this.id, 'survey_id' : this.survey_id, 'web_id' : this.web_id, 'status' : status, 'updated_at' : (new Date()).toString() }); _(answersData).each(function(answerData) { var answer = Answer.findOneById(answerData.id); answer.update(answerData.content); }); this.save(); Ti.App.fireEvent('updatedResponse'); Ti.API.info("response updated at" + this.updated_at); }, sync : function() { //TODO: REFACTOR THIS. var url = Ti.App.Properties.getString('server_url') + '/api/responses'; var self = this; this.synced = false; var params = {}; params['answers_attributes'] = this.prepRailsParams(); params['status'] = this.status; params['survey_id'] = this.survey_id; params['updated_at'] = this.updated_at; var client = Ti.Network.createHTTPClient({ // function called when the response data is available onload : function(e) { Ti.API.info("Synced response successfully: " + this.responseText); self.has_error = false; self.synced = true; Ti.App.fireEvent('response.sync', { survey_id : self.survey_id }); var received_response = JSON.parse(this.responseText); if (received_response['status'] == "complete") { self.destroy_answers(); self.destroy(); } else { self.fromArray({ 'id' : self.id, 'survey_id' : self.survey_id, 'web_id' : received_response['id'], 'status' : received_response['status'], 'updated_at' : (new Date()).toString() }); _(self.answers()).each(function(answer, index) { answer.destroy_choices(); answer.destroy(); var new_answer = Answer.newRecord({ 'response_id' : self.id, 'question_id' : received_response.answers[index].question_id, 'web_id' : received_response.answers[index].id, 'content' : received_response.answers[index].content, 'updated_at' : (new Date()).toString(), }); new_answer.save(); _(received_response.answers[index].choices).each(function(choice) { choice.answer_id = new_answer.id; Choice.newRecord(choice).save(); }) }); Ti.API.info("before save response WEB ID: " + self.web_id); self.save(); Ti.API.info("after save response WEB ID: " + self.web_id); } }, // function called when an error occurs, including a timeout onerror : function(e) { if(this.status == '410') { // Response deleted on server Ti.API.info("Response deleted on server: " + this.responseText); self.destroy_answers(); self.destroy(); } else { Ti.API.info("Erroneous Response: " + this.responseText); self.has_error = true; } self.synced = true; Ti.App.fireEvent('response.sync', { survey_id : self.survey_id }); }, timeout : 5000 // in milliseconds }); var method = self.web_id ? "PUT" : "POST"; url += self.web_id ? "/" + self.web_id : ""; url += ".json"; Ti.API.info("method: " + method); client.open(method, url); client.setRequestHeader("Content-Type", "application/json"); client.send(JSON.stringify(params)); }, answers : function() { return Answer.findBy('response_id', this.id) }, destroy_answers : function() { _(this.answers()).each(function(answer){ answer.destroy(); }) } } }); Ti.App.joli.models.initialize(); module.exports = Response;
Delete obsolete answers to subquestions on saving a response
Resources/models/response.js
Delete obsolete answers to subquestions on saving a response
<ide><path>esources/models/response.js <ide> 'status' : status, <ide> 'updated_at' : (new Date()).toString() <ide> }); <add> var self = this; <ide> _(answersData).each(function(answerData) { <ide> var answer = Answer.findOneById(answerData.id); <del> answer.update(answerData.content); <add> if (answer) <add> answer.update(answerData.content); <add> else <add> Answer.createRecord(answerData, self.id); <ide> }); <add> this.deleteObsoleteAnswers(answersData); <ide> this.save(); <ide> Ti.App.fireEvent('updatedResponse'); <ide> Ti.API.info("response updated at" + this.updated_at); <add> }, <add> <add> deleteObsoleteAnswers : function(answersData) { <add> var answerIDs = _(answersData).map(function(answerData) { <add> if(answerData.id) return answerData.id; <add> }); <add> var obsoleteAnswers = _(this.answers()).select(function(answer) { <add> Ti.API.info("answer id " + answer.id); <add> return !_(answerIDs).include(answer.id); <add> }); <add> _(obsoleteAnswers).each(function(answer) { <add> answer.destroy_choices(); <add> answer.destroy(); <add> }); <ide> }, <ide> <ide> sync : function() {
Java
bsd-3-clause
b2b957e6b31f5078b7a166530e2d43e965917c16
0
interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl
/* $Id$ */ strictfp class BodyTreeNode { // Instance counter; public static int InstanceCount = 0; // Debugging stuff; public static boolean btnDebug; /* private static final String depthStr[] = { "", ".", "..", "...", "....", ".....", "......", ".......", "........", ".........", "..........", "...........", "............", ".............", "..............", "...............", "................", ".................", "..................", "...................", "....................", }; */ // Variables protected GlobalData btnGd; protected double btnCenter_x; protected double btnCenter_y; protected double btnCenter_z; protected double btnHalfSize; private int btnBodyIndex[]; private int btnBodyCount; private int btnChildrenCount; private BodyTreeNode btnChildren[]; private double btnTotalMass; public double btnCenterOfMass_x; public double btnCenterOfMass_y; public double btnCenterOfMass_z; private int btnDepth; private double btnMaxTheta; public boolean btnCenterOfMassValid; public boolean btnCenterOfMassReceived; protected boolean btnIsLeaf; // Constructors and support functions public Body getBody(int index) { return btnGd.gdBodies[btnBodyIndex[index]]; } public int getBodyIndex(int index) { return btnBodyIndex[index]; } public BodyTreeNode getChild(int index) { return btnChildren[index]; } public double getMaxTheta() { return btnMaxTheta; } public int getNumBodies() { return btnBodyCount; } public double getSize() { return btnHalfSize * 2; } public double getMass() { return btnTotalMass; } public boolean isLeaf() { return btnIsLeaf; } protected void Initialize(GlobalData g, double center_x, double center_y, double center_z, double HalfSize, int depth) { btnGd = g; btnCenter_x = center_x; btnCenter_y = center_y; btnCenter_z = center_z; btnHalfSize = HalfSize; btnBodyCount = 0; btnIsLeaf = true; btnBodyIndex = new int[btnGd.gdMaxBodiesPerNode]; btnChildren = null; btnCenterOfMass_x = 0; btnCenterOfMass_y = 0; btnCenterOfMass_z = 0; btnChildrenCount = 0; btnDepth = depth; btnMaxTheta = btnGd.gdThetaSq * HalfSize * HalfSize; btnCenterOfMassValid = false; btnCenterOfMassReceived = false; InstanceCount++; } public BodyTreeNode(GlobalData g) { Initialize(g, 0, 0, 0, g.GD_BODY_RANGE, 0); } public BodyTreeNode(GlobalData g, double center_x, double center_y, double center_z, double HalfSize, int depth) { Initialize(g, center_x, center_y, center_z, HalfSize, depth); } int dumpTree(int level, int maxlevel) { int i, bodies = btnBodyCount; if (!btnIsLeaf) { for (i = 0; i < 8; i++) if (btnChildren[i] != null) bodies += btnChildren[i].dumpTree(level + 1, maxlevel); } if (level <= maxlevel) { String str = "l" + level + ", center (" + btnCenter_x + "," + btnCenter_y + "," + btnCenter_z + "), size " + btnHalfSize + ", cofm (" + btnCenterOfMass_x + "," + btnCenterOfMass_y + "," + btnCenterOfMass_z + "), leaf " + (btnIsLeaf ? 1 : 0) + ", bodies " + bodies + ": "; if (btnIsLeaf) for (int j = 0; j < btnBodyCount; j++) str += btnGd.gdBodies[btnBodyIndex[j]].bNumber + " "; btnGd.debugStr(str); } return bodies; } // Tree management routines private void createChild(int i) { double newSize = btnHalfSize / 2.0; switch (i) { case 7: btnChildren[7] = new BodyTreeNode(btnGd, btnCenter_x + newSize, btnCenter_y + newSize, btnCenter_z + newSize, newSize, btnDepth + 1); break; case 6: btnChildren[6] = new BodyTreeNode(btnGd, btnCenter_x - newSize, btnCenter_y + newSize, btnCenter_z + newSize, newSize, btnDepth + 1); break; case 5: btnChildren[5] = new BodyTreeNode(btnGd, btnCenter_x + newSize, btnCenter_y - newSize, btnCenter_z + newSize, newSize, btnDepth + 1); break; case 4: btnChildren[4] = new BodyTreeNode(btnGd, btnCenter_x - newSize, btnCenter_y - newSize, btnCenter_z + newSize, newSize, btnDepth + 1); break; case 3: btnChildren[3] = new BodyTreeNode(btnGd, btnCenter_x + newSize, btnCenter_y + newSize, btnCenter_z - newSize, newSize, btnDepth + 1); break; case 2: btnChildren[2] = new BodyTreeNode(btnGd, btnCenter_x - newSize, btnCenter_y + newSize, btnCenter_z - newSize, newSize, btnDepth + 1); break; case 1: btnChildren[1] = new BodyTreeNode(btnGd, btnCenter_x + newSize, btnCenter_y - newSize, btnCenter_z - newSize, newSize, btnDepth + 1); break; case 0: btnChildren[0] = new BodyTreeNode(btnGd, btnCenter_x - newSize, btnCenter_y - newSize, btnCenter_z - newSize, newSize, btnDepth + 1); break; } btnChildrenCount++; } private BodyTreeNode findContainingChild(int bodyIndex) { int index = 0; double dx, dy, dz; dx = btnGd.gdBodies[bodyIndex].bPos.x - btnCenter_x; dy = btnGd.gdBodies[bodyIndex].bPos.y - btnCenter_y; dz = btnGd.gdBodies[bodyIndex].bPos.z - btnCenter_z; if (dx >= 0) index += 1; if (dy >= 0) index += 2; if (dz >= 0) index += 4; if (Math.abs(dx) > btnHalfSize || Math.abs(dy) > btnHalfSize || Math.abs(dz) > btnHalfSize) { debugFatalStr("Error! Tree inconsistency detected, while trying to distribute body: " + bodyIndex); debugFatalStr("Cell Center: [ " + btnCenter_x + ", " + btnCenter_y + ", " + btnCenter_z + " ]"); debugFatalStr("Cell Size: " + btnHalfSize); debugFatalStr("Body: [ " + btnGd.gdBodies[bodyIndex].bPos.x + ", " + btnGd.gdBodies[bodyIndex].bPos.y + ", " + btnGd.gdBodies[bodyIndex].bPos.z + " ]"); } else { if (btnChildren[index] == null) createChild(index); return btnChildren[index]; } return null; // generates a null pointer exception if the tree is inconsistent } private BodyTreeNode findContainingChild(CenterOfMass c) { int index = 0; double dx, dy, dz; dx = c.cofmCenter_x - btnCenter_x; dy = c.cofmCenter_y - btnCenter_y; dz = c.cofmCenter_z - btnCenter_z; if (dx >= 0) index += 1; if (dy >= 0) index += 2; if (dz >= 0) index += 4; if (Math.abs(dx) > btnHalfSize || Math.abs(dy) > btnHalfSize || Math.abs(dz) > btnHalfSize) { debugFatalStr("Error! Tree inconsistency detected, while trying to add a center of mass! "); debugFatalStr("Cell Center: [ " + btnCenter_x + ", " + btnCenter_y + ", " + btnCenter_z + " ]"); debugFatalStr("Cell Size: " + btnHalfSize + " dx=" + dx + " dy=" + dy + " dz=" + dz); new Exception().printStackTrace(); } else { if (btnChildren[index] == null) createChild(index); return btnChildren[index]; } return null; // generates a null pointer exception if the tree is inconsistent } private void Split() { int i, body; // Create children btnIsLeaf = false; debugStr("Splitting node, bodies: " + btnBodyCount); btnChildren = new BodyTreeNode[8]; for (i = 0; i < 8; i++) btnChildren[i] = null; // And redistribute all bodies for (i = 0; i < btnBodyCount; i++) { body = btnBodyIndex[i]; findContainingChild(body).addBody(body); } btnBodyCount = 0; btnChildrenCount = 0; } public void addBody(int bodyIndex) { btnCenterOfMassValid = false; if (btnIsLeaf) { if (btnBodyCount < btnGd.gdMaxBodiesPerNode) { btnBodyIndex[btnBodyCount++] = bodyIndex; return; } else { Split(); } } findContainingChild(bodyIndex).addBody(bodyIndex); } void addCenterOfMass(CenterOfMass c) { // indicate that the center of mass has changed btnCenterOfMassValid = false; /* This was a direct comparison (with ==) but this turns out to * be not stable. (Ceriel) */ if (Math.abs(c.cofmCenter_x - btnCenter_x) < btnGd.GD_DOUBLE_EPSILON && Math.abs(c.cofmCenter_y - btnCenter_y) < btnGd.GD_DOUBLE_EPSILON && Math.abs(c.cofmCenter_z - btnCenter_z) < btnGd.GD_DOUBLE_EPSILON) { /* if (c.cofmCenter_x == btnCenter_x && c.cofmCenter_y == btnCenter_y && c.cofmCenter_z == btnCenter_z ) { */ // this is the right node, add the center of mass /* btnGd.debugStr("adding COFM: (" + btnCenter_x + "," + btnCenter_y + "," + btnCenter_z + "), " + c.cofmMass ); */ if (btnCenterOfMassReceived) { btnTotalMass += c.cofmMass; btnCenterOfMass_x += c.cofmCenterOfMass_x * c.cofmMass; btnCenterOfMass_y += c.cofmCenterOfMass_y * c.cofmMass; btnCenterOfMass_z += c.cofmCenterOfMass_z * c.cofmMass; } else { btnTotalMass = c.cofmMass; btnCenterOfMass_x = c.cofmCenterOfMass_x * c.cofmMass; btnCenterOfMass_y = c.cofmCenterOfMass_y * c.cofmMass; btnCenterOfMass_z = c.cofmCenterOfMass_z * c.cofmMass; btnCenterOfMassReceived = true; } /* btnGd.debugStr("updating COFM, now: (" + btnCenterOfMass_x + "," + btnCenterOfMass_y + "," + btnCenterOfMass_z + "), " + c.cofmMass ); */ return; } if (btnIsLeaf) { Split(); } findContainingChild(c).addCenterOfMass(c); } // Tree integrity check and support routines /* private boolean check( vec3 center, double size, vec3 pos ) { double maxx = center.x + size; double minx = center.x - size; double maxy = center.y + size; double miny = center.y - size; double maxz = center.z + size; double minz = center.z - size; if (pos.x>maxx) return false; if (pos.x<minx) return false; if (pos.y>maxy) return false; if (pos.y<miny) return false; if (pos.z>maxz) return false; if (pos.z<minz) return false; return true; } */ /* public int sanityCheck() { int SaneChildren = 0, i, InsaneBodies; if (btnIsLeaf) { // check all contained bodies to see if they really fit into this cell InsaneBodies = 0; for (i=0;i<btnBodyCount;i++) { int bi = btnBodyIndex[i]; if (!check( btnCenter, btnHalfSize, btnGd.gdBodies[bi].bPos)) { InsaneBodies++; debugStr( "Body: x: " + btnGd.gdBodies[bi].bPos.x + ", y: " + btnGd.gdBodies[bi].bPos.y + ", z: " + btnGd.gdBodies[bi].bPos.z ); } } if (InsaneBodies>0) { debugStr( "^^^ (" + InsaneBodies + "/" + btnBodyCount + ") outside cell bounds, center: " + "x: " + btnCenter.x + ", y: " + btnCenter.y + ", z: " + btnCenter.z + ", size: " + btnHalfSize ); SaneChildren = 1; } } else { // this is an internal node, check all children. for (i=0;i<8;i++) { if (btnChildren[i]!=null) { SaneChildren += btnChildren[i].sanityCheck(); } } } return SaneChildren; } */ public int countBodies() { int i, bodies = 0; if (btnIsLeaf) { return btnBodyCount; } else { for (i = 0; i < 8; i++) { if (btnChildren[i] != null) bodies += btnChildren[i].countBodies(); } } return bodies; } public void Iterate(int Depth) { int i; for (i = 0; i < Depth; i++) { System.out.print("."); } if (btnIsLeaf) { debugStr("LeafNode, Bodies: " + btnBodyCount + " of " + btnGd.gdMaxBodiesPerNode + "."); } else { debugStr("Internal Node, Children: " + btnChildrenCount + " of 8"); for (i = 0; i < 8; i++) { if (btnChildren[i] != null) btnChildren[i].Iterate((Depth + 1)); } } } /* private String getDepthStr() { return depthStr[ btnDepth ]; } */ protected void debugStr(String s) { if (btnDebug) btnGd.debugStr(s); } protected void debugFatalStr(String s) { btnGd.debugStr(s); } /* public static void setDebugMode( boolean debug ) { btnDebug = debug; } */ public void ComputeCenterOfMass() { int i; double recip; if (!btnCenterOfMassValid) { btnCenterOfMassValid = true; if (!btnCenterOfMassReceived) { btnTotalMass = 0.0; btnCenterOfMass_x = 0; btnCenterOfMass_y = 0; btnCenterOfMass_z = 0; } if (btnIsLeaf) { // Compute Center of mass of all bodies in this cell. for (i = 0; i < btnBodyCount; i++) { Body b = btnGd.gdBodies[btnBodyIndex[i]]; btnCenterOfMass_x += b.bPos.x * b.bMass; btnCenterOfMass_y += b.bPos.y * b.bMass; btnCenterOfMass_z += b.bPos.z * b.bMass; btnTotalMass += b.bMass; } // the following may generate an exception! recip = 1.0 / btnTotalMass; btnCenterOfMass_x *= recip; btnCenterOfMass_y *= recip; btnCenterOfMass_z *= recip; } else { // Compute the center of mass of all children if it is an internal node btnCenterOfMass_x = 0; btnCenterOfMass_y = 0; btnCenterOfMass_z = 0; btnTotalMass = 0; for (i = 0; i < 8; i++) { BodyTreeNode b = btnChildren[i]; if (b != null) { b.ComputeCenterOfMass(); btnCenterOfMass_x += b.btnCenterOfMass_x * b.btnTotalMass; btnCenterOfMass_y += b.btnCenterOfMass_y * b.btnTotalMass; btnCenterOfMass_z += b.btnCenterOfMass_z * b.btnTotalMass; btnTotalMass += b.btnTotalMass; } } recip = 1.0 / btnTotalMass; btnCenterOfMass_x *= recip; btnCenterOfMass_y *= recip; btnCenterOfMass_z *= recip; } } System.err.println("set com to: " + btnCenterOfMass_x + ", " + btnCenterOfMass_y + ", " + btnCenterOfMass_z); } void Barnes(Body b) { // Compute the acceleration this node acts on the body double Diff_x = btnCenterOfMass_x - b.bPos.x; double Diff_y = btnCenterOfMass_y - b.bPos.y; double Diff_z = btnCenterOfMass_z - b.bPos.z; double DistSq = Diff_x * Diff_x + Diff_y * Diff_y + Diff_z * Diff_z; if (DistSq >= btnMaxTheta) { // The distance was large enough to use the treenode instead of iterating all bodies. DistSq += btnGd.gdSoftSQ; double Dist = Math.sqrt(DistSq); double Factor = btnTotalMass / (DistSq * Dist); b.bAcc.x += Diff_x * Factor; b.bAcc.y += Diff_y * Factor; b.bAcc.z += Diff_z * Factor; b.bWeight++; } else { // The distance was too small. if (btnIsLeaf) { // compute accelerations on the body due to all bodies in this node. for (int i = 0; i < btnBodyCount; i++) { Body b2 = btnGd.gdBodies[btnBodyIndex[i]]; Diff_x = b2.bPos.x - b.bPos.x; Diff_y = b2.bPos.y - b.bPos.y; Diff_z = b2.bPos.z - b.bPos.z; DistSq = Diff_x * Diff_x + Diff_y * Diff_y + Diff_z * Diff_z + btnGd.gdSoftSQ; double Dist = Math.sqrt(DistSq); double Factor = b2.bMass / (DistSq * Dist); b.bAcc.x += Diff_x * Factor; b.bAcc.y += Diff_y * Factor; b.bAcc.z += Diff_z * Factor; b.bWeight++; } } else { for (int i = 0; i < 8; i++) if (btnChildren[i] != null) btnChildren[i].Barnes(b); } } System.err.println("acc for body " + " = " + b.bAcc.x + ", " + b.bAcc.y + ", " + b.bAcc.z); } int ComputeLeafAccelerationsBarnes(BodyTreeNode root) { int i, Weight = 0; Body b; // Iterate the tree for each body for (i = 0; i < btnBodyCount; i++) { b = btnGd.gdBodies[btnBodyIndex[i]]; // check if it is not an essential body if (b.bNumber == -1) continue; b.bWeight = 0; b.bAcc.x = 0; b.bAcc.y = 0; b.bAcc.z = 0; root.Barnes(b); /* btnGd.debugStr("computed accels for body " + b.bNumber + ", weight " + b.bWeight + ", (" + b.bAcc.x + "," + b.bAcc.y + "," + b.bAcc.z + ")" ); */ Weight += b.bWeight; } return Weight; } int ComputeAccelerationsBarnes(BodyTreeNode root) { int i, interactions = 0; if (btnIsLeaf) { interactions = ComputeLeafAccelerationsBarnes(root); } else { for (i = 0; i < 8; i++) { if (btnChildren[i] != null) interactions += btnChildren[i] .ComputeAccelerationsBarnes(root); } } return interactions; } }
apps/rmi/barnes/BodyTreeNode.java
/* $Id$ */ strictfp class BodyTreeNode { // Instance counter; public static int InstanceCount = 0; // Debugging stuff; public static boolean btnDebug; /* private static final String depthStr[] = { "", ".", "..", "...", "....", ".....", "......", ".......", "........", ".........", "..........", "...........", "............", ".............", "..............", "...............", "................", ".................", "..................", "...................", "....................", }; */ // Variables protected GlobalData btnGd; protected double btnCenter_x; protected double btnCenter_y; protected double btnCenter_z; protected double btnHalfSize; private int btnBodyIndex[]; private int btnBodyCount; private int btnChildrenCount; private BodyTreeNode btnChildren[]; private double btnTotalMass; public double btnCenterOfMass_x; public double btnCenterOfMass_y; public double btnCenterOfMass_z; private int btnDepth; private double btnMaxTheta; public boolean btnCenterOfMassValid; public boolean btnCenterOfMassReceived; protected boolean btnIsLeaf; // Constructors and support functions public Body getBody(int index) { return btnGd.gdBodies[btnBodyIndex[index]]; } public int getBodyIndex(int index) { return btnBodyIndex[index]; } public BodyTreeNode getChild(int index) { return btnChildren[index]; } public double getMaxTheta() { return btnMaxTheta; } public int getNumBodies() { return btnBodyCount; } public double getSize() { return btnHalfSize * 2; } public double getMass() { return btnTotalMass; } public boolean isLeaf() { return btnIsLeaf; } protected void Initialize(GlobalData g, double center_x, double center_y, double center_z, double HalfSize, int depth) { btnGd = g; btnCenter_x = center_x; btnCenter_y = center_y; btnCenter_z = center_z; btnHalfSize = HalfSize; btnBodyCount = 0; btnIsLeaf = true; btnBodyIndex = new int[btnGd.gdMaxBodiesPerNode]; btnChildren = null; btnCenterOfMass_x = 0; btnCenterOfMass_y = 0; btnCenterOfMass_z = 0; btnChildrenCount = 0; btnDepth = depth; btnMaxTheta = btnGd.gdThetaSq * HalfSize * HalfSize; btnCenterOfMassValid = false; btnCenterOfMassReceived = false; InstanceCount++; } public BodyTreeNode(GlobalData g) { Initialize(g, 0, 0, 0, g.GD_BODY_RANGE, 0); } public BodyTreeNode(GlobalData g, double center_x, double center_y, double center_z, double HalfSize, int depth) { Initialize(g, center_x, center_y, center_z, HalfSize, depth); } int dumpTree(int level, int maxlevel) { int i, bodies = btnBodyCount; if (!btnIsLeaf) { for (i = 0; i < 8; i++) if (btnChildren[i] != null) bodies += btnChildren[i].dumpTree(level + 1, maxlevel); } if (level <= maxlevel) { String str = "l" + level + ", center (" + btnCenter_x + "," + btnCenter_y + "," + btnCenter_z + "), size " + btnHalfSize + ", cofm (" + btnCenterOfMass_x + "," + btnCenterOfMass_y + "," + btnCenterOfMass_z + "), leaf " + (btnIsLeaf ? 1 : 0) + ", bodies " + bodies + ": "; if (btnIsLeaf) for (int j = 0; j < btnBodyCount; j++) str += btnGd.gdBodies[btnBodyIndex[j]].bNumber + " "; btnGd.debugStr(str); } return bodies; } // Tree management routines private void createChild(int i) { double newSize = btnHalfSize / 2.0; switch (i) { case 7: btnChildren[7] = new BodyTreeNode(btnGd, btnCenter_x + newSize, btnCenter_y + newSize, btnCenter_z + newSize, newSize, btnDepth + 1); break; case 6: btnChildren[6] = new BodyTreeNode(btnGd, btnCenter_x - newSize, btnCenter_y + newSize, btnCenter_z + newSize, newSize, btnDepth + 1); break; case 5: btnChildren[5] = new BodyTreeNode(btnGd, btnCenter_x + newSize, btnCenter_y - newSize, btnCenter_z + newSize, newSize, btnDepth + 1); break; case 4: btnChildren[4] = new BodyTreeNode(btnGd, btnCenter_x - newSize, btnCenter_y - newSize, btnCenter_z + newSize, newSize, btnDepth + 1); break; case 3: btnChildren[3] = new BodyTreeNode(btnGd, btnCenter_x + newSize, btnCenter_y + newSize, btnCenter_z - newSize, newSize, btnDepth + 1); break; case 2: btnChildren[2] = new BodyTreeNode(btnGd, btnCenter_x - newSize, btnCenter_y + newSize, btnCenter_z - newSize, newSize, btnDepth + 1); break; case 1: btnChildren[1] = new BodyTreeNode(btnGd, btnCenter_x + newSize, btnCenter_y - newSize, btnCenter_z - newSize, newSize, btnDepth + 1); break; case 0: btnChildren[0] = new BodyTreeNode(btnGd, btnCenter_x - newSize, btnCenter_y - newSize, btnCenter_z - newSize, newSize, btnDepth + 1); break; } btnChildrenCount++; } private BodyTreeNode findContainingChild(int bodyIndex) { int index = 0; double dx, dy, dz; dx = btnGd.gdBodies[bodyIndex].bPos.x - btnCenter_x; dy = btnGd.gdBodies[bodyIndex].bPos.y - btnCenter_y; dz = btnGd.gdBodies[bodyIndex].bPos.z - btnCenter_z; if (dx >= 0) index += 1; if (dy >= 0) index += 2; if (dz >= 0) index += 4; if (Math.abs(dx) > btnHalfSize || Math.abs(dy) > btnHalfSize || Math.abs(dz) > btnHalfSize) { debugFatalStr("Error! Tree inconsistency detected, while trying to distribute body: " + bodyIndex); debugFatalStr("Cell Center: [ " + btnCenter_x + ", " + btnCenter_y + ", " + btnCenter_z + " ]"); debugFatalStr("Cell Size: " + btnHalfSize); debugFatalStr("Body: [ " + btnGd.gdBodies[bodyIndex].bPos.x + ", " + btnGd.gdBodies[bodyIndex].bPos.y + ", " + btnGd.gdBodies[bodyIndex].bPos.z + " ]"); } else { if (btnChildren[index] == null) createChild(index); return btnChildren[index]; } return null; // generates a null pointer exception if the tree is inconsistent } private BodyTreeNode findContainingChild(CenterOfMass c) { int index = 0; double dx, dy, dz; dx = c.cofmCenter_x - btnCenter_x; dy = c.cofmCenter_y - btnCenter_y; dz = c.cofmCenter_z - btnCenter_z; if (dx >= 0) index += 1; if (dy >= 0) index += 2; if (dz >= 0) index += 4; if (Math.abs(dx) > btnHalfSize || Math.abs(dy) > btnHalfSize || Math.abs(dz) > btnHalfSize) { debugFatalStr("Error! Tree inconsistency detected, while trying to add a center of mass! "); debugFatalStr("Cell Center: [ " + btnCenter_x + ", " + btnCenter_y + ", " + btnCenter_z + " ]"); debugFatalStr("Cell Size: " + btnHalfSize + " dx=" + dx + " dy=" + dy + " dz=" + dz); new Exception().printStackTrace(); } else { if (btnChildren[index] == null) createChild(index); return btnChildren[index]; } return null; // generates a null pointer exception if the tree is inconsistent } private void Split() { int i, body; // Create children btnIsLeaf = false; debugStr("Splitting node, bodies: " + btnBodyCount); btnChildren = new BodyTreeNode[8]; for (i = 0; i < 8; i++) btnChildren[i] = null; // And redistribute all bodies for (i = 0; i < btnBodyCount; i++) { body = btnBodyIndex[i]; findContainingChild(body).addBody(body); } btnBodyCount = 0; btnChildrenCount = 0; } public void addBody(int bodyIndex) { btnCenterOfMassValid = false; if (btnIsLeaf) { if (btnBodyCount < btnGd.gdMaxBodiesPerNode) { btnBodyIndex[btnBodyCount++] = bodyIndex; return; } else { Split(); } } findContainingChild(bodyIndex).addBody(bodyIndex); } void addCenterOfMass(CenterOfMass c) { // indicate that the center of mass has changed btnCenterOfMassValid = false; /* This was a direct comparison (with ==) but this turns out to * be not stable. (Ceriel) */ if (Math.abs(c.cofmCenter_x - btnCenter_x) < btnGd.GD_DOUBLE_EPSILON && Math.abs(c.cofmCenter_y - btnCenter_y) < btnGd.GD_DOUBLE_EPSILON && Math.abs(c.cofmCenter_z - btnCenter_z) < btnGd.GD_DOUBLE_EPSILON) { /* if (c.cofmCenter_x == btnCenter_x && c.cofmCenter_y == btnCenter_y && c.cofmCenter_z == btnCenter_z ) { */ // this is the right node, add the center of mass /* btnGd.debugStr("adding COFM: (" + btnCenter_x + "," + btnCenter_y + "," + btnCenter_z + "), " + c.cofmMass ); */ if (btnCenterOfMassReceived) { btnTotalMass += c.cofmMass; btnCenterOfMass_x += c.cofmCenterOfMass_x * c.cofmMass; btnCenterOfMass_y += c.cofmCenterOfMass_y * c.cofmMass; btnCenterOfMass_z += c.cofmCenterOfMass_z * c.cofmMass; } else { btnTotalMass = c.cofmMass; btnCenterOfMass_x = c.cofmCenterOfMass_x * c.cofmMass; btnCenterOfMass_y = c.cofmCenterOfMass_y * c.cofmMass; btnCenterOfMass_z = c.cofmCenterOfMass_z * c.cofmMass; btnCenterOfMassReceived = true; } /* btnGd.debugStr("updating COFM, now: (" + btnCenterOfMass_x + "," + btnCenterOfMass_y + "," + btnCenterOfMass_z + "), " + c.cofmMass ); */ return; } if (btnIsLeaf) { Split(); } findContainingChild(c).addCenterOfMass(c); } // Tree integrity check and support routines /* private boolean check( vec3 center, double size, vec3 pos ) { double maxx = center.x + size; double minx = center.x - size; double maxy = center.y + size; double miny = center.y - size; double maxz = center.z + size; double minz = center.z - size; if (pos.x>maxx) return false; if (pos.x<minx) return false; if (pos.y>maxy) return false; if (pos.y<miny) return false; if (pos.z>maxz) return false; if (pos.z<minz) return false; return true; } */ /* public int sanityCheck() { int SaneChildren = 0, i, InsaneBodies; if (btnIsLeaf) { // check all contained bodies to see if they really fit into this cell InsaneBodies = 0; for (i=0;i<btnBodyCount;i++) { int bi = btnBodyIndex[i]; if (!check( btnCenter, btnHalfSize, btnGd.gdBodies[bi].bPos)) { InsaneBodies++; debugStr( "Body: x: " + btnGd.gdBodies[bi].bPos.x + ", y: " + btnGd.gdBodies[bi].bPos.y + ", z: " + btnGd.gdBodies[bi].bPos.z ); } } if (InsaneBodies>0) { debugStr( "^^^ (" + InsaneBodies + "/" + btnBodyCount + ") outside cell bounds, center: " + "x: " + btnCenter.x + ", y: " + btnCenter.y + ", z: " + btnCenter.z + ", size: " + btnHalfSize ); SaneChildren = 1; } } else { // this is an internal node, check all children. for (i=0;i<8;i++) { if (btnChildren[i]!=null) { SaneChildren += btnChildren[i].sanityCheck(); } } } return SaneChildren; } */ public int countBodies() { int i, bodies = 0; if (btnIsLeaf) { return btnBodyCount; } else { for (i = 0; i < 8; i++) { if (btnChildren[i] != null) bodies += btnChildren[i].countBodies(); } } return bodies; } public void Iterate(int Depth) { int i; for (i = 0; i < Depth; i++) { System.out.print("."); } if (btnIsLeaf) { debugStr("LeafNode, Bodies: " + btnBodyCount + " of " + btnGd.gdMaxBodiesPerNode + "."); } else { debugStr("Internal Node, Children: " + btnChildrenCount + " of 8"); for (i = 0; i < 8; i++) { if (btnChildren[i] != null) btnChildren[i].Iterate((Depth + 1)); } } } /* private String getDepthStr() { return depthStr[ btnDepth ]; } */ protected void debugStr(String s) { if (btnDebug) btnGd.debugStr(s); } protected void debugFatalStr(String s) { btnGd.debugStr(s); } /* public static void setDebugMode( boolean debug ) { btnDebug = debug; } */ public void ComputeCenterOfMass() { int i; double recip; if (!btnCenterOfMassValid) { btnCenterOfMassValid = true; if (!btnCenterOfMassReceived) { btnTotalMass = 0.0; btnCenterOfMass_x = 0; btnCenterOfMass_y = 0; btnCenterOfMass_z = 0; } if (btnIsLeaf) { // Compute Center of mass of all bodies in this cell. for (i = 0; i < btnBodyCount; i++) { Body b = btnGd.gdBodies[btnBodyIndex[i]]; btnCenterOfMass_x += b.bPos.x * b.bMass; btnCenterOfMass_y += b.bPos.y * b.bMass; btnCenterOfMass_z += b.bPos.z * b.bMass; btnTotalMass += b.bMass; } // the following may generate an exception! recip = 1.0 / btnTotalMass; btnCenterOfMass_x *= recip; btnCenterOfMass_y *= recip; btnCenterOfMass_z *= recip; } else { // Compute the center of mass of all children if it is an internal node btnCenterOfMass_x = 0; btnCenterOfMass_y = 0; btnCenterOfMass_z = 0; btnTotalMass = 0; for (i = 0; i < 8; i++) { BodyTreeNode b = btnChildren[i]; if (b != null) { b.ComputeCenterOfMass(); btnCenterOfMass_x += b.btnCenterOfMass_x * b.btnTotalMass; btnCenterOfMass_y += b.btnCenterOfMass_y * b.btnTotalMass; btnCenterOfMass_z += b.btnCenterOfMass_z * b.btnTotalMass; btnTotalMass += b.btnTotalMass; } } recip = 1.0 / btnTotalMass; btnCenterOfMass_x *= recip; btnCenterOfMass_y *= recip; btnCenterOfMass_z *= recip; } } System.err.println("set com to: " + btnCenterOfMass_x + ", " + btnCenterOfMass_y + ", " + btnCenterOfMass_z); } void Barnes(Body b) { // Compute the acceleration this node acts on the body double Diff_x = btnCenterOfMass_x - b.bPos.x; double Diff_y = btnCenterOfMass_y - b.bPos.y; double Diff_z = btnCenterOfMass_z - b.bPos.z; double DistSq = Diff_x * Diff_x + Diff_y * Diff_y + Diff_z * Diff_z; if (DistSq >= btnMaxTheta) { // The distance was large enough to use the treenode instead of iterating all bodies. DistSq += btnGd.gdSoftSQ; double Dist = Math.sqrt(DistSq); double Factor = btnTotalMass / (DistSq * Dist); b.bAcc.x += Diff_x * Factor; b.bAcc.y += Diff_y * Factor; b.bAcc.z += Diff_z * Factor; b.bWeight++; } else { // The distance was too small. if (btnIsLeaf) { // compute accelerations on the body due to all bodies in this node. for (int i = 0; i < btnBodyCount; i++) { Body b2 = btnGd.gdBodies[btnBodyIndex[i]]; Diff_x = b2.bPos.x - b.bPos.x; Diff_y = b2.bPos.y - b.bPos.y; Diff_z = b2.bPos.z - b.bPos.z; DistSq = Diff_x * Diff_x + Diff_y * Diff_y + Diff_z * Diff_z + btnGd.gdSoftSQ; double Dist = Math.sqrt(DistSq); double Factor = b2.bMass / (DistSq * Dist); b.bAcc.x += Diff_x * Factor; b.bAcc.y += Diff_y * Factor; b.bAcc.z += Diff_z * Factor; b.bWeight++; } } else { for (int i = 0; i < 8; i++) if (btnChildren[i] != null) btnChildren[i].Barnes(b); } } System.out.println("acc for body " + " = " + b.bAcc.x + ", " + b.bAcc.y + ", " + b.bAcc.z); } int ComputeLeafAccelerationsBarnes(BodyTreeNode root) { int i, Weight = 0; Body b; // Iterate the tree for each body for (i = 0; i < btnBodyCount; i++) { b = btnGd.gdBodies[btnBodyIndex[i]]; // check if it is not an essential body if (b.bNumber == -1) continue; b.bWeight = 0; b.bAcc.x = 0; b.bAcc.y = 0; b.bAcc.z = 0; root.Barnes(b); /* btnGd.debugStr("computed accels for body " + b.bNumber + ", weight " + b.bWeight + ", (" + b.bAcc.x + "," + b.bAcc.y + "," + b.bAcc.z + ")" ); */ Weight += b.bWeight; } return Weight; } int ComputeAccelerationsBarnes(BodyTreeNode root) { int i, interactions = 0; if (btnIsLeaf) { interactions = ComputeLeafAccelerationsBarnes(root); } else { for (i = 0; i < 8; i++) { if (btnChildren[i] != null) interactions += btnChildren[i] .ComputeAccelerationsBarnes(root); } } return interactions; } }
debugging barnes git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@3565 aaf88347-d911-0410-b711-e54d386773bb
apps/rmi/barnes/BodyTreeNode.java
debugging barnes
<ide><path>pps/rmi/barnes/BodyTreeNode.java <ide> } <ide> } <ide> <del> System.out.println("acc for body " + " = " + b.bAcc.x + ", " + b.bAcc.y + ", " + b.bAcc.z); <add> System.err.println("acc for body " + " = " + b.bAcc.x + ", " + b.bAcc.y + ", " + b.bAcc.z); <ide> } <ide> <ide> int ComputeLeafAccelerationsBarnes(BodyTreeNode root) {
Java
apache-2.0
c0d8bb62fda4a1c3ac0c2a30520d1cda7e1b27b2
0
hsaputra/cdap,caskdata/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,caskdata/cdap,anthcp/cdap,caskdata/cdap,hsaputra/cdap,anthcp/cdap,caskdata/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap,caskdata/cdap,anthcp/cdap,anthcp/cdap,hsaputra/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,chtyim/cdap,hsaputra/cdap,hsaputra/cdap
/* * Copyright © 2015 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.internal.app.runtime.schedule; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import org.quartz.DateBuilder; /** * Utility class for Scheduler. */ public class Schedules { /** * Converts a frequency expression into cronExpression that is usable by quartz. * Supports frequency expressions with the following resolutions: minutes, hours, days. * Example conversions: * '10m' -> '*{@literal /}10 * * * ?' * '3d' -> '0 0 *{@literal /}3 * ?' * * @return a cron expression */ public static String toCronExpr(String frequency) { Preconditions.checkArgument(!Strings.isNullOrEmpty(frequency)); // remove all whitespace frequency = frequency.replaceAll("\\s+", ""); Preconditions.checkArgument(frequency.length() >= 0); frequency = frequency.toLowerCase(); String value = frequency.substring(0, frequency.length() - 1); try { int parsedValue = Integer.parseInt(value); Preconditions.checkArgument(parsedValue > 0); // TODO: Check for regular frequency. String everyN = String.format("*/%s", value); char lastChar = frequency.charAt(frequency.length() - 1); switch (lastChar) { case 'm': DateBuilder.validateMinute(parsedValue); return String.format("%s * * * ?", everyN); case 'h': DateBuilder.validateHour(parsedValue); return String.format("0 %s * * ?", everyN); case 'd': DateBuilder.validateDayOfMonth(parsedValue); return String.format("0 0 %s * ?", everyN); } throw new IllegalArgumentException(String.format("Time unit not supported: %s", lastChar)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Could not parse the frequency"); } } }
cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/schedule/Schedules.java
/* * Copyright © 2015 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.internal.app.runtime.schedule; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import org.quartz.DateBuilder; /** * Utility class for Scheduler. */ public class Schedules { /** * Converts a frequency expression into cronExpression that is usable by quartz. * Supports frequency expressions with the following resolutions: minutes, hours, days. * Example conversions: * '10m' -> '*{@literal /}10 * * * ?' * '3d' -> '0 0 *{@literal /}3 * ?' * * @return a cron expression */ public static String toCronExpr(String frequency) { Preconditions.checkArgument(!Strings.isNullOrEmpty(frequency)); // remove all whitespace frequency = frequency.replaceAll("\\s+", ""); Preconditions.checkArgument(frequency.length() >= 0); frequency = frequency.toLowerCase(); String value = frequency.substring(0, frequency.length() - 1); try { int parsedValue = Integer.parseInt(value); Preconditions.checkArgument(parsedValue > 0); // TODO: Check for regular frequency. String everyN = String.format("*/%s", value); char lastChar = frequency.charAt(frequency.length() - 1); switch (lastChar) { case 'm': DateBuilder.validateMinute(parsedValue); return String.format("%s * * * ?", everyN); case 'h': DateBuilder.validateHour(parsedValue); return String.format("0 %s * * ?", everyN); case 'd': DateBuilder.validateDayOfMonth(parsedValue); return String.format("0 0 %s * ?", everyN); } throw new IllegalArgumentException(String.format("Time unit not supported: %s", lastChar)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Could not parse the frequency"); } } }
Remove empty lines
cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/schedule/Schedules.java
Remove empty lines
<ide><path>dap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/schedule/Schedules.java <ide> throw new IllegalArgumentException("Could not parse the frequency"); <ide> } <ide> } <del> <del> <ide> }
Java
apache-2.0
0faaba9d4cd9950b3715d8afbaa7f88061604ddc
0
AnySoftKeyboard/AnySoftKeyboard,AnySoftKeyboard/AnySoftKeyboard,OmerMachluf/Mykeyboard,AnySoftKeyboard/AnySoftKeyboard,OmerMachluf/Mykeyboard,AnySoftKeyboard/AnySoftKeyboard,OmerMachluf/Mykeyboard,OmerMachluf/Mykeyboard,OmerMachluf/Mykeyboard,AnySoftKeyboard/AnySoftKeyboard,OmerMachluf/Mykeyboard,AnySoftKeyboard/AnySoftKeyboard,OmerMachluf/Mykeyboard,AnySoftKeyboard/AnySoftKeyboard
/* * Copyright (C) 2008-2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.menny.android.anysoftkeyboard; import java.util.ArrayList; import java.util.List; import android.app.*; import android.content.*; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.inputmethodservice.*; import android.media.AudioManager; import android.os.*; import android.preference.PreferenceManager; import android.text.AutoText; import android.text.TextUtils; import android.text.method.MetaKeyKeyListener; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.menny.android.anysoftkeyboard.Dictionary.*; import com.menny.android.anysoftkeyboard.Dictionary.Dictionary.Language; import com.menny.android.anysoftkeyboard.KeyboardSwitcher.NextKeyboardType; import com.menny.android.anysoftkeyboard.keyboards.AnyKeyboard; import com.menny.android.anysoftkeyboard.keyboards.AnyKeyboard.HardKeyboardTranslator; import com.menny.android.anysoftkeyboard.tutorials.TutorialsProvider; /** * Input method implementation for Qwerty'ish keyboard. */ public class AnySoftKeyboard extends InputMethodService implements KeyboardView.OnKeyboardActionListener, OnSharedPreferenceChangeListener, AnyKeyboardContextProvider { //this is determined from the version. It includes "tester", the it will be true private static boolean DEBUG = true; public static boolean getDEBUG() {return DEBUG;} private static final boolean TRACE_SDCARD = false; private static final int MSG_UPDATE_SUGGESTIONS = 0; private static final int MSG_START_TUTORIAL = 1; private static final int KEYCODE_ENTER = 10; private static final int KEYCODE_SPACE = ' '; private static final int KEYBOARD_NOTIFICATION_ID = 1; private static final String PUNCTUATION_CHARACTERS = ".\n!?,:;@<>()[]{}"; private AnyKeyboardView mInputView; private CandidateViewContainer mCandidateViewContainer; private CandidateView mCandidateView; private Suggest mSuggest; private CompletionInfo[] mCompletions; private AlertDialog mOptionsDialog; KeyboardSwitcher mKeyboardSwitcher; private final HardKeyboardActionImpl mHardKeyboardAction; private long mMetaState; private UserDictionaryBase mUserDictionary; private StringBuilder mComposing = new StringBuilder(); private WordComposer mWord = new WordComposer(); private int mCommittedLength; private boolean mPredicting; private CharSequence mBestWord; private final boolean mPredictionLandscape = false; private boolean mPredictionOn; private boolean mCompletionOn; private boolean mAutoSpace; private boolean mAutoCorrectOn; private boolean mCapsLock; // private boolean mVibrateOn; private int mVibrationDuration; private boolean mSoundOn; private boolean mAutoCap; private boolean mQuickFixes; private boolean mShowSuggestions; private boolean mAutoComplete; private int mCorrectionMode; private String mKeyboardChangeNotificationType; private static final String KEYBOARD_NOTIFICATION_ALWAYS = "1"; private static final String KEYBOARD_NOTIFICATION_ON_PHYSICAL = "2"; private static final String KEYBOARD_NOTIFICATION_NEVER = "3"; public static String mChangeKeysMode; // Indicates whether the suggestion strip is to be on in landscape private boolean mJustAccepted; private CharSequence mJustRevertedSeparator; private AudioManager mAudioManager; private NotificationManager mNotificationManager; //private final HardKeyboardTranslator mGenericKeyboardTranslator; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_SUGGESTIONS: updateSuggestions(); break; case MSG_START_TUTORIAL: if ((mInputView != null) && mInputView.isShown()) { TutorialsProvider.ShowTutorialsIfNeeded(AnySoftKeyboard.this, mInputView); } else { // Try again soon if the view is not yet showing sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL), 100); } break; } } }; private boolean mSpaceSent; public AnySoftKeyboard() { //mGenericKeyboardTranslator = new GenericPhysicalKeyboardTranslator(this); mHardKeyboardAction = new HardKeyboardActionImpl(); } @Override public void onCreate() { super.onCreate(); Log.i("AnySoftKeyboard", "****** Starting AnySoftKeyboard:"); Log.i("AnySoftKeyboard", "** Locale:"+ getResources().getConfiguration().locale.toString()); String version = ""; try { PackageInfo info = super.getApplication().getPackageManager().getPackageInfo(getApplication().getPackageName(), 0); version = info.versionName; Log.i("AnySoftKeyboard", "** Version: "+version); } catch (NameNotFoundException e) { Log.e("AnySoftKeyboard", "Failed to locate package information! This is very weird... I'm installed."); } DEBUG = version.contains("tester"); Log.i("AnySoftKeyboard", "** Debug: "+DEBUG); //showToastMessage(R.string.toast_lengthy_start_up_operation, true); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // setStatusIcon(R.drawable.ime_qwerty); loadSettings(); mKeyboardSwitcher = new KeyboardSwitcher(this); if (mSuggest == null) { // should it be always on? if (mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) notifyKeyboardChangeIfNeeded(); initSuggest(/* getResources().getConfiguration().locale.toString() */); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.registerOnSharedPreferenceChangeListener(this); } private void initSuggest(/* String locale */) { // mLocale = locale; mSuggest = new Suggest(this/* , R.raw.main */); mSuggest.setCorrectionMode(mCorrectionMode); mUserDictionary = DictionaryFactory.createUserDictionary(this); mSuggest.setUserDictionary(mUserDictionary); setMainDictionaryForCurrentKeyboard(); // mWordSeparators = getResources().getString(R.string.word_separators); // mSentenceSeparators = // getResources().getString(R.string.sentence_separators); } @Override public void onDestroy() { DictionaryFactory.close(); // unregisterReceiver(mReceiver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.unregisterOnSharedPreferenceChangeListener(this); if (mSoundOn) { Log.i("AnySoftKeyboard", "Releasing sounds effects from AUDIO_SERVICE"); mAudioManager.unloadSoundEffects(); } mNotificationManager.cancel(KEYBOARD_NOTIFICATION_ID); super.onDestroy(); } @Override public void onFinishInputView(boolean finishingInput) { if (DEBUG) Log.d("AnySoftKeyboard", "onFinishInputView(finishingInput:"+finishingInput+")"); super.onFinishInputView(finishingInput); if (!mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) { mNotificationManager.cancel(KEYBOARD_NOTIFICATION_ID); } if (finishingInput) resetComposing();//clearing any predications }; @Override public View onCreateInputView() { mInputView = (AnyKeyboardView) getLayoutInflater().inflate(R.layout.input, null); mKeyboardSwitcher.setInputView(mInputView); mKeyboardSwitcher.makeKeyboards(false); mInputView.setOnKeyboardActionListener(this); mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, null); startTutorial(); return mInputView; } @Override public View onCreateCandidatesView() { mKeyboardSwitcher.makeKeyboards(false); mCandidateViewContainer = (CandidateViewContainer) getLayoutInflater().inflate(R.layout.candidates, null); mCandidateViewContainer.initViews(); mCandidateView = (CandidateView) mCandidateViewContainer.findViewById(R.id.candidates); mCandidateView.setService(this); setCandidatesViewShown(true); return mCandidateViewContainer; } @Override public void onStartInput(EditorInfo attribute, boolean restarting) { if (DEBUG) Log.d("AnySoftKeyboard", "onStartInput(EditorInfo:"+attribute.imeOptions+","+attribute.inputType+", restarting:"+restarting+")"); super.onStartInput(attribute, restarting); mKeyboardSwitcher.makeKeyboards(false); resetComposing();//clearing any predications TextEntryState.newSession(this); mPredictionOn = false; mCompletionOn = false; mCompletions = null; mCapsLock = false; switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) { case EditorInfo.TYPE_CLASS_NUMBER: case EditorInfo.TYPE_CLASS_DATETIME: case EditorInfo.TYPE_CLASS_PHONE: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE, attribute); break; case EditorInfo.TYPE_CLASS_TEXT: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute); // startPrediction(); mPredictionOn = true; // Make sure that passwords are not displayed in candidate view final int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION; if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD || variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) { mPredictionOn = false; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) { mAutoSpace = false; } else { mAutoSpace = true; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) { mPredictionOn = false; mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL, attribute); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) { mPredictionOn = false; mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL, attribute); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM, attribute); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) { mPredictionOn = false; } if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { mPredictionOn = false; mCompletionOn = true && isFullscreenMode(); } updateShiftKeyState(attribute); break; default: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute); updateShiftKeyState(attribute); } mComposing.setLength(0); mPredicting = false; // mDeleteCount = 0; setCandidatesViewShown(false); // loadSettings(); if (mSuggest != null) { mSuggest.setCorrectionMode(mCorrectionMode); } mPredictionOn = mPredictionOn && mCorrectionMode > 0; if (mCandidateView != null) mCandidateView.setSuggestions(null, false, false, false); if (TRACE_SDCARD) Debug.startMethodTracing("anysoftkeyboard_log.trace"); } @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { if (DEBUG) Log.d("AnySoftKeyboard", "onStartInputView(EditorInfo:"+attribute.imeOptions+","+attribute.inputType+", restarting:"+restarting+")"); super.onStartInputView(attribute, restarting); if (mInputView != null) { mInputView.closing(); if (AutoText.getSize(mInputView) < 1) mQuickFixes = true; } } @Override public void onFinishInput() { if (DEBUG) Log.d("AnySoftKeyboard", "onFinishInput()"); super.onFinishInput(); if (mInputView != null) { mInputView.closing(); } if (!mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(KEYBOARD_NOTIFICATION_ID); } //clearing any predications resetComposing(); // releasing some memory. Dictionaries, completions, etc. System.gc(); } @Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd); // If the current selection in the text view changes, we should // clear whatever candidate text we have. if (mComposing.length() > 0 && mPredicting && (newSelStart != candidatesEnd || newSelEnd != candidatesEnd)) { resetComposing(); } else if (!mPredicting && !mJustAccepted && TextEntryState.getState() == TextEntryState.STATE_ACCEPTED_DEFAULT) { TextEntryState.reset(); } mJustAccepted = false; } private void resetComposing() { InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.finishComposingText(); //commitTyped(ic); } mComposing.setLength(0); mPredicting = false; updateSuggestions(); TextEntryState.reset(); } @Override public void hideWindow() { if (TRACE_SDCARD) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } // if (mTutorial != null) { // mTutorial.close(); // mTutorial = null; // } super.hideWindow(); TextEntryState.endSession(); } @Override public void onDisplayCompletions(CompletionInfo[] completions) { if (DEBUG) { Log.i("AnySoftKeyboard", "Received completions:"); for (int i = 0; i < (completions != null ? completions.length : 0); i++) { Log.i("AnySoftKeyboard", " #" + i + ": " + completions[i]); } } if (mCompletionOn) { mCompletions = completions; if (completions == null) { mCandidateView.setSuggestions(null, false, false, false); return; } List<CharSequence> stringList = new ArrayList<CharSequence>(); for (int i = 0; i < (completions != null ? completions.length : 0); i++) { CompletionInfo ci = completions[i]; if (ci != null) stringList.add(ci.getText()); } // CharSequence typedWord = mWord.getTypedWord(); mCandidateView.setSuggestions(stringList, true, true, true); mBestWord = null; setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn); } } @Override public void setCandidatesViewShown(boolean shown) { //we show predication only in on-screen keyboard (onEvaluateInputViewShown) //or if the physical keyboard supports candidates (mPredictionLandscape) super.setCandidatesViewShown((onEvaluateInputViewShown() || mPredictionLandscape) && shown); } @Override public void onComputeInsets(InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); if (!isFullscreenMode()) { outInsets.contentTopInsets = outInsets.visibleTopInsets; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { InputConnection ic = getCurrentInputConnection(); if (!mPredictionLandscape) { // For all other keys, if we want to do transformations on // text being entered with a hard keyboard, we need to process // it and do the appropriate action. // using physical keyboard is more annoying with candidate view in // the way // so we disable it. // to clear the underline. commitTyped(ic);// to clear the underline. mPredicting = false; } if (DEBUG) Log.d("AnySoftKeyboard", "Event: Key:"+event.getKeyCode()+" Shift:"+((event.getMetaState()&KeyEvent.META_SHIFT_ON) != 0)+" ALT:"+((event.getMetaState()&KeyEvent.META_ALT_ON) != 0)+" Repeats:"+event.getRepeatCount()); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0 && mInputView != null) { if (mInputView.handleBack()) { // consuming the meta keys //mHardKeyboardAction.resetMetaState(); if (ic != null) ic.clearMetaKeyStates(Integer.MAX_VALUE);//translated, so we also take care of the metakeys. return true; } /* * else if (mTutorial != null) { mTutorial.close(); mTutorial = * null; } */ } break; // case KeyEvent.KEYCODE_DPAD_DOWN: // case KeyEvent.KEYCODE_DPAD_UP: // case KeyEvent.KEYCODE_DPAD_LEFT: // case KeyEvent.KEYCODE_DPAD_RIGHT: // // If tutorial is visible, don't allow dpad to work // if (mTutorial != null) { // return true; // } // break; case KeyEvent.KEYCODE_DEL: onKey(Keyboard.KEYCODE_DELETE, new int[]{Keyboard.KEYCODE_DELETE}); return true; case KeyEvent.KEYCODE_SPACE: if (event.isAltPressed()) { Log.d("AnySoftKeyborad", "User pressed ALT+SPACE, moving to next physical keyboard."); // consuming the meta keys //mHardKeyboardAction.resetMetaState(); if (ic != null) ic.clearMetaKeyStates(Integer.MAX_VALUE);//translated, so we also take care of the metakeys. // only physical keyboard nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.AlphabetSupportsPhysical); return true; } else { //still handling it onKey(32, new int[]{32}); return true; } default: if (mKeyboardSwitcher.isCurrentKeyboardPhysical()) { // sometimes, the physical keyboard will delete input, and then add some. // we'll try to make it nice if (ic != null) ic.beginBatchEdit(); try { mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState, keyCode, event); mHardKeyboardAction.initializeAction(event, mMetaState); //we are at a regular key press, so we'll update our meta-state member mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState); //http://article.gmane.org/gmane.comp.handhelds.openmoko.android-freerunner/629 AnyKeyboard current = mKeyboardSwitcher.getCurrentKeyboard(); String keyboardName = current.getKeyboardName(); HardKeyboardTranslator keyTranslator = (HardKeyboardTranslator)current; if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyborad", "Asking '" + keyboardName + "' to translate key: " + keyCode); if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action before translation: Shift: "+mHardKeyboardAction.isShiftActive()+", Alt: "+mHardKeyboardAction.isAltActive()+", Key code: "+mHardKeyboardAction.getKeyCode()+", changed: "+mHardKeyboardAction.getKeyCodeWasChanged()); keyTranslator.translatePhysicalCharacter(mHardKeyboardAction); if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action after translation: Key code: "+mHardKeyboardAction.getKeyCode()+", changed: "+mHardKeyboardAction.getKeyCodeWasChanged()); if (mHardKeyboardAction.getKeyCodeWasChanged()) { final int translatedChar = mHardKeyboardAction.getKeyCode(); //typing my own. onKey(translatedChar, new int[] { translatedChar }); //since we are handling the key press, we'll also handle the //meta-state of the input connection //since we want to do the reverse, we'll invert the bits final int clearStatesFlags = ~MetaKeyKeyListener.getMetaState(mMetaState); if (ic != null) ic.clearMetaKeyStates(clearStatesFlags); //my handling return true; } } finally { if (ic != null) ic.endBatchEdit(); } } } return super.onKeyDown(keyCode, event); } // private boolean askTranslatorToTranslateHardKeyboardAction(int keyCode, // InputConnection ic, String keyboardName, // HardKeyboardTranslator keyTranslator) // { // if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyborad", "Asking '" + keyboardName + "' to translate key: " + keyCode); // if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action before translation: Shift: "+mHardKeyboardAction.mPhysicalShiftState+", Alt: "+mHardKeyboardAction.mPhysicalAltState+", Key code: "+mHardKeyboardAction.getKeyCode()+", changed: "+mHardKeyboardAction.getKeyCodeWasChanged()); // keyTranslator.translatePhysicalCharacter(mHardKeyboardAction); // if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action after translation: Shift: "+mHardKeyboardAction.mPhysicalShiftState+", Alt: "+mHardKeyboardAction.mPhysicalAltState+", Key code: "+mHardKeyboardAction.getKeyCode()+", changed: "+mHardKeyboardAction.getKeyCodeWasChanged()); // // final char translatedChar = (char)mHardKeyboardAction.consumeKeyCode(); // if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action after consumeKeyCode: Shift: "+mHardKeyboardAction.mPhysicalShiftState+", Alt: "+mHardKeyboardAction.mPhysicalAltState+", Key code: "+mHardKeyboardAction.getKeyCode()); // if (mHardKeyboardAction.getKeyCodeWasChanged()) // { // // consuming the meta keys // //Since I'm handling the physical keys, I also need to clear the meta state // if (ic != null) // { // //the clear should be done only if we are not in sticky mode // int metaStateToClear = 0; // if (!mHardKeyboardAction.isShiftActive()) // { // if (DEBUG) Log.v("AnySoftKeyboard", "About to clear SHIFT state from input since shift state is:"+mHardKeyboardAction.mPhysicalShiftState); // metaStateToClear += KeyEvent.META_SHIFT_ON; // } // if (!mHardKeyboardAction.isAltActive()) // { // if (DEBUG) Log.v("AnySoftKeyboard", "About to clear ALT state from input since alt state is:"+mHardKeyboardAction.mPhysicalAltState); // metaStateToClear += KeyEvent.META_ALT_ON; // } // // ic.clearMetaKeyStates(metaStateToClear);//translated, so we also take care of the metakeys. // } // // if (AnySoftKeyboard.DEBUG) // Log.d("AnySoftKeyborad", "'"+ keyboardName + "' translated key " + keyCode + " to "+ translatedChar); // // onKey(translatedChar, new int[] { translatedChar }); // return true; // } else { // if (AnySoftKeyboard.DEBUG) // Log.d("AnySoftKeyborad", "'"+ keyboardName+ "' did not translated key " + keyCode+ "."); // return false; // } // } private void notifyKeyboardChangeIfNeeded() { // Log.d("anySoftKeyboard","notifyKeyboardChangeIfNeeded"); // Thread.dumpStack(); if (mKeyboardSwitcher == null)// happens on first onCreate. return; if ((mKeyboardSwitcher.isAlphabetMode()) && !mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_NEVER)) { AnyKeyboard current = mKeyboardSwitcher.getCurrentKeyboard(); // notifying the user about the keyboard. // creating the message Notification notification = new Notification(current.getKeyboardIcon(), current.getKeyboardName(), System.currentTimeMillis()); Intent notificationIntent = new Intent(); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(getApplicationContext(), "Any Soft Keyboard", current.getKeyboardName(), contentIntent); if (mKeyboardChangeNotificationType.equals("1")) { notification.flags |= Notification.FLAG_ONGOING_EVENT; notification.flags |= Notification.FLAG_NO_CLEAR; } else { notification.flags |= Notification.FLAG_AUTO_CANCEL; } notification.defaults = 0;// no sound, vibrate, etc. // notifying mNotificationManager.notify(KEYBOARD_NOTIFICATION_ID, notification); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // // If tutorial is visible, don't allow dpad to work // if (mTutorial != null) { // return true; // } // Enable shift key and DPAD to do selections if (mInputView != null && mInputView.isShown() && mInputView.isShifted()) { event = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(), event.getKeyCode(), event .getRepeatCount(), event.getDeviceId(), event .getScanCode(), KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON); InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.sendKeyEvent(event); return true; } break; default: mMetaState = MetaKeyKeyListener.handleKeyUp(mMetaState, keyCode, event); final int clearStatesFlags = ~MetaKeyKeyListener.getMetaState(mMetaState); InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.clearMetaKeyStates(clearStatesFlags); } return super.onKeyUp(keyCode, event); } private void commitTyped(InputConnection inputConnection) { if (mPredicting) { mPredicting = false; if (mComposing.length() > 0) { if (inputConnection != null) { inputConnection.commitText(mComposing, 1); } mCommittedLength = mComposing.length(); TextEntryState.acceptedTyped(mComposing); } updateSuggestions(); } } public void updateShiftKeyState(EditorInfo attr) { InputConnection ic = getCurrentInputConnection(); if (attr != null && mInputView != null && mKeyboardSwitcher.isAlphabetMode() && ic != null) { int caps = 0; EditorInfo ei = getCurrentInputEditorInfo(); if (mAutoCap && ei != null && ei.inputType != EditorInfo.TYPE_NULL) { caps = ic.getCursorCapsMode(attr.inputType); } mInputView.setShifted(mCapsLock || caps != 0); } } private void swapPunctuationAndSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastTwo = ic.getTextBeforeCursor(2, 0); if (lastTwo != null && lastTwo.length() == 2 && lastTwo.charAt(0) == KEYCODE_SPACE && isPunctuationCharacter(lastTwo.charAt(1))) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(lastTwo.charAt(1) + " ", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); } } private void doubleSpace() { // if (!mAutoPunctuate) return; if (mCorrectionMode == Suggest.CORRECTION_NONE) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastThree = ic.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && Character.isLetterOrDigit(lastThree.charAt(0)) && lastThree.charAt(1) == KEYCODE_SPACE && lastThree.charAt(2) == KEYCODE_SPACE) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(". ", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); } } public boolean addWordToDictionary(String word) { mUserDictionary.addWord(word, 128); return true; } /** * Helper to determine if a given character code is alphabetic. */ private boolean isAlphabet(int code) { return mKeyboardSwitcher.getCurrentKeyboard().isLetter((char)code); } // Implementation of KeyboardViewListener public void onKey(int primaryCode, int[] keyCodes) { // long when = SystemClock.uptimeMillis(); // if (primaryCode != Keyboard.KEYCODE_DELETE || // when > mLastKeyTime + QUICK_PRESS) { // mDeleteCount = 0; // } // mLastKeyTime = when; switch (primaryCode) { case Keyboard.KEYCODE_DELETE: handleBackspace(); // mDeleteCount++; break; case Keyboard.KEYCODE_SHIFT: handleShift(); break; case Keyboard.KEYCODE_CANCEL: if (mOptionsDialog == null || !mOptionsDialog.isShowing()) { handleClose(); } break; case AnyKeyboardView.KEYCODE_OPTIONS: showOptionsMenu(); break; case AnyKeyboardView.KEYCODE_SHIFT_LONGPRESS: if (mCapsLock) { handleShift(); } else { toggleCapsLock(); } break; case Keyboard.KEYCODE_MODE_CHANGE: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Symbols); break; case AnyKeyboard.KEYCODE_LANG_CHANGE: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Alphabet); break; default: if (isWordSeparator(primaryCode)) { handleSeparator(primaryCode); } else { handleCharacter(primaryCode, keyCodes); //reseting the mSpaceSent, which is set to true upon selecting candidate mSpaceSent = false; } // Cancel the just reverted state mJustRevertedSeparator = null; } } public void onText(CharSequence text) { InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); if (mPredicting) { commitTyped(ic); } ic.commitText(text, 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); mJustRevertedSeparator = null; } private void handleBackspace() { boolean deleteChar = false; InputConnection ic = getCurrentInputConnection(); if (ic == null) return; if (mPredicting) { final int length = mComposing.length(); if (length > 0) { mComposing.delete(length - 1, length); mWord.deleteLast(); ic.setComposingText(mComposing, 1); if (mComposing.length() == 0) { mPredicting = false; } postUpdateSuggestions(); } else { ic.deleteSurroundingText(1, 0); } } else { deleteChar = true; } updateShiftKeyState(getCurrentInputEditorInfo()); TextEntryState.backspace(); if (TextEntryState.getState() == TextEntryState.STATE_UNDO_COMMIT) { revertLastWord(deleteChar); return; } else if (deleteChar) { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); // if (mDeleteCount > DELETE_ACCELERATE_AT) { // sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); // } } mJustRevertedSeparator = null; } private void handleShift() { // Keyboard currentKeyboard = mInputView.getKeyboard(); if (mKeyboardSwitcher.isAlphabetMode()) { // Alphabet keyboard checkToggleCapsLock(); mInputView.setShifted(mCapsLock || !mInputView.isShifted()); } else { mKeyboardSwitcher.toggleShift(); } } private void handleCharacter(int primaryCode, int[] keyCodes) { // Log.d("AnySoftKeyboard", // "handleCharacter: "+primaryCode+", isPredictionOn:"+isPredictionOn()+", mPredicting:"+mPredicting); if (isAlphabet(primaryCode) && isPredictionOn() && !isCursorTouchingWord()) { if (!mPredicting) { mPredicting = true; mComposing.setLength(0); mWord.reset(); } } primaryCode = translatePrimaryCodeFromCurrentKeyboard(primaryCode); // if (mInputView.isShifted()) { // primaryCode = Character.toUpperCase(primaryCode); // } if (mPredicting) { if ((mInputView != null) && mInputView.isShifted() && mComposing.length() == 0) { mWord.setCapitalized(true); } mComposing.append((char) primaryCode); mWord.add(primaryCode, keyCodes); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.setComposingText(mComposing, 1); } postUpdateSuggestions(); } else { sendKeyChar((char) primaryCode); } updateShiftKeyState(getCurrentInputEditorInfo()); // measureCps(); TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode)); } private int translatePrimaryCodeFromCurrentKeyboard(int primaryCode) { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "translatePrimaryCodeFromCurrentKeyboard: " + primaryCode); if (isInputViewShown()) { if (AnySoftKeyboard.DEBUG) Log.v("AnySoftKeyboard", "translatePrimaryCodeFromCurrentKeyboard: isInputViewShown"); if ((mInputView != null) && mInputView.isShifted()) { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "translatePrimaryCodeFromCurrentKeyboard: mInputView.isShifted()"); return mKeyboardSwitcher.getCurrentKeyboard().getShiftedKeyValue(primaryCode); } } return primaryCode; } private void handleSeparator(int primaryCode) { boolean pickedDefault = false; // Handle separator InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mPredicting) { // In certain languages where single quote is a separator, it's // better // not to auto correct, but accept the typed word. For instance, // in Italian dov' should not be expanded to dove' because the // elision // requires the last vowel to be removed. if (mAutoCorrectOn && primaryCode != '\'' && (mJustRevertedSeparator == null || mJustRevertedSeparator.length() == 0 || mJustRevertedSeparator.charAt(0) != primaryCode)) { pickDefaultSuggestion(); pickedDefault = true; } else { commitTyped(ic); } } sendKeyChar((char) primaryCode); TextEntryState.typedCharacter((char) primaryCode, true); if (TextEntryState.getState() == TextEntryState.STATE_PUNCTUATION_AFTER_ACCEPTED && primaryCode != KEYCODE_ENTER && mSpaceSent) { swapPunctuationAndSpace(); } else if (isPredictionOn() && primaryCode == ' ') { // else if (TextEntryState.STATE_SPACE_AFTER_ACCEPTED) { doubleSpace(); } if (pickedDefault && mBestWord != null) { TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord); } updateShiftKeyState(getCurrentInputEditorInfo()); if (ic != null) { ic.endBatchEdit(); } } private void handleClose() { commitTyped(getCurrentInputConnection()); requestHideSelf(0); if (mInputView != null) mInputView.closing(); TextEntryState.endSession(); } private void checkToggleCapsLock() { if (mKeyboardSwitcher.getCurrentKeyboard().isShifted()) { toggleCapsLock(); } } private void toggleCapsLock() { mCapsLock = !mCapsLock; if (mKeyboardSwitcher.isAlphabetMode()) { mKeyboardSwitcher.getCurrentKeyboard().setShiftLocked(mCapsLock); } } private void postUpdateSuggestions() { mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SUGGESTIONS), 100); } private boolean isPredictionOn() { boolean predictionOn = mPredictionOn; //if (!onEvaluateInputViewShown()) predictionOn &= mPredictionLandscape; return predictionOn; } private boolean isCandidateStripVisible() { boolean shown = isPredictionOn() && mShowSuggestions; if (!onEvaluateInputViewShown()) shown &= mPredictionLandscape; return shown; } private void updateSuggestions() { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "updateSuggestions: has mSuggest:" + (mSuggest != null) + ", isPredictionOn:" + isPredictionOn() + ", mPredicting:" + mPredicting + ", mCorrectionMode:" + mCorrectionMode); // Check if we have a suggestion engine attached. if (mSuggest == null) { return; } final boolean showSuggestions = (mCandidateView != null && mPredicting && isPredictionOn() && isCandidateStripVisible()); if (!showSuggestions) { if (mCandidateView != null) mCandidateView.setSuggestions(null, false, false, false); return; } List<CharSequence> stringList = mSuggest.getSuggestions(mInputView, mWord, false); boolean correctionAvailable = mSuggest.hasMinimalCorrection(); // || mCorrectionMode == mSuggest.CORRECTION_FULL; CharSequence typedWord = mWord.getTypedWord(); // If we're in basic correct boolean typedWordValid = mSuggest.isValidWord(typedWord); if (mCorrectionMode == Suggest.CORRECTION_FULL) { correctionAvailable |= typedWordValid; } mCandidateView.setSuggestions(stringList, false, typedWordValid, correctionAvailable); if (stringList.size() > 0) { if (correctionAvailable && !typedWordValid && stringList.size() > 1) { mBestWord = stringList.get(1); } else { mBestWord = typedWord; } } else { mBestWord = null; } setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn); } private void pickDefaultSuggestion() { // Complete any pending candidate query first if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) { mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); updateSuggestions(); } if (mBestWord != null) { TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord); mJustAccepted = true; pickSuggestion(mBestWord); } } public void pickSuggestionManually(int index, CharSequence suggestion) { if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) { CompletionInfo ci = mCompletions[index]; InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.commitCompletion(ci); } mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.clear(); } updateShiftKeyState(getCurrentInputEditorInfo()); return; } pickSuggestion(suggestion); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space if (mAutoSpace) { mSpaceSent = true; sendSpace(); } // Fool the state watcher so that a subsequent backspace will not do a // revert TextEntryState.typedCharacter((char) KEYCODE_SPACE, true); } private void pickSuggestion(CharSequence suggestion) { if (mCapsLock) { suggestion = suggestion.toString().toUpperCase(); } else if (preferCapitalization() || (mKeyboardSwitcher.isAlphabetMode() && (mInputView != null) && mInputView.isShifted())) { suggestion = Character.toUpperCase(suggestion.charAt(0)) + suggestion.subSequence(1, suggestion.length()).toString(); } InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.commitText(suggestion, 1); } mPredicting = false; mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.setSuggestions(null, false, false, false); } updateShiftKeyState(getCurrentInputEditorInfo()); } private boolean isCursorTouchingWord() { InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); CharSequence toRight = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(toLeft) && !isWordSeparator(toLeft.charAt(0))) { return true; } if (!TextUtils.isEmpty(toRight) && !isWordSeparator(toRight.charAt(0))) { return true; } return false; } public void revertLastWord(boolean deleteChar) { final int length = mComposing.length(); if (!mPredicting && length > 0) { final InputConnection ic = getCurrentInputConnection(); mPredicting = true; ic.beginBatchEdit(); mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0); if (deleteChar) ic.deleteSurroundingText(1, 0); int toDelete = mCommittedLength; CharSequence toTheLeft = ic .getTextBeforeCursor(mCommittedLength, 0); if (toTheLeft != null && toTheLeft.length() > 0 && isWordSeparator(toTheLeft.charAt(0))) { toDelete--; } ic.deleteSurroundingText(toDelete, 0); ic.setComposingText(mComposing, 1); TextEntryState.backspace(); ic.endBatchEdit(); postUpdateSuggestions(); } else { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); mJustRevertedSeparator = null; } } // protected String getWordSeparators() { // return mWordSeparators; // } public boolean isWordSeparator(int code) { // String separators = getWordSeparators(); // return separators.contains(String.valueOf((char)code)); return (!isAlphabet(code)); } public boolean isPunctuationCharacter(int code) { return PUNCTUATION_CHARACTERS.contains(String.valueOf((char) code)); } private void sendSpace() { sendKeyChar((char) KEYCODE_SPACE); updateShiftKeyState(getCurrentInputEditorInfo()); } public boolean preferCapitalization() { return mWord.isCapitalized(); } public void swipeRight() { // this should be done only if swipe was enabled if (mChangeKeysMode.equals("3")) { // TODO: space/backspace (depends on direction of keyboard) } else { nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Alphabet); } } public void swipeLeft() { // this should be done only if swipe was enabled if (mChangeKeysMode.equals("3")) { // TODO: space/backspace (depends on direction of keyboard) } else { nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Symbols); } } private void nextKeyboard(EditorInfo currentEditorInfo, KeyboardSwitcher.NextKeyboardType type) { Log.d("AnySoftKeyboard", "nextKeyboard: currentEditorInfo.inputType=" + currentEditorInfo.inputType + " type:" + type); AnyKeyboard currentKeyboard = mKeyboardSwitcher.getCurrentKeyboard(); if (currentKeyboard == null) { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "nextKeyboard: Looking for next keyboard. No current keyboard."); } else { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "nextKeyboard: Looking for next keyboard. Current keyboard is:" + currentKeyboard.getKeyboardName()); } // in numeric keyboards, the LANG key will go back to the original // alphabet keyboard- // so no need to look for the next keyboard, 'mLastSelectedKeyboard' // holds the last // keyboard used. currentKeyboard = mKeyboardSwitcher.nextKeyboard(currentEditorInfo, type); Log.i("AnySoftKeyboard", "nextKeyboard: Setting next keyboard to: " + currentKeyboard.getKeyboardName()); updateShiftKeyState(currentEditorInfo); // changing dictionary setMainDictionaryForCurrentKeyboard(); // Notifying if needed if ((mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) || (mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ON_PHYSICAL) && (type == NextKeyboardType.AlphabetSupportsPhysical))) { notifyKeyboardChangeIfNeeded(); } } public void swipeDown() { handleClose(); } public void swipeUp() { handleShift(); } public void onPress(int primaryCode) { if (mVibrationDuration > 0) { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "Vibrating on key-pressed"); ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)) .vibrate(mVibrationDuration); } if (mSoundOn/* && (!mSilentMode) */) { AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // Will use sound effects ONLY if the device is not muted. if (manager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) { int keyFX = AudioManager.FX_KEY_CLICK; switch (primaryCode) { case 13: keyFX = AudioManager.FX_KEYPRESS_RETURN; case Keyboard.KEYCODE_DELETE: keyFX = AudioManager.FX_KEYPRESS_DELETE; case 32: keyFX = AudioManager.FX_KEYPRESS_SPACEBAR; } int volume = manager .getStreamVolume(AudioManager.STREAM_NOTIFICATION); if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "Sound on key-pressed. Sound ID:" + keyFX + " with volume " + volume); manager.playSoundEffect(keyFX, volume); } else { if (AnySoftKeyboard.DEBUG) Log.v("AnySoftKeyboard", "Devices is muted. No sounds on key-pressed."); } } } public void onRelease(int primaryCode) { // vibrate(); } // private void checkTutorial(String privateImeOptions) { // if (privateImeOptions == null) return; // if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) { // if (mTutorial == null) startTutorial(); // } else if // (privateImeOptions.equals("com.android.setupwizard:HideTutorial")) { // if (mTutorial != null) { // if (mTutorial.close()) { // mTutorial = null; // } // } // } // } // // private boolean mTutorialsShown = false; private void startTutorial() { // if (!mTutorialsShown) // { // mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL), 500); // mTutorialsShown = true; // } } // void tutorialDone() { // mTutorial = null; // } // // private void launchSettings() { // handleClose(); // Intent intent = new Intent(); // intent.setClass(LatinIME.this, LatinIMESettings.class); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(intent); // } private boolean loadSettings() { //setting all values to default PreferenceManager.setDefaultValues(this, R.xml.prefs, false); boolean handled = false; // Get the settings preferences SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); int newVibrationDuration = Integer.parseInt(sp.getString("vibrate_on_key_press_duration", "0")); handled = handled || (newVibrationDuration != mVibrationDuration); mVibrationDuration = newVibrationDuration; boolean newSoundOn = sp.getBoolean("sound_on", false); boolean soundChanged = (newSoundOn != mSoundOn); if (soundChanged) { if (newSoundOn) { Log.i("AnySoftKeyboard", "Loading sounds effects from AUDIO_SERVICE due to configuration change."); mAudioManager.loadSoundEffects(); } else { Log.i("AnySoftKeyboard", "Releasing sounds effects from AUDIO_SERVICE due to configuration change."); mAudioManager.unloadSoundEffects(); } } handled = handled || soundChanged; mSoundOn = newSoundOn; // in order to support the old type of configuration String newKeyboardChangeNotificationType = sp.getString("physical_keyboard_change_notification_type", KEYBOARD_NOTIFICATION_ON_PHYSICAL); boolean notificationChanged = (!newKeyboardChangeNotificationType.equalsIgnoreCase(mKeyboardChangeNotificationType)); handled = handled || notificationChanged; mKeyboardChangeNotificationType = newKeyboardChangeNotificationType; if (notificationChanged) { // now clearing the notification, and it will be re-shown if needed NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // now clearing the notification, and it will be re-shown if needed notificationManager.cancel(KEYBOARD_NOTIFICATION_ID); // should it be always on? if (mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) notifyKeyboardChangeIfNeeded(); } boolean newAutoCap = sp.getBoolean("auto_caps", true); handled = handled || (newAutoCap != mAutoCap); mAutoCap = newAutoCap; boolean newShowSuggestions = sp.getBoolean("candidates_on", true); boolean suggestionsChanged = (newShowSuggestions != mShowSuggestions); handled = handled || suggestionsChanged; mShowSuggestions = newShowSuggestions; setMainDictionaryForCurrentKeyboard(); boolean newAutoComplete = sp.getBoolean("auto_complete", true) && mShowSuggestions; handled = handled || (newAutoComplete != mAutoComplete); mAutoComplete = newAutoComplete; boolean newQuickFixes = sp.getBoolean("quick_fix", true); handled = handled || (newQuickFixes != mQuickFixes); mQuickFixes = newQuickFixes; mAutoCorrectOn = /*mSuggest != null &&*//*Suggestion always exists, maybe not at the moment, but shortly*/ (mAutoComplete || mQuickFixes); mCorrectionMode = mAutoComplete ? 2 : (mShowSuggestions/* mQuickFixes */? 1 : 0); // boolean newLandscapePredications= sp.getBoolean("physical_keyboard_suggestions", true); // handled = handled || (newLandscapePredications != mPredictionLandscape); // mPredictionLandscape = newLandscapePredications; // this change requires the recreation of the keyboards. // so we wont mark the 'handled' result. mChangeKeysMode = sp.getString("keyboard_layout_change_method", "1"); return handled; } private void setMainDictionaryForCurrentKeyboard() { if (mSuggest != null) { if (!mShowSuggestions) { Log.d("AnySoftKeyboard", "No suggestion is required. I'll try to release memory from the dictionary."); DictionaryFactory.releaseAllDictionaries(); mSuggest.setMainDictionary(null); } else { // It null at the creation of the application. if ((mKeyboardSwitcher != null) && mKeyboardSwitcher.isAlphabetMode()) { AnyKeyboard currentKeyobard = mKeyboardSwitcher.getCurrentKeyboard(); Language dictionaryLanguage = getLanguageForKeyobard(currentKeyobard); Dictionary mainDictionary = DictionaryFactory.getDictionary(dictionaryLanguage, this); mSuggest.setMainDictionary(mainDictionary); } } } } private Language getLanguageForKeyobard(AnyKeyboard currentKeyobard) { //if there is a mapping in the settings, we'll use that, else we'll return the default String mappingSettingsKey = getDictionaryOverrideKey(currentKeyobard); String defaultDictionary = currentKeyobard.getDefaultDictionaryLanguage().toString(); String dictionaryValue = getSharedPreferences().getString(mappingSettingsKey, null); if ((dictionaryValue == null) || (defaultDictionary.equals(dictionaryValue))) return currentKeyobard.getDefaultDictionaryLanguage(); else { Log.d("AnySoftKeyboard", "Default dictionary '"+defaultDictionary+"' for keyboard '"+currentKeyobard.getKeyboardPrefId()+"' has been overriden to '"+dictionaryValue+"'"); //fixing the Slovene->Slovenian if (dictionaryValue.equalsIgnoreCase("Slovene")) {//Please remove this in some future version. dictionaryValue = "Slovenian"; Editor editor = getSharedPreferences().edit(); Log.d("AnySoftKeyboard", "Dictionary override fix: Slovene->Slovenian."); editor.putString(mappingSettingsKey, dictionaryValue); editor.commit(); } Language overridingLanguage = Language.valueOf(dictionaryValue); return overridingLanguage; } } private String getDictionaryOverrideKey(AnyKeyboard currentKeyobard) { String mappingSettingsKey = currentKeyobard.getKeyboardPrefId()+"_override_dictionary"; return mappingSettingsKey; } private void launchSettings() { handleClose(); Intent intent = new Intent(); intent.setClass(AnySoftKeyboard.this, SoftKeyboardSettings.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void launchDictioanryOverriding() { AnyKeyboard currentKeyboard = mKeyboardSwitcher.getCurrentKeyboard(); final String dictionaryOverridingKey = getDictionaryOverrideKey(currentKeyboard); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(R.drawable.icon_8_key); builder.setTitle(getResources().getString(R.string.override_dictionary_title, currentKeyboard.getKeyboardName())); builder.setNegativeButton(android.R.string.cancel, null); ArrayList<CharSequence> dictioanries = new ArrayList<CharSequence>(); dictioanries.add(getString(R.string.override_dictionary_default)); for(Language lang : Language.values()) { dictioanries.add(lang.toString()); } final CharSequence[] items = new CharSequence[dictioanries.size()]; dictioanries.toArray(items); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int position) { di.dismiss(); Editor editor = getSharedPreferences().edit(); switch(position) { case 0: Log.d("AnySoftKeyboard", "Dictionary overriden disabled. User selected default."); editor.remove(dictionaryOverridingKey); showToastMessage(R.string.override_disabled, true); break; default: if ((position < 0) || (position >= items.length)) { Log.d("AnySoftKeyboard", "Dictioanry override dialog canceled."); } else { String selectedLanguageString = items[position].toString(); Log.d("AnySoftKeyboard", "Dictionary override. User selected "+selectedLanguageString); editor.putString(dictionaryOverridingKey, selectedLanguageString); showToastMessage(getString(R.string.override_enabled, selectedLanguageString), true); } break; } editor.commit(); setMainDictionaryForCurrentKeyboard(); } }); mOptionsDialog = builder.create(); Window window = mOptionsDialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = mInputView.getWindowToken(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog.show(); } private void showOptionsMenu() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(R.drawable.icon_8_key); builder.setNegativeButton(android.R.string.cancel, null); CharSequence itemSettings = getString(R.string.ime_settings); CharSequence itemOverrideDictionary = getString(R.string.override_dictionary); CharSequence itemInputMethod = getString(R.string.change_ime); builder.setItems(new CharSequence[] { itemSettings, itemOverrideDictionary, itemInputMethod}, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: launchSettings(); break; case 1: launchDictioanryOverriding(); break; case 2: ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).showInputMethodPicker(); break; } } }); builder.setTitle(getResources().getString(R.string.ime_name)); mOptionsDialog = builder.create(); Window window = mOptionsDialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = mInputView.getWindowToken(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog.show(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.i("AnySoftKeyboard", "**** onConfigurationChanged"); Log.i("AnySoftKeyboard", "** Locale:"+ newConfig.locale.toString()); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d("AnySoftKeyboard", "onSharedPreferenceChanged - key:" + key); boolean handled = loadSettings(); if (!handled) { /* AnyKeyboard removedKeyboard = */mKeyboardSwitcher.makeKeyboards(true);// maybe a new keyboard /* * if (removedKeyboard != null) { * DictionaryFactory.releaseDictionary * (removedKeyboard.getDefaultDictionaryLanguage()); } */ } } public void appendCharactersToInput(CharSequence textToCommit) { if (DEBUG) Log.d("AnySoftKeyboard", "appendCharactersToInput: "+textToCommit); mWord.append(textToCommit); mComposing.append(textToCommit); appendStringToInput(textToCommit); } private void appendStringToInput(CharSequence textToCommit) { // handleTextDirection(); if (DEBUG) Log.d("AnySoftKeyboard", "appendStringToInput: "+textToCommit); if (mCompletionOn) { getCurrentInputConnection().setComposingText(mWord.getTypedWord(), textToCommit.length()); // updateCandidates(); } else commitTyped(getCurrentInputConnection()); updateShiftKeyState(getCurrentInputEditorInfo()); } public void deleteLastCharactersFromInput(int countToDelete) { if (DEBUG) Log.d("AnySoftKeyboard", "deleteLastCharactersFromInput: "+countToDelete); if (countToDelete == 0) return; final int currentLength = mComposing.length(); boolean shouldDeleteUsingCompletion; if (currentLength > 0) { shouldDeleteUsingCompletion = true; if (currentLength > countToDelete) { mComposing.delete(currentLength - countToDelete, currentLength); mWord.deleteLast(countToDelete); } else { mComposing.setLength(0); mWord.reset(); } } else { shouldDeleteUsingCompletion = false; } if (mCompletionOn && shouldDeleteUsingCompletion) { getCurrentInputConnection().setComposingText(mComposing, 1); // updateCandidates(); } else { getCurrentInputConnection().deleteSurroundingText(countToDelete, 0); } updateShiftKeyState(getCurrentInputEditorInfo()); } public SharedPreferences getSharedPreferences() { return PreferenceManager.getDefaultSharedPreferences(this); } public void showToastMessage(int resId, boolean forShortTime) { CharSequence text = getResources().getText(resId); showToastMessage(text, forShortTime); } private void showToastMessage(CharSequence text, boolean forShortTime) { int duration = forShortTime? Toast.LENGTH_SHORT : Toast.LENGTH_LONG; if (DEBUG) Log.v("AnySoftKeyboard", "showToastMessage: '"+text+"'. For: "+duration); Toast.makeText(this.getApplication(), text, duration).show(); } public void performLengthyOperation(int textResId, final Runnable thingToDo) { thingToDo.run(); // final ProgressDialog spinner = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER); // // Thread t = new Thread() { // public void run() { // thingToDo.run(); // spinner.dismiss(); // } // }; // t.start(); // spinner.setTitle(R.string.please_wait); // spinner.setIcon(R.drawable.icon_8_key); // spinner.setMessage(getResources().getText(textResId)); // spinner.setCancelable(false); // spinner.show(); } @Override public void onLowMemory() { Log.w("AnySoftKeyboard", "The OS has reported that it is low on memory!. I'll try to clear some cache."); mKeyboardSwitcher.onLowMemory(); DictionaryFactory.onLowMemory(getLanguageForKeyobard(mKeyboardSwitcher.getCurrentKeyboard())); super.onLowMemory(); } }
src/com/menny/android/anysoftkeyboard/AnySoftKeyboard.java
/* * Copyright (C) 2008-2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.menny.android.anysoftkeyboard; import java.util.ArrayList; import java.util.List; import android.app.*; import android.content.*; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.inputmethodservice.*; import android.media.AudioManager; import android.os.*; import android.preference.PreferenceManager; import android.text.AutoText; import android.text.TextUtils; import android.text.method.MetaKeyKeyListener; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.menny.android.anysoftkeyboard.Dictionary.*; import com.menny.android.anysoftkeyboard.Dictionary.Dictionary.Language; import com.menny.android.anysoftkeyboard.KeyboardSwitcher.NextKeyboardType; import com.menny.android.anysoftkeyboard.keyboards.AnyKeyboard; import com.menny.android.anysoftkeyboard.keyboards.AnyKeyboard.HardKeyboardTranslator; import com.menny.android.anysoftkeyboard.tutorials.TutorialsProvider; /** * Input method implementation for Qwerty'ish keyboard. */ public class AnySoftKeyboard extends InputMethodService implements KeyboardView.OnKeyboardActionListener, OnSharedPreferenceChangeListener, AnyKeyboardContextProvider { //this is determined from the version. It includes "tester", the it will be true private static boolean DEBUG = true; public static boolean getDEBUG() {return DEBUG;} private static final boolean TRACE_SDCARD = false; private static final int MSG_UPDATE_SUGGESTIONS = 0; private static final int MSG_START_TUTORIAL = 1; private static final int KEYCODE_ENTER = 10; private static final int KEYCODE_SPACE = ' '; private static final int KEYBOARD_NOTIFICATION_ID = 1; private static final String PUNCTUATION_CHARACTERS = ".\n!?,:;@<>()[]{}"; private AnyKeyboardView mInputView; private CandidateViewContainer mCandidateViewContainer; private CandidateView mCandidateView; private Suggest mSuggest; private CompletionInfo[] mCompletions; private AlertDialog mOptionsDialog; KeyboardSwitcher mKeyboardSwitcher; private final HardKeyboardActionImpl mHardKeyboardAction; private long mMetaState; private UserDictionaryBase mUserDictionary; private StringBuilder mComposing = new StringBuilder(); private WordComposer mWord = new WordComposer(); private int mCommittedLength; private boolean mPredicting; private CharSequence mBestWord; private final boolean mPredictionLandscape = false; private boolean mPredictionOn; private boolean mCompletionOn; private boolean mAutoSpace; private boolean mAutoCorrectOn; private boolean mCapsLock; // private boolean mVibrateOn; private int mVibrationDuration; private boolean mSoundOn; private boolean mAutoCap; private boolean mQuickFixes; private boolean mShowSuggestions; private boolean mAutoComplete; private int mCorrectionMode; private String mKeyboardChangeNotificationType; private static final String KEYBOARD_NOTIFICATION_ALWAYS = "1"; private static final String KEYBOARD_NOTIFICATION_ON_PHYSICAL = "2"; private static final String KEYBOARD_NOTIFICATION_NEVER = "3"; public static String mChangeKeysMode; // Indicates whether the suggestion strip is to be on in landscape private boolean mJustAccepted; private CharSequence mJustRevertedSeparator; private AudioManager mAudioManager; private NotificationManager mNotificationManager; //private final HardKeyboardTranslator mGenericKeyboardTranslator; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_SUGGESTIONS: updateSuggestions(); break; case MSG_START_TUTORIAL: if ((mInputView != null) && mInputView.isShown()) { TutorialsProvider.ShowTutorialsIfNeeded(AnySoftKeyboard.this, mInputView); } else { // Try again soon if the view is not yet showing sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL), 100); } break; } } }; private boolean mSpaceSent; public AnySoftKeyboard() { //mGenericKeyboardTranslator = new GenericPhysicalKeyboardTranslator(this); mHardKeyboardAction = new HardKeyboardActionImpl(); } @Override public void onCreate() { super.onCreate(); Log.i("AnySoftKeyboard", "****** Starting AnySoftKeyboard:"); Log.i("AnySoftKeyboard", "** Locale:"+ getResources().getConfiguration().locale.toString()); String version = ""; try { PackageInfo info = super.getApplication().getPackageManager().getPackageInfo(getApplication().getPackageName(), 0); version = info.versionName; Log.i("AnySoftKeyboard", "** Version: "+version); } catch (NameNotFoundException e) { Log.e("AnySoftKeyboard", "Failed to locate package information! This is very weird... I'm installed."); } DEBUG = version.contains("tester"); Log.i("AnySoftKeyboard", "** Debug: "+DEBUG); //showToastMessage(R.string.toast_lengthy_start_up_operation, true); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // setStatusIcon(R.drawable.ime_qwerty); loadSettings(); mKeyboardSwitcher = new KeyboardSwitcher(this); if (mSuggest == null) { // should it be always on? if (mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) notifyKeyboardChangeIfNeeded(); initSuggest(/* getResources().getConfiguration().locale.toString() */); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.registerOnSharedPreferenceChangeListener(this); } private void initSuggest(/* String locale */) { // mLocale = locale; mSuggest = new Suggest(this/* , R.raw.main */); mSuggest.setCorrectionMode(mCorrectionMode); mUserDictionary = DictionaryFactory.createUserDictionary(this); mSuggest.setUserDictionary(mUserDictionary); setMainDictionaryForCurrentKeyboard(); // mWordSeparators = getResources().getString(R.string.word_separators); // mSentenceSeparators = // getResources().getString(R.string.sentence_separators); } @Override public void onDestroy() { DictionaryFactory.close(); // unregisterReceiver(mReceiver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.unregisterOnSharedPreferenceChangeListener(this); if (mSoundOn) { Log.i("AnySoftKeyboard", "Releasing sounds effects from AUDIO_SERVICE"); mAudioManager.unloadSoundEffects(); } mNotificationManager.cancel(KEYBOARD_NOTIFICATION_ID); super.onDestroy(); } @Override public void onFinishInputView(boolean finishingInput) { if (DEBUG) Log.d("AnySoftKeyboard", "onFinishInputView(finishingInput:"+finishingInput+")"); super.onFinishInputView(finishingInput); if (!mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) { mNotificationManager.cancel(KEYBOARD_NOTIFICATION_ID); } if (finishingInput) resetComposing();//clearing any predications }; @Override public View onCreateInputView() { mInputView = (AnyKeyboardView) getLayoutInflater().inflate(R.layout.input, null); mKeyboardSwitcher.setInputView(mInputView); mKeyboardSwitcher.makeKeyboards(false); mInputView.setOnKeyboardActionListener(this); mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, null); startTutorial(); return mInputView; } @Override public View onCreateCandidatesView() { mKeyboardSwitcher.makeKeyboards(false); mCandidateViewContainer = (CandidateViewContainer) getLayoutInflater().inflate(R.layout.candidates, null); mCandidateViewContainer.initViews(); mCandidateView = (CandidateView) mCandidateViewContainer.findViewById(R.id.candidates); mCandidateView.setService(this); setCandidatesViewShown(true); return mCandidateViewContainer; } @Override public void onStartInput(EditorInfo attribute, boolean restarting) { if (DEBUG) Log.d("AnySoftKeyboard", "onStartInput(EditorInfo:"+attribute.imeOptions+","+attribute.inputType+", restarting:"+restarting+")"); super.onStartInput(attribute, restarting); mKeyboardSwitcher.makeKeyboards(false); resetComposing();//clearing any predications TextEntryState.newSession(this); mPredictionOn = false; mCompletionOn = false; mCompletions = null; mCapsLock = false; switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) { case EditorInfo.TYPE_CLASS_NUMBER: case EditorInfo.TYPE_CLASS_DATETIME: case EditorInfo.TYPE_CLASS_PHONE: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE, attribute); break; case EditorInfo.TYPE_CLASS_TEXT: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute); // startPrediction(); mPredictionOn = true; // Make sure that passwords are not displayed in candidate view final int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION; if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD || variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) { mPredictionOn = false; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) { mAutoSpace = false; } else { mAutoSpace = true; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) { mPredictionOn = false; mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL, attribute); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) { mPredictionOn = false; mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL, attribute); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM, attribute); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) { mPredictionOn = false; } if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { mPredictionOn = false; mCompletionOn = true && isFullscreenMode(); } updateShiftKeyState(attribute); break; default: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute); updateShiftKeyState(attribute); } mComposing.setLength(0); mPredicting = false; // mDeleteCount = 0; setCandidatesViewShown(false); // loadSettings(); if (mSuggest != null) { mSuggest.setCorrectionMode(mCorrectionMode); } mPredictionOn = mPredictionOn && mCorrectionMode > 0; if (mCandidateView != null) mCandidateView.setSuggestions(null, false, false, false); if (TRACE_SDCARD) Debug.startMethodTracing("anysoftkeyboard_log.trace"); } @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { if (DEBUG) Log.d("AnySoftKeyboard", "onStartInputView(EditorInfo:"+attribute.imeOptions+","+attribute.inputType+", restarting:"+restarting+")"); super.onStartInputView(attribute, restarting); if (mInputView != null) { mInputView.closing(); if (AutoText.getSize(mInputView) < 1) mQuickFixes = true; } } @Override public void onFinishInput() { if (DEBUG) Log.d("AnySoftKeyboard", "onFinishInput()"); super.onFinishInput(); if (mInputView != null) { mInputView.closing(); } if (!mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(KEYBOARD_NOTIFICATION_ID); } //clearing any predications resetComposing(); // releasing some memory. Dictionaries, completions, etc. System.gc(); } @Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd); // If the current selection in the text view changes, we should // clear whatever candidate text we have. if (mComposing.length() > 0 && mPredicting && (newSelStart != candidatesEnd || newSelEnd != candidatesEnd)) { resetComposing(); } else if (!mPredicting && !mJustAccepted && TextEntryState.getState() == TextEntryState.STATE_ACCEPTED_DEFAULT) { TextEntryState.reset(); } mJustAccepted = false; } private void resetComposing() { InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.finishComposingText(); //commitTyped(ic); } mComposing.setLength(0); mPredicting = false; updateSuggestions(); TextEntryState.reset(); } @Override public void hideWindow() { if (TRACE_SDCARD) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } // if (mTutorial != null) { // mTutorial.close(); // mTutorial = null; // } super.hideWindow(); TextEntryState.endSession(); } @Override public void onDisplayCompletions(CompletionInfo[] completions) { if (DEBUG) { Log.i("AnySoftKeyboard", "Received completions:"); for (int i = 0; i < (completions != null ? completions.length : 0); i++) { Log.i("AnySoftKeyboard", " #" + i + ": " + completions[i]); } } if (mCompletionOn) { mCompletions = completions; if (completions == null) { mCandidateView.setSuggestions(null, false, false, false); return; } List<CharSequence> stringList = new ArrayList<CharSequence>(); for (int i = 0; i < (completions != null ? completions.length : 0); i++) { CompletionInfo ci = completions[i]; if (ci != null) stringList.add(ci.getText()); } // CharSequence typedWord = mWord.getTypedWord(); mCandidateView.setSuggestions(stringList, true, true, true); mBestWord = null; setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn); } } @Override public void setCandidatesViewShown(boolean shown) { //we show predication only in on-screen keyboard (onEvaluateInputViewShown) //or if the physical keyboard supports candidates (mPredictionLandscape) super.setCandidatesViewShown((onEvaluateInputViewShown() || mPredictionLandscape) && shown); } @Override public void onComputeInsets(InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); if (!isFullscreenMode()) { outInsets.contentTopInsets = outInsets.visibleTopInsets; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { InputConnection ic = getCurrentInputConnection(); if (!mPredictionLandscape) { // For all other keys, if we want to do transformations on // text being entered with a hard keyboard, we need to process // it and do the appropriate action. // using physical keyboard is more annoying with candidate view in // the way // so we disable it. // to clear the underline. commitTyped(ic);// to clear the underline. mPredicting = false; } if (DEBUG) Log.d("AnySoftKeyboard", "Event: Key:"+event.getKeyCode()+" Shift:"+((event.getMetaState()&KeyEvent.META_SHIFT_ON) != 0)+" ALT:"+((event.getMetaState()&KeyEvent.META_ALT_ON) != 0)+" Repeats:"+event.getRepeatCount()); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0 && mInputView != null) { if (mInputView.handleBack()) { // consuming the meta keys //mHardKeyboardAction.resetMetaState(); if (ic != null) ic.clearMetaKeyStates(Integer.MAX_VALUE);//translated, so we also take care of the metakeys. return true; } /* * else if (mTutorial != null) { mTutorial.close(); mTutorial = * null; } */ } break; // case KeyEvent.KEYCODE_DPAD_DOWN: // case KeyEvent.KEYCODE_DPAD_UP: // case KeyEvent.KEYCODE_DPAD_LEFT: // case KeyEvent.KEYCODE_DPAD_RIGHT: // // If tutorial is visible, don't allow dpad to work // if (mTutorial != null) { // return true; // } // break; case KeyEvent.KEYCODE_DEL: onKey(Keyboard.KEYCODE_DELETE, new int[]{Keyboard.KEYCODE_DELETE}); return true; case KeyEvent.KEYCODE_SPACE: if (event.isAltPressed()) { Log.d("AnySoftKeyborad", "User pressed ALT+SPACE, moving to next physical keyboard."); // consuming the meta keys //mHardKeyboardAction.resetMetaState(); if (ic != null) ic.clearMetaKeyStates(Integer.MAX_VALUE);//translated, so we also take care of the metakeys. // only physical keyboard nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.AlphabetSupportsPhysical); return true; } else { //still handling it onKey(32, new int[]{32}); return true; } default: if (mKeyboardSwitcher.isCurrentKeyboardPhysical()) { // sometimes, the physical keyboard will delete input, and then add some. // we'll try to make it nice if (ic != null) ic.beginBatchEdit(); try { mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState, keyCode, event); mHardKeyboardAction.initializeAction(event, mMetaState); //we are at a regular key press, so we'll update our meta-state member mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState); //http://article.gmane.org/gmane.comp.handhelds.openmoko.android-freerunner/629 AnyKeyboard current = mKeyboardSwitcher.getCurrentKeyboard(); String keyboardName = current.getKeyboardName(); HardKeyboardTranslator keyTranslator = (HardKeyboardTranslator)current; if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyborad", "Asking '" + keyboardName + "' to translate key: " + keyCode); if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action before translation: Shift: "+mHardKeyboardAction.isShiftActive()+", Alt: "+mHardKeyboardAction.isAltActive()+", Key code: "+mHardKeyboardAction.getKeyCode()+", changed: "+mHardKeyboardAction.getKeyCodeWasChanged()); keyTranslator.translatePhysicalCharacter(mHardKeyboardAction); if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action after translation: Key code: "+mHardKeyboardAction.getKeyCode()+", changed: "+mHardKeyboardAction.getKeyCodeWasChanged()); if (mHardKeyboardAction.getKeyCodeWasChanged()) { final int translatedChar = mHardKeyboardAction.getKeyCode(); //typing my own. onKey(translatedChar, new int[] { translatedChar }); //since we are handling the key press, we'll also handle the //meta-state of the input connection //since we want to do the reverse, we'll invert the bits final int clearStatesFlags = ~MetaKeyKeyListener.getMetaState(mMetaState); if (ic != null) ic.clearMetaKeyStates(clearStatesFlags); //my handling return true; } } finally { if (ic != null) ic.endBatchEdit(); } } } return super.onKeyDown(keyCode, event); } // private boolean askTranslatorToTranslateHardKeyboardAction(int keyCode, // InputConnection ic, String keyboardName, // HardKeyboardTranslator keyTranslator) // { // if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyborad", "Asking '" + keyboardName + "' to translate key: " + keyCode); // if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action before translation: Shift: "+mHardKeyboardAction.mPhysicalShiftState+", Alt: "+mHardKeyboardAction.mPhysicalAltState+", Key code: "+mHardKeyboardAction.getKeyCode()+", changed: "+mHardKeyboardAction.getKeyCodeWasChanged()); // keyTranslator.translatePhysicalCharacter(mHardKeyboardAction); // if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action after translation: Shift: "+mHardKeyboardAction.mPhysicalShiftState+", Alt: "+mHardKeyboardAction.mPhysicalAltState+", Key code: "+mHardKeyboardAction.getKeyCode()+", changed: "+mHardKeyboardAction.getKeyCodeWasChanged()); // // final char translatedChar = (char)mHardKeyboardAction.consumeKeyCode(); // if (DEBUG) Log.v("AnySoftKeyboard", "Hard Keyboard Action after consumeKeyCode: Shift: "+mHardKeyboardAction.mPhysicalShiftState+", Alt: "+mHardKeyboardAction.mPhysicalAltState+", Key code: "+mHardKeyboardAction.getKeyCode()); // if (mHardKeyboardAction.getKeyCodeWasChanged()) // { // // consuming the meta keys // //Since I'm handling the physical keys, I also need to clear the meta state // if (ic != null) // { // //the clear should be done only if we are not in sticky mode // int metaStateToClear = 0; // if (!mHardKeyboardAction.isShiftActive()) // { // if (DEBUG) Log.v("AnySoftKeyboard", "About to clear SHIFT state from input since shift state is:"+mHardKeyboardAction.mPhysicalShiftState); // metaStateToClear += KeyEvent.META_SHIFT_ON; // } // if (!mHardKeyboardAction.isAltActive()) // { // if (DEBUG) Log.v("AnySoftKeyboard", "About to clear ALT state from input since alt state is:"+mHardKeyboardAction.mPhysicalAltState); // metaStateToClear += KeyEvent.META_ALT_ON; // } // // ic.clearMetaKeyStates(metaStateToClear);//translated, so we also take care of the metakeys. // } // // if (AnySoftKeyboard.DEBUG) // Log.d("AnySoftKeyborad", "'"+ keyboardName + "' translated key " + keyCode + " to "+ translatedChar); // // onKey(translatedChar, new int[] { translatedChar }); // return true; // } else { // if (AnySoftKeyboard.DEBUG) // Log.d("AnySoftKeyborad", "'"+ keyboardName+ "' did not translated key " + keyCode+ "."); // return false; // } // } private void notifyKeyboardChangeIfNeeded() { // Log.d("anySoftKeyboard","notifyKeyboardChangeIfNeeded"); // Thread.dumpStack(); if (mKeyboardSwitcher == null)// happens on first onCreate. return; if ((mKeyboardSwitcher.isAlphabetMode()) && !mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_NEVER)) { AnyKeyboard current = mKeyboardSwitcher.getCurrentKeyboard(); // notifying the user about the keyboard. // creating the message Notification notification = new Notification(current.getKeyboardIcon(), current.getKeyboardName(), System.currentTimeMillis()); Intent notificationIntent = new Intent(); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(getApplicationContext(), "Any Soft Keyboard", current.getKeyboardName(), contentIntent); if (mKeyboardChangeNotificationType.equals("1")) { notification.flags |= Notification.FLAG_ONGOING_EVENT; notification.flags |= Notification.FLAG_NO_CLEAR; } else { notification.flags |= Notification.FLAG_AUTO_CANCEL; } notification.defaults = 0;// no sound, vibrate, etc. // notifying mNotificationManager.notify(KEYBOARD_NOTIFICATION_ID, notification); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // // If tutorial is visible, don't allow dpad to work // if (mTutorial != null) { // return true; // } // Enable shift key and DPAD to do selections if (mInputView != null && mInputView.isShown() && mInputView.isShifted()) { event = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(), event.getKeyCode(), event .getRepeatCount(), event.getDeviceId(), event .getScanCode(), KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON); InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.sendKeyEvent(event); return true; } break; default: mMetaState = MetaKeyKeyListener.handleKeyUp(mMetaState, keyCode, event); } return super.onKeyUp(keyCode, event); } private void commitTyped(InputConnection inputConnection) { if (mPredicting) { mPredicting = false; if (mComposing.length() > 0) { if (inputConnection != null) { inputConnection.commitText(mComposing, 1); } mCommittedLength = mComposing.length(); TextEntryState.acceptedTyped(mComposing); } updateSuggestions(); } } public void updateShiftKeyState(EditorInfo attr) { InputConnection ic = getCurrentInputConnection(); if (attr != null && mInputView != null && mKeyboardSwitcher.isAlphabetMode() && ic != null) { int caps = 0; EditorInfo ei = getCurrentInputEditorInfo(); if (mAutoCap && ei != null && ei.inputType != EditorInfo.TYPE_NULL) { caps = ic.getCursorCapsMode(attr.inputType); } mInputView.setShifted(mCapsLock || caps != 0); } } private void swapPunctuationAndSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastTwo = ic.getTextBeforeCursor(2, 0); if (lastTwo != null && lastTwo.length() == 2 && lastTwo.charAt(0) == KEYCODE_SPACE && isPunctuationCharacter(lastTwo.charAt(1))) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(lastTwo.charAt(1) + " ", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); } } private void doubleSpace() { // if (!mAutoPunctuate) return; if (mCorrectionMode == Suggest.CORRECTION_NONE) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastThree = ic.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && Character.isLetterOrDigit(lastThree.charAt(0)) && lastThree.charAt(1) == KEYCODE_SPACE && lastThree.charAt(2) == KEYCODE_SPACE) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(". ", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); } } public boolean addWordToDictionary(String word) { mUserDictionary.addWord(word, 128); return true; } /** * Helper to determine if a given character code is alphabetic. */ private boolean isAlphabet(int code) { return mKeyboardSwitcher.getCurrentKeyboard().isLetter((char)code); } // Implementation of KeyboardViewListener public void onKey(int primaryCode, int[] keyCodes) { // long when = SystemClock.uptimeMillis(); // if (primaryCode != Keyboard.KEYCODE_DELETE || // when > mLastKeyTime + QUICK_PRESS) { // mDeleteCount = 0; // } // mLastKeyTime = when; switch (primaryCode) { case Keyboard.KEYCODE_DELETE: handleBackspace(); // mDeleteCount++; break; case Keyboard.KEYCODE_SHIFT: handleShift(); break; case Keyboard.KEYCODE_CANCEL: if (mOptionsDialog == null || !mOptionsDialog.isShowing()) { handleClose(); } break; case AnyKeyboardView.KEYCODE_OPTIONS: showOptionsMenu(); break; case AnyKeyboardView.KEYCODE_SHIFT_LONGPRESS: if (mCapsLock) { handleShift(); } else { toggleCapsLock(); } break; case Keyboard.KEYCODE_MODE_CHANGE: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Symbols); break; case AnyKeyboard.KEYCODE_LANG_CHANGE: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Alphabet); break; default: if (isWordSeparator(primaryCode)) { handleSeparator(primaryCode); } else { handleCharacter(primaryCode, keyCodes); //reseting the mSpaceSent, which is set to true upon selecting candidate mSpaceSent = false; } // Cancel the just reverted state mJustRevertedSeparator = null; } } public void onText(CharSequence text) { InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); if (mPredicting) { commitTyped(ic); } ic.commitText(text, 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); mJustRevertedSeparator = null; } private void handleBackspace() { boolean deleteChar = false; InputConnection ic = getCurrentInputConnection(); if (ic == null) return; if (mPredicting) { final int length = mComposing.length(); if (length > 0) { mComposing.delete(length - 1, length); mWord.deleteLast(); ic.setComposingText(mComposing, 1); if (mComposing.length() == 0) { mPredicting = false; } postUpdateSuggestions(); } else { ic.deleteSurroundingText(1, 0); } } else { deleteChar = true; } updateShiftKeyState(getCurrentInputEditorInfo()); TextEntryState.backspace(); if (TextEntryState.getState() == TextEntryState.STATE_UNDO_COMMIT) { revertLastWord(deleteChar); return; } else if (deleteChar) { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); // if (mDeleteCount > DELETE_ACCELERATE_AT) { // sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); // } } mJustRevertedSeparator = null; } private void handleShift() { // Keyboard currentKeyboard = mInputView.getKeyboard(); if (mKeyboardSwitcher.isAlphabetMode()) { // Alphabet keyboard checkToggleCapsLock(); mInputView.setShifted(mCapsLock || !mInputView.isShifted()); } else { mKeyboardSwitcher.toggleShift(); } } private void handleCharacter(int primaryCode, int[] keyCodes) { // Log.d("AnySoftKeyboard", // "handleCharacter: "+primaryCode+", isPredictionOn:"+isPredictionOn()+", mPredicting:"+mPredicting); if (isAlphabet(primaryCode) && isPredictionOn() && !isCursorTouchingWord()) { if (!mPredicting) { mPredicting = true; mComposing.setLength(0); mWord.reset(); } } primaryCode = translatePrimaryCodeFromCurrentKeyboard(primaryCode); // if (mInputView.isShifted()) { // primaryCode = Character.toUpperCase(primaryCode); // } if (mPredicting) { if ((mInputView != null) && mInputView.isShifted() && mComposing.length() == 0) { mWord.setCapitalized(true); } mComposing.append((char) primaryCode); mWord.add(primaryCode, keyCodes); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.setComposingText(mComposing, 1); } postUpdateSuggestions(); } else { sendKeyChar((char) primaryCode); } updateShiftKeyState(getCurrentInputEditorInfo()); // measureCps(); TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode)); } private int translatePrimaryCodeFromCurrentKeyboard(int primaryCode) { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "translatePrimaryCodeFromCurrentKeyboard: " + primaryCode); if (isInputViewShown()) { if (AnySoftKeyboard.DEBUG) Log.v("AnySoftKeyboard", "translatePrimaryCodeFromCurrentKeyboard: isInputViewShown"); if ((mInputView != null) && mInputView.isShifted()) { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "translatePrimaryCodeFromCurrentKeyboard: mInputView.isShifted()"); return mKeyboardSwitcher.getCurrentKeyboard().getShiftedKeyValue(primaryCode); } } return primaryCode; } private void handleSeparator(int primaryCode) { boolean pickedDefault = false; // Handle separator InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mPredicting) { // In certain languages where single quote is a separator, it's // better // not to auto correct, but accept the typed word. For instance, // in Italian dov' should not be expanded to dove' because the // elision // requires the last vowel to be removed. if (mAutoCorrectOn && primaryCode != '\'' && (mJustRevertedSeparator == null || mJustRevertedSeparator.length() == 0 || mJustRevertedSeparator.charAt(0) != primaryCode)) { pickDefaultSuggestion(); pickedDefault = true; } else { commitTyped(ic); } } sendKeyChar((char) primaryCode); TextEntryState.typedCharacter((char) primaryCode, true); if (TextEntryState.getState() == TextEntryState.STATE_PUNCTUATION_AFTER_ACCEPTED && primaryCode != KEYCODE_ENTER && mSpaceSent) { swapPunctuationAndSpace(); } else if (isPredictionOn() && primaryCode == ' ') { // else if (TextEntryState.STATE_SPACE_AFTER_ACCEPTED) { doubleSpace(); } if (pickedDefault && mBestWord != null) { TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord); } updateShiftKeyState(getCurrentInputEditorInfo()); if (ic != null) { ic.endBatchEdit(); } } private void handleClose() { commitTyped(getCurrentInputConnection()); requestHideSelf(0); if (mInputView != null) mInputView.closing(); TextEntryState.endSession(); } private void checkToggleCapsLock() { if (mKeyboardSwitcher.getCurrentKeyboard().isShifted()) { toggleCapsLock(); } } private void toggleCapsLock() { mCapsLock = !mCapsLock; if (mKeyboardSwitcher.isAlphabetMode()) { mKeyboardSwitcher.getCurrentKeyboard().setShiftLocked(mCapsLock); } } private void postUpdateSuggestions() { mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SUGGESTIONS), 100); } private boolean isPredictionOn() { boolean predictionOn = mPredictionOn; //if (!onEvaluateInputViewShown()) predictionOn &= mPredictionLandscape; return predictionOn; } private boolean isCandidateStripVisible() { boolean shown = isPredictionOn() && mShowSuggestions; if (!onEvaluateInputViewShown()) shown &= mPredictionLandscape; return shown; } private void updateSuggestions() { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "updateSuggestions: has mSuggest:" + (mSuggest != null) + ", isPredictionOn:" + isPredictionOn() + ", mPredicting:" + mPredicting + ", mCorrectionMode:" + mCorrectionMode); // Check if we have a suggestion engine attached. if (mSuggest == null) { return; } final boolean showSuggestions = (mCandidateView != null && mPredicting && isPredictionOn() && isCandidateStripVisible()); if (!showSuggestions) { if (mCandidateView != null) mCandidateView.setSuggestions(null, false, false, false); return; } List<CharSequence> stringList = mSuggest.getSuggestions(mInputView, mWord, false); boolean correctionAvailable = mSuggest.hasMinimalCorrection(); // || mCorrectionMode == mSuggest.CORRECTION_FULL; CharSequence typedWord = mWord.getTypedWord(); // If we're in basic correct boolean typedWordValid = mSuggest.isValidWord(typedWord); if (mCorrectionMode == Suggest.CORRECTION_FULL) { correctionAvailable |= typedWordValid; } mCandidateView.setSuggestions(stringList, false, typedWordValid, correctionAvailable); if (stringList.size() > 0) { if (correctionAvailable && !typedWordValid && stringList.size() > 1) { mBestWord = stringList.get(1); } else { mBestWord = typedWord; } } else { mBestWord = null; } setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn); } private void pickDefaultSuggestion() { // Complete any pending candidate query first if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) { mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); updateSuggestions(); } if (mBestWord != null) { TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord); mJustAccepted = true; pickSuggestion(mBestWord); } } public void pickSuggestionManually(int index, CharSequence suggestion) { if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) { CompletionInfo ci = mCompletions[index]; InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.commitCompletion(ci); } mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.clear(); } updateShiftKeyState(getCurrentInputEditorInfo()); return; } pickSuggestion(suggestion); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space if (mAutoSpace) { mSpaceSent = true; sendSpace(); } // Fool the state watcher so that a subsequent backspace will not do a // revert TextEntryState.typedCharacter((char) KEYCODE_SPACE, true); } private void pickSuggestion(CharSequence suggestion) { if (mCapsLock) { suggestion = suggestion.toString().toUpperCase(); } else if (preferCapitalization() || (mKeyboardSwitcher.isAlphabetMode() && (mInputView != null) && mInputView.isShifted())) { suggestion = Character.toUpperCase(suggestion.charAt(0)) + suggestion.subSequence(1, suggestion.length()).toString(); } InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.commitText(suggestion, 1); } mPredicting = false; mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.setSuggestions(null, false, false, false); } updateShiftKeyState(getCurrentInputEditorInfo()); } private boolean isCursorTouchingWord() { InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); CharSequence toRight = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(toLeft) && !isWordSeparator(toLeft.charAt(0))) { return true; } if (!TextUtils.isEmpty(toRight) && !isWordSeparator(toRight.charAt(0))) { return true; } return false; } public void revertLastWord(boolean deleteChar) { final int length = mComposing.length(); if (!mPredicting && length > 0) { final InputConnection ic = getCurrentInputConnection(); mPredicting = true; ic.beginBatchEdit(); mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0); if (deleteChar) ic.deleteSurroundingText(1, 0); int toDelete = mCommittedLength; CharSequence toTheLeft = ic .getTextBeforeCursor(mCommittedLength, 0); if (toTheLeft != null && toTheLeft.length() > 0 && isWordSeparator(toTheLeft.charAt(0))) { toDelete--; } ic.deleteSurroundingText(toDelete, 0); ic.setComposingText(mComposing, 1); TextEntryState.backspace(); ic.endBatchEdit(); postUpdateSuggestions(); } else { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); mJustRevertedSeparator = null; } } // protected String getWordSeparators() { // return mWordSeparators; // } public boolean isWordSeparator(int code) { // String separators = getWordSeparators(); // return separators.contains(String.valueOf((char)code)); return (!isAlphabet(code)); } public boolean isPunctuationCharacter(int code) { return PUNCTUATION_CHARACTERS.contains(String.valueOf((char) code)); } private void sendSpace() { sendKeyChar((char) KEYCODE_SPACE); updateShiftKeyState(getCurrentInputEditorInfo()); } public boolean preferCapitalization() { return mWord.isCapitalized(); } public void swipeRight() { // this should be done only if swipe was enabled if (mChangeKeysMode.equals("3")) { // TODO: space/backspace (depends on direction of keyboard) } else { nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Alphabet); } } public void swipeLeft() { // this should be done only if swipe was enabled if (mChangeKeysMode.equals("3")) { // TODO: space/backspace (depends on direction of keyboard) } else { nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Symbols); } } private void nextKeyboard(EditorInfo currentEditorInfo, KeyboardSwitcher.NextKeyboardType type) { Log.d("AnySoftKeyboard", "nextKeyboard: currentEditorInfo.inputType=" + currentEditorInfo.inputType + " type:" + type); AnyKeyboard currentKeyboard = mKeyboardSwitcher.getCurrentKeyboard(); if (currentKeyboard == null) { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "nextKeyboard: Looking for next keyboard. No current keyboard."); } else { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "nextKeyboard: Looking for next keyboard. Current keyboard is:" + currentKeyboard.getKeyboardName()); } // in numeric keyboards, the LANG key will go back to the original // alphabet keyboard- // so no need to look for the next keyboard, 'mLastSelectedKeyboard' // holds the last // keyboard used. currentKeyboard = mKeyboardSwitcher.nextKeyboard(currentEditorInfo, type); Log.i("AnySoftKeyboard", "nextKeyboard: Setting next keyboard to: " + currentKeyboard.getKeyboardName()); updateShiftKeyState(currentEditorInfo); // changing dictionary setMainDictionaryForCurrentKeyboard(); // Notifying if needed if ((mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) || (mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ON_PHYSICAL) && (type == NextKeyboardType.AlphabetSupportsPhysical))) { notifyKeyboardChangeIfNeeded(); } } public void swipeDown() { handleClose(); } public void swipeUp() { handleShift(); } public void onPress(int primaryCode) { if (mVibrationDuration > 0) { if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "Vibrating on key-pressed"); ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)) .vibrate(mVibrationDuration); } if (mSoundOn/* && (!mSilentMode) */) { AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // Will use sound effects ONLY if the device is not muted. if (manager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) { int keyFX = AudioManager.FX_KEY_CLICK; switch (primaryCode) { case 13: keyFX = AudioManager.FX_KEYPRESS_RETURN; case Keyboard.KEYCODE_DELETE: keyFX = AudioManager.FX_KEYPRESS_DELETE; case 32: keyFX = AudioManager.FX_KEYPRESS_SPACEBAR; } int volume = manager .getStreamVolume(AudioManager.STREAM_NOTIFICATION); if (AnySoftKeyboard.DEBUG) Log.d("AnySoftKeyboard", "Sound on key-pressed. Sound ID:" + keyFX + " with volume " + volume); manager.playSoundEffect(keyFX, volume); } else { if (AnySoftKeyboard.DEBUG) Log.v("AnySoftKeyboard", "Devices is muted. No sounds on key-pressed."); } } } public void onRelease(int primaryCode) { // vibrate(); } // private void checkTutorial(String privateImeOptions) { // if (privateImeOptions == null) return; // if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) { // if (mTutorial == null) startTutorial(); // } else if // (privateImeOptions.equals("com.android.setupwizard:HideTutorial")) { // if (mTutorial != null) { // if (mTutorial.close()) { // mTutorial = null; // } // } // } // } // // private boolean mTutorialsShown = false; private void startTutorial() { // if (!mTutorialsShown) // { // mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL), 500); // mTutorialsShown = true; // } } // void tutorialDone() { // mTutorial = null; // } // // private void launchSettings() { // handleClose(); // Intent intent = new Intent(); // intent.setClass(LatinIME.this, LatinIMESettings.class); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(intent); // } private boolean loadSettings() { //setting all values to default PreferenceManager.setDefaultValues(this, R.xml.prefs, false); boolean handled = false; // Get the settings preferences SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); int newVibrationDuration = Integer.parseInt(sp.getString("vibrate_on_key_press_duration", "0")); handled = handled || (newVibrationDuration != mVibrationDuration); mVibrationDuration = newVibrationDuration; boolean newSoundOn = sp.getBoolean("sound_on", false); boolean soundChanged = (newSoundOn != mSoundOn); if (soundChanged) { if (newSoundOn) { Log.i("AnySoftKeyboard", "Loading sounds effects from AUDIO_SERVICE due to configuration change."); mAudioManager.loadSoundEffects(); } else { Log.i("AnySoftKeyboard", "Releasing sounds effects from AUDIO_SERVICE due to configuration change."); mAudioManager.unloadSoundEffects(); } } handled = handled || soundChanged; mSoundOn = newSoundOn; // in order to support the old type of configuration String newKeyboardChangeNotificationType = sp.getString("physical_keyboard_change_notification_type", KEYBOARD_NOTIFICATION_ON_PHYSICAL); boolean notificationChanged = (!newKeyboardChangeNotificationType.equalsIgnoreCase(mKeyboardChangeNotificationType)); handled = handled || notificationChanged; mKeyboardChangeNotificationType = newKeyboardChangeNotificationType; if (notificationChanged) { // now clearing the notification, and it will be re-shown if needed NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // now clearing the notification, and it will be re-shown if needed notificationManager.cancel(KEYBOARD_NOTIFICATION_ID); // should it be always on? if (mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS)) notifyKeyboardChangeIfNeeded(); } boolean newAutoCap = sp.getBoolean("auto_caps", true); handled = handled || (newAutoCap != mAutoCap); mAutoCap = newAutoCap; boolean newShowSuggestions = sp.getBoolean("candidates_on", true); boolean suggestionsChanged = (newShowSuggestions != mShowSuggestions); handled = handled || suggestionsChanged; mShowSuggestions = newShowSuggestions; setMainDictionaryForCurrentKeyboard(); boolean newAutoComplete = sp.getBoolean("auto_complete", true) && mShowSuggestions; handled = handled || (newAutoComplete != mAutoComplete); mAutoComplete = newAutoComplete; boolean newQuickFixes = sp.getBoolean("quick_fix", true); handled = handled || (newQuickFixes != mQuickFixes); mQuickFixes = newQuickFixes; mAutoCorrectOn = /*mSuggest != null &&*//*Suggestion always exists, maybe not at the moment, but shortly*/ (mAutoComplete || mQuickFixes); mCorrectionMode = mAutoComplete ? 2 : (mShowSuggestions/* mQuickFixes */? 1 : 0); // boolean newLandscapePredications= sp.getBoolean("physical_keyboard_suggestions", true); // handled = handled || (newLandscapePredications != mPredictionLandscape); // mPredictionLandscape = newLandscapePredications; // this change requires the recreation of the keyboards. // so we wont mark the 'handled' result. mChangeKeysMode = sp.getString("keyboard_layout_change_method", "1"); return handled; } private void setMainDictionaryForCurrentKeyboard() { if (mSuggest != null) { if (!mShowSuggestions) { Log.d("AnySoftKeyboard", "No suggestion is required. I'll try to release memory from the dictionary."); DictionaryFactory.releaseAllDictionaries(); mSuggest.setMainDictionary(null); } else { // It null at the creation of the application. if ((mKeyboardSwitcher != null) && mKeyboardSwitcher.isAlphabetMode()) { AnyKeyboard currentKeyobard = mKeyboardSwitcher.getCurrentKeyboard(); Language dictionaryLanguage = getLanguageForKeyobard(currentKeyobard); Dictionary mainDictionary = DictionaryFactory.getDictionary(dictionaryLanguage, this); mSuggest.setMainDictionary(mainDictionary); } } } } private Language getLanguageForKeyobard(AnyKeyboard currentKeyobard) { //if there is a mapping in the settings, we'll use that, else we'll return the default String mappingSettingsKey = getDictionaryOverrideKey(currentKeyobard); String defaultDictionary = currentKeyobard.getDefaultDictionaryLanguage().toString(); String dictionaryValue = getSharedPreferences().getString(mappingSettingsKey, null); if ((dictionaryValue == null) || (defaultDictionary.equals(dictionaryValue))) return currentKeyobard.getDefaultDictionaryLanguage(); else { Log.d("AnySoftKeyboard", "Default dictionary '"+defaultDictionary+"' for keyboard '"+currentKeyobard.getKeyboardPrefId()+"' has been overriden to '"+dictionaryValue+"'"); //fixing the Slovene->Slovenian if (dictionaryValue.equalsIgnoreCase("Slovene")) {//Please remove this in some future version. dictionaryValue = "Slovenian"; Editor editor = getSharedPreferences().edit(); Log.d("AnySoftKeyboard", "Dictionary override fix: Slovene->Slovenian."); editor.putString(mappingSettingsKey, dictionaryValue); editor.commit(); } Language overridingLanguage = Language.valueOf(dictionaryValue); return overridingLanguage; } } private String getDictionaryOverrideKey(AnyKeyboard currentKeyobard) { String mappingSettingsKey = currentKeyobard.getKeyboardPrefId()+"_override_dictionary"; return mappingSettingsKey; } private void launchSettings() { handleClose(); Intent intent = new Intent(); intent.setClass(AnySoftKeyboard.this, SoftKeyboardSettings.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void launchDictioanryOverriding() { AnyKeyboard currentKeyboard = mKeyboardSwitcher.getCurrentKeyboard(); final String dictionaryOverridingKey = getDictionaryOverrideKey(currentKeyboard); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(R.drawable.icon_8_key); builder.setTitle(getResources().getString(R.string.override_dictionary_title, currentKeyboard.getKeyboardName())); builder.setNegativeButton(android.R.string.cancel, null); ArrayList<CharSequence> dictioanries = new ArrayList<CharSequence>(); dictioanries.add(getString(R.string.override_dictionary_default)); for(Language lang : Language.values()) { dictioanries.add(lang.toString()); } final CharSequence[] items = new CharSequence[dictioanries.size()]; dictioanries.toArray(items); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int position) { di.dismiss(); Editor editor = getSharedPreferences().edit(); switch(position) { case 0: Log.d("AnySoftKeyboard", "Dictionary overriden disabled. User selected default."); editor.remove(dictionaryOverridingKey); showToastMessage(R.string.override_disabled, true); break; default: if ((position < 0) || (position >= items.length)) { Log.d("AnySoftKeyboard", "Dictioanry override dialog canceled."); } else { String selectedLanguageString = items[position].toString(); Log.d("AnySoftKeyboard", "Dictionary override. User selected "+selectedLanguageString); editor.putString(dictionaryOverridingKey, selectedLanguageString); showToastMessage(getString(R.string.override_enabled, selectedLanguageString), true); } break; } editor.commit(); setMainDictionaryForCurrentKeyboard(); } }); mOptionsDialog = builder.create(); Window window = mOptionsDialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = mInputView.getWindowToken(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog.show(); } private void showOptionsMenu() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(R.drawable.icon_8_key); builder.setNegativeButton(android.R.string.cancel, null); CharSequence itemSettings = getString(R.string.ime_settings); CharSequence itemOverrideDictionary = getString(R.string.override_dictionary); CharSequence itemInputMethod = getString(R.string.change_ime); builder.setItems(new CharSequence[] { itemSettings, itemOverrideDictionary, itemInputMethod}, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: launchSettings(); break; case 1: launchDictioanryOverriding(); break; case 2: ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).showInputMethodPicker(); break; } } }); builder.setTitle(getResources().getString(R.string.ime_name)); mOptionsDialog = builder.create(); Window window = mOptionsDialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = mInputView.getWindowToken(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog.show(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.i("AnySoftKeyboard", "**** onConfigurationChanged"); Log.i("AnySoftKeyboard", "** Locale:"+ newConfig.locale.toString()); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d("AnySoftKeyboard", "onSharedPreferenceChanged - key:" + key); boolean handled = loadSettings(); if (!handled) { /* AnyKeyboard removedKeyboard = */mKeyboardSwitcher.makeKeyboards(true);// maybe a new keyboard /* * if (removedKeyboard != null) { * DictionaryFactory.releaseDictionary * (removedKeyboard.getDefaultDictionaryLanguage()); } */ } } public void appendCharactersToInput(CharSequence textToCommit) { if (DEBUG) Log.d("AnySoftKeyboard", "appendCharactersToInput: "+textToCommit); mWord.append(textToCommit); mComposing.append(textToCommit); appendStringToInput(textToCommit); } private void appendStringToInput(CharSequence textToCommit) { // handleTextDirection(); if (DEBUG) Log.d("AnySoftKeyboard", "appendStringToInput: "+textToCommit); if (mCompletionOn) { getCurrentInputConnection().setComposingText(mWord.getTypedWord(), textToCommit.length()); // updateCandidates(); } else commitTyped(getCurrentInputConnection()); updateShiftKeyState(getCurrentInputEditorInfo()); } public void deleteLastCharactersFromInput(int countToDelete) { if (DEBUG) Log.d("AnySoftKeyboard", "deleteLastCharactersFromInput: "+countToDelete); if (countToDelete == 0) return; final int currentLength = mComposing.length(); boolean shouldDeleteUsingCompletion; if (currentLength > 0) { shouldDeleteUsingCompletion = true; if (currentLength > countToDelete) { mComposing.delete(currentLength - countToDelete, currentLength); mWord.deleteLast(countToDelete); } else { mComposing.setLength(0); mWord.reset(); } } else { shouldDeleteUsingCompletion = false; } if (mCompletionOn && shouldDeleteUsingCompletion) { getCurrentInputConnection().setComposingText(mComposing, 1); // updateCandidates(); } else { getCurrentInputConnection().deleteSurroundingText(countToDelete, 0); } updateShiftKeyState(getCurrentInputEditorInfo()); } public SharedPreferences getSharedPreferences() { return PreferenceManager.getDefaultSharedPreferences(this); } public void showToastMessage(int resId, boolean forShortTime) { CharSequence text = getResources().getText(resId); showToastMessage(text, forShortTime); } private void showToastMessage(CharSequence text, boolean forShortTime) { int duration = forShortTime? Toast.LENGTH_SHORT : Toast.LENGTH_LONG; if (DEBUG) Log.v("AnySoftKeyboard", "showToastMessage: '"+text+"'. For: "+duration); Toast.makeText(this.getApplication(), text, duration).show(); } public void performLengthyOperation(int textResId, final Runnable thingToDo) { thingToDo.run(); // final ProgressDialog spinner = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER); // // Thread t = new Thread() { // public void run() { // thingToDo.run(); // spinner.dismiss(); // } // }; // t.start(); // spinner.setTitle(R.string.please_wait); // spinner.setIcon(R.drawable.icon_8_key); // spinner.setMessage(getResources().getText(textResId)); // spinner.setCancelable(false); // spinner.show(); } @Override public void onLowMemory() { Log.w("AnySoftKeyboard", "The OS has reported that it is low on memory!. I'll try to clear some cache."); mKeyboardSwitcher.onLowMemory(); DictionaryFactory.onLowMemory(getLanguageForKeyobard(mKeyboardSwitcher.getCurrentKeyboard())); super.onLowMemory(); } }
Issue 162 - even better
src/com/menny/android/anysoftkeyboard/AnySoftKeyboard.java
Issue 162 - even better
<ide><path>rc/com/menny/android/anysoftkeyboard/AnySoftKeyboard.java <ide> break; <ide> default: <ide> mMetaState = MetaKeyKeyListener.handleKeyUp(mMetaState, keyCode, event); <add> final int clearStatesFlags = ~MetaKeyKeyListener.getMetaState(mMetaState); <add> InputConnection ic = getCurrentInputConnection(); <add> if (ic != null) <add> ic.clearMetaKeyStates(clearStatesFlags); <ide> } <ide> return super.onKeyUp(keyCode, event); <ide> }
Java
mit
258b3c76452696ed2d4d2a841831680003294d0c
0
Bammerbom/UltimateCore
/* * This file is part of UltimateCore, licensed under the MIT License (MIT). * * Copyright (c) Bammerbom * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package bammerbom.ultimatecore.sponge.modules.item.api; import bammerbom.ultimatecore.sponge.api.permission.Permission; import bammerbom.ultimatecore.sponge.api.permission.PermissionLevel; import org.spongepowered.api.text.Text; public class ItemPermissions { public static Permission UC_ITEM_MORE_BASE = Permission.create("uc.item.more.base", "item", PermissionLevel.ADMIN, "more", Text.of("Allows you to use the more command.")); public static Permission UC_ITEM_REPAIR_BASE = Permission.create("uc.item.repair.base", "item", PermissionLevel.ADMIN, "repair", Text.of("Allows you to use the repair command for both all and one item.")); public static Permission UC_ITEM_REPAIR_ALL = Permission.create("uc.item.repair.all", "item", PermissionLevel.ADMIN, "repair", Text.of("Allows you to use the repair command for all items.")); public static Permission UC_ITEM_REPAIR_ONE = Permission.create("uc.item.repair.one", "item", PermissionLevel.ADMIN, "repair", Text.of("Allows you to use the repair command for one item.")); public static Permission UC_ITEM_ITEMNAME_BASE = Permission.create("uc.item.itemname.base", "item", PermissionLevel.ADMIN, "itemname", Text.of("Allows you to use the itemname command.")); public static Permission UC_ITEM_ITEMLORE_BASE = Permission.create("uc.item.itemlore.base", "item", PermissionLevel.ADMIN, "itemlore", Text.of("Allows you to use the itemlore command.")); public static Permission UC_ITEM_ITEMQUANTITY_BASE = Permission.create("uc.item.itemquantity.base", "item", PermissionLevel.ADMIN, "itemquantity", Text.of("Allows you to use the itemquantity command.")); public static Permission UC_ITEM_ITEMDURABILITY_BASE = Permission.create("uc.item.itemdurability.base", "item", PermissionLevel.ADMIN, "itemdurability", Text.of("Allows you to use the itemdurability command.")); public static Permission UC_ITEM_ITEMUNBREAKABLE_BASE = Permission.create("uc.item.itemunbreakable.base", "item", PermissionLevel.ADMIN, "itemunbreakable", Text.of("Allows you to use the itemunbreakable command.")); //public static Permission UC_ITEM_ITEMGLOW_BASE = Permission.create("uc.item.itemglow.base", "item", PermissionLevel.ADMIN, "itemglow", Text.of("Allows you to use the itemglow command.")); public static Permission UC_ITEM_ITEMCANPLACEON_BASE = Permission.create("uc.item.itemcanplaceon.base", "item", PermissionLevel.ADMIN, "itemcanplaceon", Text.of("Allows you to use the itemcanplaceon command.")); public static Permission UC_ITEM_ITEMCANBREAK_BASE = Permission.create("uc.item.itemcanbreak.base", "item", PermissionLevel.ADMIN, "itemcanbreak", Text.of("Allows you to use the itemcanbreak command.")); public static Permission UC_ITEM_ITEMHIDETAGS_BASE = Permission.create("uc.item.itemhidetags.base", "item", PermissionLevel.ADMIN, "itemhidetags", Text.of("Allows you to use the itemhidetags command.")); public static Permission UC_ITEM_ITEMENCHANT_BASE = Permission.create("uc.item.itemenchant.base", "item", PermissionLevel.ADMIN, "itemenchant", Text.of("Allows you to use the itemenchant command.")); // public static Permission UC_ITEM_ITEMMAXHEALTH_BASE = Permission.create("uc.item.itemmaxhealth.base", "item", PermissionLevel.ADMIN, "itemmaxhealth", Text.of("Allows you to use the itemmaxhealth command.")); // public static Permission UC_ITEM_ITEMDAMAGE_BASE = Permission.create("uc.item.itemdamage.base", "item", PermissionLevel.ADMIN, "itemdamage", Text.of("Allows you to use the itemdamage command.")); // public static Permission UC_ITEM_ITEMSPEED_BASE = Permission.create("uc.item.itemspeed.base", "item", PermissionLevel.ADMIN, "itemspeed", Text.of("Allows you to use the itemspeed command.")); // public static Permission UC_ITEM_ITEMKNOCKBACKRESISTANCE_BASE = Permission.create("uc.item.itemknockbackresistance.base", "item", PermissionLevel.ADMIN, "itemknockbackresistance", Text.of("Allows you to use the itemknockbackresistance command.")); // // public static Permission UC_ITEM_SKULL_BASE = Permission.create("uc.item.skull.base", "item", PermissionLevel.ADMIN, "skull", Text.of("Allows you to use the skull command.")); // public static Permission UC_ITEM_BOOKAUTHOR_BASE = Permission.create("uc.item.bookauthor.base", "item", PermissionLevel.ADMIN, "bookauthor", Text.of("Allows you to use the bookauthor command.")); // public static Permission UC_ITEM_BOOKTITLE_BASE = Permission.create("uc.item.booktitle.base", "item", PermissionLevel.ADMIN, "booktitle", Text.of("Allows you to use the booktitle command.")); // public static Permission UC_ITEM_BOOKEDIT_BASE = Permission.create("uc.item.bookedit.base", "item", PermissionLevel.ADMIN, "bookedit", Text.of("Allows you to use the bookedit command.")); // public static Permission UC_ITEM_FIREWORK_BASE = Permission.create("uc.item.firework.base", "item", PermissionLevel.ADMIN, "firework", Text.of("Allows you to use the firework command.")); // public static Permission UC_ITEM_LEATHERARMORCOLOR_BASE = Permission.create("uc.item.leatherarmorcolor.base", "item", PermissionLevel.ADMIN, "leatherarmorcolor", Text.of("Allows you to use the leatherarmorcolor command.")); }
src/main/java/bammerbom/ultimatecore/sponge/modules/item/api/ItemPermissions.java
/* * This file is part of UltimateCore, licensed under the MIT License (MIT). * * Copyright (c) Bammerbom * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package bammerbom.ultimatecore.sponge.modules.item.api; import bammerbom.ultimatecore.sponge.api.permission.Permission; import bammerbom.ultimatecore.sponge.api.permission.PermissionLevel; import org.spongepowered.api.text.Text; public class ItemPermissions { public static Permission UC_ITEM_MORE_BASE = Permission.create("uc.item.more.base", "item", PermissionLevel.ADMIN, "more", Text.of("Allows you to use the more command.")); public static Permission UC_ITEM_REPAIR_BASE = Permission.create("uc.item.repair.base", "item", PermissionLevel.ADMIN, "repair", Text.of("Allows you to use the repair command for both all and one item.")); public static Permission UC_ITEM_REPAIR_ALL = Permission.create("uc.item.repair.all", "item", PermissionLevel.ADMIN, "repair", Text.of("Allows you to use the repair command for all items.")); public static Permission UC_ITEM_REPAIR_ONE = Permission.create("uc.item.repair.one", "item", PermissionLevel.ADMIN, "repair", Text.of("Allows you to use the repair command for one item.")); public static Permission UC_ITEM_ITEMNAME_BASE = Permission.create("uc.item.itemname.base", "item", PermissionLevel.ADMIN, "itemname", Text.of("Allows you to use the itemname command.")); public static Permission UC_ITEM_ITEMLORE_BASE = Permission.create("uc.item.itemlore.base", "item", PermissionLevel.ADMIN, "itemlore", Text.of("Allows you to use the itemlore command.")); public static Permission UC_ITEM_ITEMQUANTITY_BASE = Permission.create("uc.item.itemquantity.base", "item", PermissionLevel.ADMIN, "itemquantity", Text.of("Allows you to use the itemquantity command.")); public static Permission UC_ITEM_ITEMDURABILITY_BASE = Permission.create("uc.item.itemdurability.base", "item", PermissionLevel.ADMIN, "itemdurability", Text.of("Allows you to use the itemdurability command.")); public static Permission UC_ITEM_ITEMUNBREAKABLE_BASE = Permission.create("uc.item.itemunbreakable.base", "item", PermissionLevel.ADMIN, "itemunbreakable", Text.of("Allows you to use the itemunbreakable command.")); //public static Permission UC_ITEM_ITEMGLOW_BASE = Permission.create("uc.item.itemglow.base", "item", PermissionLevel.ADMIN, "itemglow", Text.of("Allows you to use the itemglow command.")); public static Permission UC_ITEM_ITEMCANPLACEON_BASE = Permission.create("uc.item.itemcanplaceon.base", "item", PermissionLevel.ADMIN, "itemcanplaceon", Text.of("Allows you to use the itemcanplaceon command.")); public static Permission UC_ITEM_ITEMCANBREAK_BASE = Permission.create("uc.item.itemcanbreak.base", "item", PermissionLevel.ADMIN, "itemcanbreak", Text.of("Allows you to use the itemcanbreak command.")); public static Permission UC_ITEM_ITEMHIDETAGS_BASE = Permission.create("uc.item.itemhidetags.base", "item", PermissionLevel.ADMIN, "itemhidetags", Text.of("Allows you to use the itemhidetags command.")); public static Permission UC_ITEM_ITEMENCHANT_BASE = Permission.create("uc.item.itemenchant.base", "item", PermissionLevel.ADMIN, "itemenchant", Text.of("Allows you to use the itemenchant command.")); public static Permission UC_ITEM_ITEMMAXHEALTH_BASE = Permission.create("uc.item.itemmaxhealth.base", "item", PermissionLevel.ADMIN, "itemmaxhealth", Text.of("Allows you to use the itemmaxhealth command.")); public static Permission UC_ITEM_ITEMDAMAGE_BASE = Permission.create("uc.item.itemdamage.base", "item", PermissionLevel.ADMIN, "itemdamage", Text.of("Allows you to use the itemdamage command.")); public static Permission UC_ITEM_ITEMSPEED_BASE = Permission.create("uc.item.itemspeed.base", "item", PermissionLevel.ADMIN, "itemspeed", Text.of("Allows you to use the itemspeed command.")); public static Permission UC_ITEM_ITEMKNOCKBACKRESISTANCE_BASE = Permission.create("uc.item.itemknockbackresistance.base", "item", PermissionLevel.ADMIN, "itemknockbackresistance", Text.of("Allows you to use the itemknockbackresistance command.")); public static Permission UC_ITEM_SKULL_BASE = Permission.create("uc.item.skull.base", "item", PermissionLevel.ADMIN, "skull", Text.of("Allows you to use the skull command.")); public static Permission UC_ITEM_BOOKAUTHOR_BASE = Permission.create("uc.item.bookauthor.base", "item", PermissionLevel.ADMIN, "bookauthor", Text.of("Allows you to use the bookauthor command.")); public static Permission UC_ITEM_BOOKTITLE_BASE = Permission.create("uc.item.booktitle.base", "item", PermissionLevel.ADMIN, "booktitle", Text.of("Allows you to use the booktitle command.")); public static Permission UC_ITEM_BOOKEDIT_BASE = Permission.create("uc.item.bookedit.base", "item", PermissionLevel.ADMIN, "bookedit", Text.of("Allows you to use the bookedit command.")); public static Permission UC_ITEM_FIREWORK_BASE = Permission.create("uc.item.firework.base", "item", PermissionLevel.ADMIN, "firework", Text.of("Allows you to use the firework command.")); public static Permission UC_ITEM_LEATHERARMORCOLOR_BASE = Permission.create("uc.item.leatherarmorcolor.base", "item", PermissionLevel.ADMIN, "leatherarmorcolor", Text.of("Allows you to use the leatherarmorcolor command.")); }
Comment permissions which are unused for now
src/main/java/bammerbom/ultimatecore/sponge/modules/item/api/ItemPermissions.java
Comment permissions which are unused for now
<ide><path>rc/main/java/bammerbom/ultimatecore/sponge/modules/item/api/ItemPermissions.java <ide> public static Permission UC_ITEM_ITEMHIDETAGS_BASE = Permission.create("uc.item.itemhidetags.base", "item", PermissionLevel.ADMIN, "itemhidetags", Text.of("Allows you to use the itemhidetags command.")); <ide> public static Permission UC_ITEM_ITEMENCHANT_BASE = Permission.create("uc.item.itemenchant.base", "item", PermissionLevel.ADMIN, "itemenchant", Text.of("Allows you to use the itemenchant command.")); <ide> <del> public static Permission UC_ITEM_ITEMMAXHEALTH_BASE = Permission.create("uc.item.itemmaxhealth.base", "item", PermissionLevel.ADMIN, "itemmaxhealth", Text.of("Allows you to use the itemmaxhealth command.")); <del> public static Permission UC_ITEM_ITEMDAMAGE_BASE = Permission.create("uc.item.itemdamage.base", "item", PermissionLevel.ADMIN, "itemdamage", Text.of("Allows you to use the itemdamage command.")); <del> public static Permission UC_ITEM_ITEMSPEED_BASE = Permission.create("uc.item.itemspeed.base", "item", PermissionLevel.ADMIN, "itemspeed", Text.of("Allows you to use the itemspeed command.")); <del> public static Permission UC_ITEM_ITEMKNOCKBACKRESISTANCE_BASE = Permission.create("uc.item.itemknockbackresistance.base", "item", PermissionLevel.ADMIN, "itemknockbackresistance", Text.of("Allows you to use the itemknockbackresistance command.")); <del> <del> public static Permission UC_ITEM_SKULL_BASE = Permission.create("uc.item.skull.base", "item", PermissionLevel.ADMIN, "skull", Text.of("Allows you to use the skull command.")); <del> public static Permission UC_ITEM_BOOKAUTHOR_BASE = Permission.create("uc.item.bookauthor.base", "item", PermissionLevel.ADMIN, "bookauthor", Text.of("Allows you to use the bookauthor command.")); <del> public static Permission UC_ITEM_BOOKTITLE_BASE = Permission.create("uc.item.booktitle.base", "item", PermissionLevel.ADMIN, "booktitle", Text.of("Allows you to use the booktitle command.")); <del> public static Permission UC_ITEM_BOOKEDIT_BASE = Permission.create("uc.item.bookedit.base", "item", PermissionLevel.ADMIN, "bookedit", Text.of("Allows you to use the bookedit command.")); <del> public static Permission UC_ITEM_FIREWORK_BASE = Permission.create("uc.item.firework.base", "item", PermissionLevel.ADMIN, "firework", Text.of("Allows you to use the firework command.")); <del> public static Permission UC_ITEM_LEATHERARMORCOLOR_BASE = Permission.create("uc.item.leatherarmorcolor.base", "item", PermissionLevel.ADMIN, "leatherarmorcolor", Text.of("Allows you to use the leatherarmorcolor command.")); <add>// public static Permission UC_ITEM_ITEMMAXHEALTH_BASE = Permission.create("uc.item.itemmaxhealth.base", "item", PermissionLevel.ADMIN, "itemmaxhealth", Text.of("Allows you to use the itemmaxhealth command.")); <add>// public static Permission UC_ITEM_ITEMDAMAGE_BASE = Permission.create("uc.item.itemdamage.base", "item", PermissionLevel.ADMIN, "itemdamage", Text.of("Allows you to use the itemdamage command.")); <add>// public static Permission UC_ITEM_ITEMSPEED_BASE = Permission.create("uc.item.itemspeed.base", "item", PermissionLevel.ADMIN, "itemspeed", Text.of("Allows you to use the itemspeed command.")); <add>// public static Permission UC_ITEM_ITEMKNOCKBACKRESISTANCE_BASE = Permission.create("uc.item.itemknockbackresistance.base", "item", PermissionLevel.ADMIN, "itemknockbackresistance", Text.of("Allows you to use the itemknockbackresistance command.")); <add>// <add>// public static Permission UC_ITEM_SKULL_BASE = Permission.create("uc.item.skull.base", "item", PermissionLevel.ADMIN, "skull", Text.of("Allows you to use the skull command.")); <add>// public static Permission UC_ITEM_BOOKAUTHOR_BASE = Permission.create("uc.item.bookauthor.base", "item", PermissionLevel.ADMIN, "bookauthor", Text.of("Allows you to use the bookauthor command.")); <add>// public static Permission UC_ITEM_BOOKTITLE_BASE = Permission.create("uc.item.booktitle.base", "item", PermissionLevel.ADMIN, "booktitle", Text.of("Allows you to use the booktitle command.")); <add>// public static Permission UC_ITEM_BOOKEDIT_BASE = Permission.create("uc.item.bookedit.base", "item", PermissionLevel.ADMIN, "bookedit", Text.of("Allows you to use the bookedit command.")); <add>// public static Permission UC_ITEM_FIREWORK_BASE = Permission.create("uc.item.firework.base", "item", PermissionLevel.ADMIN, "firework", Text.of("Allows you to use the firework command.")); <add>// public static Permission UC_ITEM_LEATHERARMORCOLOR_BASE = Permission.create("uc.item.leatherarmorcolor.base", "item", PermissionLevel.ADMIN, "leatherarmorcolor", Text.of("Allows you to use the leatherarmorcolor command.")); <ide> }
Java
mit
b9218f5976440d2ed638803cf70a4875be212b8f
0
relayrides/pushy,urbanairship/pushy,relayrides/pushy,urbanairship/pushy,relayrides/pushy,urbanairship/pushy
/* Copyright (c) 2013 RelayRides * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.relayrides.pushy.apns; import io.netty.channel.nio.NioEventLoopGroup; import java.lang.Thread.UncaughtExceptionHandler; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Push managers manage connections to the APNs gateway and send notifications from their queue. Push managers * should always be created using the {@link PushManagerFactory} class. Push managers are the main public-facing point * of interaction with Pushy.</p> * * <h2>Queues</h2> * * <p>A push manager has two queues: the public queue through which callers add notifications to be sent, and a private, * internal &quot;retry queue.&quot; Callers send push notifications by adding them to the push manager's public queue * (see {@link PushManager#getQueue()}). The push manager will take and notifications from the public queue as quickly * as it is able to do so, and will never put notifications back in the public queue. Callers are free to manipulate the * public queue however they see fit.</p> * * <p>If, for any reason other than a permanent rejection, a notification could not be delivered, it will be returned to * the push manager's internal retry queue. The push manager will always try to drain its retry queue before taking new * notifications from the public queue.</p> * * <h2>Shutting down</h2> * * <p>A push manager can be shut down with or without a timeout, though shutting down without a timeout provides * stronger guarantees with regard to the state of sent notifications. Regardless of whether a timeout is specified, * push managers will stop taking notifications from the public queue as soon the shutdown process has started. Push * managers shut down by asking all of their connections to shut down gracefully by sending a known-bad notification to * the APNs gateway. The push manager will restore closed connections and keep trying to send notifications from its * internal retry queue until either the queue is empty or the timeout expires. If the timeout expires while there are * still open connections, all remaining connections are closed immediately.</p> * * <p>When shutting down without a timeout, it is guaranteed that the push manager's internal retry queue will be empty * and all sent notifications will have reached and been processed by the APNs gateway. Any notifications not rejected * by the gateway by the time the shutdown process completes will have been accepted by the gateway (though no * guarantees are made that they will ever be delivered to the destination device).</p> * * <h2>Error handling</h2> * * <p>Callers may register listeners to handle notifications permanently rejected by the APNs gateway and to handle * failed attempts to connect to the gateway.</p> * * <p>When a notification is rejected by the APNs gateway, the rejection should be considered permanent and callers * should not try to resend the notification. When a connection fails, the push manager will report the failure to * registered listeners, but will continue trying to connect until shut down. Callers should shut down the push manager * in the event of a failure unlikely to be resolved by retrying the connection (the most common case is an * {@link SSLHandshakeException}, which usually indicates a certificate problem of some kind).</p> * * @author <a href="mailto:[email protected]">Jon Chambers</a> * * @see PushManager#getQueue() * @see PushManagerFactory */ public class PushManager<T extends ApnsPushNotification> implements ApnsConnectionListener<T> { private final BlockingQueue<T> queue; private final LinkedBlockingQueue<T> retryQueue; private final ApnsEnvironment environment; private final SSLContext sslContext; private final int concurrentConnectionCount; private final HashSet<ApnsConnection<T>> activeConnections; private final ApnsConnectionPool<T> writableConnectionPool; private final FeedbackServiceClient feedbackServiceClient; private final ArrayList<RejectedNotificationListener<? super T>> rejectedNotificationListeners; private final ArrayList<FailedConnectionListener<? super T>> failedConnectionListeners; private Thread dispatchThread; private boolean dispatchThreadShouldContinue = true; private final NioEventLoopGroup eventLoopGroup; private final boolean shouldShutDownEventLoopGroup; private final ExecutorService listenerExecutorService; private final boolean shouldShutDownListenerExecutorService; private boolean shutDownStarted = false; private boolean shutDownFinished = false; private static final Logger log = LoggerFactory.getLogger(PushManager.class); private static class DispatchThreadExceptionHandler<T extends ApnsPushNotification> implements UncaughtExceptionHandler { private final Logger log = LoggerFactory.getLogger(DispatchThreadExceptionHandler.class); final PushManager<T> manager; public DispatchThreadExceptionHandler(final PushManager<T> manager) { this.manager = manager; } public void uncaughtException(final Thread t, final Throwable e) { log.error("Dispatch thread died unexpectedly. Please file a bug with the exception details.", e); if (this.manager.isStarted()) { this.manager.createAndStartDispatchThread(); } } } /** * <p>Constructs a new {@code PushManager} that operates in the given environment with the given SSL context and the * given number of parallel connections to APNs. See * <a href="http://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW6"> * Best Practices for Managing Connections</a> for additional information.</p> * * <p>This constructor may take an event loop group as an argument; if an event loop group is provided, the caller * is responsible for managing the lifecycle of the group and <strong>must</strong> shut it down after shutting down * this {@code PushManager}.</p> * * @param environment the environment in which this {@code PushManager} operates * @param sslContext the SSL context in which APNs connections controlled by this {@code PushManager} will operate * @param concurrentConnectionCount the number of parallel connections to maintain * @param eventLoopGroup the event loop group this push manager should use for its connections to the APNs gateway and * feedback service; if {@code null}, a new event loop group will be created and will be shut down automatically * when the push manager is shut down. If not {@code null}, the caller <strong>must</strong> shut down the event * loop group after shutting down the push manager. * @param listenerExecutorService the executor service this push manager should use to dispatch notifications to * registered listeners. If {@code null}, a new single-thread executor service will be created and will be shut * down automatically with the push manager is shut down. If not {@code null}, the caller <strong>must</strong> * shut down the executor service after shutting down the push manager. * @param queue the queue to be used to pass new notifications to this push manager */ protected PushManager(final ApnsEnvironment environment, final SSLContext sslContext, final int concurrentConnectionCount, final NioEventLoopGroup eventLoopGroup, final ExecutorService listenerExecutorService, final BlockingQueue<T> queue) { this.queue = queue != null ? queue : new LinkedBlockingQueue<T>(); this.retryQueue = new LinkedBlockingQueue<T>(); this.rejectedNotificationListeners = new ArrayList<RejectedNotificationListener<? super T>>(); this.failedConnectionListeners = new ArrayList<FailedConnectionListener<? super T>>(); this.environment = environment; this.sslContext = sslContext; this.concurrentConnectionCount = concurrentConnectionCount; this.writableConnectionPool = new ApnsConnectionPool<T>(); this.activeConnections = new HashSet<ApnsConnection<T>>(); if (eventLoopGroup != null) { this.eventLoopGroup = eventLoopGroup; this.shouldShutDownEventLoopGroup = false; } else { // Never use more threads than concurrent connections (Netty binds a channel to a single thread, so the // excess threads would always go unused) final int threadCount = Math.min(concurrentConnectionCount, Runtime.getRuntime().availableProcessors() * 2); this.eventLoopGroup = new NioEventLoopGroup(threadCount); this.shouldShutDownEventLoopGroup = true; } if (listenerExecutorService != null) { this.listenerExecutorService = listenerExecutorService; this.shouldShutDownListenerExecutorService = false; } else { this.listenerExecutorService = Executors.newSingleThreadExecutor(); this.shouldShutDownListenerExecutorService = true; } this.feedbackServiceClient = new FeedbackServiceClient(this.environment, this.sslContext, this.eventLoopGroup); } /** * <p>Opens all connections to APNs and prepares to send push notifications. Note that enqueued push notifications * will <strong>not</strong> be sent until this method is called.</p> * * <p>Push managers may only be started once and cannot be reused after being shut down.</p> * * @throws IllegalStateException if the push manager has already been started or has already been shut down */ public synchronized void start() { if (this.isStarted()) { throw new IllegalStateException("Push manager has already been started."); } if (this.isShutDown()) { throw new IllegalStateException("Push manager has already been shut down and may not be restarted."); } log.info("Push manager starting."); for (int i = 0; i < this.concurrentConnectionCount; i++) { this.startNewConnection(); } this.createAndStartDispatchThread(); } private void createAndStartDispatchThread() { this.dispatchThread = createDispatchThread(); this.dispatchThread.setUncaughtExceptionHandler(new DispatchThreadExceptionHandler<T>(this)); this.dispatchThread.start(); } protected Thread createDispatchThread() { return new Thread(new Runnable() { public void run() { while (dispatchThreadShouldContinue) { try { final ApnsConnection<T> connection = writableConnectionPool.getNextConnection(); final T notificationToRetry = retryQueue.poll(); if (notificationToRetry != null) { connection.sendNotification(notificationToRetry); } else { if (shutDownStarted) { // We're trying to drain the retry queue before shutting down, and the retry queue is // now empty. Close the connection and see if it stays that way. connection.shutdownGracefully(); writableConnectionPool.removeConnection(connection); } else { // We'll park here either until a new notification is available from the outside or until // something shows up in the retry queue, at which point we'll be interrupted. connection.sendNotification(queue.take()); } } } catch (InterruptedException e) { continue; } } } }); } /** * Indicates whether this push manager has been started and not yet shut down. * * @return {@code true} if this push manager has been started and has not yet been shut down or {@code false} * otherwise */ public boolean isStarted() { if (this.isShutDown()) { return false; } else { return this.dispatchThread != null; } } /** * Indicates whether this push manager has been shut down (or is in the process of shutting down). Once a push * manager has been shut down, it may not be restarted. * * @return {@code true} if this push manager has been shut down or is in the process of shutting down or * {@code false} otherwise */ public boolean isShutDown() { return this.shutDownStarted; } /** * <p>Disconnects from APNs and gracefully shuts down all connections. This method will block until the internal * retry queue has been emptied and until all connections have shut down gracefully. Calling this method is * identical to calling {@link PushManager#shutdown(long)} with a timeout of {@code 0}.</p> * * <p>By the time this method return normally, all notifications removed from the public queue are guaranteed to * have been delivered to the APNs gateway and either accepted or rejected (i.e. the state of all sent * notifications is known).</p> * * @throws InterruptedException if interrupted while waiting for connections to close cleanly * @throws IllegalStateException if this method is called before the push manager has been started */ public synchronized void shutdown() throws InterruptedException { this.shutdown(0); } /** * <p>Disconnects from the APNs and gracefully shuts down all connections. This method will wait until either the * given timeout expires or until the internal retry queue has been emptied and connections have closed gracefully. * If the timeout expires, the push manager will close all connections immediately.</p> * * <p>This method returns the notifications that are still in the internal retry queue by the time this push manager * has shut down. If this method is called with a non-zero timeout, a collection of notifications still in the push * manager's internal retry queue will be returned. The returned collection will <em>not</em> contain notifications * in the public queue (since callers can work with the public queue directly). When shutting down with a non-zero * timeout, no guarantees are made that notifications that were sent (i.e. are in neither the public queue nor the * retry queue) were actually received or processed by the APNs gateway.</p> * * <p>If called with a timeout of {@code 0}, the returned collection of unsent notifications will be empty. By the * time this method exits, all notifications taken from the public queue are guaranteed to have been delivered to * the APNs gateway and either accepted or rejected (i.e. the state of all sent notifications is known).</p> * * @param timeout the timeout, in milliseconds, after which client threads should be shut down as quickly as * possible; if {@code 0}, this method will wait indefinitely for the retry queue to empty and connections to close * * @return a list of notifications not sent before the {@code PushManager} shut down * * @throws InterruptedException if interrupted while waiting for connections to close cleanly * @throws IllegalStateException if this method is called before the push manager has been started */ public synchronized List<T> shutdown(long timeout) throws InterruptedException { if (this.isShutDown()) { log.warn("Push manager has already been shut down; shutting down multiple times is harmless, but may " + "indicate a problem elsewhere."); } else { log.info("Push manager shutting down."); } if (this.shutDownFinished) { // We COULD throw an IllegalStateException here, but it seems unnecessary when we could just silently return // the same result without harm. return new ArrayList<T>(this.retryQueue); } if (!this.isStarted()) { throw new IllegalStateException("Push manager has not yet been started and cannot be shut down."); } this.shutDownStarted = true; this.dispatchThread.interrupt(); final Date deadline = timeout > 0 ? new Date(System.currentTimeMillis() + timeout) : null; // The dispatch thread will close connections when the retry queue is empty this.waitForAllConnectionsToFinish(deadline); this.dispatchThreadShouldContinue = false; this.dispatchThread.interrupt(); this.dispatchThread.join(); if (deadline == null) { assert this.retryQueue.isEmpty(); assert this.activeConnections.isEmpty(); } synchronized (this.activeConnections) { for (final ApnsConnection<T> connection : this.activeConnections) { connection.shutdownImmediately(); } } synchronized (this.rejectedNotificationListeners) { this.rejectedNotificationListeners.clear(); } synchronized (this.failedConnectionListeners) { this.failedConnectionListeners.clear(); } if (this.shouldShutDownListenerExecutorService) { this.listenerExecutorService.shutdown(); } if (this.shouldShutDownEventLoopGroup) { this.eventLoopGroup.shutdownGracefully().await(); } this.shutDownFinished = true; return new ArrayList<T>(this.retryQueue); } /** * <p>Registers a listener for notifications rejected by APNs for specific reasons.</p> * * @param listener the listener to register * * @throws IllegalStateException if this push manager has already been shut down * * @see PushManager#unregisterRejectedNotificationListener(RejectedNotificationListener) */ public void registerRejectedNotificationListener(final RejectedNotificationListener<? super T> listener) { if (this.isShutDown()) { throw new IllegalStateException("Rejected notification listeners may not be registered after a push manager has been shut down."); } synchronized (this.rejectedNotificationListeners) { this.rejectedNotificationListeners.add(listener); } } /** * <p>Un-registers a rejected notification listener.</p> * * @param listener the listener to un-register * * @return {@code true} if the given listener was registered with this push manager and removed or {@code false} if * the listener was not already registered with this push manager */ public boolean unregisterRejectedNotificationListener(final RejectedNotificationListener<? super T> listener) { synchronized (this.rejectedNotificationListeners) { return this.rejectedNotificationListeners.remove(listener); } } /** * <p>Registers a listener for failed attempts to connect to the APNs gateway.</p> * * @param listener the listener to register * * @throws IllegalStateException if this push manager has already been shut down * * @see PushManager#unregisterFailedConnectionListener(FailedConnectionListener) */ public void registerFailedConnectionListener(final FailedConnectionListener<? super T> listener) { if (this.isShutDown()) { throw new IllegalStateException("Failed connection listeners may not be registered after a push manager has been shut down."); } synchronized (this.failedConnectionListeners) { this.failedConnectionListeners.add(listener); } } /** * <p>Un-registers a connection failure listener.</p> * * @param listener the listener to un-register * * @return {@code true} if the given listener was registered with this push manager and removed or {@code false} if * the listener was not already registered with this push manager */ public boolean unregisterFailedConnectionListener(final FailedConnectionListener<? super T> listener) { synchronized (this.failedConnectionListeners) { return this.failedConnectionListeners.remove(listener); } } /** * <p>Returns the queue of messages to be sent to the APNs gateway. Callers should add notifications to this queue * directly to send notifications. Notifications will be removed from this queue by Pushy when a send attempt is * started, but are not guaranteed to have reached the APNs gateway until the push manager has been shut down * without a timeout (see {@link PushManager#shutdown(long)}). Successful delivery is not acknowledged by the APNs * gateway. Notifications rejected by APNs for specific reasons will be passed to registered * {@link RejectedNotificationListener}s, and notifications that could not be sent due to temporary I/O problems * will be scheduled for re-transmission in a separate, internal queue.</p> * * <p>Notifications in this queue will only be consumed when the {@code PushManager} is running, has active * connections, and the internal &quot;retry queue&quot; is empty.</p> * * @return the queue of new notifications to send to the APNs gateway * * @see PushManager#registerRejectedNotificationListener(RejectedNotificationListener) */ public BlockingQueue<T> getQueue() { return this.queue; } protected BlockingQueue<T> getRetryQueue() { return this.retryQueue; } /** * <p>Queries the APNs feedback service for expired tokens using a reasonable default timeout. Be warned that this * is a <strong>destructive operation</strong>. According to Apple's documentation:</p> * * <blockquote>The feedback service’s list is cleared after you read it. Each time you connect to the feedback * service, the information it returns lists only the failures that have happened since you last * connected.</blockquote> * * <p>The push manager must be started before calling this method.</p> * * @return a list of tokens that have expired since the last connection to the feedback service * * @throws InterruptedException if interrupted while waiting for a response from the feedback service * @throws FeedbackConnectionException if the attempt to connect to the feedback service failed for any reason */ public List<ExpiredToken> getExpiredTokens() throws InterruptedException, FeedbackConnectionException { return this.getExpiredTokens(1, TimeUnit.SECONDS); } /** * <p>Queries the APNs feedback service for expired tokens using the given timeout. Be warned that this is a * <strong>destructive operation</strong>. According to Apple's documentation:</p> * * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback * service, the information it returns lists only the failures that have happened since you last * connected.</blockquote> * * <p>The push manager must be started before calling this method.</p> * * @param timeout the time after the last received data after which the connection to the feedback service should * be closed * @param timeoutUnit the unit of time in which the given {@code timeout} is measured * * @return a list of tokens that have expired since the last connection to the feedback service * * @throws InterruptedException if interrupted while waiting for a response from the feedback service * @throws FeedbackConnectionException if the attempt to connect to the feedback service failed for any reason * @throws IllegalStateException if this push manager has not been started yet or has already been shut down */ public List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException, FeedbackConnectionException { if (!this.isStarted()) { throw new IllegalStateException("Push manager has not been started yet."); } if (this.isShutDown()) { throw new IllegalStateException("Push manager has already been shut down."); } return this.feedbackServiceClient.getExpiredTokens(timeout, timeoutUnit); } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleConnectionSuccess(com.relayrides.pushy.apns.ApnsConnection) */ public void handleConnectionSuccess(final ApnsConnection<T> connection) { log.trace("Connection succeeded: {}", connection); if (this.dispatchThreadShouldContinue) { this.writableConnectionPool.addConnection(connection); } else { // There's no dispatch thread to use this connection, so shut it down immediately connection.shutdownImmediately(); } } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleConnectionFailure(com.relayrides.pushy.apns.ApnsConnection, java.lang.Throwable) */ public void handleConnectionFailure(final ApnsConnection<T> connection, final Throwable cause) { log.trace("Connection failed: {}", connection, cause); this.removeActiveConnection(connection); // We tried to open a connection, but failed. As long as we're not shut down, try to open a new one. final PushManager<T> pushManager = this; synchronized (this.failedConnectionListeners) { for (final FailedConnectionListener<? super T> listener : this.failedConnectionListeners) { // Handle connection failures in a separate thread in case a handler takes a long time to run this.listenerExecutorService.submit(new Runnable() { public void run() { listener.handleFailedConnection(pushManager, cause); } }); } } // As long as we're not shut down, keep trying to open a replacement connection. if (this.shouldReplaceClosedConnection()) { this.startNewConnection(); } } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleConnectionWritabilityChange(com.relayrides.pushy.apns.ApnsConnection, boolean) */ public void handleConnectionWritabilityChange(final ApnsConnection<T> connection, final boolean writable) { log.trace("Writability for {} changed to {}", connection, writable); if (writable) { this.writableConnectionPool.addConnection(connection); } else { this.writableConnectionPool.removeConnection(connection); this.dispatchThread.interrupt(); } } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleConnectionClosure(com.relayrides.pushy.apns.ApnsConnection) */ public void handleConnectionClosure(final ApnsConnection<T> connection) { log.trace("Connection closed: {}", connection); this.writableConnectionPool.removeConnection(connection); this.dispatchThread.interrupt(); final PushManager<T> pushManager = this; this.listenerExecutorService.execute(new Runnable() { public void run() { try { connection.waitForPendingWritesToFinish(); if (pushManager.shouldReplaceClosedConnection()) { pushManager.startNewConnection(); } removeActiveConnection(connection); } catch (InterruptedException e) { log.warn("Interrupted while waiting for closed connection's pending operations to finish."); } } }); } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleWriteFailure(com.relayrides.pushy.apns.ApnsConnection, com.relayrides.pushy.apns.ApnsPushNotification, java.lang.Throwable) */ public void handleWriteFailure(ApnsConnection<T> connection, T notification, Throwable cause) { this.retryQueue.add(notification); this.dispatchThread.interrupt(); } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleRejectedNotification(com.relayrides.pushy.apns.ApnsConnection, com.relayrides.pushy.apns.ApnsPushNotification, com.relayrides.pushy.apns.RejectedNotificationReason) */ public void handleRejectedNotification(final ApnsConnection<T> connection, final T rejectedNotification, final RejectedNotificationReason reason) { log.trace("{} rejected {}: {}", connection, rejectedNotification, reason); final PushManager<T> pushManager = this; synchronized (this.rejectedNotificationListeners) { for (final RejectedNotificationListener<? super T> listener : this.rejectedNotificationListeners) { // Handle the notifications in a separate thread in case a listener takes a long time to run this.listenerExecutorService.execute(new Runnable() { public void run() { listener.handleRejectedNotification(pushManager, rejectedNotification, reason); } }); } } } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleUnprocessedNotifications(com.relayrides.pushy.apns.ApnsConnection, java.util.Collection) */ public void handleUnprocessedNotifications(ApnsConnection<T> connection, Collection<T> unprocessedNotifications) { log.trace("{} returned {} unprocessed notifications", connection, unprocessedNotifications.size()); this.retryQueue.addAll(unprocessedNotifications); this.dispatchThread.interrupt(); } private void startNewConnection() { synchronized (this.activeConnections) { final ApnsConnection<T> connection = new ApnsConnection<T>(this.environment, this.sslContext, this.eventLoopGroup, this); connection.connect(); this.activeConnections.add(connection); } } private void removeActiveConnection(final ApnsConnection<T> connection) { synchronized (this.activeConnections) { final boolean removedConnection = this.activeConnections.remove(connection); assert removedConnection; if (this.activeConnections.isEmpty()) { this.activeConnections.notifyAll(); } } } private void waitForAllConnectionsToFinish(final Date deadline) throws InterruptedException { synchronized (this.activeConnections) { while (!this.activeConnections.isEmpty() && !PushManager.hasDeadlineExpired(deadline)) { if (deadline != null) { this.activeConnections.wait(PushManager.getMillisToWaitForDeadline(deadline)); } else { this.activeConnections.wait(); } } } } private static long getMillisToWaitForDeadline(final Date deadline) { return Math.max(deadline.getTime() - System.currentTimeMillis(), 1); } private static boolean hasDeadlineExpired(final Date deadline) { if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } } private boolean shouldReplaceClosedConnection() { if (this.shutDownStarted) { if (this.dispatchThreadShouldContinue) { // We're shutting down, but the dispatch thread is still working to drain the retry queue. Replace // closed connections until the retry queue is empty. return !this.retryQueue.isEmpty(); } else { // If this dispatch thread should stop, there's nothing to make use of the connections return false; } } else { // We always want to replace closed connections if we're running normally return true; } } }
src/main/java/com/relayrides/pushy/apns/PushManager.java
/* Copyright (c) 2013 RelayRides * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.relayrides.pushy.apns; import io.netty.channel.nio.NioEventLoopGroup; import java.lang.Thread.UncaughtExceptionHandler; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Push managers manage connections to the APNs gateway and send notifications from their queue. Push managers * should always be created using the {@link PushManagerFactory} class. Push managers are the main public-facing point * of interaction with Pushy.</p> * * <h2>Queues</h2> * * <p>A push manager has two queues: the public queue through which callers add notifications to be sent, and a private, * internal &quot;retry queue.&quot; Callers send push notifications by adding them to the push manager's public queue * (see {@link PushManager#getQueue()}). The push manager will take and notifications from the public queue as quickly * as it is able to do so, and will never put notifications back in the public queue. Callers are free to manipulate the * public queue however they see fit.</p> * * <p>If, for any reason other than a permanent rejection, a notification could not be delivered, it will be returned to * the push manager's internal retry queue. The push manager will always try to drain its retry queue before taking new * notifications from the public queue.</p> * * <h2>Shutting down</h2> * * <p>A push manager can be shut down with or without a timeout, though shutting down without a timeout provides * stronger guarantees with regard to the state of sent notifications. Regardless of whether a timeout is specified, * push managers will stop taking notifications from the public queue as soon the shutdown process has started. Push * managers shut down by asking all of their connections to shut down gracefully by sending a known-bad notification to * the APNs gateway. The push manager will restore closed connections and keep trying to send notifications from its * internal retry queue until either the queue is empty or the timeout expires. If the timeout expires while there are * still open connections, all remaining connections are closed immediately.</p> * * <p>When shutting down without a timeout, it is guaranteed that the push manager's internal retry queue will be empty * and all sent notifications will have reached and been processed by the APNs gateway. Any notifications not rejected * by the gateway by the time the shutdown process completes will have been accepted by the gateway (though no * guarantees are made that they will ever be delivered to the destination device).</p> * * <h2>Error handling</h2> * * <p>Callers may register listeners to handle notifications permanently rejected by the APNs gateway and to handle * failed attempts to connect to the gateway.</p> * * <p>When a notification is rejected by the APNs gateway, the rejection should be considered permanent and callers * should not try to resend the notification. When a connection fails, the push manager will report the failure to * registered listeners, but will continue trying to connect until shut down. Callers should shut down the push manager * in the event of a failure unlikely to be resolved by retrying the connection (the most common case is an * {@link SSLHandshakeException}, which usually indicates a certificate problem of some kind).</p> * * @author <a href="mailto:[email protected]">Jon Chambers</a> * * @see PushManager#getQueue() * @see PushManagerFactory */ public class PushManager<T extends ApnsPushNotification> implements ApnsConnectionListener<T> { private final BlockingQueue<T> queue; private final LinkedBlockingQueue<T> retryQueue; private final ApnsEnvironment environment; private final SSLContext sslContext; private final int concurrentConnectionCount; private final HashSet<ApnsConnection<T>> activeConnections; private final ApnsConnectionPool<T> writableConnectionPool; private final FeedbackServiceClient feedbackServiceClient; private final ArrayList<RejectedNotificationListener<? super T>> rejectedNotificationListeners; private final ArrayList<FailedConnectionListener<? super T>> failedConnectionListeners; private Thread dispatchThread; private boolean dispatchThreadShouldContinue = true; private final NioEventLoopGroup eventLoopGroup; private final boolean shouldShutDownEventLoopGroup; private final ExecutorService listenerExecutorService; private final boolean shouldShutDownListenerExecutorService; private boolean shutDownStarted = false; private boolean shutDownFinished = false; private static final Logger log = LoggerFactory.getLogger(PushManager.class); private static class DispatchThreadExceptionHandler<T extends ApnsPushNotification> implements UncaughtExceptionHandler { private final Logger log = LoggerFactory.getLogger(DispatchThreadExceptionHandler.class); final PushManager<T> manager; public DispatchThreadExceptionHandler(final PushManager<T> manager) { this.manager = manager; } public void uncaughtException(final Thread t, final Throwable e) { log.error("Dispatch thread died unexpectedly. Please file a bug with the exception details.", e); if (this.manager.isStarted()) { this.manager.createAndStartDispatchThread(); } } } /** * <p>Constructs a new {@code PushManager} that operates in the given environment with the given SSL context and the * given number of parallel connections to APNs. See * <a href="http://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW6"> * Best Practices for Managing Connections</a> for additional information.</p> * * <p>This constructor may take an event loop group as an argument; if an event loop group is provided, the caller * is responsible for managing the lifecycle of the group and <strong>must</strong> shut it down after shutting down * this {@code PushManager}.</p> * * @param environment the environment in which this {@code PushManager} operates * @param sslContext the SSL context in which APNs connections controlled by this {@code PushManager} will operate * @param concurrentConnectionCount the number of parallel connections to maintain * @param eventLoopGroup the event loop group this push manager should use for its connections to the APNs gateway and * feedback service; if {@code null}, a new event loop group will be created and will be shut down automatically * when the push manager is shut down. If not {@code null}, the caller <strong>must</strong> shut down the event * loop group after shutting down the push manager. * @param listenerExecutorService the executor service this push manager should use to dispatch notifications to * registered listeners. If {@code null}, a new single-thread executor service will be created and will be shut * down automatically with the push manager is shut down. If not {@code null}, the caller <strong>must</strong> * shut down the executor service after shutting down the push manager. * @param queue the queue to be used to pass new notifications to this push manager */ protected PushManager(final ApnsEnvironment environment, final SSLContext sslContext, final int concurrentConnectionCount, final NioEventLoopGroup eventLoopGroup, final ExecutorService listenerExecutorService, final BlockingQueue<T> queue) { this.queue = queue != null ? queue : new LinkedBlockingQueue<T>(); this.retryQueue = new LinkedBlockingQueue<T>(); this.rejectedNotificationListeners = new ArrayList<RejectedNotificationListener<? super T>>(); this.failedConnectionListeners = new ArrayList<FailedConnectionListener<? super T>>(); this.environment = environment; this.sslContext = sslContext; this.concurrentConnectionCount = concurrentConnectionCount; this.writableConnectionPool = new ApnsConnectionPool<T>(); this.activeConnections = new HashSet<ApnsConnection<T>>(); if (eventLoopGroup != null) { this.eventLoopGroup = eventLoopGroup; this.shouldShutDownEventLoopGroup = false; } else { // Never use more threads than concurrent connections (Netty binds a channel to a single thread, so the // excess threads would always go unused) final int threadCounts = Math.min(concurrentConnectionCount, Runtime.getRuntime().availableProcessors() * 2); this.eventLoopGroup = new NioEventLoopGroup(threadCounts); this.shouldShutDownEventLoopGroup = true; } if (listenerExecutorService != null) { this.listenerExecutorService = listenerExecutorService; this.shouldShutDownListenerExecutorService = false; } else { this.listenerExecutorService = Executors.newSingleThreadExecutor(); this.shouldShutDownListenerExecutorService = true; } this.feedbackServiceClient = new FeedbackServiceClient(this.environment, this.sslContext, this.eventLoopGroup); } /** * <p>Opens all connections to APNs and prepares to send push notifications. Note that enqueued push notifications * will <strong>not</strong> be sent until this method is called.</p> * * <p>Push managers may only be started once and cannot be reused after being shut down.</p> * * @throws IllegalStateException if the push manager has already been started or has already been shut down */ public synchronized void start() { if (this.isStarted()) { throw new IllegalStateException("Push manager has already been started."); } if (this.isShutDown()) { throw new IllegalStateException("Push manager has already been shut down and may not be restarted."); } log.info("Push manager starting."); for (int i = 0; i < this.concurrentConnectionCount; i++) { this.startNewConnection(); } this.createAndStartDispatchThread(); } private void createAndStartDispatchThread() { this.dispatchThread = createDispatchThread(); this.dispatchThread.setUncaughtExceptionHandler(new DispatchThreadExceptionHandler<T>(this)); this.dispatchThread.start(); } protected Thread createDispatchThread() { return new Thread(new Runnable() { public void run() { while (dispatchThreadShouldContinue) { try { final ApnsConnection<T> connection = writableConnectionPool.getNextConnection(); final T notificationToRetry = retryQueue.poll(); if (notificationToRetry != null) { connection.sendNotification(notificationToRetry); } else { if (shutDownStarted) { // We're trying to drain the retry queue before shutting down, and the retry queue is // now empty. Close the connection and see if it stays that way. connection.shutdownGracefully(); writableConnectionPool.removeConnection(connection); } else { // We'll park here either until a new notification is available from the outside or until // something shows up in the retry queue, at which point we'll be interrupted. connection.sendNotification(queue.take()); } } } catch (InterruptedException e) { continue; } } } }); } /** * Indicates whether this push manager has been started and not yet shut down. * * @return {@code true} if this push manager has been started and has not yet been shut down or {@code false} * otherwise */ public boolean isStarted() { if (this.isShutDown()) { return false; } else { return this.dispatchThread != null; } } /** * Indicates whether this push manager has been shut down (or is in the process of shutting down). Once a push * manager has been shut down, it may not be restarted. * * @return {@code true} if this push manager has been shut down or is in the process of shutting down or * {@code false} otherwise */ public boolean isShutDown() { return this.shutDownStarted; } /** * <p>Disconnects from APNs and gracefully shuts down all connections. This method will block until the internal * retry queue has been emptied and until all connections have shut down gracefully. Calling this method is * identical to calling {@link PushManager#shutdown(long)} with a timeout of {@code 0}.</p> * * <p>By the time this method return normally, all notifications removed from the public queue are guaranteed to * have been delivered to the APNs gateway and either accepted or rejected (i.e. the state of all sent * notifications is known).</p> * * @throws InterruptedException if interrupted while waiting for connections to close cleanly * @throws IllegalStateException if this method is called before the push manager has been started */ public synchronized void shutdown() throws InterruptedException { this.shutdown(0); } /** * <p>Disconnects from the APNs and gracefully shuts down all connections. This method will wait until either the * given timeout expires or until the internal retry queue has been emptied and connections have closed gracefully. * If the timeout expires, the push manager will close all connections immediately.</p> * * <p>This method returns the notifications that are still in the internal retry queue by the time this push manager * has shut down. If this method is called with a non-zero timeout, a collection of notifications still in the push * manager's internal retry queue will be returned. The returned collection will <em>not</em> contain notifications * in the public queue (since callers can work with the public queue directly). When shutting down with a non-zero * timeout, no guarantees are made that notifications that were sent (i.e. are in neither the public queue nor the * retry queue) were actually received or processed by the APNs gateway.</p> * * <p>If called with a timeout of {@code 0}, the returned collection of unsent notifications will be empty. By the * time this method exits, all notifications taken from the public queue are guaranteed to have been delivered to * the APNs gateway and either accepted or rejected (i.e. the state of all sent notifications is known).</p> * * @param timeout the timeout, in milliseconds, after which client threads should be shut down as quickly as * possible; if {@code 0}, this method will wait indefinitely for the retry queue to empty and connections to close * * @return a list of notifications not sent before the {@code PushManager} shut down * * @throws InterruptedException if interrupted while waiting for connections to close cleanly * @throws IllegalStateException if this method is called before the push manager has been started */ public synchronized List<T> shutdown(long timeout) throws InterruptedException { if (this.isShutDown()) { log.warn("Push manager has already been shut down; shutting down multiple times is harmless, but may " + "indicate a problem elsewhere."); } else { log.info("Push manager shutting down."); } if (this.shutDownFinished) { // We COULD throw an IllegalStateException here, but it seems unnecessary when we could just silently return // the same result without harm. return new ArrayList<T>(this.retryQueue); } if (!this.isStarted()) { throw new IllegalStateException("Push manager has not yet been started and cannot be shut down."); } this.shutDownStarted = true; this.dispatchThread.interrupt(); final Date deadline = timeout > 0 ? new Date(System.currentTimeMillis() + timeout) : null; // The dispatch thread will close connections when the retry queue is empty this.waitForAllConnectionsToFinish(deadline); this.dispatchThreadShouldContinue = false; this.dispatchThread.interrupt(); this.dispatchThread.join(); if (deadline == null) { assert this.retryQueue.isEmpty(); assert this.activeConnections.isEmpty(); } synchronized (this.activeConnections) { for (final ApnsConnection<T> connection : this.activeConnections) { connection.shutdownImmediately(); } } synchronized (this.rejectedNotificationListeners) { this.rejectedNotificationListeners.clear(); } synchronized (this.failedConnectionListeners) { this.failedConnectionListeners.clear(); } if (this.shouldShutDownListenerExecutorService) { this.listenerExecutorService.shutdown(); } if (this.shouldShutDownEventLoopGroup) { this.eventLoopGroup.shutdownGracefully().await(); } this.shutDownFinished = true; return new ArrayList<T>(this.retryQueue); } /** * <p>Registers a listener for notifications rejected by APNs for specific reasons.</p> * * @param listener the listener to register * * @throws IllegalStateException if this push manager has already been shut down * * @see PushManager#unregisterRejectedNotificationListener(RejectedNotificationListener) */ public void registerRejectedNotificationListener(final RejectedNotificationListener<? super T> listener) { if (this.isShutDown()) { throw new IllegalStateException("Rejected notification listeners may not be registered after a push manager has been shut down."); } synchronized (this.rejectedNotificationListeners) { this.rejectedNotificationListeners.add(listener); } } /** * <p>Un-registers a rejected notification listener.</p> * * @param listener the listener to un-register * * @return {@code true} if the given listener was registered with this push manager and removed or {@code false} if * the listener was not already registered with this push manager */ public boolean unregisterRejectedNotificationListener(final RejectedNotificationListener<? super T> listener) { synchronized (this.rejectedNotificationListeners) { return this.rejectedNotificationListeners.remove(listener); } } /** * <p>Registers a listener for failed attempts to connect to the APNs gateway.</p> * * @param listener the listener to register * * @throws IllegalStateException if this push manager has already been shut down * * @see PushManager#unregisterFailedConnectionListener(FailedConnectionListener) */ public void registerFailedConnectionListener(final FailedConnectionListener<? super T> listener) { if (this.isShutDown()) { throw new IllegalStateException("Failed connection listeners may not be registered after a push manager has been shut down."); } synchronized (this.failedConnectionListeners) { this.failedConnectionListeners.add(listener); } } /** * <p>Un-registers a connection failure listener.</p> * * @param listener the listener to un-register * * @return {@code true} if the given listener was registered with this push manager and removed or {@code false} if * the listener was not already registered with this push manager */ public boolean unregisterFailedConnectionListener(final FailedConnectionListener<? super T> listener) { synchronized (this.failedConnectionListeners) { return this.failedConnectionListeners.remove(listener); } } /** * <p>Returns the queue of messages to be sent to the APNs gateway. Callers should add notifications to this queue * directly to send notifications. Notifications will be removed from this queue by Pushy when a send attempt is * started, but are not guaranteed to have reached the APNs gateway until the push manager has been shut down * without a timeout (see {@link PushManager#shutdown(long)}). Successful delivery is not acknowledged by the APNs * gateway. Notifications rejected by APNs for specific reasons will be passed to registered * {@link RejectedNotificationListener}s, and notifications that could not be sent due to temporary I/O problems * will be scheduled for re-transmission in a separate, internal queue.</p> * * <p>Notifications in this queue will only be consumed when the {@code PushManager} is running, has active * connections, and the internal &quot;retry queue&quot; is empty.</p> * * @return the queue of new notifications to send to the APNs gateway * * @see PushManager#registerRejectedNotificationListener(RejectedNotificationListener) */ public BlockingQueue<T> getQueue() { return this.queue; } protected BlockingQueue<T> getRetryQueue() { return this.retryQueue; } /** * <p>Queries the APNs feedback service for expired tokens using a reasonable default timeout. Be warned that this * is a <strong>destructive operation</strong>. According to Apple's documentation:</p> * * <blockquote>The feedback service’s list is cleared after you read it. Each time you connect to the feedback * service, the information it returns lists only the failures that have happened since you last * connected.</blockquote> * * <p>The push manager must be started before calling this method.</p> * * @return a list of tokens that have expired since the last connection to the feedback service * * @throws InterruptedException if interrupted while waiting for a response from the feedback service * @throws FeedbackConnectionException if the attempt to connect to the feedback service failed for any reason */ public List<ExpiredToken> getExpiredTokens() throws InterruptedException, FeedbackConnectionException { return this.getExpiredTokens(1, TimeUnit.SECONDS); } /** * <p>Queries the APNs feedback service for expired tokens using the given timeout. Be warned that this is a * <strong>destructive operation</strong>. According to Apple's documentation:</p> * * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback * service, the information it returns lists only the failures that have happened since you last * connected.</blockquote> * * <p>The push manager must be started before calling this method.</p> * * @param timeout the time after the last received data after which the connection to the feedback service should * be closed * @param timeoutUnit the unit of time in which the given {@code timeout} is measured * * @return a list of tokens that have expired since the last connection to the feedback service * * @throws InterruptedException if interrupted while waiting for a response from the feedback service * @throws FeedbackConnectionException if the attempt to connect to the feedback service failed for any reason * @throws IllegalStateException if this push manager has not been started yet or has already been shut down */ public List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException, FeedbackConnectionException { if (!this.isStarted()) { throw new IllegalStateException("Push manager has not been started yet."); } if (this.isShutDown()) { throw new IllegalStateException("Push manager has already been shut down."); } return this.feedbackServiceClient.getExpiredTokens(timeout, timeoutUnit); } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleConnectionSuccess(com.relayrides.pushy.apns.ApnsConnection) */ public void handleConnectionSuccess(final ApnsConnection<T> connection) { log.trace("Connection succeeded: {}", connection); if (this.dispatchThreadShouldContinue) { this.writableConnectionPool.addConnection(connection); } else { // There's no dispatch thread to use this connection, so shut it down immediately connection.shutdownImmediately(); } } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleConnectionFailure(com.relayrides.pushy.apns.ApnsConnection, java.lang.Throwable) */ public void handleConnectionFailure(final ApnsConnection<T> connection, final Throwable cause) { log.trace("Connection failed: {}", connection, cause); this.removeActiveConnection(connection); // We tried to open a connection, but failed. As long as we're not shut down, try to open a new one. final PushManager<T> pushManager = this; synchronized (this.failedConnectionListeners) { for (final FailedConnectionListener<? super T> listener : this.failedConnectionListeners) { // Handle connection failures in a separate thread in case a handler takes a long time to run this.listenerExecutorService.submit(new Runnable() { public void run() { listener.handleFailedConnection(pushManager, cause); } }); } } // As long as we're not shut down, keep trying to open a replacement connection. if (this.shouldReplaceClosedConnection()) { this.startNewConnection(); } } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleConnectionWritabilityChange(com.relayrides.pushy.apns.ApnsConnection, boolean) */ public void handleConnectionWritabilityChange(final ApnsConnection<T> connection, final boolean writable) { log.trace("Writability for {} changed to {}", connection, writable); if (writable) { this.writableConnectionPool.addConnection(connection); } else { this.writableConnectionPool.removeConnection(connection); this.dispatchThread.interrupt(); } } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleConnectionClosure(com.relayrides.pushy.apns.ApnsConnection) */ public void handleConnectionClosure(final ApnsConnection<T> connection) { log.trace("Connection closed: {}", connection); this.writableConnectionPool.removeConnection(connection); this.dispatchThread.interrupt(); final PushManager<T> pushManager = this; this.listenerExecutorService.execute(new Runnable() { public void run() { try { connection.waitForPendingWritesToFinish(); if (pushManager.shouldReplaceClosedConnection()) { pushManager.startNewConnection(); } removeActiveConnection(connection); } catch (InterruptedException e) { log.warn("Interrupted while waiting for closed connection's pending operations to finish."); } } }); } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleWriteFailure(com.relayrides.pushy.apns.ApnsConnection, com.relayrides.pushy.apns.ApnsPushNotification, java.lang.Throwable) */ public void handleWriteFailure(ApnsConnection<T> connection, T notification, Throwable cause) { this.retryQueue.add(notification); this.dispatchThread.interrupt(); } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleRejectedNotification(com.relayrides.pushy.apns.ApnsConnection, com.relayrides.pushy.apns.ApnsPushNotification, com.relayrides.pushy.apns.RejectedNotificationReason) */ public void handleRejectedNotification(final ApnsConnection<T> connection, final T rejectedNotification, final RejectedNotificationReason reason) { log.trace("{} rejected {}: {}", connection, rejectedNotification, reason); final PushManager<T> pushManager = this; synchronized (this.rejectedNotificationListeners) { for (final RejectedNotificationListener<? super T> listener : this.rejectedNotificationListeners) { // Handle the notifications in a separate thread in case a listener takes a long time to run this.listenerExecutorService.execute(new Runnable() { public void run() { listener.handleRejectedNotification(pushManager, rejectedNotification, reason); } }); } } } /* * (non-Javadoc) * @see com.relayrides.pushy.apns.ApnsConnectionListener#handleUnprocessedNotifications(com.relayrides.pushy.apns.ApnsConnection, java.util.Collection) */ public void handleUnprocessedNotifications(ApnsConnection<T> connection, Collection<T> unprocessedNotifications) { log.trace("{} returned {} unprocessed notifications", connection, unprocessedNotifications.size()); this.retryQueue.addAll(unprocessedNotifications); this.dispatchThread.interrupt(); } private void startNewConnection() { synchronized (this.activeConnections) { final ApnsConnection<T> connection = new ApnsConnection<T>(this.environment, this.sslContext, this.eventLoopGroup, this); connection.connect(); this.activeConnections.add(connection); } } private void removeActiveConnection(final ApnsConnection<T> connection) { synchronized (this.activeConnections) { final boolean removedConnection = this.activeConnections.remove(connection); assert removedConnection; if (this.activeConnections.isEmpty()) { this.activeConnections.notifyAll(); } } } private void waitForAllConnectionsToFinish(final Date deadline) throws InterruptedException { synchronized (this.activeConnections) { while (!this.activeConnections.isEmpty() && !PushManager.hasDeadlineExpired(deadline)) { if (deadline != null) { this.activeConnections.wait(PushManager.getMillisToWaitForDeadline(deadline)); } else { this.activeConnections.wait(); } } } } private static long getMillisToWaitForDeadline(final Date deadline) { return Math.max(deadline.getTime() - System.currentTimeMillis(), 1); } private static boolean hasDeadlineExpired(final Date deadline) { if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } } private boolean shouldReplaceClosedConnection() { if (this.shutDownStarted) { if (this.dispatchThreadShouldContinue) { // We're shutting down, but the dispatch thread is still working to drain the retry queue. Replace // closed connections until the retry queue is empty. return !this.retryQueue.isEmpty(); } else { // If this dispatch thread should stop, there's nothing to make use of the connections return false; } } else { // We always want to replace closed connections if we're running normally return true; } } }
Fixed a dumb typo.
src/main/java/com/relayrides/pushy/apns/PushManager.java
Fixed a dumb typo.
<ide><path>rc/main/java/com/relayrides/pushy/apns/PushManager.java <ide> } else { <ide> // Never use more threads than concurrent connections (Netty binds a channel to a single thread, so the <ide> // excess threads would always go unused) <del> final int threadCounts = Math.min(concurrentConnectionCount, Runtime.getRuntime().availableProcessors() * 2); <del> <del> this.eventLoopGroup = new NioEventLoopGroup(threadCounts); <add> final int threadCount = Math.min(concurrentConnectionCount, Runtime.getRuntime().availableProcessors() * 2); <add> <add> this.eventLoopGroup = new NioEventLoopGroup(threadCount); <ide> this.shouldShutDownEventLoopGroup = true; <ide> } <ide>
JavaScript
mit
2f144fdec26c8ab39ec7e54ed7f1dd6cb63f7928
0
BostonGlobe/slush-globeapp,BostonGlobe/slush-globeapp
import setPathCookie from './utils/setPathCookie' import removeMobileHover from './utils/removeMobileHover' import wireSocialButtons from './utils/wireSocialButtons' removeMobileHover() setPathCookie() // Add class to html if JS is loaded document.querySelector('html').classList.add('has-loaded') // Wire header social if present if (document.querySelectorAll('.g-header__share').length) { wireSocialButtons({ facebook: '.g-header__share-button--fb', twitter: '.g-header__share-button--tw', }) }
templates/src/js/app.js
import setPathCookie from './utils/setPathCookie' import removeMobileHover from './utils/removeMobileHover' import wireSocialButtons from './utils/wireSocialButtons' removeMobileHover() setPathCookie() // Add class to html if JS is loaded document.querySelector('html').classList.add('has-loaded') // Wire header social if present if (document.querySelectorAll('.g-header__share').length > 0) { wireSocialButtons({ facebook: '.g-header__share-button--fb', twitter: '.g-header__share-button--tw', }) }
Remove unnecessary syntax
templates/src/js/app.js
Remove unnecessary syntax
<ide><path>emplates/src/js/app.js <ide> document.querySelector('html').classList.add('has-loaded') <ide> <ide> // Wire header social if present <del>if (document.querySelectorAll('.g-header__share').length > 0) { <add>if (document.querySelectorAll('.g-header__share').length) { <ide> wireSocialButtons({ <ide> facebook: '.g-header__share-button--fb', <ide> twitter: '.g-header__share-button--tw',
Java
mit
c8a21724585ced0b4eb1ceaf02d748a37aafda6e
0
epam/NGB,epam/NGB,epam/NGB,epam/NGB
/* * MIT License * * Copyright (c) 2016-2021 EPAM Systems * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.epam.catgenome.manager; import com.epam.catgenome.component.MessageHelper; import com.epam.catgenome.constant.MessagesConstants; import com.epam.catgenome.controller.vo.ItemsByProject; import com.epam.catgenome.dao.index.FeatureIndexDao; import com.epam.catgenome.dao.index.indexer.BigVcfFeatureIndexBuilder; import com.epam.catgenome.dao.index.searcher.LuceneIndexSearcher; import com.epam.catgenome.entity.BaseEntity; import com.epam.catgenome.entity.BiologicalDataItemFormat; import com.epam.catgenome.entity.FeatureFile; import com.epam.catgenome.entity.bed.BedFile; import com.epam.catgenome.entity.gene.Gene; import com.epam.catgenome.entity.gene.GeneFile; import com.epam.catgenome.entity.gene.GeneFileType; import com.epam.catgenome.entity.gene.GeneFilterForm; import com.epam.catgenome.entity.gene.GeneFilterInfo; import com.epam.catgenome.entity.index.FeatureIndexEntry; import com.epam.catgenome.entity.index.FeatureType; import com.epam.catgenome.entity.index.GeneIndexEntry; import com.epam.catgenome.entity.index.Group; import com.epam.catgenome.entity.index.IndexSearchResult; import com.epam.catgenome.entity.index.VcfIndexEntry; import com.epam.catgenome.entity.project.Project; import com.epam.catgenome.entity.reference.Chromosome; import com.epam.catgenome.entity.reference.Reference; import com.epam.catgenome.entity.track.Track; import com.epam.catgenome.entity.vcf.VcfFile; import com.epam.catgenome.entity.vcf.VcfFilterForm; import com.epam.catgenome.entity.vcf.VcfFilterInfo; import com.epam.catgenome.exception.FeatureIndexException; import com.epam.catgenome.exception.GeneReadingException; import com.epam.catgenome.manager.bed.BedManager; import com.epam.catgenome.manager.bed.parser.NggbBedFeature; import com.epam.catgenome.manager.gene.GeneFileManager; import com.epam.catgenome.manager.gene.GeneUtils; import com.epam.catgenome.manager.gene.GffManager; import com.epam.catgenome.manager.gene.parser.GeneFeature; import com.epam.catgenome.manager.gene.reader.AbstractGeneReader; import com.epam.catgenome.manager.parallel.TaskExecutorService; import com.epam.catgenome.manager.project.ProjectManager; import com.epam.catgenome.manager.reference.BookmarkManager; import com.epam.catgenome.manager.reference.ReferenceGenomeManager; import com.epam.catgenome.manager.vcf.VcfFileManager; import com.epam.catgenome.manager.vcf.VcfManager; import com.epam.catgenome.util.Utils; import com.epam.catgenome.util.feature.reader.AbstractFeatureReader; import htsjdk.samtools.util.CloseableIterator; import htsjdk.tribble.Feature; import htsjdk.tribble.FeatureReader; import htsjdk.tribble.readers.LineIterator; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFHeader; import org.apache.commons.lang3.tuple.Pair; import org.apache.lucene.search.Sort; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.epam.catgenome.dao.index.searcher.AbstractIndexSearcher.getIndexSearcher; /** * Source: VcfIndexManager * Created: 28.04.16, 18:01 * Project: CATGenome Browser * Make: IntelliJ IDEA 14.1.4, JDK 1.8 * * <p> * A service class, that contains logic, connected with feature indexes. They are used for fast feature * search (variations, genes) by various criteria. * </p> */ @Service public class FeatureIndexManager { private static final Logger LOGGER = LoggerFactory.getLogger(FeatureIndexManager.class); private static final String VCF_FILE_IDS_FIELD = "vcfFileIds"; @Autowired private FileManager fileManager; @Autowired private ReferenceGenomeManager referenceGenomeManager; @Autowired private GffManager gffManager; @Autowired private VcfFileManager vcfFileManager; @Autowired private VcfManager vcfManager; @Autowired private ProjectManager projectManager; @Autowired private FeatureIndexDao featureIndexDao; @Autowired private GeneFileManager geneFileManager; @Autowired private BedManager bedManager; @Autowired private BookmarkManager bookmarkManager; @Autowired private TaskExecutorService taskExecutorService; @Value("#{catgenome['search.features.max.results'] ?: 100}") private Integer maxFeatureSearchResultsCount; @Value("#{catgenome['search.indexer.buffer.size'] ?: 256}") private int indexBufferSize; /** * Deletes features from specified feature files from project's index * * @param projectId a project to delete index entries * @param fileIds files, which entries to delete */ public void deleteFromIndexByFileId(final long projectId, List<Pair<FeatureType, Long>> fileIds) { featureIndexDao.deleteFromIndexByFileId(projectId, fileIds); } /** * Searches gene IDs, affected by variations in specified VCF files in a specified project * * @param gene a prefix of a gene ID to search * @param vcfFileIds a {@code List} of IDs of VCF files in project to search for gene IDs * @return a {@code Set} of gene IDs, that are affected by some variations in specified VCf files * @throws IOException */ public Set<String> searchGenesInVcfFilesInProject(long projectId, String gene, List<Long> vcfFileIds) throws IOException { Project project = projectManager.load(projectId); List<VcfFile> vcfFiles = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); List<VcfFile> selectedVcfFiles; if (CollectionUtils.isEmpty(vcfFileIds)) { selectedVcfFiles = vcfFiles; } else { selectedVcfFiles = vcfFiles.stream().filter(f -> vcfFileIds.contains(f.getId())) .collect(Collectors.toList()); } return featureIndexDao.searchGenesInVcfFiles(gene, selectedVcfFiles); } /** * Searches gene IDs, affected by variations in specified VCF files in a specified project * * @param gene a prefix of a gene ID to search * @param vcfFileIds a {@code List} of IDs of VCF files in project to search for gene IDs * @return a {@code Set} of gene IDs, that are affected by some variations in specified VCf fileFs * @throws IOException if something goes wrong with file system */ public Set<String> searchGenesInVcfFiles(String gene, List<Long> vcfFileIds) throws IOException { List<VcfFile> vcfFiles = vcfFileManager.loadVcfFiles(vcfFileIds); return featureIndexDao.searchGenesInVcfFiles(gene, vcfFiles); } /** * Filer chromosomes that contain variations, specified by filter * * @param filterForm a {@code VcfFilterForm} to filter out chromosomes * @param projectId a {@code Project}s ID to filter * @return a {@code List} of {@code Chromosome} that corresponds to specified filter * @throws IOException */ public List<Chromosome> filterChromosomes(VcfFilterForm filterForm, long projectId) throws IOException { Assert.isTrue(filterForm.getVcfFileIds() != null && !filterForm.getVcfFileIds().isEmpty(), MessageHelper .getMessage(MessagesConstants.ERROR_NULL_PARAM, VCF_FILE_IDS_FIELD)); Project project = projectManager.load(projectId); List<VcfFile> vcfFiles = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); List<Chromosome> chromosomes = referenceGenomeManager.loadChromosomes(vcfFiles.get(0).getReferenceId()); Map<Long, Chromosome> chromosomeMap = chromosomes.parallelStream() .collect(Collectors.toMap(BaseEntity::getId, chromosome -> chromosome)); List<Long> chromosomeIds = featureIndexDao.getChromosomeIdsWhereVariationsPresentFacet(vcfFiles, filterForm .computeQuery(FeatureType.VARIATION)); return chromosomeIds.stream().map(chromosomeMap::get).collect(Collectors.toList()); } /** * Filer chromosomes that contain variations, specified by filter * * @param filterForm a {@code VcfFilterForm} to filter out chromosomes * @return a {@code List} of {@code Chromosome} that corresponds to specified filter * @throws IOException */ public List<Chromosome> filterChromosomes(VcfFilterForm filterForm) throws IOException { Assert.isTrue(filterForm.getVcfFileIds() != null && !filterForm.getVcfFileIds().isEmpty(), MessageHelper .getMessage(MessagesConstants.ERROR_NULL_PARAM, VCF_FILE_IDS_FIELD)); List<VcfFile> vcfFiles = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds()); List<Chromosome> chromosomes = referenceGenomeManager.loadChromosomes(vcfFiles.get(0).getReferenceId()); Map<Long, Chromosome> chromosomeMap = chromosomes.parallelStream() .collect(Collectors.toMap(BaseEntity::getId, chromosome -> chromosome)); List<Long> chromosomeIds = featureIndexDao.getChromosomeIdsWhereVariationsPresentFacet(vcfFiles, filterForm .computeQuery(FeatureType.VARIATION)); return chromosomeIds.stream().map(chromosomeMap::get).collect(Collectors.toList()); } /** * Filter variations in a feature index for a project, specified by ID * * @param filterForm {@code VcfFilterForm}, setting filter options * @param projectId an ID of a project, which index to work with * @return a {@code List} of {@code VcfIndexEntry}, representing variations that satisfy the filter * @throws IOException */ public IndexSearchResult<VcfIndexEntry> filterVariations(VcfFilterForm filterForm, long projectId) throws IOException { Project project = projectManager.load(projectId); List<VcfFile> files = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); return getVcfSearchResult(filterForm, files); } public int getTotalPagesCount(VcfFilterForm filterForm) throws IOException { if (filterForm.getPageSize() == null) { throw new IllegalArgumentException("No page size is specified"); } List<VcfFile> files = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds()); int totalCount = featureIndexDao.getTotalVariationsCountFacet(files, filterForm.computeQuery( FeatureType.VARIATION)); return (int) Math.ceil(totalCount / filterForm.getPageSize().doubleValue()); } public int getTotalPagesCount(VcfFilterForm filterForm, long projectId) throws IOException { if (filterForm.getPageSize() == null) { throw new IllegalArgumentException("No page size is specified"); } Project project = projectManager.load(projectId); List<VcfFile> files = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); int totalCount = featureIndexDao.getTotalVariationsCountFacet(files, filterForm.computeQuery( FeatureType.VARIATION)); return (int) Math.ceil(totalCount / filterForm.getPageSize().doubleValue()); } /** * Groups variations from specified {@link List} of {@link VcfFile}s by specified field * @param filterForm {@code VcfFilterForm}, setting filter options * @param projectId a {@code Project}s ID to filter * @param groupByField a field to perform grouping * @return a {@link List} of {@link Pair}s, mapping field value to number of variations, having this value * @throws IOException if something goes wrong with the file system */ public List<Group> groupVariations(VcfFilterForm filterForm, long projectId, String groupByField) throws IOException { Project project = projectManager.load(projectId); List<VcfFile> files = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); return featureIndexDao.groupVariations(files, filterForm.computeQuery(FeatureType.VARIATION), groupByField); } /** * Groups variations from specified {@link List} of {@link VcfFile}s by specified field * @param filterForm {@code VcfFilterForm}, setting filter options * @param groupByField a field to perform grouping * @return a {@link List} of {@link Pair}s, mapping field value to number of variations, having this value * @throws IOException if something goes wrong with the file system */ public List<Group> groupVariations(VcfFilterForm filterForm, String groupByField) throws IOException { List<VcfFile> files = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds()); return featureIndexDao.groupVariations(files, filterForm.computeQuery(FeatureType.VARIATION), groupByField); } /** * Filter variations in a feature index for a project, specified by ID * * @param filterForm {@code VcfFilterForm}, setting filter options * @return a {@code List} of {@code VcfIndexEntry}, representing variations that satisfy the filter * @throws IOException */ public IndexSearchResult<VcfIndexEntry> filterVariations(VcfFilterForm filterForm) throws IOException { List<VcfFile> files = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds()); return getVcfSearchResult(filterForm, files); } private IndexSearchResult<VcfIndexEntry> getVcfSearchResult(final VcfFilterForm filterForm, final List<VcfFile> vcfFiles) throws IOException { if (filterForm.getPage() != null && filterForm.getPageSize() != null) { final LuceneIndexSearcher<VcfIndexEntry> indexSearcher = getIndexSearcher(filterForm, featureIndexDao, fileManager, taskExecutorService.getSearchExecutor()); final Sort sort = featureIndexDao.createVcfSorting(filterForm.getOrderBy(), vcfFiles); final IndexSearchResult<VcfIndexEntry> res = indexSearcher.getSearchResults(vcfFiles, filterForm.computeQuery(FeatureType.VARIATION), sort); res.setTotalPagesCount((int) Math.ceil(res.getTotalResultsCount() / filterForm.getPageSize().doubleValue())); return res; } else { final IndexSearchResult<VcfIndexEntry> res = featureIndexDao.searchFileIndexes(vcfFiles, filterForm.computeQuery(FeatureType.VARIATION), filterForm.getAdditionalFields(), null, null); res.setExceedsLimit(false); return res; } } private IndexSearchResult<GeneIndexEntry> getGeneSearchResult(final GeneFilterForm filterForm, final List<? extends FeatureFile> featureFiles) throws IOException { Assert.notNull(filterForm.getPageSize(), "Page size shall be specified"); final LuceneIndexSearcher<GeneIndexEntry> indexSearcher = getIndexSearcher(filterForm, featureIndexDao, fileManager, taskExecutorService.getSearchExecutor()); final Sort sort = Optional.ofNullable( featureIndexDao.createGeneSorting(filterForm.getOrderBy(), featureFiles)) .orElseGet(filterForm::defaultSort); final IndexSearchResult<GeneIndexEntry> res = indexSearcher.getSearchResults(featureFiles, filterForm.computeQuery(), sort); res.setTotalPagesCount((int) Math.ceil(res.getTotalResultsCount() / filterForm.getPageSize().doubleValue())); return res; } /** * Searches genes by it's ID in project's gene files. Minimum featureId prefix length == 2 * * @param featureId a feature ID prefix to search for * @return a {@code List} of {@code FeatureIndexEntry} * @throws IOException if something goes wrong with the file system */ public IndexSearchResult<FeatureIndexEntry> searchFeaturesInProject(final String featureId, final long projectId) throws IOException { if (featureId == null || featureId.length() < 2) { return new IndexSearchResult<>(Collections.emptyList(), false, 0); } final IndexSearchResult<FeatureIndexEntry> bookmarkSearchRes = bookmarkManager.searchBookmarks(featureId, maxFeatureSearchResultsCount); final Project project = projectManager.load(projectId); final Optional<Reference> opt = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.REFERENCE) .map(i -> (Reference) i.getBioDataItem()) .findFirst(); if (opt.isPresent() && opt.get().getGeneFile() != null) { final IndexSearchResult<FeatureIndexEntry> res = featureIndexDao.searchFeatures(featureId, geneFileManager.load(opt.get().getGeneFile().getId()), maxFeatureSearchResultsCount); bookmarkSearchRes.mergeFrom(res); return bookmarkSearchRes; } return bookmarkSearchRes; } public IndexSearchResult<GeneIndexEntry> searchGenesByReference(final GeneFilterForm filterForm, final long referenceId) throws IOException { final List<? extends FeatureFile> files = getGeneFilesForReference(referenceId, filterForm.getFileIds()); if (CollectionUtils.isEmpty(files)) { return new IndexSearchResult<>(); } return getGeneSearchResult(filterForm, files); } public GeneFilterInfo getAvailableGeneFieldsToSearch(final Long referenceId, final ItemsByProject fileIdsByProjectId) { final List<? extends FeatureFile> files = getGeneFilesForReference(referenceId, Optional.ofNullable(fileIdsByProjectId) .map(ItemsByProject::getFileIds).orElse(Collections.emptyList())); if (CollectionUtils.isEmpty(files)) { return GeneFilterInfo.builder().build(); } return featureIndexDao.getAvailableFieldsToSearch(files); } public Set<String> getAvailableFieldValues(final Long referenceId, final ItemsByProject fileIdsByProjectId, final String fieldName) { final List<? extends FeatureFile> files = getGeneFilesForReference(referenceId, Optional.ofNullable(fileIdsByProjectId) .map(ItemsByProject::getFileIds).orElse(Collections.emptyList())); if (CollectionUtils.isEmpty(files)) { return Collections.emptySet(); } return featureIndexDao.getAvailableFieldValues( files, fieldName); } private List<? extends FeatureFile> getGeneFilesForReference(final long referenceId, final List<Long> fileIds) { if (CollectionUtils.isEmpty(fileIds)) { return Stream.concat( Optional.ofNullable(getGeneFile(referenceId)) .map(Collections::singletonList).orElse(Collections.emptyList()).stream(), getFeatureFiles(referenceId).stream() ).filter(featureFile -> featureFile.getFormat() == BiologicalDataItemFormat.GENE) .distinct().collect(Collectors.toList()); } else { return geneFileManager.loadFiles(fileIds); } } public IndexSearchResult<FeatureIndexEntry> searchFeaturesByReference(final String featureId, final long referenceId) throws IOException { if (featureId == null || featureId.length() < 2) { return new IndexSearchResult<>(Collections.emptyList(), false, 0); } final IndexSearchResult<FeatureIndexEntry> res = featureIndexDao.searchFeatures( featureId, getFeatureFiles(referenceId), maxFeatureSearchResultsCount ); return mergeWithBookmarkSearch(res, featureId); } /** * Loads {@code VcfFilterInfo} object for a specified project. {@code VcfFilterInfo} contains information about * available fields to perform filtering and display results * * @param projectId a {@code Project}'s ID to load filter info * @return a {@code VcfFilterInfo} object * @throws IOException */ public VcfFilterInfo loadVcfFilterInfoForProject(long projectId) throws IOException { Project project = projectManager.load(projectId); List<Long> vcfIds = project.getItems().stream() .filter(item -> item.getBioDataItem() != null && item.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(item -> (item.getBioDataItem()).getId()) .collect(Collectors.toList()); return vcfManager.getFiltersInfo(vcfIds); } public void buildIndexForFile(FeatureFile featureFile) throws FeatureIndexException, IOException { if (!fileManager.indexForFeatureFileExists(featureFile)) { switch (featureFile.getFormat()) { case BED: bedManager.reindexBedFile(featureFile.getId()); break; case GENE: // use false here, because it's default parameter for reindexing in GeneController gffManager.reindexGeneFile(featureFile.getId(), false, false); break; case VCF: vcfManager.reindexVcfFile(featureFile.getId(), false); break; default: throw new IllegalArgumentException("Wrong FeatureType: " + featureFile.getFormat().name()); } } } /** * Fetch gene IDs of genes, affected by variation. The variation is specified by it's start and end indexes * * @param start a start index of the variation * @param end an end index of the variation * @param geneFiles a {@code List} of {@code GeneFile} to look for genes * @param chromosome a {@code Chromosome} * @return a {@code Set} of IDs of genes, affected by the variation * @throws GeneReadingException */ public Set<String> fetchGeneIds(int start, int end, List<GeneFile> geneFiles, Chromosome chromosome) throws GeneReadingException { Set<String> geneIds = new HashSet<>(); for (GeneFile geneFile : geneFiles) { List<Gene> genes = new ArrayList<>(); Track<Gene> track = new Track<>(); track.setStartIndex(start); track.setEndIndex(end); track.setId(geneFile.getId()); track.setChromosome(chromosome); track.setScaleFactor(AbstractGeneReader.LARGE_SCALE_FACTOR_LIMIT); if (end > start) { track.setStartIndex(start); track.setEndIndex(start); track = gffManager.loadGenes(track, geneFile, chromosome, false); genes.addAll(track.getBlocks()); track.setStartIndex(end); track.setEndIndex(end); track = gffManager.loadGenes(track, geneFile, chromosome, false); genes.addAll(track.getBlocks()); } else { track.setStartIndex(start); track.setEndIndex(end); track = gffManager.loadGenes(track, geneFile, chromosome, false); genes = track.getBlocks(); } geneIds.addAll(genes.stream() .filter(GeneUtils::isGene) .map(Gene::getGroupId) .collect(Collectors.toList())); } return geneIds; } /** * Writes index entries for specified {@link FeatureFile} to file system * @param featureFile a {@link FeatureFile}, for which index is written * @param entries a list of index entries * @throws IOException if error occurred while writing to file system */ public void writeLuceneIndexForFile(final FeatureFile featureFile, final List<? extends FeatureIndexEntry> entries, VcfFilterInfo vcfFilterInfo) throws IOException { featureIndexDao.writeLuceneIndexForFile(featureFile, entries, vcfFilterInfo); } public void makeIndexForBedReader(BedFile bedFile, AbstractFeatureReader<NggbBedFeature, LineIterator> reader, Map<String, Chromosome> chromosomeMap) throws IOException { CloseableIterator<NggbBedFeature> iterator = reader.iterator(); List<FeatureIndexEntry> allEntries = new ArrayList<>(); while (iterator.hasNext()) { NggbBedFeature next = iterator.next(); FeatureIndexEntry entry = new FeatureIndexEntry(); entry.setFeatureFileId(bedFile.getId()); entry.setChromosome(Utils.getFromChromosomeMap(chromosomeMap, next.getContig())); entry.setStartIndex(next.getStart()); entry.setEndIndex(next.getEnd()); entry.setFeatureId(next.getName()); entry.setFeatureName(next.getName()); entry.setUuid(UUID.randomUUID()); entry.setFeatureType(FeatureType.BED_FEATURE); allEntries.add(entry); } featureIndexDao.writeLuceneIndexForFile(bedFile, allEntries, null); } /** * Creates a VCF file feature index * @param vcfFile a VCF file to create index * @param reader a reader to file * @param geneFiles a {@code List} of {@code GeneFile} to look for genes * @param chromosomeMap a Map of {@link Chromosome}s to chromosome names * @param info VCF file's info data * @throws FeatureIndexException if an error occured while building an index */ public void makeIndexForVcfReader(VcfFile vcfFile, FeatureReader<VariantContext> reader, List<GeneFile> geneFiles, Map<String, Chromosome> chromosomeMap, VcfFilterInfo info) throws FeatureIndexException { VCFHeader vcfHeader = (VCFHeader) reader.getHeader(); try { CloseableIterator<VariantContext> iterator = reader.iterator(); String currentKey = null; VariantContext variantContext = null; BigVcfFeatureIndexBuilder indexer = new BigVcfFeatureIndexBuilder(info, vcfHeader, featureIndexDao, vcfFile, fileManager, geneFiles, indexBufferSize); while (iterator.hasNext()) { variantContext = iterator.next(); if (!variantContext.getContig().equals(currentKey)) { indexer.clear(); currentKey = variantContext.getContig(); LOGGER.info(MessageHelper .getMessage(MessagesConstants.INFO_FEATURE_INDEX_CHROMOSOME_WROTE, currentKey)); } indexer.add(variantContext, chromosomeMap); } // Put the last one if (variantContext != null && currentKey != null && Utils .chromosomeMapContains(chromosomeMap, currentKey)) { LOGGER.info(MessageHelper .getMessage(MessagesConstants.INFO_FEATURE_INDEX_CHROMOSOME_WROTE, currentKey)); indexer.clear(); } indexer.close(); } catch (IOException e) { throw new FeatureIndexException(vcfFile, e); } } /** * Creates Gene file's feature index * @param geneFile a {@link GeneFile} to create index * @param chromosomeMap a Map of {@link Chromosome}s to chromosome names * @param full * @throws IOException if an error occurred while writing index */ public void processGeneFile(GeneFile geneFile, final Map<String, Chromosome> chromosomeMap, boolean full) throws IOException { List<FeatureIndexEntry> allEntries = new ArrayList<>(); LOGGER.info("Writing feature index for file {}:{}", geneFile.getId(), geneFile.getName()); if (!full && fileManager.checkGeneFileExists(geneFile, GeneFileType.TRANSCRIPT)) { try (AbstractFeatureReader<GeneFeature, LineIterator> largeScaleReader = fileManager.makeGeneReader( geneFile, GeneFileType.LARGE_SCALE); AbstractFeatureReader<GeneFeature, LineIterator> transcriptReader = fileManager.makeGeneReader( geneFile, GeneFileType.TRANSCRIPT)) { CloseableIterator<GeneFeature> largeScaleIterator = largeScaleReader.iterator(); CloseableIterator<GeneFeature> transcriptIterator = transcriptReader.iterator(); addFeaturesFromIteratorToIndex(largeScaleIterator, chromosomeMap, geneFile, allEntries, false); addFeaturesFromIteratorToIndex(transcriptIterator, chromosomeMap, geneFile, allEntries, true); } } else { addFeaturesFromUsualGeneFileToIndex(geneFile, chromosomeMap, allEntries); } } private IndexSearchResult<FeatureIndexEntry> mergeWithBookmarkSearch(final IndexSearchResult<FeatureIndexEntry> res, final String featureId) { final IndexSearchResult<FeatureIndexEntry> bookmarkSearchRes = bookmarkManager.searchBookmarks(featureId, maxFeatureSearchResultsCount); bookmarkSearchRes.mergeFrom(res); return bookmarkSearchRes; } private List<FeatureFile> getFeatureFiles(final long referenceId) { final Reference reference = referenceGenomeManager.load(referenceId); final List<FeatureFile> annotationFiles = referenceGenomeManager.getReferenceAnnotationFiles(referenceId) .stream() .map(biologicalDataItem -> (FeatureFile) biologicalDataItem) .collect(Collectors.toList()); final GeneFile geneFile = reference.getGeneFile(); if (geneFile != null) { final Long geneFileId = geneFile.getId(); annotationFiles.add(geneFileManager.load(geneFileId)); } return annotationFiles; } private FeatureFile getGeneFile(final long referenceId) { return referenceGenomeManager.load(referenceId).getGeneFile(); } private void addFeaturesFromUsualGeneFileToIndex(GeneFile geneFile, Map<String, Chromosome> chromosomeMap, List<FeatureIndexEntry> allEntries) throws IOException { try (AbstractFeatureReader<GeneFeature, LineIterator> usualReader = fileManager.makeGeneReader( geneFile, GeneFileType.ORIGINAL)) { CloseableIterator<GeneFeature> iterator = usualReader.iterator(); GeneFeature feature = null; String currentKey = null; while (iterator.hasNext()) { feature = iterator.next(); currentKey = checkNextChromosome(feature, currentKey, chromosomeMap, allEntries, geneFile); if (GeneUtils.isGene(feature) || GeneUtils.isTranscript(feature) || GeneUtils.isExon(feature)) { addGeneFeatureToIndex(allEntries, feature, chromosomeMap); } } // Put the last one if (feature != null && currentKey != null && (chromosomeMap.containsKey(currentKey) || chromosomeMap.containsKey(Utils.changeChromosomeName(currentKey)))) { featureIndexDao.writeLuceneIndexForFile(geneFile, allEntries, null); allEntries.clear(); } } } private void addFeaturesFromIteratorToIndex(CloseableIterator<GeneFeature> iterator, Map<String, Chromosome> chromosomeMap, GeneFile geneFile, List<FeatureIndexEntry> allEntries, boolean transcriptIterator) throws IOException { GeneFeature feature = null; String currentKey = null; while (iterator.hasNext()) { feature = iterator.next(); currentKey = checkNextChromosome(feature, currentKey, chromosomeMap, allEntries, geneFile); if (transcriptIterator || GeneUtils.isGene(feature) || GeneUtils.isExon(feature)) { addGeneFeatureToIndex(allEntries, feature, chromosomeMap); } } // Put the last one if (feature != null && currentKey != null && (chromosomeMap.containsKey(currentKey) || chromosomeMap.containsKey(Utils.changeChromosomeName(currentKey)))) { featureIndexDao.writeLuceneIndexForFile(geneFile, allEntries, null); allEntries.clear(); } } private String checkNextChromosome(Feature feature, String currentChromosomeName, Map<String, Chromosome> chromosomeMap, List<FeatureIndexEntry> allEntries, GeneFile geneFile) throws IOException { if (!feature.getContig().equals(currentChromosomeName)) { if (currentChromosomeName != null && (chromosomeMap.containsKey(currentChromosomeName) || chromosomeMap.containsKey(Utils.changeChromosomeName(currentChromosomeName)))) { featureIndexDao.writeLuceneIndexForFile(geneFile, allEntries, null); LOGGER.info(MessageHelper.getMessage( MessagesConstants.INFO_FEATURE_INDEX_CHROMOSOME_WROTE, currentChromosomeName)); allEntries.clear(); } return feature.getContig(); } return currentChromosomeName; } public void addGeneFeatureToIndex(List<FeatureIndexEntry> allEntries, GeneFeature feature, Map<String, Chromosome> chromosomeMap) { if (chromosomeMap.containsKey(feature.getContig()) || chromosomeMap.containsKey(Utils.changeChromosomeName(feature.getContig()))) { GeneIndexEntry masterEntry = new GeneIndexEntry(); masterEntry.setFeatureId(feature.getFeatureId()); masterEntry.setUuid(UUID.randomUUID()); masterEntry.setChromosome(chromosomeMap.containsKey(feature.getContig()) ? chromosomeMap.get(feature.getContig()) : chromosomeMap.get(Utils.changeChromosomeName(feature.getContig()))); masterEntry.setStartIndex(feature.getStart()); masterEntry.setEndIndex(feature.getEnd()); masterEntry.setFeatureType(GeneUtils.fetchType(feature)); masterEntry.setFeature(feature.getFeature()); masterEntry.setSource(feature.getSource()); masterEntry.setScore(feature.getScore()); masterEntry.setFrame(feature.getFrame()); Optional.ofNullable(feature.getStrand()).ifPresent(strand -> masterEntry.setStrand(strand.toValue())); masterEntry.setAttributes(feature.getAttributes()); allEntries.add(masterEntry); String featureName = feature.getFeatureName(); masterEntry.setFeatureName(featureName); } } }
server/catgenome/src/main/java/com/epam/catgenome/manager/FeatureIndexManager.java
/* * MIT License * * Copyright (c) 2016-2021 EPAM Systems * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.epam.catgenome.manager; import com.epam.catgenome.component.MessageHelper; import com.epam.catgenome.constant.MessagesConstants; import com.epam.catgenome.controller.vo.ItemsByProject; import com.epam.catgenome.dao.index.FeatureIndexDao; import com.epam.catgenome.dao.index.indexer.BigVcfFeatureIndexBuilder; import com.epam.catgenome.dao.index.searcher.LuceneIndexSearcher; import com.epam.catgenome.entity.BaseEntity; import com.epam.catgenome.entity.BiologicalDataItemFormat; import com.epam.catgenome.entity.FeatureFile; import com.epam.catgenome.entity.bed.BedFile; import com.epam.catgenome.entity.gene.Gene; import com.epam.catgenome.entity.gene.GeneFile; import com.epam.catgenome.entity.gene.GeneFileType; import com.epam.catgenome.entity.gene.GeneFilterForm; import com.epam.catgenome.entity.gene.GeneFilterInfo; import com.epam.catgenome.entity.index.FeatureIndexEntry; import com.epam.catgenome.entity.index.FeatureType; import com.epam.catgenome.entity.index.GeneIndexEntry; import com.epam.catgenome.entity.index.Group; import com.epam.catgenome.entity.index.IndexSearchResult; import com.epam.catgenome.entity.index.VcfIndexEntry; import com.epam.catgenome.entity.project.Project; import com.epam.catgenome.entity.reference.Chromosome; import com.epam.catgenome.entity.reference.Reference; import com.epam.catgenome.entity.track.Track; import com.epam.catgenome.entity.vcf.VcfFile; import com.epam.catgenome.entity.vcf.VcfFilterForm; import com.epam.catgenome.entity.vcf.VcfFilterInfo; import com.epam.catgenome.exception.FeatureIndexException; import com.epam.catgenome.exception.GeneReadingException; import com.epam.catgenome.manager.bed.BedManager; import com.epam.catgenome.manager.bed.parser.NggbBedFeature; import com.epam.catgenome.manager.gene.GeneFileManager; import com.epam.catgenome.manager.gene.GeneUtils; import com.epam.catgenome.manager.gene.GffManager; import com.epam.catgenome.manager.gene.parser.GeneFeature; import com.epam.catgenome.manager.gene.reader.AbstractGeneReader; import com.epam.catgenome.manager.parallel.TaskExecutorService; import com.epam.catgenome.manager.project.ProjectManager; import com.epam.catgenome.manager.reference.BookmarkManager; import com.epam.catgenome.manager.reference.ReferenceGenomeManager; import com.epam.catgenome.manager.vcf.VcfFileManager; import com.epam.catgenome.manager.vcf.VcfManager; import com.epam.catgenome.util.Utils; import com.epam.catgenome.util.feature.reader.AbstractFeatureReader; import htsjdk.samtools.util.CloseableIterator; import htsjdk.tribble.Feature; import htsjdk.tribble.FeatureReader; import htsjdk.tribble.readers.LineIterator; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFHeader; import org.apache.commons.lang3.tuple.Pair; import org.apache.lucene.search.Sort; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.epam.catgenome.dao.index.searcher.AbstractIndexSearcher.getIndexSearcher; /** * Source: VcfIndexManager * Created: 28.04.16, 18:01 * Project: CATGenome Browser * Make: IntelliJ IDEA 14.1.4, JDK 1.8 * * <p> * A service class, that contains logic, connected with feature indexes. They are used for fast feature * search (variations, genes) by various criteria. * </p> */ @Service public class FeatureIndexManager { private static final Logger LOGGER = LoggerFactory.getLogger(FeatureIndexManager.class); private static final String VCF_FILE_IDS_FIELD = "vcfFileIds"; @Autowired private FileManager fileManager; @Autowired private ReferenceGenomeManager referenceGenomeManager; @Autowired private GffManager gffManager; @Autowired private VcfFileManager vcfFileManager; @Autowired private VcfManager vcfManager; @Autowired private ProjectManager projectManager; @Autowired private FeatureIndexDao featureIndexDao; @Autowired private GeneFileManager geneFileManager; @Autowired private BedManager bedManager; @Autowired private BookmarkManager bookmarkManager; @Autowired private TaskExecutorService taskExecutorService; @Value("#{catgenome['search.features.max.results'] ?: 100}") private Integer maxFeatureSearchResultsCount; @Value("#{catgenome['search.indexer.buffer.size'] ?: 256}") private int indexBufferSize; /** * Deletes features from specified feature files from project's index * * @param projectId a project to delete index entries * @param fileIds files, which entries to delete */ public void deleteFromIndexByFileId(final long projectId, List<Pair<FeatureType, Long>> fileIds) { featureIndexDao.deleteFromIndexByFileId(projectId, fileIds); } /** * Searches gene IDs, affected by variations in specified VCF files in a specified project * * @param gene a prefix of a gene ID to search * @param vcfFileIds a {@code List} of IDs of VCF files in project to search for gene IDs * @return a {@code Set} of gene IDs, that are affected by some variations in specified VCf files * @throws IOException */ public Set<String> searchGenesInVcfFilesInProject(long projectId, String gene, List<Long> vcfFileIds) throws IOException { Project project = projectManager.load(projectId); List<VcfFile> vcfFiles = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); List<VcfFile> selectedVcfFiles; if (CollectionUtils.isEmpty(vcfFileIds)) { selectedVcfFiles = vcfFiles; } else { selectedVcfFiles = vcfFiles.stream().filter(f -> vcfFileIds.contains(f.getId())) .collect(Collectors.toList()); } return featureIndexDao.searchGenesInVcfFiles(gene, selectedVcfFiles); } /** * Searches gene IDs, affected by variations in specified VCF files in a specified project * * @param gene a prefix of a gene ID to search * @param vcfFileIds a {@code List} of IDs of VCF files in project to search for gene IDs * @return a {@code Set} of gene IDs, that are affected by some variations in specified VCf fileFs * @throws IOException if something goes wrong with file system */ public Set<String> searchGenesInVcfFiles(String gene, List<Long> vcfFileIds) throws IOException { List<VcfFile> vcfFiles = vcfFileManager.loadVcfFiles(vcfFileIds); return featureIndexDao.searchGenesInVcfFiles(gene, vcfFiles); } /** * Filer chromosomes that contain variations, specified by filter * * @param filterForm a {@code VcfFilterForm} to filter out chromosomes * @param projectId a {@code Project}s ID to filter * @return a {@code List} of {@code Chromosome} that corresponds to specified filter * @throws IOException */ public List<Chromosome> filterChromosomes(VcfFilterForm filterForm, long projectId) throws IOException { Assert.isTrue(filterForm.getVcfFileIds() != null && !filterForm.getVcfFileIds().isEmpty(), MessageHelper .getMessage(MessagesConstants.ERROR_NULL_PARAM, VCF_FILE_IDS_FIELD)); Project project = projectManager.load(projectId); List<VcfFile> vcfFiles = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); List<Chromosome> chromosomes = referenceGenomeManager.loadChromosomes(vcfFiles.get(0).getReferenceId()); Map<Long, Chromosome> chromosomeMap = chromosomes.parallelStream() .collect(Collectors.toMap(BaseEntity::getId, chromosome -> chromosome)); List<Long> chromosomeIds = featureIndexDao.getChromosomeIdsWhereVariationsPresentFacet(vcfFiles, filterForm .computeQuery(FeatureType.VARIATION)); return chromosomeIds.stream().map(chromosomeMap::get).collect(Collectors.toList()); } /** * Filer chromosomes that contain variations, specified by filter * * @param filterForm a {@code VcfFilterForm} to filter out chromosomes * @return a {@code List} of {@code Chromosome} that corresponds to specified filter * @throws IOException */ public List<Chromosome> filterChromosomes(VcfFilterForm filterForm) throws IOException { Assert.isTrue(filterForm.getVcfFileIds() != null && !filterForm.getVcfFileIds().isEmpty(), MessageHelper .getMessage(MessagesConstants.ERROR_NULL_PARAM, VCF_FILE_IDS_FIELD)); List<VcfFile> vcfFiles = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds()); List<Chromosome> chromosomes = referenceGenomeManager.loadChromosomes(vcfFiles.get(0).getReferenceId()); Map<Long, Chromosome> chromosomeMap = chromosomes.parallelStream() .collect(Collectors.toMap(BaseEntity::getId, chromosome -> chromosome)); List<Long> chromosomeIds = featureIndexDao.getChromosomeIdsWhereVariationsPresentFacet(vcfFiles, filterForm .computeQuery(FeatureType.VARIATION)); return chromosomeIds.stream().map(chromosomeMap::get).collect(Collectors.toList()); } /** * Filter variations in a feature index for a project, specified by ID * * @param filterForm {@code VcfFilterForm}, setting filter options * @param projectId an ID of a project, which index to work with * @return a {@code List} of {@code VcfIndexEntry}, representing variations that satisfy the filter * @throws IOException */ public IndexSearchResult<VcfIndexEntry> filterVariations(VcfFilterForm filterForm, long projectId) throws IOException { Project project = projectManager.load(projectId); List<VcfFile> files = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); return getVcfSearchResult(filterForm, files); } public int getTotalPagesCount(VcfFilterForm filterForm) throws IOException { if (filterForm.getPageSize() == null) { throw new IllegalArgumentException("No page size is specified"); } List<VcfFile> files = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds()); int totalCount = featureIndexDao.getTotalVariationsCountFacet(files, filterForm.computeQuery( FeatureType.VARIATION)); return (int) Math.ceil(totalCount / filterForm.getPageSize().doubleValue()); } public int getTotalPagesCount(VcfFilterForm filterForm, long projectId) throws IOException { if (filterForm.getPageSize() == null) { throw new IllegalArgumentException("No page size is specified"); } Project project = projectManager.load(projectId); List<VcfFile> files = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); int totalCount = featureIndexDao.getTotalVariationsCountFacet(files, filterForm.computeQuery( FeatureType.VARIATION)); return (int) Math.ceil(totalCount / filterForm.getPageSize().doubleValue()); } /** * Groups variations from specified {@link List} of {@link VcfFile}s by specified field * @param filterForm {@code VcfFilterForm}, setting filter options * @param projectId a {@code Project}s ID to filter * @param groupByField a field to perform grouping * @return a {@link List} of {@link Pair}s, mapping field value to number of variations, having this value * @throws IOException if something goes wrong with the file system */ public List<Group> groupVariations(VcfFilterForm filterForm, long projectId, String groupByField) throws IOException { Project project = projectManager.load(projectId); List<VcfFile> files = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(i -> (VcfFile) i.getBioDataItem()) .collect(Collectors.toList()); return featureIndexDao.groupVariations(files, filterForm.computeQuery(FeatureType.VARIATION), groupByField); } /** * Groups variations from specified {@link List} of {@link VcfFile}s by specified field * @param filterForm {@code VcfFilterForm}, setting filter options * @param groupByField a field to perform grouping * @return a {@link List} of {@link Pair}s, mapping field value to number of variations, having this value * @throws IOException if something goes wrong with the file system */ public List<Group> groupVariations(VcfFilterForm filterForm, String groupByField) throws IOException { List<VcfFile> files = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds()); return featureIndexDao.groupVariations(files, filterForm.computeQuery(FeatureType.VARIATION), groupByField); } /** * Filter variations in a feature index for a project, specified by ID * * @param filterForm {@code VcfFilterForm}, setting filter options * @return a {@code List} of {@code VcfIndexEntry}, representing variations that satisfy the filter * @throws IOException */ public IndexSearchResult<VcfIndexEntry> filterVariations(VcfFilterForm filterForm) throws IOException { List<VcfFile> files = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds()); return getVcfSearchResult(filterForm, files); } private IndexSearchResult<VcfIndexEntry> getVcfSearchResult(final VcfFilterForm filterForm, final List<VcfFile> vcfFiles) throws IOException { if (filterForm.getPage() != null && filterForm.getPageSize() != null) { final LuceneIndexSearcher<VcfIndexEntry> indexSearcher = getIndexSearcher(filterForm, featureIndexDao, fileManager, taskExecutorService.getSearchExecutor()); final Sort sort = featureIndexDao.createVcfSorting(filterForm.getOrderBy(), vcfFiles); final IndexSearchResult<VcfIndexEntry> res = indexSearcher.getSearchResults(vcfFiles, filterForm.computeQuery(FeatureType.VARIATION), sort); res.setTotalPagesCount((int) Math.ceil(res.getTotalResultsCount() / filterForm.getPageSize().doubleValue())); return res; } else { final IndexSearchResult<VcfIndexEntry> res = featureIndexDao.searchFileIndexes(vcfFiles, filterForm.computeQuery(FeatureType.VARIATION), filterForm.getAdditionalFields(), null, null); res.setExceedsLimit(false); return res; } } private IndexSearchResult<GeneIndexEntry> getGeneSearchResult(final GeneFilterForm filterForm, final List<? extends FeatureFile> featureFiles) throws IOException { Assert.notNull(filterForm.getPageSize(), "Page size shall be specified"); final LuceneIndexSearcher<GeneIndexEntry> indexSearcher = getIndexSearcher(filterForm, featureIndexDao, fileManager, taskExecutorService.getSearchExecutor()); final Sort sort = Optional.ofNullable( featureIndexDao.createGeneSorting(filterForm.getOrderBy(), featureFiles)) .orElseGet(filterForm::defaultSort); final IndexSearchResult<GeneIndexEntry> res = indexSearcher.getSearchResults(featureFiles, filterForm.computeQuery(), sort); res.setTotalPagesCount((int) Math.ceil(res.getTotalResultsCount() / filterForm.getPageSize().doubleValue())); return res; } /** * Searches genes by it's ID in project's gene files. Minimum featureId prefix length == 2 * * @param featureId a feature ID prefix to search for * @return a {@code List} of {@code FeatureIndexEntry} * @throws IOException if something goes wrong with the file system */ public IndexSearchResult<FeatureIndexEntry> searchFeaturesInProject(final String featureId, final long projectId) throws IOException { if (featureId == null || featureId.length() < 2) { return new IndexSearchResult<>(Collections.emptyList(), false, 0); } final IndexSearchResult<FeatureIndexEntry> bookmarkSearchRes = bookmarkManager.searchBookmarks(featureId, maxFeatureSearchResultsCount); final Project project = projectManager.load(projectId); final Optional<Reference> opt = project.getItems().stream() .filter(i -> i.getBioDataItem().getFormat() == BiologicalDataItemFormat.REFERENCE) .map(i -> (Reference) i.getBioDataItem()) .findFirst(); if (opt.isPresent() && opt.get().getGeneFile() != null) { final IndexSearchResult<FeatureIndexEntry> res = featureIndexDao.searchFeatures(featureId, geneFileManager.load(opt.get().getGeneFile().getId()), maxFeatureSearchResultsCount); bookmarkSearchRes.mergeFrom(res); return bookmarkSearchRes; } return bookmarkSearchRes; } public IndexSearchResult<GeneIndexEntry> searchGenesByReference(final GeneFilterForm filterForm, final long referenceId) throws IOException { final List<? extends FeatureFile> files = getGeneFilesForReference(referenceId, filterForm.getFileIds()); if (CollectionUtils.isEmpty(files)) { return new IndexSearchResult<>(); } return getGeneSearchResult(filterForm, files); } public GeneFilterInfo getAvailableGeneFieldsToSearch(final Long referenceId, ItemsByProject fileIdsByProjectId) { final List<? extends FeatureFile> files = getGeneFilesForReference(referenceId, Optional.ofNullable(fileIdsByProjectId) .map(ItemsByProject::getFileIds).orElse(Collections.emptyList())); if (CollectionUtils.isEmpty(files)) { return GeneFilterInfo.builder().build(); } return featureIndexDao.getAvailableFieldsToSearch( files); } public Set<String> getAvailableFieldValues(final Long referenceId, final ItemsByProject fileIdsByProjectId, final String fieldName) { final List<Long> fileIds = Optional.ofNullable(fileIdsByProjectId) .map(ItemsByProject::getFileIds).orElse(Collections.emptyList()); if (CollectionUtils.isEmpty(fileIds)) { return Collections.emptySet(); } return featureIndexDao.getAvailableFieldValues( getGeneFilesForReference(referenceId, fileIds), fieldName); } private List<? extends FeatureFile> getGeneFilesForReference(final long referenceId, final List<Long> fileIds) { if (CollectionUtils.isEmpty(fileIds)) { return Stream.concat( Optional.ofNullable(getGeneFile(referenceId)) .map(Collections::singletonList).orElse(Collections.emptyList()).stream(), getFeatureFiles(referenceId).stream() ).filter(featureFile -> featureFile.getFormat() == BiologicalDataItemFormat.GENE) .distinct().collect(Collectors.toList()); } else { return geneFileManager.loadFiles(fileIds); } } public IndexSearchResult<FeatureIndexEntry> searchFeaturesByReference(final String featureId, final long referenceId) throws IOException { if (featureId == null || featureId.length() < 2) { return new IndexSearchResult<>(Collections.emptyList(), false, 0); } final IndexSearchResult<FeatureIndexEntry> res = featureIndexDao.searchFeatures( featureId, getFeatureFiles(referenceId), maxFeatureSearchResultsCount ); return mergeWithBookmarkSearch(res, featureId); } /** * Loads {@code VcfFilterInfo} object for a specified project. {@code VcfFilterInfo} contains information about * available fields to perform filtering and display results * * @param projectId a {@code Project}'s ID to load filter info * @return a {@code VcfFilterInfo} object * @throws IOException */ public VcfFilterInfo loadVcfFilterInfoForProject(long projectId) throws IOException { Project project = projectManager.load(projectId); List<Long> vcfIds = project.getItems().stream() .filter(item -> item.getBioDataItem() != null && item.getBioDataItem().getFormat() == BiologicalDataItemFormat.VCF) .map(item -> (item.getBioDataItem()).getId()) .collect(Collectors.toList()); return vcfManager.getFiltersInfo(vcfIds); } public void buildIndexForFile(FeatureFile featureFile) throws FeatureIndexException, IOException { if (!fileManager.indexForFeatureFileExists(featureFile)) { switch (featureFile.getFormat()) { case BED: bedManager.reindexBedFile(featureFile.getId()); break; case GENE: // use false here, because it's default parameter for reindexing in GeneController gffManager.reindexGeneFile(featureFile.getId(), false, false); break; case VCF: vcfManager.reindexVcfFile(featureFile.getId(), false); break; default: throw new IllegalArgumentException("Wrong FeatureType: " + featureFile.getFormat().name()); } } } /** * Fetch gene IDs of genes, affected by variation. The variation is specified by it's start and end indexes * * @param start a start index of the variation * @param end an end index of the variation * @param geneFiles a {@code List} of {@code GeneFile} to look for genes * @param chromosome a {@code Chromosome} * @return a {@code Set} of IDs of genes, affected by the variation * @throws GeneReadingException */ public Set<String> fetchGeneIds(int start, int end, List<GeneFile> geneFiles, Chromosome chromosome) throws GeneReadingException { Set<String> geneIds = new HashSet<>(); for (GeneFile geneFile : geneFiles) { List<Gene> genes = new ArrayList<>(); Track<Gene> track = new Track<>(); track.setStartIndex(start); track.setEndIndex(end); track.setId(geneFile.getId()); track.setChromosome(chromosome); track.setScaleFactor(AbstractGeneReader.LARGE_SCALE_FACTOR_LIMIT); if (end > start) { track.setStartIndex(start); track.setEndIndex(start); track = gffManager.loadGenes(track, geneFile, chromosome, false); genes.addAll(track.getBlocks()); track.setStartIndex(end); track.setEndIndex(end); track = gffManager.loadGenes(track, geneFile, chromosome, false); genes.addAll(track.getBlocks()); } else { track.setStartIndex(start); track.setEndIndex(end); track = gffManager.loadGenes(track, geneFile, chromosome, false); genes = track.getBlocks(); } geneIds.addAll(genes.stream() .filter(GeneUtils::isGene) .map(Gene::getGroupId) .collect(Collectors.toList())); } return geneIds; } /** * Writes index entries for specified {@link FeatureFile} to file system * @param featureFile a {@link FeatureFile}, for which index is written * @param entries a list of index entries * @throws IOException if error occurred while writing to file system */ public void writeLuceneIndexForFile(final FeatureFile featureFile, final List<? extends FeatureIndexEntry> entries, VcfFilterInfo vcfFilterInfo) throws IOException { featureIndexDao.writeLuceneIndexForFile(featureFile, entries, vcfFilterInfo); } public void makeIndexForBedReader(BedFile bedFile, AbstractFeatureReader<NggbBedFeature, LineIterator> reader, Map<String, Chromosome> chromosomeMap) throws IOException { CloseableIterator<NggbBedFeature> iterator = reader.iterator(); List<FeatureIndexEntry> allEntries = new ArrayList<>(); while (iterator.hasNext()) { NggbBedFeature next = iterator.next(); FeatureIndexEntry entry = new FeatureIndexEntry(); entry.setFeatureFileId(bedFile.getId()); entry.setChromosome(Utils.getFromChromosomeMap(chromosomeMap, next.getContig())); entry.setStartIndex(next.getStart()); entry.setEndIndex(next.getEnd()); entry.setFeatureId(next.getName()); entry.setFeatureName(next.getName()); entry.setUuid(UUID.randomUUID()); entry.setFeatureType(FeatureType.BED_FEATURE); allEntries.add(entry); } featureIndexDao.writeLuceneIndexForFile(bedFile, allEntries, null); } /** * Creates a VCF file feature index * @param vcfFile a VCF file to create index * @param reader a reader to file * @param geneFiles a {@code List} of {@code GeneFile} to look for genes * @param chromosomeMap a Map of {@link Chromosome}s to chromosome names * @param info VCF file's info data * @throws FeatureIndexException if an error occured while building an index */ public void makeIndexForVcfReader(VcfFile vcfFile, FeatureReader<VariantContext> reader, List<GeneFile> geneFiles, Map<String, Chromosome> chromosomeMap, VcfFilterInfo info) throws FeatureIndexException { VCFHeader vcfHeader = (VCFHeader) reader.getHeader(); try { CloseableIterator<VariantContext> iterator = reader.iterator(); String currentKey = null; VariantContext variantContext = null; BigVcfFeatureIndexBuilder indexer = new BigVcfFeatureIndexBuilder(info, vcfHeader, featureIndexDao, vcfFile, fileManager, geneFiles, indexBufferSize); while (iterator.hasNext()) { variantContext = iterator.next(); if (!variantContext.getContig().equals(currentKey)) { indexer.clear(); currentKey = variantContext.getContig(); LOGGER.info(MessageHelper .getMessage(MessagesConstants.INFO_FEATURE_INDEX_CHROMOSOME_WROTE, currentKey)); } indexer.add(variantContext, chromosomeMap); } // Put the last one if (variantContext != null && currentKey != null && Utils .chromosomeMapContains(chromosomeMap, currentKey)) { LOGGER.info(MessageHelper .getMessage(MessagesConstants.INFO_FEATURE_INDEX_CHROMOSOME_WROTE, currentKey)); indexer.clear(); } indexer.close(); } catch (IOException e) { throw new FeatureIndexException(vcfFile, e); } } /** * Creates Gene file's feature index * @param geneFile a {@link GeneFile} to create index * @param chromosomeMap a Map of {@link Chromosome}s to chromosome names * @param full * @throws IOException if an error occurred while writing index */ public void processGeneFile(GeneFile geneFile, final Map<String, Chromosome> chromosomeMap, boolean full) throws IOException { List<FeatureIndexEntry> allEntries = new ArrayList<>(); LOGGER.info("Writing feature index for file {}:{}", geneFile.getId(), geneFile.getName()); if (!full && fileManager.checkGeneFileExists(geneFile, GeneFileType.TRANSCRIPT)) { try (AbstractFeatureReader<GeneFeature, LineIterator> largeScaleReader = fileManager.makeGeneReader( geneFile, GeneFileType.LARGE_SCALE); AbstractFeatureReader<GeneFeature, LineIterator> transcriptReader = fileManager.makeGeneReader( geneFile, GeneFileType.TRANSCRIPT)) { CloseableIterator<GeneFeature> largeScaleIterator = largeScaleReader.iterator(); CloseableIterator<GeneFeature> transcriptIterator = transcriptReader.iterator(); addFeaturesFromIteratorToIndex(largeScaleIterator, chromosomeMap, geneFile, allEntries, false); addFeaturesFromIteratorToIndex(transcriptIterator, chromosomeMap, geneFile, allEntries, true); } } else { addFeaturesFromUsualGeneFileToIndex(geneFile, chromosomeMap, allEntries); } } private IndexSearchResult<FeatureIndexEntry> mergeWithBookmarkSearch(final IndexSearchResult<FeatureIndexEntry> res, final String featureId) { final IndexSearchResult<FeatureIndexEntry> bookmarkSearchRes = bookmarkManager.searchBookmarks(featureId, maxFeatureSearchResultsCount); bookmarkSearchRes.mergeFrom(res); return bookmarkSearchRes; } private List<FeatureFile> getFeatureFiles(final long referenceId) { final Reference reference = referenceGenomeManager.load(referenceId); final List<FeatureFile> annotationFiles = referenceGenomeManager.getReferenceAnnotationFiles(referenceId) .stream() .map(biologicalDataItem -> (FeatureFile) biologicalDataItem) .collect(Collectors.toList()); final GeneFile geneFile = reference.getGeneFile(); if (geneFile != null) { final Long geneFileId = geneFile.getId(); annotationFiles.add(geneFileManager.load(geneFileId)); } return annotationFiles; } private FeatureFile getGeneFile(final long referenceId) { return referenceGenomeManager.load(referenceId).getGeneFile(); } private void addFeaturesFromUsualGeneFileToIndex(GeneFile geneFile, Map<String, Chromosome> chromosomeMap, List<FeatureIndexEntry> allEntries) throws IOException { try (AbstractFeatureReader<GeneFeature, LineIterator> usualReader = fileManager.makeGeneReader( geneFile, GeneFileType.ORIGINAL)) { CloseableIterator<GeneFeature> iterator = usualReader.iterator(); GeneFeature feature = null; String currentKey = null; while (iterator.hasNext()) { feature = iterator.next(); currentKey = checkNextChromosome(feature, currentKey, chromosomeMap, allEntries, geneFile); if (GeneUtils.isGene(feature) || GeneUtils.isTranscript(feature) || GeneUtils.isExon(feature)) { addGeneFeatureToIndex(allEntries, feature, chromosomeMap); } } // Put the last one if (feature != null && currentKey != null && (chromosomeMap.containsKey(currentKey) || chromosomeMap.containsKey(Utils.changeChromosomeName(currentKey)))) { featureIndexDao.writeLuceneIndexForFile(geneFile, allEntries, null); allEntries.clear(); } } } private void addFeaturesFromIteratorToIndex(CloseableIterator<GeneFeature> iterator, Map<String, Chromosome> chromosomeMap, GeneFile geneFile, List<FeatureIndexEntry> allEntries, boolean transcriptIterator) throws IOException { GeneFeature feature = null; String currentKey = null; while (iterator.hasNext()) { feature = iterator.next(); currentKey = checkNextChromosome(feature, currentKey, chromosomeMap, allEntries, geneFile); if (transcriptIterator || GeneUtils.isGene(feature) || GeneUtils.isExon(feature)) { addGeneFeatureToIndex(allEntries, feature, chromosomeMap); } } // Put the last one if (feature != null && currentKey != null && (chromosomeMap.containsKey(currentKey) || chromosomeMap.containsKey(Utils.changeChromosomeName(currentKey)))) { featureIndexDao.writeLuceneIndexForFile(geneFile, allEntries, null); allEntries.clear(); } } private String checkNextChromosome(Feature feature, String currentChromosomeName, Map<String, Chromosome> chromosomeMap, List<FeatureIndexEntry> allEntries, GeneFile geneFile) throws IOException { if (!feature.getContig().equals(currentChromosomeName)) { if (currentChromosomeName != null && (chromosomeMap.containsKey(currentChromosomeName) || chromosomeMap.containsKey(Utils.changeChromosomeName(currentChromosomeName)))) { featureIndexDao.writeLuceneIndexForFile(geneFile, allEntries, null); LOGGER.info(MessageHelper.getMessage( MessagesConstants.INFO_FEATURE_INDEX_CHROMOSOME_WROTE, currentChromosomeName)); allEntries.clear(); } return feature.getContig(); } return currentChromosomeName; } public void addGeneFeatureToIndex(List<FeatureIndexEntry> allEntries, GeneFeature feature, Map<String, Chromosome> chromosomeMap) { if (chromosomeMap.containsKey(feature.getContig()) || chromosomeMap.containsKey(Utils.changeChromosomeName(feature.getContig()))) { GeneIndexEntry masterEntry = new GeneIndexEntry(); masterEntry.setFeatureId(feature.getFeatureId()); masterEntry.setUuid(UUID.randomUUID()); masterEntry.setChromosome(chromosomeMap.containsKey(feature.getContig()) ? chromosomeMap.get(feature.getContig()) : chromosomeMap.get(Utils.changeChromosomeName(feature.getContig()))); masterEntry.setStartIndex(feature.getStart()); masterEntry.setEndIndex(feature.getEnd()); masterEntry.setFeatureType(GeneUtils.fetchType(feature)); masterEntry.setFeature(feature.getFeature()); masterEntry.setSource(feature.getSource()); masterEntry.setScore(feature.getScore()); masterEntry.setFrame(feature.getFrame()); Optional.ofNullable(feature.getStrand()).ifPresent(strand -> masterEntry.setStrand(strand.toValue())); masterEntry.setAttributes(feature.getAttributes()); allEntries.add(masterEntry); String featureName = feature.getFeatureName(); masterEntry.setFeatureName(featureName); } } }
Fix gene field values method
server/catgenome/src/main/java/com/epam/catgenome/manager/FeatureIndexManager.java
Fix gene field values method
<ide><path>erver/catgenome/src/main/java/com/epam/catgenome/manager/FeatureIndexManager.java <ide> } <ide> <ide> public IndexSearchResult<GeneIndexEntry> searchGenesByReference(final GeneFilterForm filterForm, <del> final long referenceId) throws IOException { <add> final long referenceId) throws IOException { <ide> final List<? extends FeatureFile> files = getGeneFilesForReference(referenceId, filterForm.getFileIds()); <ide> if (CollectionUtils.isEmpty(files)) { <ide> return new IndexSearchResult<>(); <ide> return getGeneSearchResult(filterForm, files); <ide> } <ide> <del> public GeneFilterInfo getAvailableGeneFieldsToSearch(final Long referenceId, ItemsByProject fileIdsByProjectId) { <add> public GeneFilterInfo getAvailableGeneFieldsToSearch(final Long referenceId, <add> final ItemsByProject fileIdsByProjectId) { <ide> final List<? extends FeatureFile> files = <ide> getGeneFilesForReference(referenceId, Optional.ofNullable(fileIdsByProjectId) <ide> .map(ItemsByProject::getFileIds).orElse(Collections.emptyList())); <ide> if (CollectionUtils.isEmpty(files)) { <ide> return GeneFilterInfo.builder().build(); <ide> } <del> return featureIndexDao.getAvailableFieldsToSearch( <del> files); <del> } <del> <del> public Set<String> getAvailableFieldValues(final Long referenceId, final ItemsByProject fileIdsByProjectId, <add> return featureIndexDao.getAvailableFieldsToSearch(files); <add> } <add> <add> public Set<String> getAvailableFieldValues(final Long referenceId, <add> final ItemsByProject fileIdsByProjectId, <ide> final String fieldName) { <del> final List<Long> fileIds = Optional.ofNullable(fileIdsByProjectId) <del> .map(ItemsByProject::getFileIds).orElse(Collections.emptyList()); <del> if (CollectionUtils.isEmpty(fileIds)) { <add> final List<? extends FeatureFile> files = getGeneFilesForReference(referenceId, <add> Optional.ofNullable(fileIdsByProjectId) <add> .map(ItemsByProject::getFileIds).orElse(Collections.emptyList())); <add> if (CollectionUtils.isEmpty(files)) { <ide> return Collections.emptySet(); <ide> } <ide> return featureIndexDao.getAvailableFieldValues( <del> getGeneFilesForReference(referenceId, fileIds), fieldName); <add> files, fieldName); <ide> } <ide> <ide> private List<? extends FeatureFile> getGeneFilesForReference(final long referenceId, final List<Long> fileIds) {
Java
mpl-2.0
fef497f2abf155d8941b552603fe1ea7b22a164b
0
ydautremay/seed,jin19910624/seed,kavi87/seed,ydautremay/seed,tbouvet/seed,ydautremay/seed,kavi87/seed,jin19910624/seed,seedstack/seed,kavi87/seed,pith/seed,adrienlauer/seed,seedstack/seed,jin19910624/seed,Sherpard/seed,seedstack/seed,tbouvet/seed,pith/seed,adrienlauer/seed,Sherpard/seed,tbouvet/seed,jin19910624/seed,adrienlauer/seed,ydautremay/seed,pith/seed,Sherpard/seed
/** * Copyright (c) 2013-2015 by The SeedStack authors. All rights reserved. * * This file is part of SeedStack, An enterprise-oriented full development stack. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.security.internal; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.inject.Inject; import org.apache.commons.lang.ArrayUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.mgt.RealmSecurityManager; import org.apache.shiro.realm.Realm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.seedstack.seed.security.api.Domain; import org.seedstack.seed.security.api.RealmProvider; import org.seedstack.seed.security.api.Role; import org.seedstack.seed.security.api.Scope; import org.seedstack.seed.security.api.exceptions.AuthorizationException; import org.seedstack.seed.security.api.principals.PrincipalProvider; import org.seedstack.seed.security.api.principals.Principals; import org.seedstack.seed.security.api.principals.SimplePrincipalProvider; import org.seedstack.seed.security.internal.authorization.ScopePermission; import org.seedstack.seed.security.internal.authorization.SeedAuthorizationInfo; import org.seedstack.seed.security.internal.realms.ShiroRealmAdapter; /** * Implementation of SecuritySupport for Shiro * * @author [email protected] */ public class ShiroSecuritySupport implements RealmProvider { @Inject private Set<Realm> realms; @Override public PrincipalProvider<?> getIdentityPrincipal() { Subject subject = SecurityUtils.getSubject(); if (subject.getPrincipal() instanceof PrincipalProvider) { return (PrincipalProvider<?>) subject.getPrincipal(); } return Principals.identityPrincipal(""); } @Override public Collection<PrincipalProvider<?>> getOtherPrincipals() { Collection<PrincipalProvider<?>> principals = new ArrayList<PrincipalProvider<?>>(); PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals(); if (principalCollection == null) { return Collections.emptyList(); } for (Object shiroPrincipal : principalCollection.asList()) { if (shiroPrincipal instanceof PrincipalProvider) { principals.add((PrincipalProvider<?>) shiroPrincipal); } } return principals; } @Override public <T extends Serializable> Collection<PrincipalProvider<T>> getPrincipalsByType(Class<T> principalClass) { return Principals.getPrincipalsByType(getOtherPrincipals(), principalClass); } @Override public Collection<SimplePrincipalProvider> getSimplePrincipals() { return Principals.getSimplePrincipals(getOtherPrincipals()); } @Override public SimplePrincipalProvider getSimplePrincipalByName(String principalName) { return Principals.getSimplePrincipalByName(getOtherPrincipals(), principalName); } @Override public boolean isAuthenticated() { return SecurityUtils.getSubject().isAuthenticated(); } @Override public boolean isPermitted(String permission) { return SecurityUtils.getSubject().isPermitted(permission); } @Override public boolean isPermitted(String permission, Scope... scopes) { if (ArrayUtils.isEmpty(scopes)) { return isPermitted(permission); } boolean isPermitted = true; for (Scope scope : scopes) { isPermitted = isPermitted && SecurityUtils.getSubject().isPermitted(new ScopePermission(permission, scope)); } return isPermitted; } @Override public boolean isPermittedAll(String... permissions) { return SecurityUtils.getSubject().isPermittedAll(permissions); } @Override public boolean isPermittedAny(String... permissions) { boolean[] bools = SecurityUtils.getSubject().isPermitted(permissions); return ArrayUtils.contains(bools, true); } @Override public void checkPermission(String permission) { try { SecurityUtils.getSubject().checkPermission(permission); } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have permission " + permission, e); } } @Override public void checkPermission(String permission, Scope... scopes) { try { if (ArrayUtils.isEmpty(scopes)) { checkPermission(permission); } else { for (Scope scope : scopes) { SecurityUtils.getSubject().checkPermission(new ScopePermission(permission, scope)); } } } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have permission " + permission, e); } } @Override public void checkPermissions(String... stringPermissions) { Collection<org.apache.shiro.authz.Permission> permissions = new ArrayList<org.apache.shiro.authz.Permission>(); for (String stringPermission : stringPermissions) { permissions.add(new ScopePermission(stringPermission)); } try { SecurityUtils.getSubject().checkPermissions(permissions); } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have permissions " + Arrays.toString(stringPermissions), e); } } @Override public boolean hasRole(String roleIdentifier) { return SecurityUtils.getSubject().hasRole(roleIdentifier); } @Override public boolean hasRole(String roleIdentifier, Scope... scopes) { if (ArrayUtils.isEmpty(scopes)) { return hasRole(roleIdentifier); } Role role = null; Set<Role> roles = getRoles(); for (Role role2 : roles) { if (role2.getName().equals(roleIdentifier)) { role = role2; break; } } if (role == null) { return false; } return role.getScopes().containsAll(Arrays.asList(scopes)); } @Override public boolean hasAllRoles(String... roleIdentifiers) { return SecurityUtils.getSubject().hasAllRoles(Arrays.asList(roleIdentifiers)); } @Override public boolean hasAnyRole(String... roleIdentifiers) { boolean[] hasRoles = SecurityUtils.getSubject().hasRoles(Arrays.asList(roleIdentifiers)); return ArrayUtils.contains(hasRoles, true); } @Override public void checkRole(String roleIdentifier) { try { SecurityUtils.getSubject().checkRole(roleIdentifier); } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have role " + roleIdentifier, e); } } @Override public void checkRoles(String... roleIdentifiers) { try { SecurityUtils.getSubject().checkRoles(roleIdentifiers); } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have roles " + Arrays.toString(roleIdentifiers), e); } } @Override public void logout() { SecurityUtils.getSubject().logout(); } @Override @Deprecated public Set<org.seedstack.seed.security.api.Realm> provideRealms() { Set<org.seedstack.seed.security.api.Realm> result = new HashSet<org.seedstack.seed.security.api.Realm>(); org.apache.shiro.mgt.SecurityManager securityManager = SecurityUtils.getSecurityManager(); if (!(securityManager instanceof RealmSecurityManager)) { return Collections.emptySet(); } Collection<Realm> shiroRealms = ((RealmSecurityManager) securityManager).getRealms(); for (Realm shiroRealm : shiroRealms) { if (shiroRealm instanceof ShiroRealmAdapter) { result.add(((ShiroRealmAdapter) shiroRealm).getRealm()); } } return result; } private SeedAuthorizationInfo getAuthorizationInfo(Realm realm) { SeedAuthorizationInfo authzInfo = null; if (realm instanceof ShiroRealmAdapter) { AuthorizationInfo tmpInfo = ((ShiroRealmAdapter) realm).getAuthorizationInfo(SecurityUtils.getSubject().getPrincipals()); authzInfo = (SeedAuthorizationInfo) tmpInfo; } return authzInfo; } @Override public Set<Role> getRoles() { Set<Role> roles = new HashSet<Role>(); for (Realm realm : realms) { SeedAuthorizationInfo authzInfo = getAuthorizationInfo(realm); if (authzInfo != null) { for (Role role : authzInfo.getSeedRoles()) { roles.add(Role.unmodifiableRole(role)); } } } return roles; } @Override public Set<Domain> getDomains() { Set<Domain> domains = new HashSet<Domain>(); for (Role role : getRoles()) { domains.addAll(role.getScopesByType(Domain.class)); } return domains; } @Override public String getHost() { Session s = SecurityUtils.getSubject().getSession(false); if (s == null) { return null; } return s.getHost(); } }
security-support/core/src/main/java/org/seedstack/seed/security/internal/ShiroSecuritySupport.java
/** * Copyright (c) 2013-2015 by The SeedStack authors. All rights reserved. * * This file is part of SeedStack, An enterprise-oriented full development stack. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.security.internal; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.inject.Inject; import org.apache.commons.lang.ArrayUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.mgt.RealmSecurityManager; import org.apache.shiro.realm.Realm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.seedstack.seed.security.api.Domain; import org.seedstack.seed.security.api.RealmProvider; import org.seedstack.seed.security.api.Role; import org.seedstack.seed.security.api.Scope; import org.seedstack.seed.security.api.exceptions.AuthorizationException; import org.seedstack.seed.security.api.principals.PrincipalProvider; import org.seedstack.seed.security.api.principals.Principals; import org.seedstack.seed.security.api.principals.SimplePrincipalProvider; import org.seedstack.seed.security.internal.authorization.ScopePermission; import org.seedstack.seed.security.internal.authorization.SeedAuthorizationInfo; import org.seedstack.seed.security.internal.realms.ShiroRealmAdapter; /** * Implementation of SecuritySupport for Shiro * * @author [email protected] */ public class ShiroSecuritySupport implements RealmProvider { @Inject private Set<Realm> realms; @Override public PrincipalProvider<?> getIdentityPrincipal() { Subject subject = SecurityUtils.getSubject(); if (subject.getPrincipal() instanceof PrincipalProvider) { return (PrincipalProvider<?>) subject.getPrincipal(); } return Principals.identityPrincipal(""); } @Override public Collection<PrincipalProvider<?>> getOtherPrincipals() { Collection<PrincipalProvider<?>> principals = new ArrayList<PrincipalProvider<?>>(); for (Object shiroPrincipal : SecurityUtils.getSubject().getPrincipals().asList()) { if (shiroPrincipal instanceof PrincipalProvider) { principals.add((PrincipalProvider<?>) shiroPrincipal); } } return principals; } @Override public <T extends Serializable> Collection<PrincipalProvider<T>> getPrincipalsByType(Class<T> principalClass) { return Principals.getPrincipalsByType(getOtherPrincipals(), principalClass); } @Override public Collection<SimplePrincipalProvider> getSimplePrincipals() { return Principals.getSimplePrincipals(getOtherPrincipals()); } @Override public SimplePrincipalProvider getSimplePrincipalByName(String principalName) { return Principals.getSimplePrincipalByName(getOtherPrincipals(), principalName); } @Override public boolean isAuthenticated() { return SecurityUtils.getSubject().isAuthenticated(); } @Override public boolean isPermitted(String permission) { return SecurityUtils.getSubject().isPermitted(permission); } @Override public boolean isPermitted(String permission, Scope... scopes) { if (ArrayUtils.isEmpty(scopes)) { return isPermitted(permission); } boolean isPermitted = true; for (Scope scope : scopes) { isPermitted = isPermitted && SecurityUtils.getSubject().isPermitted(new ScopePermission(permission, scope)); } return isPermitted; } @Override public boolean isPermittedAll(String... permissions) { return SecurityUtils.getSubject().isPermittedAll(permissions); } @Override public boolean isPermittedAny(String... permissions) { boolean[] bools = SecurityUtils.getSubject().isPermitted(permissions); return ArrayUtils.contains(bools, true); } @Override public void checkPermission(String permission) { try { SecurityUtils.getSubject().checkPermission(permission); } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have permission " + permission, e); } } @Override public void checkPermission(String permission, Scope... scopes) { try { if (ArrayUtils.isEmpty(scopes)) { checkPermission(permission); } else { for (Scope scope : scopes) { SecurityUtils.getSubject().checkPermission(new ScopePermission(permission, scope)); } } } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have permission " + permission, e); } } @Override public void checkPermissions(String... stringPermissions) { Collection<org.apache.shiro.authz.Permission> permissions = new ArrayList<org.apache.shiro.authz.Permission>(); for (String stringPermission : stringPermissions) { permissions.add(new ScopePermission(stringPermission)); } try { SecurityUtils.getSubject().checkPermissions(permissions); } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have permissions " + Arrays.toString(stringPermissions), e); } } @Override public boolean hasRole(String roleIdentifier) { return SecurityUtils.getSubject().hasRole(roleIdentifier); } @Override public boolean hasRole(String roleIdentifier, Scope... scopes) { if (ArrayUtils.isEmpty(scopes)) { return hasRole(roleIdentifier); } Role role = null; Set<Role> roles = getRoles(); for (Role role2 : roles) { if (role2.getName().equals(roleIdentifier)) { role = role2; break; } } if (role == null) { return false; } return role.getScopes().containsAll(Arrays.asList(scopes)); } @Override public boolean hasAllRoles(String... roleIdentifiers) { return SecurityUtils.getSubject().hasAllRoles(Arrays.asList(roleIdentifiers)); } @Override public boolean hasAnyRole(String... roleIdentifiers) { boolean[] hasRoles = SecurityUtils.getSubject().hasRoles(Arrays.asList(roleIdentifiers)); return ArrayUtils.contains(hasRoles, true); } @Override public void checkRole(String roleIdentifier) { try { SecurityUtils.getSubject().checkRole(roleIdentifier); } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have role " + roleIdentifier, e); } } @Override public void checkRoles(String... roleIdentifiers) { try { SecurityUtils.getSubject().checkRoles(roleIdentifiers); } catch (org.apache.shiro.authz.AuthorizationException e) { throw new AuthorizationException("Subject doesn't have roles " + Arrays.toString(roleIdentifiers), e); } } @Override public void logout() { SecurityUtils.getSubject().logout(); } @Override @Deprecated public Set<org.seedstack.seed.security.api.Realm> provideRealms() { Set<org.seedstack.seed.security.api.Realm> result = new HashSet<org.seedstack.seed.security.api.Realm>(); org.apache.shiro.mgt.SecurityManager securityManager = SecurityUtils.getSecurityManager(); if (!(securityManager instanceof RealmSecurityManager)) { return Collections.emptySet(); } Collection<Realm> shiroRealms = ((RealmSecurityManager) securityManager).getRealms(); for (Realm shiroRealm : shiroRealms) { if (shiroRealm instanceof ShiroRealmAdapter) { result.add(((ShiroRealmAdapter) shiroRealm).getRealm()); } } return result; } private SeedAuthorizationInfo getAuthorizationInfo(Realm realm) { SeedAuthorizationInfo authzInfo = null; if (realm instanceof ShiroRealmAdapter) { AuthorizationInfo tmpInfo = ((ShiroRealmAdapter) realm).getAuthorizationInfo(SecurityUtils.getSubject().getPrincipals()); authzInfo = (SeedAuthorizationInfo) tmpInfo; } return authzInfo; } @Override public Set<Role> getRoles() { Set<Role> roles = new HashSet<Role>(); for (Realm realm : realms) { SeedAuthorizationInfo authzInfo = getAuthorizationInfo(realm); if (authzInfo != null) { for (Role role : authzInfo.getSeedRoles()) { roles.add(Role.unmodifiableRole(role)); } } } return roles; } @Override public Set<Domain> getDomains() { Set<Domain> domains = new HashSet<Domain>(); for (Role role : getRoles()) { domains.addAll(role.getScopesByType(Domain.class)); } return domains; } @Override public String getHost() { Session s = SecurityUtils.getSubject().getSession(false); if (s == null) { return null; } return s.getHost(); } }
Null object detected and dealt with by returning empty collection
security-support/core/src/main/java/org/seedstack/seed/security/internal/ShiroSecuritySupport.java
Null object detected and dealt with by returning empty collection
<ide><path>ecurity-support/core/src/main/java/org/seedstack/seed/security/internal/ShiroSecuritySupport.java <ide> import org.apache.shiro.mgt.RealmSecurityManager; <ide> import org.apache.shiro.realm.Realm; <ide> import org.apache.shiro.session.Session; <add>import org.apache.shiro.subject.PrincipalCollection; <ide> import org.apache.shiro.subject.Subject; <del> <ide> import org.seedstack.seed.security.api.Domain; <ide> import org.seedstack.seed.security.api.RealmProvider; <ide> import org.seedstack.seed.security.api.Role; <ide> @Override <ide> public Collection<PrincipalProvider<?>> getOtherPrincipals() { <ide> Collection<PrincipalProvider<?>> principals = new ArrayList<PrincipalProvider<?>>(); <del> for (Object shiroPrincipal : SecurityUtils.getSubject().getPrincipals().asList()) { <add> PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals(); <add> if (principalCollection == null) { <add> return Collections.emptyList(); <add> } <add> for (Object shiroPrincipal : principalCollection.asList()) { <ide> if (shiroPrincipal instanceof PrincipalProvider) { <ide> principals.add((PrincipalProvider<?>) shiroPrincipal); <ide> }
Java
agpl-3.0
f1f5ef3ad116baf999c4c39339b2fb5fdea7a61f
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
ac93370a-2e5f-11e5-9284-b827eb9e62be
hello.java
ac8db262-2e5f-11e5-9284-b827eb9e62be
ac93370a-2e5f-11e5-9284-b827eb9e62be
hello.java
ac93370a-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>ac8db262-2e5f-11e5-9284-b827eb9e62be <add>ac93370a-2e5f-11e5-9284-b827eb9e62be
JavaScript
mit
178c59bb6235425b6d882895632beca74d215ef2
0
scola84/node-validator
import Check from '../check'; export default class ArrayCheck extends Check { constructor() { super(); this._with = null; } with(...check) { this._with = check; return this; } check(value, options = {}) { if (!Array.isArray(value)) { return this._reason(false); } if (!this._with) { return true; } let result = null; return value.every((entry) => { return this._with.some((check) => { result = check.check(entry, options); return result === true; }); }) ? true : this._reason(result); } _reason(reason) { return { array: reason }; } }
src/check/array.js
import Check from '../check'; export default class ArrayCheck extends Check { constructor() { super(); this._with = null; } with(check) { this._with = check; return this; } check(value, options = {}) { if (!Array.isArray(value)) { return this._reason(false); } if (!this._with) { return true; } let result = null; return value.every((entry) => { result = this._with.check(entry, options); return result === true; }) ? true : this._reason(result); } _reason(reason) { return { array: reason }; } }
Accept multiple checks in array
src/check/array.js
Accept multiple checks in array
<ide><path>rc/check/array.js <ide> this._with = null; <ide> } <ide> <del> with(check) { <add> with(...check) { <ide> this._with = check; <ide> return this; <ide> } <ide> let result = null; <ide> <ide> return value.every((entry) => { <del> result = this._with.check(entry, options); <del> return result === true; <add> return this._with.some((check) => { <add> result = check.check(entry, options); <add> return result === true; <add> }); <ide> }) ? true : this._reason(result); <ide> } <ide>
Java
mit
9ac055a5c6b74724d65a0825ad39e12b818a8e39
0
jonalmeida/JOHN
package com.jonalmeida.john; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.jonalmeida.john.item.Item; import java.util.LinkedList; /** * A list fragment representing a list of NewsItems. This fragment * also supports tablet devices by allowing list items to be given an * 'activated' state upon selection. This helps indicate which item is * currently being viewed in a {@link NewsItemDetailFragment}. * <p/> */ public class NewsItemsRecyclerFragment extends Fragment implements NewsItemsRecyclerAdapter.OnListItemClickListener { private static final String TAG = "ItemsRecyclerFragment"; private RecyclerView mRecyclerView; private NewsItemsRecyclerAdapter mAdapter; private LinearLayoutManager mLinearLayoutManager; private LayoutInflater mLayoutInflater; private SwipeRefreshLayout mSwipeRefreshLayout; private LinkedList<Item> items; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private boolean mTwoPane = false; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public NewsItemsRecyclerFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); items = new LinkedList<>(); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_news_list_layout, container, false); mLayoutInflater = inflater; mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.fragment_main_swipe_refresh_layout); mAdapter = new NewsItemsRecyclerAdapter(items, inflater); insertTopStories(); init(v); return v; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRecyclerView.setAdapter(mAdapter); setSwipeRefresher(); } private void refreshContent() { // Shit, is this the best way to do this?! final NewsItemsRecyclerFragment newsItemsRecyclerFragment = this; new Handler().postDelayed(new Runnable() { @Override public void run() { items.clear(); mAdapter = new NewsItemsRecyclerAdapter(items, mLayoutInflater); mAdapter.setOnClickListener(newsItemsRecyclerFragment); mRecyclerView.setAdapter(mAdapter); insertTopStories(); mSwipeRefreshLayout.setRefreshing(false); } }, 1000); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); items.clear(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } private void init(View v) { mTwoPane = getResources().getBoolean(R.bool.twoPane); mAdapter.setOnClickListener(this); mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_story_list); mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST)); mLinearLayoutManager = new LinearLayoutManager(getActivity()); mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(mLinearLayoutManager); setScrollListener(mRecyclerView); } @Override public void onStoryClicked(Item i) { Log.d(TAG, "We're getting the item here: " + i.getId()); if (mTwoPane) { NewsItemDetailFragment fragment = NewsItemDetailFragment.newInstance(mTwoPane, i); this.getFragmentManager().beginTransaction() .replace(R.id.newsitem_detail_container, fragment) .commit(); } else { Intent detailIntent = new Intent(getActivity(), NewsItemDetailActivity.class); detailIntent.putExtra(Constants.ARG_ITEM, i); detailIntent.putExtra(Constants.ARG_TWO_PANE_MODE, mTwoPane); startActivity(detailIntent); getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } } @Override public void onCommentClicked(Item i) { Log.d(TAG, "We're getting an item's comments here: " + i.getId()); if (mTwoPane) { CommentItemsFragment fragment = CommentItemsFragment.newInstance(mTwoPane, i); this.getFragmentManager().beginTransaction() .replace(R.id.newsitem_detail_container, fragment) .commit(); } else { Intent commentIntent = new Intent(getActivity(), CommentItemsActivity.class); commentIntent.putExtra(Constants.ARG_ITEM, i); commentIntent.putExtra(Constants.ARG_TWO_PANE_MODE, mTwoPane); startActivity(commentIntent); getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } } private void insertTopStories() { if (mAdapter.getItemCount() <= 0) Log.d(TAG, "No items in top stories adapter, getting updated ones."); ItemUpdateHelper.getInstance().getTopStories(mAdapter, 0, 30); } private void setSwipeRefresher() { mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshContent(); } }); mSwipeRefreshLayout.setColorSchemeResources(R.color.primary); } private void setScrollListener(RecyclerView view) { view.setOnScrollListener(new RecyclerView.OnScrollListener() { int mLastFirstVisibleItem = 0; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); final int currentFirstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition(); if (currentFirstVisibleItem > this.mLastFirstVisibleItem) { ((NewsItemsRecyclerActivity) getActivity()).getSupportActionBar().hide(); } else if (currentFirstVisibleItem < this.mLastFirstVisibleItem) { ((NewsItemsRecyclerActivity) getActivity()).getSupportActionBar().show(); } this.mLastFirstVisibleItem = currentFirstVisibleItem; } }); } }
app/src/main/java/com/jonalmeida/john/NewsItemsRecyclerFragment.java
package com.jonalmeida.john; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.jonalmeida.john.item.Item; import java.util.LinkedList; /** * A list fragment representing a list of NewsItems. This fragment * also supports tablet devices by allowing list items to be given an * 'activated' state upon selection. This helps indicate which item is * currently being viewed in a {@link NewsItemDetailFragment}. * <p/> */ public class NewsItemsRecyclerFragment extends Fragment implements NewsItemsRecyclerAdapter.OnListItemClickListener { private static final String TAG = "ItemsRecyclerFragment"; private RecyclerView mRecyclerView; private NewsItemsRecyclerAdapter mAdapter; private LinearLayoutManager mLinearLayoutManager; private LayoutInflater mLayoutInflater; private SwipeRefreshLayout mSwipeRefreshLayout; private LinkedList<Item> items; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private boolean mTwoPane = false; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public NewsItemsRecyclerFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); items = new LinkedList<>(); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_news_list_layout, container, false); mLayoutInflater = inflater; mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.fragment_main_swipe_refresh_layout); mAdapter = new NewsItemsRecyclerAdapter(items, inflater); insertTopStories(); init(v); return v; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRecyclerView.setAdapter(mAdapter); setSwipeRefresher(); } private void refreshContent() { // Shit, is this the best way to do this?! final NewsItemsRecyclerFragment newsItemsRecyclerFragment = this; new Handler().postDelayed(new Runnable() { @Override public void run() { items.clear(); mAdapter = new NewsItemsRecyclerAdapter(items, mLayoutInflater); mAdapter.setOnClickListener(newsItemsRecyclerFragment); mRecyclerView.setAdapter(mAdapter); insertTopStories(); mSwipeRefreshLayout.setRefreshing(false); } }, 1000); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); items.clear(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } private void init(View v) { mTwoPane = getResources().getBoolean(R.bool.twoPane); mAdapter.setOnClickListener(this); mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_story_list); mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST)); mLinearLayoutManager = new LinearLayoutManager(getActivity()); mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(mLinearLayoutManager); } @Override public void onStoryClicked(Item i) { Log.d(TAG, "We're getting the item here: " + i.getId()); if (mTwoPane) { NewsItemDetailFragment fragment = NewsItemDetailFragment.newInstance(mTwoPane, i); this.getFragmentManager().beginTransaction() .replace(R.id.newsitem_detail_container, fragment) .commit(); } else { Intent detailIntent = new Intent(getActivity(), NewsItemDetailActivity.class); detailIntent.putExtra(Constants.ARG_ITEM, i); detailIntent.putExtra(Constants.ARG_TWO_PANE_MODE, mTwoPane); startActivity(detailIntent); getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } } @Override public void onCommentClicked(Item i) { Log.d(TAG, "We're getting an item's comments here: " + i.getId()); if (mTwoPane) { CommentItemsFragment fragment = CommentItemsFragment.newInstance(mTwoPane, i); this.getFragmentManager().beginTransaction() .replace(R.id.newsitem_detail_container, fragment) .commit(); } else { Intent commentIntent = new Intent(getActivity(), CommentItemsActivity.class); commentIntent.putExtra(Constants.ARG_ITEM, i); commentIntent.putExtra(Constants.ARG_TWO_PANE_MODE, mTwoPane); startActivity(commentIntent); getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } } private void insertTopStories() { if (mAdapter.getItemCount() <= 0) Log.d(TAG, "No items in top stories adapter, getting updated ones."); ItemUpdateHelper.getInstance().getTopStories(mAdapter, 0, 30); } private void setSwipeRefresher() { mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshContent(); } }); mSwipeRefreshLayout.setColorSchemeResources(R.color.primary); } }
Scroll listener to hide SupportActionBar
app/src/main/java/com/jonalmeida/john/NewsItemsRecyclerFragment.java
Scroll listener to hide SupportActionBar
<ide><path>pp/src/main/java/com/jonalmeida/john/NewsItemsRecyclerFragment.java <ide> mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); <ide> <ide> mRecyclerView.setLayoutManager(mLinearLayoutManager); <add> <add> setScrollListener(mRecyclerView); <ide> <ide> } <ide> <ide> mSwipeRefreshLayout.setColorSchemeResources(R.color.primary); <ide> } <ide> <add> private void setScrollListener(RecyclerView view) { <add> view.setOnScrollListener(new RecyclerView.OnScrollListener() { <add> int mLastFirstVisibleItem = 0; <add> <add> @Override <add> public void onScrollStateChanged(RecyclerView recyclerView, int newState) { <add> } <add> <add> @Override <add> public void onScrolled(RecyclerView recyclerView, int dx, int dy) { <add> super.onScrolled(recyclerView, dx, dy); <add> final int currentFirstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition(); <add> <add> if (currentFirstVisibleItem > this.mLastFirstVisibleItem) { <add> ((NewsItemsRecyclerActivity) getActivity()).getSupportActionBar().hide(); <add> } else if (currentFirstVisibleItem < this.mLastFirstVisibleItem) { <add> ((NewsItemsRecyclerActivity) getActivity()).getSupportActionBar().show(); <add> } <add> <add> this.mLastFirstVisibleItem = currentFirstVisibleItem; <add> } <add> }); <add> } <add> <ide> }
JavaScript
agpl-3.0
c3df6eab89896ceff4fe2e961de19c2b95c51b64
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
01149036-2e64-11e5-9284-b827eb9e62be
helloWorld.js
010f1ae8-2e64-11e5-9284-b827eb9e62be
01149036-2e64-11e5-9284-b827eb9e62be
helloWorld.js
01149036-2e64-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>010f1ae8-2e64-11e5-9284-b827eb9e62be <add>01149036-2e64-11e5-9284-b827eb9e62be
JavaScript
bsd-3-clause
48eec5efbe92b523e4f35e7e29dfaaf516567e58
0
Ventero/greasemonkey,HasClass0/greasemonkey,the8472/greasemonkey,the8472/greasemonkey,HasClass0/greasemonkey,Martii/greasemonkey,Ventero/greasemonkey,Martii/greasemonkey
const EXPORTED_SYMBOLS = ['timeout']; function timeout(aCallback, aDelay) { // Create the timer object. var timer = Components.classes["@mozilla.org/timer;1"] .createInstance(Components.interfaces.nsITimer); // The timer object may be garbage collected before it fires, so we need to // keep a reference to it alive (https://bugzil.la/647998). // However, simply creating a closure over the timer object without using it // may not be enough, as the timer might get optimized out of the closure // scope (https://bugzil.la/640629#c9). To work around this, the timer object // is explicitly stored as a property of the observer. var observer = { 'observe': function() { delete observer.timer; aCallback(); }, 'timer': timer }; timer.init(observer, aDelay, Components.interfaces.nsITimer.TYPE_ONE_SHOT); }
modules/util/timeout.js
Components.utils.import('resource://greasemonkey/util.js'); const EXPORTED_SYMBOLS = ['timeout']; function timeout(aCallback, aDelay, aType) { var type = aType; if ('undefined' == typeof type) { type = Components.interfaces.nsITimer.TYPE_ONE_SHOT; } // Create the timer object. var timer = Components.classes["@mozilla.org/timer;1"] .createInstance(Components.interfaces.nsITimer); // Init the callback, with a closure reference to the timer, so that it is // not garbage collected before it fires. timer.init( { 'observe': function() { timer; // Here's the reference that keeps the timer alive! aCallback(); } }, aDelay, type); }
Use more robust way to keep the timer reference alive. Strict mode generates a warning about |timer;| being a useless expression, which suggest that this might be optimized away at some point (see also https://bugzil.la/640629#c9). Instead, explicitly store the timer in the observer object.
modules/util/timeout.js
Use more robust way to keep the timer reference alive.
<ide><path>odules/util/timeout.js <del>Components.utils.import('resource://greasemonkey/util.js'); <del> <ide> const EXPORTED_SYMBOLS = ['timeout']; <ide> <del>function timeout(aCallback, aDelay, aType) { <del> var type = aType; <del> if ('undefined' == typeof type) { <del> type = Components.interfaces.nsITimer.TYPE_ONE_SHOT; <del> } <del> <add>function timeout(aCallback, aDelay) { <ide> // Create the timer object. <ide> var timer = Components.classes["@mozilla.org/timer;1"] <ide> .createInstance(Components.interfaces.nsITimer); <del> // Init the callback, with a closure reference to the timer, so that it is <del> // not garbage collected before it fires. <del> timer.init( <del> { <del> 'observe': function() { <del> timer; // Here's the reference that keeps the timer alive! <del> aCallback(); <del> } <del> }, <del> aDelay, type); <add> <add> // The timer object may be garbage collected before it fires, so we need to <add> // keep a reference to it alive (https://bugzil.la/647998). <add> // However, simply creating a closure over the timer object without using it <add> // may not be enough, as the timer might get optimized out of the closure <add> // scope (https://bugzil.la/640629#c9). To work around this, the timer object <add> // is explicitly stored as a property of the observer. <add> var observer = { <add> 'observe': function() { <add> delete observer.timer; <add> aCallback(); <add> }, <add> 'timer': timer <add> }; <add> <add> timer.init(observer, aDelay, Components.interfaces.nsITimer.TYPE_ONE_SHOT); <ide> }
JavaScript
mit
e381202fac51e1daef88a4877094809589bfd596
0
dantman/4query,dantman/4query
/* * jQuery @VERSION - New Wave Javascript * * Copyright (c) 2006 John Resig (jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Date$ * $Rev$ */ // Global undefined variable window.undefined = window.undefined; /** * Create a new jQuery Object * * @test ok( Array.prototype.push, "Array.push()" ); * ok( Function.prototype.apply, "Function.apply()" ); * ok( document.getElementById, "getElementById" ); * ok( document.getElementsByTagName, "getElementsByTagName" ); * ok( RegExp, "RegExp" ); * ok( jQuery, "jQuery" ); * ok( $, "$()" ); * * @constructor * @private * @name jQuery * @cat Core */ var jQuery = function(a,c) { // Shortcut for document ready (because $(document).each() is silly) if ( a && typeof a == "function" && jQuery.fn.ready ) return jQuery(document).ready(a); // Make sure that a selection was provided a = a || jQuery.context || document; // Watch for when a jQuery object is passed as the selector if ( a.jquery ) return jQuery( jQuery.merge( a, [] ) ); // Watch for when a jQuery object is passed at the context if ( c && c.jquery ) return jQuery( c ).find(a); // If the context is global, return a new object if ( window == this ) return new jQuery(a,c); // Handle HTML strings if ( a.constructor == String ) { var m = /^[^<]*(<.+>)[^>]*$/.exec(a); if ( m ) a = jQuery.clean( [ m[1] ] ); } // Watch for when an array is passed in this.get( a.constructor == Array || a.length && !a.nodeType && a[0] != undefined && a[0].nodeType ? // Assume that it is an array of DOM Elements jQuery.merge( a, [] ) : // Find the matching elements and save them for later jQuery.find( a, c ) ); // See if an extra function was provided var fn = arguments[ arguments.length - 1 ]; // If so, execute it in context if ( fn && typeof fn == "function" ) this.each(fn); return this; }; // Map over the $ in case of overwrite if ( typeof $ != "undefined" ) jQuery._$ = $; /** * This function accepts a string containing a CSS selector, * basic XPath, or raw HTML, which is then used to match a set of elements. * The HTML string is different from the traditional selectors in that * it creates the DOM elements representing that HTML string, on the fly, * to be (assumedly) inserted into the document later. * * The core functionality of jQuery centers around this function. * Everything in jQuery is based upon this, or uses this in some way. * The most basic use of this function is to pass in an expression * (usually consisting of CSS or XPath), which then finds all matching * elements and remembers them for later use. * * By default, $() looks for DOM elements within the context of the * current HTML document. * * @example $("div > p") * @desc This finds all p elements that are children of a div element. * @before <p>one</p> <div><p>two</p></div> <p>three</p> * @result [ <p>two</p> ] * * @example $("<div><p>Hello</p></div>").appendTo("#body") * @desc Creates a div element (and all of its contents) dynamically, * and appends it to the element with the ID of body. Internally, an * element is created and it's innerHTML property set to the given markup. * It is therefore both quite flexible and limited. * * @name $ * @param String expr An expression to search with, or a string of HTML to create on the fly. * @cat Core * @type jQuery */ /** * This function accepts a string containing a CSS selector, or * basic XPath, which is then used to match a set of elements with the * context of the specified DOM element, or document * * @example $("div", xml.responseXML) * @desc This finds all div elements within the specified XML document. * * @name $ * @param String expr An expression to search with. * @param Element context A DOM Element, or Document, representing the base context. * @cat Core * @type jQuery */ /** * Wrap jQuery functionality around a specific DOM Element. * This function also accepts XML Documents and Window objects * as valid arguments (even though they are not DOM Elements). * * @example $(document).find("div > p") * @before <p>one</p> <div><p>two</p></div> <p>three</p> * @result [ <p>two</p> ] * * @example $(document.body).background( "black" ); * @desc Sets the background color of the page to black. * * @name $ * @param Element elem A DOM element to be encapsulated by a jQuery object. * @cat Core * @type jQuery */ /** * Wrap jQuery functionality around a set of DOM Elements. * * @example $( myForm.elements ).hide() * @desc Hides all the input elements within a form * * @name $ * @param Array<Element> elems An array of DOM elements to be encapsulated by a jQuery object. * @cat Core * @type jQuery */ /** * A shorthand for $(document).ready(), allowing you to bind a function * to be executed when the DOM document has finished loading. This function * behaves just like $(document).ready(), in that it should be used to wrap * all of the other $() operations on your page. While this function is, * technically, chainable - there really isn't much use for chaining against it. * You can have as many $(document).ready events on your page as you like. * * @example $(function(){ * // Document is ready * }); * @desc Executes the function when the DOM is ready to be used. * * @name $ * @param Function fn The function to execute when the DOM is ready. * @cat Core * @type jQuery */ /** * A means of creating a cloned copy of a jQuery object. This function * copies the set of matched elements from one jQuery object and creates * another, new, jQuery object containing the same elements. * * @example var div = $("div"); * $( div ).find("p"); * @desc Locates all p elements with all div elements, without disrupting the original jQuery object contained in 'div' (as would normally be the case if a simple div.find("p") was done). * * @name $ * @param jQuery obj The jQuery object to be cloned. * @cat Core * @type jQuery */ // Map the jQuery namespace to the '$' one var $ = jQuery; jQuery.fn = jQuery.prototype = { /** * The current version of jQuery. * * @private * @property * @name jquery * @type String * @cat Core */ jquery: "@VERSION", /** * The number of elements currently matched. * * @example $("img").length; * @before <img src="test1.jpg"/> <img src="test2.jpg"/> * @result 2 * * @test ok( $("div").length == 2, "Get Number of Elements Found" ); * * @property * @name length * @type Number * @cat Core */ /** * The number of elements currently matched. * * @example $("img").size(); * @before <img src="test1.jpg"/> <img src="test2.jpg"/> * @result 2 * * @test ok( $("div").size() == 2, "Get Number of Elements Found" ); * * @name size * @type Number * @cat Core */ size: function() { return this.length; }, /** * Access all matched elements. This serves as a backwards-compatible * way of accessing all matched elements (other than the jQuery object * itself, which is, in fact, an array of elements). * * @example $("img").get(); * @before <img src="test1.jpg"/> <img src="test2.jpg"/> * @result [ <img src="test1.jpg"/> <img src="test2.jpg"/> ] * * @test isSet( $("div").get(), q("main","foo"), "Get All Elements" ); * * @name get * @type Array<Element> * @cat Core */ /** * Access a single matched element. num is used to access the * Nth element matched. * * @example $("img").get(1); * @before <img src="test1.jpg"/> <img src="test2.jpg"/> * @result [ <img src="test1.jpg"/> ] * * @test ok( $("div").get(0) == document.getElementById("main"), "Get A Single Element" ); * * @name get * @type Element * @param Number num Access the element in the Nth position. * @cat Core */ /** * Set the jQuery object to an array of elements. * * @example $("img").get([ document.body ]); * @result $("img").get() == [ document.body ] * * @private * @name get * @type jQuery * @param Elements elems An array of elements * @cat Core */ get: function( num ) { // Watch for when an array (of elements) is passed in if ( num && num.constructor == Array ) { // Use a tricky hack to make the jQuery object // look and feel like an array this.length = 0; [].push.apply( this, num ); return this; } else return num == undefined ? // Return a 'clean' array jQuery.merge( this, [] ) : // Return just the object this[num]; }, /** * Execute a function within the context of every matched element. * This means that every time the passed-in function is executed * (which is once for every element matched) the 'this' keyword * points to the specific element. * * Additionally, the function, when executed, is passed a single * argument representing the position of the element in the matched * set. * * @example $("img").each(function(){ * this.src = "test.jpg"; * }); * @before <img/> <img/> * @result <img src="test.jpg"/> <img src="test.jpg"/> * * @example $("img").each(function(i){ * alert( "Image #" + i + " is " + this ); * }); * @before <img/> <img/> * @result <img src="test.jpg"/> <img src="test.jpg"/> * * @test var div = $("div"); * div.each(function(){this.foo = 'zoo';}); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).foo != "zoo" ) pass = false; * } * ok( pass, "Execute a function, Relative" ); * * @name each * @type jQuery * @param Function fn A function to execute * @cat Core */ each: function( fn, args ) { return jQuery.each( this, fn, args ); }, /** * Searches every matched element for the object and returns * the index of the element, if found, starting with zero. * Returns -1 if the object wasn't found. * * @example $("*").index(document.getElementById('foobar')) * @before <div id="foobar"></div><b></b><span id="foo"></span> * @result 0 * * @example $("*").index(document.getElementById('foo')) * @before <div id="foobar"></div><b></b><span id="foo"></span> * @result 2 * * @example $("*").index(document.getElementById('bar')) * @before <div id="foobar"></div><b></b><span id="foo"></span> * @result -1 * * @test ok( $([window, document]).index(window) == 0, "Check for index of elements" ); * ok( $([window, document]).index(document) == 1, "Check for index of elements" ); * var inputElements = $('#radio1,#radio2,#check1,#check2'); * ok( inputElements.index(document.getElementById('radio1')) == 0, "Check for index of elements" ); * ok( inputElements.index(document.getElementById('radio2')) == 1, "Check for index of elements" ); * ok( inputElements.index(document.getElementById('check1')) == 2, "Check for index of elements" ); * ok( inputElements.index(document.getElementById('check2')) == 3, "Check for index of elements" ); * ok( inputElements.index(window) == -1, "Check for not found index" ); * ok( inputElements.index(document) == -1, "Check for not found index" ); * * @name index * @type Number * @param Object obj Object to search for * @cat Core */ index: function( obj ) { var pos = -1; this.each(function(i){ if ( this == obj ) pos = i; }); return pos; }, /** * Access a property on the first matched element. * This method makes it easy to retrieve a property value * from the first matched element. * * @example $("img").attr("src"); * @before <img src="test.jpg"/> * @result test.jpg * * @test ok( $('#text1').attr('value') == "Test", 'Check for value attribute' ); * ok( $('#text1').attr('type') == "text", 'Check for type attribute' ); * ok( $('#radio1').attr('type') == "radio", 'Check for type attribute' ); * ok( $('#check1').attr('type') == "checkbox", 'Check for type attribute' ); * ok( $('#simon1').attr('rel') == "bookmark", 'Check for rel attribute' ); * ok( $('#google').attr('title') == "Google!", 'Check for title attribute' ); * ok( $('#mark').attr('hreflang') == "en", 'Check for hreflang attribute' ); * ok( $('#en').attr('lang') == "en", 'Check for lang attribute' ); * ok( $('#simon').attr('class') == "blog link", 'Check for class attribute' ); * ok( $('#name').attr('name') == "name", 'Check for name attribute' ); * ok( $('#text1').attr('name') == "action", 'Check for name attribute' ); * ok( $('#form').attr('action').indexOf("formaction") >= 0, 'Check for action attribute' ); * * @name attr * @type Object * @param String name The name of the property to access. * @cat DOM */ /** * Set a hash of key/value object properties to all matched elements. * This serves as the best way to set a large number of properties * on all matched elements. * * @example $("img").attr({ src: "test.jpg", alt: "Test Image" }); * @before <img/> * @result <img src="test.jpg" alt="Test Image"/> * * @test var pass = true; * $("div").attr({foo: 'baz', zoo: 'ping'}).each(function(){ * if ( this.getAttribute('foo') != "baz" && this.getAttribute('zoo') != "ping" ) pass = false; * }); * ok( pass, "Set Multiple Attributes" ); * * @name attr * @type jQuery * @param Hash prop A set of key/value pairs to set as object properties. * @cat DOM */ /** * Set a single property to a value, on all matched elements. * * @example $("img").attr("src","test.jpg"); * @before <img/> * @result <img src="test.jpg"/> * * @test var div = $("div"); * div.attr("foo", "bar"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).getAttribute('foo') != "bar" ) pass = false; * } * ok( pass, "Set Attribute" ); * * $("#name").attr('name', 'something'); * ok( $("#name").name() == 'something', 'Set name attribute' ); * $("#check2").attr('checked', true); * ok( document.getElementById('check2').checked == true, 'Set checked attribute' ); * $("#check2").attr('checked', false); * ok( document.getElementById('check2').checked == false, 'Set checked attribute' ); * $("#text1").attr('readonly', true); * ok( document.getElementById('text1').readOnly == true, 'Set readonly attribute' ); * $("#text1").attr('readonly', false); * ok( document.getElementById('text1').readOnly == false, 'Set readonly attribute' ); * * @test stop(); * $.get('data/dashboard.xml', function(xml) { * var titles = []; * $('tab', xml).each(function() { * titles.push($(this).attr('title')); * }); * ok( titles[0] == 'Location', 'attr() in XML context: Check first title' ); * ok( titles[1] == 'Users', 'attr() in XML context: Check second title' ); * start(); * }); * * @name attr * @type jQuery * @param String key The name of the property to set. * @param Object value The value to set the property to. * @cat DOM */ attr: function( key, value, type ) { // Check to see if we're setting style values return key.constructor != String || value != undefined ? this.each(function(){ // See if we're setting a hash of styles if ( value == undefined ) // Set all the styles for ( var prop in key ) jQuery.attr( type ? this.style : this, prop, key[prop] ); // See if we're setting a single key/value style else jQuery.attr( type ? this.style : this, key, value ); }) : // Look for the case where we're accessing a style value jQuery[ type || "attr" ]( this[0], key ); }, /** * Access a style property on the first matched element. * This method makes it easy to retrieve a style property value * from the first matched element. * * @example $("p").css("color"); * @before <p style="color:red;">Test Paragraph.</p> * @result red * @desc Retrieves the color style of the first paragraph * * @example $("p").css("fontWeight"); * @before <p style="font-weight: bold;">Test Paragraph.</p> * @result bold * @desc Retrieves the font-weight style of the first paragraph. * Note that for all style properties with a dash (like 'font-weight'), you have to * write it in camelCase. In other words: Every time you have a '-' in a * property, remove it and replace the next character with an uppercase * representation of itself. Eg. fontWeight, fontSize, fontFamily, borderWidth, * borderStyle, borderBottomWidth etc. * * @test ok( $('#main').css("display") == 'none', 'Check for css property "display"'); * * @name css * @type Object * @param String name The name of the property to access. * @cat CSS */ /** * Set a hash of key/value style properties to all matched elements. * This serves as the best way to set a large number of style properties * on all matched elements. * * @example $("p").css({ color: "red", background: "blue" }); * @before <p>Test Paragraph.</p> * @result <p style="color:red; background:blue;">Test Paragraph.</p> * * @test ok( $('#foo').is(':visible'), 'Modifying CSS display: Assert element is visible'); * $('#foo').css({display: 'none'}); * ok( !$('#foo').is(':visible'), 'Modified CSS display: Assert element is hidden'); * $('#foo').css({display: 'block'}); * ok( $('#foo').is(':visible'), 'Modified CSS display: Assert element is visible'); * $('#floatTest').css({styleFloat: 'right'}); * ok( $('#floatTest').css('styleFloat') == 'right', 'Modified CSS float using "styleFloat": Assert float is right'); * $('#floatTest').css({cssFloat: 'left'}); * ok( $('#floatTest').css('cssFloat') == 'left', 'Modified CSS float using "cssFloat": Assert float is left'); * $('#floatTest').css({'float': 'right'}); * ok( $('#floatTest').css('float') == 'right', 'Modified CSS float using "float": Assert float is right'); * $('#floatTest').css({'font-size': '30px'}); * ok( $('#floatTest').css('font-size') == '30px', 'Modified CSS font-size: Assert font-size is 30px'); * * @name css * @type jQuery * @param Hash prop A set of key/value pairs to set as style properties. * @cat CSS */ /** * Set a single style property to a value, on all matched elements. * * @example $("p").css("color","red"); * @before <p>Test Paragraph.</p> * @result <p style="color:red;">Test Paragraph.</p> * @desc Changes the color of all paragraphs to red * * * @test ok( $('#foo').is(':visible'), 'Modifying CSS display: Assert element is visible'); * $('#foo').css('display', 'none'); * ok( !$('#foo').is(':visible'), 'Modified CSS display: Assert element is hidden'); * $('#foo').css('display', 'block'); * ok( $('#foo').is(':visible'), 'Modified CSS display: Assert element is visible'); * $('#floatTest').css('styleFloat', 'left'); * ok( $('#floatTest').css('styleFloat') == 'left', 'Modified CSS float using "styleFloat": Assert float is left'); * $('#floatTest').css('cssFloat', 'right'); * ok( $('#floatTest').css('cssFloat') == 'right', 'Modified CSS float using "cssFloat": Assert float is right'); * $('#floatTest').css('float', 'left'); * ok( $('#floatTest').css('float') == 'left', 'Modified CSS float using "float": Assert float is left'); * $('#floatTest').css('font-size', '20px'); * ok( $('#floatTest').css('font-size') == '20px', 'Modified CSS font-size: Assert font-size is 20px'); * * @name css * @type jQuery * @param String key The name of the property to set. * @param Object value The value to set the property to. * @cat CSS */ css: function( key, value ) { return this.attr( key, value, "curCSS" ); }, /** * Retrieve the text contents of all matched elements. The result is * a string that contains the combined text contents of all matched * elements. This method works on both HTML and XML documents. * * @example $("p").text(); * @before <p>Test Paragraph.</p> * @result Test Paragraph. * * @test var expected = "This link has class=\"blog\": Simon Willison's Weblog"; * ok( $('#sap').text() == expected, 'Check for merged text of more then one element.' ); * * @name text * @type String * @cat DOM */ text: function(e) { e = e || this; var t = ""; for ( var j = 0; j < e.length; j++ ) { var r = e[j].childNodes; for ( var i = 0; i < r.length; i++ ) if ( r[i].nodeType != 8 ) t += r[i].nodeType != 1 ? r[i].nodeValue : jQuery.fn.text([ r[i] ]); } return t; }, /** * Wrap all matched elements with a structure of other elements. * This wrapping process is most useful for injecting additional * stucture into a document, without ruining the original semantic * qualities of a document. * * This works by going through the first element * provided (which is generated, on the fly, from the provided HTML) * and finds the deepest ancestor element within its * structure - it is that element that will en-wrap everything else. * * This does not work with elements that contain text. Any necessary text * must be added after the wrapping is done. * * @example $("p").wrap("<div class='wrap'></div>"); * @before <p>Test Paragraph.</p> * @result <div class='wrap'><p>Test Paragraph.</p></div> * * @test var defaultText = 'Try them out:' * var result = $('#first').wrap('<div class="red"><span></span></div>').text(); * ok( defaultText == result, 'Check for wrapping of on-the-fly html' ); * ok( $('#first').parent().parent().is('.red'), 'Check if wrapper has class "red"' ); * * @name wrap * @type jQuery * @param String html A string of HTML, that will be created on the fly and wrapped around the target. * @cat DOM/Manipulation */ /** * Wrap all matched elements with a structure of other elements. * This wrapping process is most useful for injecting additional * stucture into a document, without ruining the original semantic * qualities of a document. * * This works by going through the first element * provided and finding the deepest ancestor element within its * structure - it is that element that will en-wrap everything else. * * This does not work with elements that contain text. Any necessary text * must be added after the wrapping is done. * * @example $("p").wrap( document.getElementById('content') ); * @before <p>Test Paragraph.</p><div id="content"></div> * @result <div id="content"><p>Test Paragraph.</p></div> * * @test var defaultText = 'Try them out:' * var result = $('#first').wrap(document.getElementById('empty')).parent(); * ok( result.is('ol'), 'Check for element wrapping' ); * ok( result.text() == defaultText, 'Check for element wrapping' ); * * @name wrap * @type jQuery * @param Element elem A DOM element that will be wrapped. * @cat DOM/Manipulation */ wrap: function() { // The elements to wrap the target around var a = jQuery.clean(arguments); // Wrap each of the matched elements individually return this.each(function(){ // Clone the structure that we're using to wrap var b = a[0].cloneNode(true); // Insert it before the element to be wrapped this.parentNode.insertBefore( b, this ); // Find the deepest point in the wrap structure while ( b.firstChild ) b = b.firstChild; // Move the matched element to within the wrap structure b.appendChild( this ); }); }, /** * Append any number of elements to the inside of every matched elements, * generated from the provided HTML. * This operation is similar to doing an appendChild to all the * specified elements, adding them into the document. * * @example $("p").append("<b>Hello</b>"); * @before <p>I would like to say: </p> * @result <p>I would like to say: <b>Hello</b></p> * * @test var defaultText = 'Try them out:' * var result = $('#first').append('<b>buga</b>'); * ok( result.text() == defaultText + 'buga', 'Check if text appending works' ); * ok( $('#select3').append('<option value="appendTest">Append Test</option>').find('option:last-child').attr('value') == 'appendTest', 'Appending html options to select element'); * * @name append * @type jQuery * @param String html A string of HTML, that will be created on the fly and appended to the target. * @cat DOM/Manipulation */ /** * Append an element to the inside of all matched elements. * This operation is similar to doing an appendChild to all the * specified elements, adding them into the document. * * @example $("p").append( $("#foo")[0] ); * @before <p>I would like to say: </p><b id="foo">Hello</b> * @result <p>I would like to say: <b id="foo">Hello</b></p> * * @test var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:"; * $('#sap').append(document.getElementById('first')); * ok( expected == $('#sap').text(), "Check for appending of element" ); * * @name append * @type jQuery * @param Element elem A DOM element that will be appended. * @cat DOM/Manipulation */ /** * Append any number of elements to the inside of all matched elements. * This operation is similar to doing an appendChild to all the * specified elements, adding them into the document. * * @example $("p").append( $("b") ); * @before <p>I would like to say: </p><b>Hello</b> * @result <p>I would like to say: <b>Hello</b></p> * * @test var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo"; * $('#sap').append([document.getElementById('first'), document.getElementById('yahoo')]); * ok( expected == $('#sap').text(), "Check for appending of array of elements" ); * * @name append * @type jQuery * @param Array<Element> elems An array of elements, all of which will be appended. * @cat DOM/Manipulation */ append: function() { return this.domManip(arguments, true, 1, function(a){ this.appendChild( a ); }); }, /** * Prepend any number of elements to the inside of every matched elements, * generated from the provided HTML. * This operation is the best way to insert dynamically created elements * inside, at the beginning, of all the matched element. * * @example $("p").prepend("<b>Hello</b>"); * @before <p>I would like to say: </p> * @result <p><b>Hello</b>I would like to say: </p> * * @test var defaultText = 'Try them out:' * var result = $('#first').prepend('<b>buga</b>'); * ok( result.text() == 'buga' + defaultText, 'Check if text prepending works' ); * ok( $('#select3').prepend('<option value="prependTest">Prepend Test</option>').find('option:first-child').attr('value') == 'prependTest', 'Prepending html options to select element'); * * @name prepend * @type jQuery * @param String html A string of HTML, that will be created on the fly and appended to the target. * @cat DOM/Manipulation */ /** * Prepend an element to the inside of all matched elements. * This operation is the best way to insert an element inside, at the * beginning, of all the matched element. * * @example $("p").prepend( $("#foo")[0] ); * @before <p>I would like to say: </p><b id="foo">Hello</b> * @result <p><b id="foo">Hello</b>I would like to say: </p> * * @test var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog"; * $('#sap').prepend(document.getElementById('first')); * ok( expected == $('#sap').text(), "Check for prepending of element" ); * * @name prepend * @type jQuery * @param Element elem A DOM element that will be appended. * @cat DOM/Manipulation */ /** * Prepend any number of elements to the inside of all matched elements. * This operation is the best way to insert a set of elements inside, at the * beginning, of all the matched element. * * @example $("p").prepend( $("b") ); * @before <p>I would like to say: </p><b>Hello</b> * @result <p><b>Hello</b>I would like to say: </p> * * @test var expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog"; * $('#sap').prepend([document.getElementById('first'), document.getElementById('yahoo')]); * ok( expected == $('#sap').text(), "Check for prepending of array of elements" ); * * @name prepend * @type jQuery * @param Array<Element> elems An array of elements, all of which will be appended. * @cat DOM/Manipulation */ prepend: function() { return this.domManip(arguments, true, -1, function(a){ this.insertBefore( a, this.firstChild ); }); }, /** * Insert any number of dynamically generated elements before each of the * matched elements. * * @example $("p").before("<b>Hello</b>"); * @before <p>I would like to say: </p> * @result <b>Hello</b><p>I would like to say: </p> * * @test var expected = 'This is a normal link: bugaYahoo'; * $('#yahoo').before('<b>buga</b>'); * ok( expected == $('#en').text(), 'Insert String before' ); * * @name before * @type jQuery * @param String html A string of HTML, that will be created on the fly and appended to the target. * @cat DOM/Manipulation */ /** * Insert an element before each of the matched elements. * * @example $("p").before( $("#foo")[0] ); * @before <p>I would like to say: </p><b id="foo">Hello</b> * @result <b id="foo">Hello</b><p>I would like to say: </p> * * @test var expected = "This is a normal link: Try them out:Yahoo"; * $('#yahoo').before(document.getElementById('first')); * ok( expected == $('#en').text(), "Insert element before" ); * * @name before * @type jQuery * @param Element elem A DOM element that will be appended. * @cat DOM/Manipulation */ /** * Insert any number of elements before each of the matched elements. * * @example $("p").before( $("b") ); * @before <p>I would like to say: </p><b>Hello</b> * @result <b>Hello</b><p>I would like to say: </p> * * @test var expected = "This is a normal link: Try them out:diveintomarkYahoo"; * $('#yahoo').before([document.getElementById('first'), document.getElementById('mark')]); * ok( expected == $('#en').text(), "Insert array of elements before" ); * * @name before * @type jQuery * @param Array<Element> elems An array of elements, all of which will be appended. * @cat DOM/Manipulation */ before: function() { return this.domManip(arguments, false, 1, function(a){ this.parentNode.insertBefore( a, this ); }); }, /** * Insert any number of dynamically generated elements after each of the * matched elements. * * @example $("p").after("<b>Hello</b>"); * @before <p>I would like to say: </p> * @result <p>I would like to say: </p><b>Hello</b> * * @test var expected = 'This is a normal link: Yahoobuga'; * $('#yahoo').after('<b>buga</b>'); * ok( expected == $('#en').text(), 'Insert String after' ); * * @name after * @type jQuery * @param String html A string of HTML, that will be created on the fly and appended to the target. * @cat DOM/Manipulation */ /** * Insert an element after each of the matched elements. * * @example $("p").after( $("#foo")[0] ); * @before <b id="foo">Hello</b><p>I would like to say: </p> * @result <p>I would like to say: </p><b id="foo">Hello</b> * * @test var expected = "This is a normal link: YahooTry them out:"; * $('#yahoo').after(document.getElementById('first')); * ok( expected == $('#en').text(), "Insert element after" ); * * @name after * @type jQuery * @param Element elem A DOM element that will be appended. * @cat DOM/Manipulation */ /** * Insert any number of elements after each of the matched elements. * * @example $("p").after( $("b") ); * @before <b>Hello</b><p>I would like to say: </p> * @result <p>I would like to say: </p><b>Hello</b> * * @test var expected = "This is a normal link: YahooTry them out:diveintomark"; * $('#yahoo').after([document.getElementById('first'), document.getElementById('mark')]); * ok( expected == $('#en').text(), "Insert array of elements after" ); * * @name after * @type jQuery * @param Array<Element> elems An array of elements, all of which will be appended. * @cat DOM/Manipulation */ after: function() { return this.domManip(arguments, false, -1, function(a){ this.parentNode.insertBefore( a, this.nextSibling ); }); }, /** * End the most recent 'destructive' operation, reverting the list of matched elements * back to its previous state. After an end operation, the list of matched elements will * revert to the last state of matched elements. * * @example $("p").find("span").end(); * @before <p><span>Hello</span>, how are you?</p> * @result $("p").find("span").end() == [ <p>...</p> ] * * @test ok( 'Yahoo' == $('#yahoo').parent().end().text(), 'Check for end' ); * * @name end * @type jQuery * @cat DOM/Traversing */ end: function() { return this.get( this.stack.pop() ); }, /** * Searches for all elements that match the specified expression. * This method is the optimal way of finding additional descendant * elements with which to process. * * All searching is done using a jQuery expression. The expression can be * written using CSS 1-3 Selector syntax, or basic XPath. * * @example $("p").find("span"); * @before <p><span>Hello</span>, how are you?</p> * @result $("p").find("span") == [ <span>Hello</span> ] * * @test ok( 'Yahoo' == $('#foo').find('.blogTest').text(), 'Check for find' ); * * @name find * @type jQuery * @param String expr An expression to search with. * @cat DOM/Traversing */ find: function(t) { return this.pushStack( jQuery.map( this, function(a){ return jQuery.find(t,a); }), arguments ); }, /** * Create cloned copies of all matched DOM Elements. This does * not create a cloned copy of this particular jQuery object, * instead it creates duplicate copies of all DOM Elements. * This is useful for moving copies of the elements to another * location in the DOM. * * @example $("b").clone().prependTo("p"); * @before <b>Hello</b><p>, how are you?</p> * @result <b>Hello</b><p><b>Hello</b>, how are you?</p> * * @test ok( 'This is a normal link: Yahoo' == $('#en').text(), 'Assert text for #en' ); * var clone = $('#yahoo').clone(); * ok( 'Try them out:Yahoo' == $('#first').append(clone).text(), 'Check for clone' ); * ok( 'This is a normal link: Yahoo' == $('#en').text(), 'Reassert text for #en' ); * * @name clone * @type jQuery * @cat DOM/Manipulation */ clone: function(deep) { return this.pushStack( jQuery.map( this, function(a){ return a.cloneNode( deep != undefined ? deep : true ); }), arguments ); }, /** * Removes all elements from the set of matched elements that do not * match the specified expression. This method is used to narrow down * the results of a search. * * All searching is done using a jQuery expression. The expression * can be written using CSS 1-3 Selector syntax, or basic XPath. * * @example $("p").filter(".selected") * @before <p class="selected">Hello</p><p>How are you?</p> * @result $("p").filter(".selected") == [ <p class="selected">Hello</p> ] * * @test isSet( $("input").filter(":checked").get(), q("radio2", "check1"), "Filter elements" ); * @test $("input").filter(":checked",function(i){ * ok( this == q("radio2", "check1")[i], "Filter elements, context" ); * }); * @test $("#main > p#ap > a").filter("#foobar",function(){},function(i){ * ok( this == q("google","groups", "mark")[i], "Filter elements, else context" ); * }); * * @name filter * @type jQuery * @param String expr An expression to search with. * @cat DOM/Traversing */ /** * Removes all elements from the set of matched elements that do not * match at least one of the expressions passed to the function. This * method is used when you want to filter the set of matched elements * through more than one expression. * * Elements will be retained in the jQuery object if they match at * least one of the expressions passed. * * @example $("p").filter([".selected", ":first"]) * @before <p>Hello</p><p>Hello Again</p><p class="selected">And Again</p> * @result $("p").filter([".selected", ":first"]) == [ <p>Hello</p>, <p class="selected">And Again</p> ] * * @name filter * @type jQuery * @param Array<String> exprs A set of expressions to evaluate against * @cat DOM/Traversing */ filter: function(t) { return this.pushStack( t.constructor == Array && jQuery.map(this,function(a){ for ( var i = 0; i < t.length; i++ ) if ( jQuery.filter(t[i],[a]).r.length ) return a; return false; }) || t.constructor == Boolean && ( t ? this.get() : [] ) || typeof t == "function" && jQuery.grep( this, t ) || jQuery.filter(t,this).r, arguments ); }, /** * Removes the specified Element from the set of matched elements. This * method is used to remove a single Element from a jQuery object. * * @example $("p").not( document.getElementById("selected") ) * @before <p>Hello</p><p id="selected">Hello Again</p> * @result [ <p>Hello</p> ] * * @name not * @type jQuery * @param Element el An element to remove from the set * @cat DOM/Traversing */ /** * Removes elements matching the specified expression from the set * of matched elements. This method is used to remove one or more * elements from a jQuery object. * * @example $("p").not("#selected") * @before <p>Hello</p><p id="selected">Hello Again</p> * @result [ <p>Hello</p> ] * * @test ok($("#main > p#ap > a").not("#google").length == 2, ".not") * * @name not * @type jQuery * @param String expr An expression with which to remove matching elements * @cat DOM/Traversing */ not: function(t) { return this.pushStack( t.constructor == String ? jQuery.filter(t,this,false).r : jQuery.grep(this,function(a){ return a != t; }), arguments ); }, /** * Adds the elements matched by the expression to the jQuery object. This * can be used to concatenate the result sets of two expressions. * * @example $("p").add("span") * @before <p>Hello</p><p><span>Hello Again</span></p> * @result [ <p>Hello</p>, <span>Hello Again</span> ] * * @name add * @type jQuery * @param String expr An expression whose matched elements are added * @cat DOM/Traversing */ /** * Adds each of the Elements in the array to the set of matched elements. * This is used to add a set of Elements to a jQuery object. * * @example $("p").add([document.getElementById("a"), document.getElementById("b")]) * @before <p>Hello</p><p><span id="a">Hello Again</span><span id="b">And Again</span></p> * @result [ <p>Hello</p>, <span id="a">Hello Again</span>, <span id="b">And Again</span> ] * * @name add * @type jQuery * @param Array<Element> els An array of Elements to add * @cat DOM/Traversing */ /** * Adds a single Element to the set of matched elements. This is used to * add a single Element to a jQuery object. * * @example $("p").add( document.getElementById("a") ) * @before <p>Hello</p><p><span id="a">Hello Again</span></p> * @result [ <p>Hello</p>, <span id="a">Hello Again</span> ] * * @name add * @type jQuery * @param Element el An Element to add * @cat DOM/Traversing */ add: function(t) { return this.pushStack( jQuery.merge( this, t.constructor == String ? jQuery.find(t) : t.constructor == Array ? t : [t] ), arguments ); }, /** * Checks the current selection against an expression and returns true, * if the selection fits the given expression. Does return false, if the * selection does not fit or the expression is not valid. * * @example $("input[@type='checkbox']").parent().is("form") * @before <form><input type="checkbox" /></form> * @result true * @desc Returns true, because the parent of the input is a form element * * @example $("input[@type='checkbox']").parent().is("form") * @before <form><p><input type="checkbox" /></p></form> * @result false * @desc Returns false, because the parent of the input is a p element * * @example $("form").is(null) * @before <form></form> * @result false * @desc An invalid expression always returns false. * * @test ok( $('#form').is('form'), 'Check for element: A form must be a form' ); * ok( !$('#form').is('div'), 'Check for element: A form is not a div' ); * ok( $('#mark').is('.blog'), 'Check for class: Expected class "blog"' ); * ok( !$('#mark').is('.link'), 'Check for class: Did not expect class "link"' ); * ok( $('#simon').is('.blog.link'), 'Check for multiple classes: Expected classes "blog" and "link"' ); * ok( !$('#simon').is('.blogTest'), 'Check for multiple classes: Expected classes "blog" and "link", but not "blogTest"' ); * ok( $('#en').is('[@lang="en"]'), 'Check for attribute: Expected attribute lang to be "en"' ); * ok( !$('#en').is('[@lang="de"]'), 'Check for attribute: Expected attribute lang to be "en", not "de"' ); * ok( $('#text1').is('[@type="text"]'), 'Check for attribute: Expected attribute type to be "text"' ); * ok( !$('#text1').is('[@type="radio"]'), 'Check for attribute: Expected attribute type to be "text", not "radio"' ); * ok( $('#text2').is(':disabled'), 'Check for pseudoclass: Expected to be disabled' ); * ok( !$('#text1').is(':disabled'), 'Check for pseudoclass: Expected not disabled' ); * ok( $('#radio2').is(':checked'), 'Check for pseudoclass: Expected to be checked' ); * ok( !$('#radio1').is(':checked'), 'Check for pseudoclass: Expected not checked' ); * ok( $('#foo').is('[p]'), 'Check for child: Expected a child "p" element' ); * ok( !$('#foo').is('[ul]'), 'Check for child: Did not expect "ul" element' ); * ok( $('#foo').is('[p][a][code]'), 'Check for childs: Expected "p", "a" and "code" child elements' ); * ok( !$('#foo').is('[p][a][code][ol]'), 'Check for childs: Expected "p", "a" and "code" child elements, but no "ol"' ); * ok( !$('#foo').is(0), 'Expected false for an invalid expression - 0' ); * ok( !$('#foo').is(null), 'Expected false for an invalid expression - null' ); * ok( !$('#foo').is(''), 'Expected false for an invalid expression - ""' ); * ok( !$('#foo').is(undefined), 'Expected false for an invalid expression - undefined' ); * * @name is * @type Boolean * @param String expr The expression with which to filter * @cat DOM/Traversing */ is: function(expr) { return expr ? jQuery.filter(expr,this).r.length > 0 : false; }, /** * * * @private * @name domManip * @param Array args * @param Boolean table * @param Number int * @param Function fn The function doing the DOM manipulation. * @type jQuery * @cat Core */ domManip: function(args, table, dir, fn){ var clone = this.size() > 1; var a = jQuery.clean(args); return this.each(function(){ var obj = this; if ( table && this.nodeName.toUpperCase() == "TABLE" && a[0].nodeName.toUpperCase() != "THEAD" ) { var tbody = this.getElementsByTagName("tbody"); if ( !tbody.length ) { obj = document.createElement("tbody"); this.appendChild( obj ); } else obj = tbody[0]; } for ( var i = ( dir < 0 ? a.length - 1 : 0 ); i != ( dir < 0 ? dir : a.length ); i += dir ) { fn.apply( obj, [ clone ? a[i].cloneNode(true) : a[i] ] ); } }); }, /** * * * @private * @name pushStack * @param Array a * @param Array args * @type jQuery * @cat Core */ pushStack: function(a,args) { var fn = args && args[args.length-1]; var fn2 = args && args[args.length-2]; if ( fn && fn.constructor != Function ) fn = null; if ( fn2 && fn2.constructor != Function ) fn2 = null; if ( !fn ) { if ( !this.stack ) this.stack = []; this.stack.push( this.get() ); this.get( a ); } else { var old = this.get(); this.get( a ); if ( fn2 && a.length || !fn2 ) this.each( fn2 || fn ).get( old ); else this.get( old ).each( fn ); } return this; } }; /** * Extends the jQuery object itself. Can be used to add both static * functions and plugin methods. * * @example $.fn.extend({ * check: function() { * this.each(function() { this.checked = true; }); * ), * uncheck: function() { * this.each(function() { this.checked = false; }); * } * }); * $("input[@type=checkbox]").check(); * $("input[@type=radio]").uncheck(); * @desc Adds two plugin methods. * * @private * @name extend * @param Object obj * @type Object * @cat Core */ /** * Extend one object with another, returning the original, * modified, object. This is a great utility for simple inheritance. * * @example var settings = { validate: false, limit: 5, name: "foo" }; * var options = { validate: true, name: "bar" }; * jQuery.extend(settings, options); * @result settings == { validate: true, limit: 5, name: "bar" } * * @test var settings = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" }; * var options = { xnumber2: 1, xstring2: "x", xxx: "newstring" }; * var optionsCopy = { xnumber2: 1, xstring2: "x", xxx: "newstring" }; * var merged = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "x", xxx: "newstring" }; * jQuery.extend(settings, options); * isSet( settings, merged, "Check if extended: settings must be extended" ); * isSet ( options, optionsCopy, "Check if not modified: options must not be modified" ); * * @name $.extend * @param Object obj The object to extend * @param Object prop The object that will be merged into the first. * @type Object * @cat Javascript */ jQuery.extend = jQuery.fn.extend = function(obj,prop) { // Watch for the case where null or undefined gets passed in by accident if ( arguments.length > 1 && (prop === null || prop == undefined) ) return obj; // If no property object was provided, then we're extending jQuery if ( !prop ) { prop = obj; obj = this; } // Extend the base object for ( var i in prop ) obj[i] = prop[i]; // Return the modified object return obj; }; jQuery.extend({ /** * @private * @name init * @type undefined * @cat Core */ init: function(){ jQuery.initDone = true; jQuery.each( jQuery.macros.axis, function(i,n){ jQuery.fn[ i ] = function(a) { var ret = jQuery.map(this,n); if ( a && a.constructor == String ) ret = jQuery.filter(a,ret).r; return this.pushStack( ret, arguments ); }; }); jQuery.each( jQuery.macros.to, function(i,n){ jQuery.fn[ i ] = function(){ var a = arguments; return this.each(function(){ for ( var j = 0; j < a.length; j++ ) jQuery(a[j])[n]( this ); }); }; }); jQuery.each( jQuery.macros.each, function(i,n){ jQuery.fn[ i ] = function() { return this.each( n, arguments ); }; }); jQuery.each( jQuery.macros.filter, function(i,n){ jQuery.fn[ n ] = function(num,fn) { return this.filter( ":" + n + "(" + num + ")", fn ); }; }); jQuery.each( jQuery.macros.attr, function(i,n){ n = n || i; jQuery.fn[ i ] = function(h) { return h == undefined ? this.length ? this[0][n] : null : this.attr( n, h ); }; }); jQuery.each( jQuery.macros.css, function(i,n){ jQuery.fn[ n ] = function(h) { return h == undefined ? ( this.length ? jQuery.css( this[0], n ) : null ) : this.css( n, h ); }; }); }, /** * A generic iterator function, which can be used to seemlessly * iterate over both objects and arrays. This function is not the same * as $().each() - which is used to iterate, exclusively, over a jQuery * object. This function can be used to iterate over anything. * * @example $.each( [0,1,2], function(i){ * alert( "Item #" + i + ": " + this ); * }); * @desc This is an example of iterating over the items in an array, accessing both the current item and its index. * * @example $.each( { name: "John", lang: "JS" }, function(i){ * alert( "Name: " + i + ", Value: " + this ); * }); * @desc This is an example of iterating over the properties in an Object, accessing both the current item and its key. * * @name $.each * @param Object obj The object, or array, to iterate over. * @param Function fn The function that will be executed on every object. * @type Object * @cat Javascript */ each: function( obj, fn, args ) { if ( obj.length == undefined ) for ( var i in obj ) fn.apply( obj[i], args || [i, obj[i]] ); else for ( var i = 0; i < obj.length; i++ ) if ( fn.apply( obj[i], args || [i, obj[i]] ) === false ) break; return obj; }, className: { add: function(o,c){ if (jQuery.className.has(o,c)) return; o.className += ( o.className ? " " : "" ) + c; }, remove: function(o,c){ if( !c ) { o.className = ""; } else { var classes = o.className.split(" "); for(var i=0; i<classes.length; i++) { if(classes[i] == c) { classes.splice(i, 1); break; } } o.className = classes.join(' '); } }, has: function(e,a) { if ( e.className != undefined ) e = e.className; return new RegExp("(^|\\s)" + a + "(\\s|$)").test(e); } }, /** * Swap in/out style options. * @private */ swap: function(e,o,f) { for ( var i in o ) { e.style["old"+i] = e.style[i]; e.style[i] = o[i]; } f.apply( e, [] ); for ( var i in o ) e.style[i] = e.style["old"+i]; }, css: function(e,p) { if ( p == "height" || p == "width" ) { var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"]; for ( var i in d ) { old["padding" + d[i]] = 0; old["border" + d[i] + "Width"] = 0; } jQuery.swap( e, old, function() { if (jQuery.css(e,"display") != "none") { oHeight = e.offsetHeight; oWidth = e.offsetWidth; } else { e = jQuery(e.cloneNode(true)) .find(":radio").removeAttr("checked").end() .css({ visibility: "hidden", position: "absolute", display: "block", right: "0", left: "0" }).appendTo(e.parentNode)[0]; var parPos = jQuery.css(e.parentNode,"position"); if ( parPos == "" || parPos == "static" ) e.parentNode.style.position = "relative"; oHeight = e.clientHeight; oWidth = e.clientWidth; if ( parPos == "" || parPos == "static" ) e.parentNode.style.position = "static"; e.parentNode.removeChild(e); } }); return p == "height" ? oHeight : oWidth; } return jQuery.curCSS( e, p ); }, curCSS: function(elem, prop, force) { var ret; if (prop == 'opacity' && jQuery.browser.msie) return jQuery.attr(elem.style, 'opacity'); if (prop == "float" || prop == "cssFloat") prop = jQuery.browser.msie ? "styleFloat" : "cssFloat"; if (!force && elem.style[prop]) { ret = elem.style[prop]; } else if (elem.currentStyle) { var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();}); ret = elem.currentStyle[prop] || elem.currentStyle[newProp]; } else if (document.defaultView && document.defaultView.getComputedStyle) { if (prop == "cssFloat" || prop == "styleFloat") prop = "float"; prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase(); var cur = document.defaultView.getComputedStyle(elem, null); if ( cur ) ret = cur.getPropertyValue(prop); else if ( prop == 'display' ) ret = 'none'; else jQuery.swap(elem, { display: 'block' }, function() { ret = document.defaultView.getComputedStyle(this,null).getPropertyValue(prop); }); } return ret; }, clean: function(a) { var r = []; for ( var i = 0; i < a.length; i++ ) { var arg = a[i]; if ( arg.constructor == String ) { // Convert html string into DOM nodes // Trim whitespace, otherwise indexOf won't work as expected var s = jQuery.trim(arg), div = document.createElement("div"), wrap = [0,"",""]; if ( !s.indexOf("<opt") ) // option or optgroup wrap = [1, "<select>", "</select>"]; else if ( !s.indexOf("<thead") || !s.indexOf("<tbody") ) wrap = [1, "<table>", "</table>"]; else if ( !s.indexOf("<tr") ) wrap = [2, "<table>", "</table>"]; // tbody auto-inserted else if ( !s.indexOf("<td") || !s.indexOf("<th") ) wrap = [3, "<table><tbody><tr>", "</tr></tbody></table>"]; // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + s + wrap[2]; while ( wrap[0]-- ) div = div.firstChild; // Have to loop through the childNodes here to // prevent a Safari crash with text nodes and /n characters for ( var j = 0; j < div.childNodes.length; j++ ) r.push( div.childNodes[j] ); } else if ( arg.length != undefined && !arg.nodeType ) // Handles Array, jQuery, DOM NodeList collections for ( var n = 0; n < arg.length; n++ ) r.push(arg[n]); else r.push( arg.nodeType ? arg : document.createTextNode(arg.toString()) ); } return r; }, expr: { "": "m[2]== '*'||a.nodeName.toUpperCase()==m[2].toUpperCase()", "#": "a.getAttribute('id')&&a.getAttribute('id')==m[2]", ":": { // Position Checks lt: "i<m[3]-0", gt: "i>m[3]-0", nth: "m[3]-0==i", eq: "m[3]-0==i", first: "i==0", last: "i==r.length-1", even: "i%2==0", odd: "i%2", // Child Checks "nth-child": "jQuery.sibling(a,m[3]).cur", "first-child": "jQuery.sibling(a,0).cur", "last-child": "jQuery.sibling(a,0).last", "only-child": "jQuery.sibling(a).length==1", // Parent Checks parent: "a.childNodes.length", empty: "!a.childNodes.length", // Text Check contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0", // Visibility visible: "a.type!='hidden'&&jQuery.css(a,'display')!='none'&&jQuery.css(a,'visibility')!='hidden'", hidden: "a.type=='hidden'||jQuery.css(a,'display')=='none'||jQuery.css(a,'visibility')=='hidden'", // Form attributes enabled: "!a.disabled", disabled: "a.disabled", checked: "a.checked", selected: "a.selected || jQuery.attr(a, 'selected')", // Form elements text: "a.type=='text'", radio: "a.type=='radio'", checkbox: "a.type=='checkbox'", file: "a.type=='file'", password: "a.type=='password'", submit: "a.type=='submit'", image: "a.type=='image'", reset: "a.type=='reset'", button: "a.type=='button'", input: "a.nodeName.toLowerCase().match(/input|select|textarea|button/)" }, ".": "jQuery.className.has(a,m[2])", "@": { "=": "z==m[4]", "!=": "z!=m[4]", "^=": "z && !z.indexOf(m[4])", "$=": "z && z.substr(z.length - m[4].length,m[4].length)==m[4]", "*=": "z && z.indexOf(m[4])>=0", "": "z" }, "[": "jQuery.find(m[2],a).length" }, token: [ "\\.\\.|/\\.\\.", "a.parentNode", ">|/", "jQuery.sibling(a.firstChild)", "\\+", "jQuery.sibling(a).next", "~", function(a){ var r = []; var s = jQuery.sibling(a); if ( s.n > 0 ) for ( var i = s.n; i < s.length; i++ ) r.push( s[i] ); return r; } ], /** * * @test t( "Element Selector", "div", ["main","foo"] ); * t( "Element Selector", "body", ["body"] ); * t( "Element Selector", "html", ["html"] ); * ok( $("*").size() >= 30, "Element Selector" ); * t( "Parent Element", "div div", ["foo"] ); * * t( "ID Selector", "#body", ["body"] ); * t( "ID Selector w/ Element", "body#body", ["body"] ); * t( "ID Selector w/ Element", "ul#first", [] ); * * t( "Class Selector", ".blog", ["mark","simon"] ); * t( "Class Selector", ".blog.link", ["simon"] ); * t( "Class Selector w/ Element", "a.blog", ["mark","simon"] ); * t( "Parent Class Selector", "p .blog", ["mark","simon"] ); * * t( "Comma Support", "a.blog, div", ["mark","simon","main","foo"] ); * t( "Comma Support", "a.blog , div", ["mark","simon","main","foo"] ); * t( "Comma Support", "a.blog ,div", ["mark","simon","main","foo"] ); * t( "Comma Support", "a.blog,div", ["mark","simon","main","foo"] ); * * t( "Child", "p > a", ["simon1","google","groups","mark","yahoo","simon"] ); * t( "Child", "p> a", ["simon1","google","groups","mark","yahoo","simon"] ); * t( "Child", "p >a", ["simon1","google","groups","mark","yahoo","simon"] ); * t( "Child", "p>a", ["simon1","google","groups","mark","yahoo","simon"] ); * t( "Child w/ Class", "p > a.blog", ["mark","simon"] ); * t( "All Children", "code > *", ["anchor1","anchor2"] ); * t( "All Grandchildren", "p > * > *", ["anchor1","anchor2"] ); * t( "Adjacent", "a + a", ["groups"] ); * t( "Adjacent", "a +a", ["groups"] ); * t( "Adjacent", "a+ a", ["groups"] ); * t( "Adjacent", "a+a", ["groups"] ); * t( "Adjacent", "p + p", ["ap","en","sap"] ); * t( "Comma, Child, and Adjacent", "a + a, code > a", ["groups","anchor1","anchor2"] ); * t( "First Child", "p:first-child", ["firstp","sndp"] ); * t( "Attribute Exists", "a[@title]", ["google"] ); * t( "Attribute Exists", "*[@title]", ["google"] ); * t( "Attribute Exists", "[@title]", ["google"] ); * * t( "Non-existing part of attribute", "[@name*=bla]", [] ); * t( "Non-existing start of attribute", "[@name^=bla]", [] ); * t( "Non-existing end of attribute", "[@name$=bla]", [] ); * * t( "Attribute Equals", "a[@rel='bookmark']", ["simon1"] ); * t( "Attribute Equals", 'a[@rel="bookmark"]', ["simon1"] ); * t( "Attribute Equals", "a[@rel=bookmark]", ["simon1"] ); * t( "Multiple Attribute Equals", "input[@type='hidden'],input[@type='radio']", ["hidden1","radio1","radio2"] ); * t( "Multiple Attribute Equals", "input[@type=\"hidden\"],input[@type='radio']", ["hidden1","radio1","radio2"] ); * t( "Multiple Attribute Equals", "input[@type=hidden],input[@type=radio]", ["hidden1","radio1","radio2"] ); * * t( "Attribute Begins With", "a[@href ^= 'http://www']", ["google","yahoo"] ); * t( "Attribute Ends With", "a[@href $= 'org/']", ["mark"] ); * t( "Attribute Contains", "a[@href *= 'google']", ["google","groups"] ); * t( "First Child", "p:first-child", ["firstp","sndp"] ); * t( "Last Child", "p:last-child", ["sap"] ); * t( "Only Child", "a:only-child", ["simon1","anchor1","yahoo","anchor2"] ); * t( "Empty", "ul:empty", ["firstUL"] ); * t( "Enabled UI Element", "input:enabled", ["text1","radio1","radio2","check1","check2","hidden1","hidden2","name"] ); * t( "Disabled UI Element", "input:disabled", ["text2"] ); * t( "Checked UI Element", "input:checked", ["radio2","check1"] ); * t( "Selected Option Element", "option:selected", ["option1a","option2d","option3b","option3c"] ); * t( "Text Contains", "a:contains('Google')", ["google","groups"] ); * t( "Text Contains", "a:contains('Google Groups')", ["groups"] ); * t( "Element Preceded By", "p ~ div", ["foo"] ); * t( "Not", "a.blog:not(.link)", ["mark"] ); * * ok( jQuery.find("//*").length >= 30, "All Elements (//*)" ); * t( "All Div Elements", "//div", ["main","foo"] ); * t( "Absolute Path", "/html/body", ["body"] ); * t( "Absolute Path w/ *", "/* /body", ["body"] ); * t( "Long Absolute Path", "/html/body/dl/div/div/p", ["sndp","en","sap"] ); * t( "Absolute and Relative Paths", "/html//div", ["main","foo"] ); * t( "All Children, Explicit", "//code/*", ["anchor1","anchor2"] ); * t( "All Children, Implicit", "//code/", ["anchor1","anchor2"] ); * t( "Attribute Exists", "//a[@title]", ["google"] ); * t( "Attribute Equals", "//a[@rel='bookmark']", ["simon1"] ); * t( "Parent Axis", "//p/..", ["main","foo"] ); * t( "Sibling Axis", "//p/../", ["firstp","ap","foo","first","firstUL","empty","form","sndp","en","sap"] ); * t( "Sibling Axis", "//p/../*", ["firstp","ap","foo","first","firstUL","empty","form","sndp","en","sap"] ); * t( "Has Children", "//p[a]", ["firstp","ap","en","sap"] ); * * t( "nth Element", "p:nth(1)", ["ap"] ); * t( "First Element", "p:first", ["firstp"] ); * t( "Last Element", "p:last", ["first"] ); * t( "Even Elements", "p:even", ["firstp","sndp","sap"] ); * t( "Odd Elements", "p:odd", ["ap","en","first"] ); * t( "Position Equals", "p:eq(1)", ["ap"] ); * t( "Position Greater Than", "p:gt(0)", ["ap","sndp","en","sap","first"] ); * t( "Position Less Than", "p:lt(3)", ["firstp","ap","sndp"] ); * t( "Is A Parent", "p:parent", ["firstp","ap","sndp","en","sap","first"] ); * t( "Is Visible", "input:visible", ["text1","text2","radio1","radio2","check1","check2","name"] ); * t( "Is Hidden", "input:hidden", ["hidden1","hidden2"] ); * * t( "Grouped Form Elements", "input[@name='foo[bar]']", ["hidden2"] ); * * t( "All Children of ID", "#foo/*", ["sndp", "en", "sap"] ); * t( "All Children of ID with no children", "#firstUL/*", [] ); * * t( "Form element :input", ":input", ["text1", "text2", "radio1", "radio2", "check1", "check2", "hidden1", "hidden2", "name", "button", "area1", "select1", "select2", "select3"] ); * t( "Form element :radio", ":radio", ["radio1", "radio2"] ); * t( "Form element :checkbox", ":checkbox", ["check1", "check2"] ); * t( "Form element :text", ":text", ["text1", "text2", "hidden2", "name"] ); * t( "Form element :radio:checked", ":radio:checked", ["radio2"] ); * t( "Form element :checkbox:checked", ":checkbox:checked", ["check1"] ); * t( "Form element :checkbox:checked, :radio:checked", ":checkbox:checked, :radio:checked", ["check1", "radio2"] ); * * t( ":not() Existing attribute", "select:not([@multiple])", ["select1", "select2"]); * t( ":not() Equals attribute", "select:not([@name=select1])", ["select2", "select3"]); * t( ":not() Equals quoted attribute", "select:not([@name='select1'])", ["select2", "select3"]); * * @name $.find * @type Array<Element> * @private * @cat Core */ find: function( t, context ) { // Make sure that the context is a DOM Element if ( context && context.nodeType == undefined ) context = null; // Set the correct context (if none is provided) context = context || jQuery.context || document; if ( t.constructor != String ) return [t]; if ( !t.indexOf("//") ) { context = context.documentElement; t = t.substr(2,t.length); } else if ( !t.indexOf("/") ) { context = context.documentElement; t = t.substr(1,t.length); // FIX Assume the root element is right :( if ( t.indexOf("/") >= 1 ) t = t.substr(t.indexOf("/"),t.length); } var ret = [context]; var done = []; var last = null; while ( t.length > 0 && last != t ) { var r = []; last = t; t = jQuery.trim(t).replace( /^\/\//i, "" ); var foundToken = false; for ( var i = 0; i < jQuery.token.length; i += 2 ) { if ( foundToken ) continue; var re = new RegExp("^(" + jQuery.token[i] + ")"); var m = re.exec(t); if ( m ) { r = ret = jQuery.map( ret, jQuery.token[i+1] ); t = jQuery.trim( t.replace( re, "" ) ); foundToken = true; } } if ( !foundToken ) { if ( !t.indexOf(",") || !t.indexOf("|") ) { if ( ret[0] == context ) ret.shift(); done = jQuery.merge( done, ret ); r = ret = [context]; t = " " + t.substr(1,t.length); } else { var re2 = /^([#.]?)([a-z0-9\\*_-]*)/i; var m = re2.exec(t); if ( m[1] == "#" ) { // Ummm, should make this work in all XML docs var oid = document.getElementById(m[2]); r = ret = oid ? [oid] : []; t = t.replace( re2, "" ); } else { if ( !m[2] || m[1] == "." ) m[2] = "*"; for ( var i = 0; i < ret.length; i++ ) r = jQuery.merge( r, m[2] == "*" ? jQuery.getAll(ret[i]) : ret[i].getElementsByTagName(m[2]) ); } } } if ( t ) { var val = jQuery.filter(t,r); ret = r = val.r; t = jQuery.trim(val.t); } } if ( ret && ret[0] == context ) ret.shift(); done = jQuery.merge( done, ret ); return done; }, getAll: function(o,r) { r = r || []; var s = o.childNodes; for ( var i = 0; i < s.length; i++ ) if ( s[i].nodeType == 1 ) { r.push( s[i] ); jQuery.getAll( s[i], r ); } return r; }, attr: function(elem, name, value){ var fix = { "for": "htmlFor", "class": "className", "float": jQuery.browser.msie ? "styleFloat" : "cssFloat", cssFloat: jQuery.browser.msie ? "styleFloat" : "cssFloat", innerHTML: "innerHTML", className: "className", value: "value", disabled: "disabled", checked: "checked", readonly: "readOnly" }; // IE actually uses filters for opacity ... elem is actually elem.style if (name == "opacity" && jQuery.browser.msie && value != undefined) { // IE has trouble with opacity if it does not have layout // Would prefer to check element.hasLayout first but don't have access to the element here elem['zoom'] = 1; if (value == 1) // Remove filter to avoid more IE weirdness return elem["filter"] = elem["filter"].replace(/alpha\([^\)]*\)/gi,""); else return elem["filter"] = elem["filter"].replace(/alpha\([^\)]*\)/gi,"") + "alpha(opacity=" + value * 100 + ")"; } else if (name == "opacity" && jQuery.browser.msie) { return elem["filter"] ? parseFloat( elem["filter"].match(/alpha\(opacity=(.*)\)/)[1] )/100 : 1; } // Mozilla doesn't play well with opacity 1 if (name == "opacity" && jQuery.browser.mozilla && value == 1) value = 0.9999; if ( fix[name] ) { if ( value != undefined ) elem[fix[name]] = value; return elem[fix[name]]; } else if( value == undefined && jQuery.browser.msie && elem.nodeName && elem.nodeName.toUpperCase() == 'FORM' && (name == 'action' || name == 'method') ) { return elem.getAttributeNode(name).nodeValue; } else if ( elem.getAttribute != undefined && elem.tagName ) { // IE elem.getAttribute passes even for style if ( value != undefined ) elem.setAttribute( name, value ); return elem.getAttribute( name ); } else { name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();}); if ( value != undefined ) elem[name] = value; return elem[name]; } }, // The regular expressions that power the parsing engine parse: [ // Match: [@value='test'], [@foo] "\\[ *(@)S *([!*$^=]*) *('?\"?)(.*?)\\4 *\\]", // Match: [div], [div p] "(\\[)\s*(.*?)\s*\\]", // Match: :contains('foo') "(:)S\\(\"?'?([^\\)]*?)\"?'?\\)", // Match: :even, :last-chlid "([:.#]*)S" ], filter: function(t,r,not) { // Figure out if we're doing regular, or inverse, filtering var g = not !== false ? jQuery.grep : function(a,f) {return jQuery.grep(a,f,true);}; while ( t && /^[a-z[({<*:.#]/i.test(t) ) { var p = jQuery.parse; for ( var i = 0; i < p.length; i++ ) { // Look for, and replace, string-like sequences // and finally build a regexp out of it var re = new RegExp( "^" + p[i].replace("S", "([a-z*_-][a-z0-9_-]*)"), "i" ); var m = re.exec( t ); if ( m ) { // Re-organize the first match if ( !i ) m = ["",m[1], m[3], m[2], m[5]]; // Remove what we just matched t = t.replace( re, "" ); break; } } // :not() is a special case that can be optimized by // keeping it out of the expression list if ( m[1] == ":" && m[2] == "not" ) r = jQuery.filter(m[3],r,false).r; // Otherwise, find the expression to execute else { var f = jQuery.expr[m[1]]; if ( f.constructor != String ) f = jQuery.expr[m[1]][m[2]]; // Build a custom macro to enclose it eval("f = function(a,i){" + ( m[1] == "@" ? "z=jQuery.attr(a,m[3]);" : "" ) + "return " + f + "}"); // Execute it against the current filter r = g( r, f ); } } // Return an array of filtered elements (r) // and the modified expression string (t) return { r: r, t: t }; }, /** * Remove the whitespace from the beginning and end of a string. * * @example $.trim(" hello, how are you? "); * @result "hello, how are you?" * * @name $.trim * @type String * @param String str The string to trim. * @cat Javascript */ trim: function(t){ return t.replace(/^\s+|\s+$/g, ""); }, /** * All ancestors of a given element. * * @private * @name $.parents * @type Array<Element> * @param Element elem The element to find the ancestors of. * @cat DOM/Traversing */ parents: function( elem ){ var matched = []; var cur = elem.parentNode; while ( cur && cur != document ) { matched.push( cur ); cur = cur.parentNode; } return matched; }, /** * All elements on a specified axis. * * @private * @name $.sibling * @type Array * @param Element elem The element to find all the siblings of (including itself). * @cat DOM/Traversing */ sibling: function(elem, pos, not) { var elems = []; if(elem) { var siblings = elem.parentNode.childNodes; for ( var i = 0; i < siblings.length; i++ ) { if ( not === true && siblings[i] == elem ) continue; if ( siblings[i].nodeType == 1 ) elems.push( siblings[i] ); if ( siblings[i] == elem ) elems.n = elems.length - 1; } } return jQuery.extend( elems, { last: elems.n == elems.length - 1, cur: pos == "even" && elems.n % 2 == 0 || pos == "odd" && elems.n % 2 || elems[pos] == elem, prev: elems[elems.n - 1], next: elems[elems.n + 1] }); }, /** * Merge two arrays together, removing all duplicates. The final order * or the new array is: All the results from the first array, followed * by the unique results from the second array. * * @example $.merge( [0,1,2], [2,3,4] ) * @result [0,1,2,3,4] * * @example $.merge( [3,2,1], [4,3,2] ) * @result [3,2,1,4] * * @name $.merge * @type Array * @param Array first The first array to merge. * @param Array second The second array to merge. * @cat Javascript */ merge: function(first, second) { var result = []; // Move b over to the new array (this helps to avoid // StaticNodeList instances) for ( var k = 0; k < first.length; k++ ) result[k] = first[k]; // Now check for duplicates between a and b and only // add the unique items for ( var i = 0; i < second.length; i++ ) { var noCollision = true; // The collision-checking process for ( var j = 0; j < first.length; j++ ) if ( second[i] == first[j] ) noCollision = false; // If the item is unique, add it if ( noCollision ) result.push( second[i] ); } return result; }, /** * Filter items out of an array, by using a filter function. * The specified function will be passed two arguments: The * current array item and the index of the item in the array. The * function should return 'true' if you wish to keep the item in * the array, false if it should be removed. * * @example $.grep( [0,1,2], function(i){ * return i > 0; * }); * @result [1, 2] * * @name $.grep * @type Array * @param Array array The Array to find items in. * @param Function fn The function to process each item against. * @param Boolean inv Invert the selection - select the opposite of the function. * @cat Javascript */ grep: function(elems, fn, inv) { // If a string is passed in for the function, make a function // for it (a handy shortcut) if ( fn.constructor == String ) fn = new Function("a","i","return " + fn); var result = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0; i < elems.length; i++ ) if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) ) result.push( elems[i] ); return result; }, /** * Translate all items in an array to another array of items. * The translation function that is provided to this method is * called for each item in the array and is passed one argument: * The item to be translated. The function can then return: * The translated value, 'null' (to remove the item), or * an array of values - which will be flattened into the full array. * * @example $.map( [0,1,2], function(i){ * return i + 4; * }); * @result [4, 5, 6] * * @example $.map( [0,1,2], function(i){ * return i > 0 ? i + 1 : null; * }); * @result [2, 3] * * @example $.map( [0,1,2], function(i){ * return [ i, i + 1 ]; * }); * @result [0, 1, 1, 2, 2, 3] * * @name $.map * @type Array * @param Array array The Array to translate. * @param Function fn The function to process each item against. * @cat Javascript */ map: function(elems, fn) { // If a string is passed in for the function, make a function // for it (a handy shortcut) if ( fn.constructor == String ) fn = new Function("a","return " + fn); var result = []; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0; i < elems.length; i++ ) { var val = fn(elems[i],i); if ( val !== null && val != undefined ) { if ( val.constructor != Array ) val = [val]; result = jQuery.merge( result, val ); } } return result; }, /* * A number of helper functions used for managing events. * Many of the ideas behind this code orignated from Dean Edwards' addEvent library. */ event: { // Bind an event to an element // Original by Dean Edwards add: function(element, type, handler) { // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.browser.msie && element.setInterval != undefined ) element = window; // Make sure that the function being executed has a unique ID if ( !handler.guid ) handler.guid = this.guid++; // Init the element's event structure if (!element.events) element.events = {}; // Get the current list of functions bound to this event var handlers = element.events[type]; // If it hasn't been initialized yet if (!handlers) { // Init the event handler queue handlers = element.events[type] = {}; // Remember an existing handler, if it's already there if (element["on" + type]) handlers[0] = element["on" + type]; } // Add the function to the element's handler list handlers[handler.guid] = handler; // And bind the global event handler to the element element["on" + type] = this.handle; // Remember the function in a global list (for triggering) if (!this.global[type]) this.global[type] = []; this.global[type].push( element ); }, guid: 1, global: {}, // Detach an event or set of events from an element remove: function(element, type, handler) { if (element.events) if (type && element.events[type]) if ( handler ) delete element.events[type][handler.guid]; else for ( var i in element.events[type] ) delete element.events[type][i]; else for ( var j in element.events ) this.remove( element, j ); }, trigger: function(type,data,element) { // Touch up the incoming data data = data || []; // Handle a global trigger if ( !element ) { var g = this.global[type]; if ( g ) for ( var i = 0; i < g.length; i++ ) this.trigger( type, data, g[i] ); // Handle triggering a single element } else if ( element["on" + type] ) { // Pass along a fake event data.unshift( this.fix({ type: type, target: element }) ); // Trigger the event element["on" + type].apply( element, data ); } }, handle: function(event) { if ( typeof jQuery == "undefined" ) return false; event = event || jQuery.event.fix( window.event ); // If no correct event was found, fail if ( !event ) return false; var returnValue = true; var c = this.events[event.type]; var args = [].slice.call( arguments, 1 ); args.unshift( event ); for ( var j in c ) { if ( c[j].apply( this, args ) === false ) { event.preventDefault(); event.stopPropagation(); returnValue = false; } } return returnValue; }, fix: function(event) { // check IE if(jQuery.browser.msie) { // get real event from window.event event = window.event; // fix target property event.target = event.srcElement; // check safari and if target is a textnode } else if(jQuery.browser.safari && event.target.nodeType == 3) { // target is readonly, clone the event object event = jQuery.extend({}, event); // get parentnode from textnode event.target = event.target.parentNode; } // fix preventDefault and stopPropagation event.preventDefault = function() { this.returnValue = false; }; event.stopPropagation = function() { this.cancelBubble = true; }; return event; } } }); /** * Contains flags for the useragent, read from navigator.userAgent. * Available flags are: safari, opera, msie, mozilla * This property is available before the DOM is ready, therefore you can * use it to add ready events only for certain browsers. * * See <a href="http://davecardwell.co.uk/geekery/javascript/jquery/jqbrowser/"> * jQBrowser plugin</a> for advanced browser detection: * * @example $.browser.msie * @desc returns true if the current useragent is some version of microsoft's internet explorer * * @example if($.browser.safari) { $( function() { alert("this is safari!"); } ); } * @desc Alerts "this is safari!" only for safari browsers * * @name $.browser * @type Boolean * @cat Javascript */ new function() { var b = navigator.userAgent.toLowerCase(); // Figure out what browser is being used jQuery.browser = { safari: /webkit/.test(b), opera: /opera/.test(b), msie: /msie/.test(b) && !/opera/.test(b), mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b) }; // Check to see if the W3C box model is being used jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat"; }; jQuery.macros = { to: { /** * Append all of the matched elements to another, specified, set of elements. * This operation is, essentially, the reverse of doing a regular * $(A).append(B), in that instead of appending B to A, you're appending * A to B. * * @example $("p").appendTo("#foo"); * @before <p>I would like to say: </p><div id="foo"></div> * @result <div id="foo"><p>I would like to say: </p></div> * * @name appendTo * @type jQuery * @param String expr A jQuery expression of elements to match. * @cat DOM/Manipulation */ appendTo: "append", /** * Prepend all of the matched elements to another, specified, set of elements. * This operation is, essentially, the reverse of doing a regular * $(A).prepend(B), in that instead of prepending B to A, you're prepending * A to B. * * @example $("p").prependTo("#foo"); * @before <p>I would like to say: </p><div id="foo"><b>Hello</b></div> * @result <div id="foo"><p>I would like to say: </p><b>Hello</b></div> * * @name prependTo * @type jQuery * @param String expr A jQuery expression of elements to match. * @cat DOM/Manipulation */ prependTo: "prepend", /** * Insert all of the matched elements before another, specified, set of elements. * This operation is, essentially, the reverse of doing a regular * $(A).before(B), in that instead of inserting B before A, you're inserting * A before B. * * @example $("p").insertBefore("#foo"); * @before <div id="foo">Hello</div><p>I would like to say: </p> * @result <p>I would like to say: </p><div id="foo">Hello</div> * * @name insertBefore * @type jQuery * @param String expr A jQuery expression of elements to match. * @cat DOM/Manipulation */ insertBefore: "before", /** * Insert all of the matched elements after another, specified, set of elements. * This operation is, essentially, the reverse of doing a regular * $(A).after(B), in that instead of inserting B after A, you're inserting * A after B. * * @example $("p").insertAfter("#foo"); * @before <p>I would like to say: </p><div id="foo">Hello</div> * @result <div id="foo">Hello</div><p>I would like to say: </p> * * @name insertAfter * @type jQuery * @param String expr A jQuery expression of elements to match. * @cat DOM/Manipulation */ insertAfter: "after" }, /** * Get the current CSS width of the first matched element. * * @example $("p").width(); * @before <p>This is just a test.</p> * @result "300px" * * @name width * @type String * @cat CSS */ /** * Set the CSS width of every matched element. Be sure to include * the "px" (or other unit of measurement) after the number that you * specify, otherwise you might get strange results. * * @example $("p").width("20px"); * @before <p>This is just a test.</p> * @result <p style="width:20px;">This is just a test.</p> * * @name width * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS height of the first matched element. * * @example $("p").height(); * @before <p>This is just a test.</p> * @result "14px" * * @name height * @type String * @cat CSS */ /** * Set the CSS height of every matched element. Be sure to include * the "px" (or other unit of measurement) after the number that you * specify, otherwise you might get strange results. * * @example $("p").height("20px"); * @before <p>This is just a test.</p> * @result <p style="height:20px;">This is just a test.</p> * * @name height * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS top of the first matched element. * * @example $("p").top(); * @before <p>This is just a test.</p> * @result "0px" * * @name top * @type String * @cat CSS */ /** * Set the CSS top of every matched element. Be sure to include * the "px" (or other unit of measurement) after the number that you * specify, otherwise you might get strange results. * * @example $("p").top("20px"); * @before <p>This is just a test.</p> * @result <p style="top:20px;">This is just a test.</p> * * @name top * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS left of the first matched element. * * @example $("p").left(); * @before <p>This is just a test.</p> * @result "0px" * * @name left * @type String * @cat CSS */ /** * Set the CSS left of every matched element. Be sure to include * the "px" (or other unit of measurement) after the number that you * specify, otherwise you might get strange results. * * @example $("p").left("20px"); * @before <p>This is just a test.</p> * @result <p style="left:20px;">This is just a test.</p> * * @name left * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS position of the first matched element. * * @example $("p").position(); * @before <p>This is just a test.</p> * @result "static" * * @name position * @type String * @cat CSS */ /** * Set the CSS position of every matched element. * * @example $("p").position("relative"); * @before <p>This is just a test.</p> * @result <p style="position:relative;">This is just a test.</p> * * @name position * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS float of the first matched element. * * @example $("p").float(); * @before <p>This is just a test.</p> * @result "none" * * @name float * @type String * @cat CSS */ /** * Set the CSS float of every matched element. * * @example $("p").float("left"); * @before <p>This is just a test.</p> * @result <p style="float:left;">This is just a test.</p> * * @name float * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS overflow of the first matched element. * * @example $("p").overflow(); * @before <p>This is just a test.</p> * @result "none" * * @name overflow * @type String * @cat CSS */ /** * Set the CSS overflow of every matched element. * * @example $("p").overflow("auto"); * @before <p>This is just a test.</p> * @result <p style="overflow:auto;">This is just a test.</p> * * @name overflow * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS color of the first matched element. * * @example $("p").color(); * @before <p>This is just a test.</p> * @result "black" * * @name color * @type String * @cat CSS */ /** * Set the CSS color of every matched element. * * @example $("p").color("blue"); * @before <p>This is just a test.</p> * @result <p style="color:blue;">This is just a test.</p> * * @name color * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS background of the first matched element. * * @example $("p").background(); * @before <p style="background:blue;">This is just a test.</p> * @result "blue" * * @name background * @type String * @cat CSS */ /** * Set the CSS background of every matched element. * * @example $("p").background("blue"); * @before <p>This is just a test.</p> * @result <p style="background:blue;">This is just a test.</p> * * @name background * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ css: "width,height,top,left,position,float,overflow,color,background".split(","), /** * Reduce the set of matched elements to a single element. * The position of the element in the set of matched elements * starts at 0 and goes to length - 1. * * @example $("p").eq(1) * @before <p>This is just a test.</p><p>So is this</p> * @result [ <p>So is this</p> ] * * @name eq * @type jQuery * @param Number pos The index of the element that you wish to limit to. * @cat Core */ /** * Reduce the set of matched elements to all elements before a given position. * The position of the element in the set of matched elements * starts at 0 and goes to length - 1. * * @example $("p").lt(1) * @before <p>This is just a test.</p><p>So is this</p> * @result [ <p>This is just a test.</p> ] * * @name lt * @type jQuery * @param Number pos Reduce the set to all elements below this position. * @cat Core */ /** * Reduce the set of matched elements to all elements after a given position. * The position of the element in the set of matched elements * starts at 0 and goes to length - 1. * * @example $("p").gt(0) * @before <p>This is just a test.</p><p>So is this</p> * @result [ <p>So is this</p> ] * * @name gt * @type jQuery * @param Number pos Reduce the set to all elements after this position. * @cat Core */ /** * Filter the set of elements to those that contain the specified text. * * @example $("p").contains("test") * @before <p>This is just a test.</p><p>So is this</p> * @result [ <p>This is just a test.</p> ] * * @name contains * @type jQuery * @param String str The string that will be contained within the text of an element. * @cat DOM/Traversing */ filter: [ "eq", "lt", "gt", "contains" ], attr: { /** * Get the current value of the first matched element. * * @example $("input").val(); * @before <input type="text" value="some text"/> * @result "some text" * * @test ok( $("#text1").val() == "Test", "Check for value of input element" ); * ok( !$("#text1").val() == "", "Check for value of input element" ); * * @name val * @type String * @cat DOM/Attributes */ /** * Set the value of every matched element. * * @example $("input").val("test"); * @before <input type="text" value="some text"/> * @result <input type="text" value="test"/> * * @test document.getElementById('text1').value = "bla"; * ok( $("#text1").val() == "bla", "Check for modified value of input element" ); * $("#text1").val('test'); * ok ( document.getElementById('text1').value == "test", "Check for modified (via val(String)) value of input element" ); * * @name val * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ val: "value", /** * Get the html contents of the first matched element. * * @example $("div").html(); * @before <div><input/></div> * @result <input/> * * @name html * @type String * @cat DOM/Attributes */ /** * Set the html contents of every matched element. * * @example $("div").html("<b>new stuff</b>"); * @before <div><input/></div> * @result <div><b>new stuff</b></div> * * @test var div = $("div"); * div.html("<b>test</b>"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).childNodes.length == 0 ) pass = false; * } * ok( pass, "Set HTML" ); * * @name html * @type jQuery * @param String val Set the html contents to the specified value. * @cat DOM/Attributes */ html: "innerHTML", /** * Get the current id of the first matched element. * * @example $("input").id(); * @before <input type="text" id="test" value="some text"/> * @result "test" * * @test ok( $(document.getElementById('main')).id() == "main", "Check for id" ); * ok( $("#foo").id() == "foo", "Check for id" ); * ok( !$("head").id(), "Check for id" ); * * @name id * @type String * @cat DOM/Attributes */ /** * Set the id of every matched element. * * @example $("input").id("newid"); * @before <input type="text" id="test" value="some text"/> * @result <input type="text" id="newid" value="some text"/> * * @name id * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ id: null, /** * Get the current title of the first matched element. * * @example $("img").title(); * @before <img src="test.jpg" title="my image"/> * @result "my image" * * @test ok( $(document.getElementById('google')).title() == "Google!", "Check for title" ); * ok( !$("#yahoo").title(), "Check for title" ); * * @name title * @type String * @cat DOM/Attributes */ /** * Set the title of every matched element. * * @example $("img").title("new title"); * @before <img src="test.jpg" title="my image"/> * @result <img src="test.jpg" title="new image"/> * * @name title * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ title: null, /** * Get the current name of the first matched element. * * @example $("input").name(); * @before <input type="text" name="username"/> * @result "username" * * @test ok( $(document.getElementById('text1')).name() == "action", "Check for name" ); * ok( $("#hidden1").name() == "hidden", "Check for name" ); * ok( !$("#area1").name(), "Check for name" ); * * @name name * @type String * @cat DOM/Attributes */ /** * Set the name of every matched element. * * @example $("input").name("user"); * @before <input type="text" name="username"/> * @result <input type="text" name="user"/> * * @name name * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ name: null, /** * Get the current href of the first matched element. * * @example $("a").href(); * @before <a href="test.html">my link</a> * @result "test.html" * * @name href * @type String * @cat DOM/Attributes */ /** * Set the href of every matched element. * * @example $("a").href("test2.html"); * @before <a href="test.html">my link</a> * @result <a href="test2.html">my link</a> * * @name href * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ href: null, /** * Get the current src of the first matched element. * * @example $("img").src(); * @before <img src="test.jpg" title="my image"/> * @result "test.jpg" * * @name src * @type String * @cat DOM/Attributes */ /** * Set the src of every matched element. * * @example $("img").src("test2.jpg"); * @before <img src="test.jpg" title="my image"/> * @result <img src="test2.jpg" title="my image"/> * * @name src * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ src: null, /** * Get the current rel of the first matched element. * * @example $("a").rel(); * @before <a href="test.html" rel="nofollow">my link</a> * @result "nofollow" * * @name rel * @type String * @cat DOM/Attributes */ /** * Set the rel of every matched element. * * @example $("a").rel("nofollow"); * @before <a href="test.html">my link</a> * @result <a href="test.html" rel="nofollow">my link</a> * * @name rel * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ rel: null }, axis: { /** * Get a set of elements containing the unique parents of the matched * set of elements. * * @example $("p").parent() * @before <div><p>Hello</p><p>Hello</p></div> * @result [ <div><p>Hello</p><p>Hello</p></div> ] * * @name parent * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique parents of the matched * set of elements, and filtered by an expression. * * @example $("p").parent(".selected") * @before <div><p>Hello</p></div><div class="selected"><p>Hello Again</p></div> * @result [ <div class="selected"><p>Hello Again</p></div> ] * * @name parent * @type jQuery * @param String expr An expression to filter the parents with * @cat DOM/Traversing */ parent: "a.parentNode", /** * Get a set of elements containing the unique ancestors of the matched * set of elements (except for the root element). * * @example $("span").ancestors() * @before <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html> * @result [ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ] * * @name ancestors * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique ancestors of the matched * set of elements, and filtered by an expression. * * @example $("span").ancestors("p") * @before <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html> * @result [ <p><span>Hello</span></p> ] * * @name ancestors * @type jQuery * @param String expr An expression to filter the ancestors with * @cat DOM/Traversing */ ancestors: jQuery.parents, /** * Get a set of elements containing the unique ancestors of the matched * set of elements (except for the root element). * * @example $("span").ancestors() * @before <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html> * @result [ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ] * * @name parents * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique ancestors of the matched * set of elements, and filtered by an expression. * * @example $("span").ancestors("p") * @before <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html> * @result [ <p><span>Hello</span></p> ] * * @name parents * @type jQuery * @param String expr An expression to filter the ancestors with * @cat DOM/Traversing */ parents: jQuery.parents, /** * Get a set of elements containing the unique next siblings of each of the * matched set of elements. * * It only returns the very next sibling, not all next siblings. * * @example $("p").next() * @before <p>Hello</p><p>Hello Again</p><div><span>And Again</span></div> * @result [ <p>Hello Again</p>, <div><span>And Again</span></div> ] * * @name next * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique next siblings of each of the * matched set of elements, and filtered by an expression. * * It only returns the very next sibling, not all next siblings. * * @example $("p").next(".selected") * @before <p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div> * @result [ <p class="selected">Hello Again</p> ] * * @name next * @type jQuery * @param String expr An expression to filter the next Elements with * @cat DOM/Traversing */ next: "jQuery.sibling(a).next", /** * Get a set of elements containing the unique previous siblings of each of the * matched set of elements. * * It only returns the immediately previous sibling, not all previous siblings. * * @example $("p").prev() * @before <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p> * @result [ <div><span>Hello Again</span></div> ] * * @name prev * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique previous siblings of each of the * matched set of elements, and filtered by an expression. * * It only returns the immediately previous sibling, not all previous siblings. * * @example $("p").prev(".selected") * @before <div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p> * @result [ <div><span>Hello</span></div> ] * * @name prev * @type jQuery * @param String expr An expression to filter the previous Elements with * @cat DOM/Traversing */ prev: "jQuery.sibling(a).prev", /** * Get a set of elements containing all of the unique siblings of each of the * matched set of elements. * * @example $("div").siblings() * @before <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p> * @result [ <p>Hello</p>, <p>And Again</p> ] * * @test isSet( $("#en").siblings().get(), q("sndp", "sap"), "Check for siblings" ); * * @name siblings * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing all of the unique siblings of each of the * matched set of elements, and filtered by an expression. * * @example $("div").siblings(".selected") * @before <div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p> * @result [ <p class="selected">Hello Again</p> ] * * @test isSet( $("#sndp").siblings("[code]").get(), q("sap"), "Check for filtered siblings (has code child element)" ); * isSet( $("#sndp").siblings("[a]").get(), q("en", "sap"), "Check for filtered siblings (has anchor child element)" ); * * @name siblings * @type jQuery * @param String expr An expression to filter the sibling Elements with * @cat DOM/Traversing */ siblings: "jQuery.sibling(a, null, true)", /** * Get a set of elements containing all of the unique children of each of the * matched set of elements. * * @example $("div").children() * @before <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p> * @result [ <span>Hello Again</span> ] * * @test isSet( $("#foo").children().get(), q("sndp", "en", "sap"), "Check for children" ); * * @name children * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing all of the unique children of each of the * matched set of elements, and filtered by an expression. * * @example $("div").children(".selected") * @before <div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div> * @result [ <p class="selected">Hello Again</p> ] * * @test isSet( $("#foo").children("[code]").get(), q("sndp", "sap"), "Check for filtered children" ); * * @name children * @type jQuery * @param String expr An expression to filter the child Elements with * @cat DOM/Traversing */ children: "jQuery.sibling(a.firstChild)" }, each: { /** * Remove an attribute from each of the matched elements. * * @example $("input").removeAttr("disabled") * @before <input disabled="disabled"/> * @result <input/> * * @name removeAttr * @type jQuery * @param String name The name of the attribute to remove. * @cat DOM */ removeAttr: function( key ) { this.removeAttribute( key ); }, /** * Displays each of the set of matched elements if they are hidden. * * @example $("p").show() * @before <p style="display: none">Hello</p> * @result [ <p style="display: block">Hello</p> ] * * @test var pass = true, div = $("div"); * div.show().each(function(){ * if ( this.style.display == "none" ) pass = false; * }); * ok( pass, "Show" ); * * @name show * @type jQuery * @cat Effects */ show: function(){ this.style.display = this.oldblock ? this.oldblock : ""; if ( jQuery.css(this,"display") == "none" ) this.style.display = "block"; }, /** * Hides each of the set of matched elements if they are shown. * * @example $("p").hide() * @before <p>Hello</p> * @result [ <p style="display: none">Hello</p> ] * * var pass = true, div = $("div"); * div.hide().each(function(){ * if ( this.style.display != "none" ) pass = false; * }); * ok( pass, "Hide" ); * * @name hide * @type jQuery * @cat Effects */ hide: function(){ this.oldblock = this.oldblock || jQuery.css(this,"display"); if ( this.oldblock == "none" ) this.oldblock = "block"; this.style.display = "none"; }, /** * Toggles each of the set of matched elements. If they are shown, * toggle makes them hidden. If they are hidden, toggle * makes them shown. * * @example $("p").toggle() * @before <p>Hello</p><p style="display: none">Hello Again</p> * @result [ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ] * * @name toggle * @type jQuery * @cat Effects */ toggle: function(){ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ].apply( jQuery(this), arguments ); }, /** * Adds the specified class to each of the set of matched elements. * * @example $("p").addClass("selected") * @before <p>Hello</p> * @result [ <p class="selected">Hello</p> ] * * @test var div = $("div"); * div.addClass("test"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).className.indexOf("test") == -1 ) pass = false; * } * ok( pass, "Add Class" ); * * @name addClass * @type jQuery * @param String class A CSS class to add to the elements * @cat DOM */ addClass: function(c){ jQuery.className.add(this,c); }, /** * Removes the specified class from the set of matched elements. * * @example $("p").removeClass("selected") * @before <p class="selected">Hello</p> * @result [ <p>Hello</p> ] * * @test var div = $("div").addClass("test"); * div.removeClass("test"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).className.indexOf("test") != -1 ) pass = false; * } * ok( pass, "Remove Class" ); * * reset(); * * var div = $("div").addClass("test").addClass("foo").addClass("bar"); * div.removeClass("test").removeClass("bar").removeClass("foo"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).className.match(/test|bar|foo/) ) pass = false; * } * ok( pass, "Remove multiple classes" ); * * @name removeClass * @type jQuery * @param String class A CSS class to remove from the elements * @cat DOM */ removeClass: function(c){ jQuery.className.remove(this,c); }, /** * Adds the specified class if it is present, removes it if it is * not present. * * @example $("p").toggleClass("selected") * @before <p>Hello</p><p class="selected">Hello Again</p> * @result [ <p class="selected">Hello</p>, <p>Hello Again</p> ] * * @name toggleClass * @type jQuery * @param String class A CSS class with which to toggle the elements * @cat DOM */ toggleClass: function( c ){ jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this,c); }, /** * Removes all matched elements from the DOM. This does NOT remove them from the * jQuery object, allowing you to use the matched elements further. * * @example $("p").remove(); * @before <p>Hello</p> how are <p>you?</p> * @result how are * * @name remove * @type jQuery * @cat DOM/Manipulation */ /** * Removes only elements (out of the list of matched elements) that match * the specified jQuery expression. This does NOT remove them from the * jQuery object, allowing you to use the matched elements further. * * @example $("p").remove(".hello"); * @before <p class="hello">Hello</p> how are <p>you?</p> * @result how are <p>you?</p> * * @name remove * @type jQuery * @param String expr A jQuery expression to filter elements by. * @cat DOM/Manipulation */ remove: function(a){ if ( !a || jQuery.filter( a, [this] ).r ) this.parentNode.removeChild( this ); }, /** * Removes all child nodes from the set of matched elements. * * @example $("p").empty() * @before <p>Hello, <span>Person</span> <a href="#">and person</a></p> * @result [ <p></p> ] * * @name empty * @type jQuery * @cat DOM/Manipulation */ empty: function(){ while ( this.firstChild ) this.removeChild( this.firstChild ); }, /** * Binds a handler to a particular event (like click) for each matched element. * The event handler is passed an event object that you can use to prevent * default behaviour. To stop both default action and event bubbling, your handler * has to return false. * * @example $("p").bind( "click", function() { * alert( $(this).text() ); * } ) * @before <p>Hello</p> * @result alert("Hello") * * @example $("form").bind( "submit", function() { return false; } ) * @desc Cancel a default action and prevent it from bubbling by returning false * from your function. * * @example $("form").bind( "submit", function(event) { * event.preventDefault(); * } ); * @desc Cancel only the default action by using the preventDefault method. * * * @example $("form").bind( "submit", function(event) { * event.stopPropagation(); * } ) * @desc Stop only an event from bubbling by using the stopPropagation method. * * @name bind * @type jQuery * @param String type An event type * @param Function fn A function to bind to the event on each of the set of matched elements * @cat Events */ bind: function( type, fn ) { if ( fn.constructor == String ) fn = new Function("e", ( !fn.indexOf(".") ? "jQuery(this)" : "return " ) + fn); jQuery.event.add( this, type, fn ); }, /** * The opposite of bind, removes a bound event from each of the matched * elements. You must pass the identical function that was used in the original * bind method. * * @example $("p").unbind( "click", function() { alert("Hello"); } ) * @before <p onclick="alert('Hello');">Hello</p> * @result [ <p>Hello</p> ] * * @name unbind * @type jQuery * @param String type An event type * @param Function fn A function to unbind from the event on each of the set of matched elements * @cat Events */ /** * Removes all bound events of a particular type from each of the matched * elements. * * @example $("p").unbind( "click" ) * @before <p onclick="alert('Hello');">Hello</p> * @result [ <p>Hello</p> ] * * @name unbind * @type jQuery * @param String type An event type * @cat Events */ /** * Removes all bound events from each of the matched elements. * * @example $("p").unbind() * @before <p onclick="alert('Hello');">Hello</p> * @result [ <p>Hello</p> ] * * @name unbind * @type jQuery * @cat Events */ unbind: function( type, fn ) { jQuery.event.remove( this, type, fn ); }, /** * Trigger a type of event on every matched element. * * @example $("p").trigger("click") * @before <p click="alert('hello')">Hello</p> * @result alert('hello') * * @name trigger * @type jQuery * @param String type An event type to trigger. * @cat Events */ trigger: function( type, data ) { jQuery.event.trigger( type, data, this ); } } }; jQuery.init();
src/jquery/jquery.js
/* * jQuery @VERSION - New Wave Javascript * * Copyright (c) 2006 John Resig (jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Date$ * $Rev$ */ // Global undefined variable window.undefined = window.undefined; /** * Create a new jQuery Object * * @test ok( Array.prototype.push, "Array.push()" ); * ok( Function.prototype.apply, "Function.apply()" ); * ok( document.getElementById, "getElementById" ); * ok( document.getElementsByTagName, "getElementsByTagName" ); * ok( RegExp, "RegExp" ); * ok( jQuery, "jQuery" ); * ok( $, "$()" ); * * @constructor * @private * @name jQuery * @cat Core */ var jQuery = function(a,c) { // Shortcut for document ready (because $(document).each() is silly) if ( a && typeof a == "function" && jQuery.fn.ready ) return jQuery(document).ready(a); // Make sure that a selection was provided a = a || jQuery.context || document; // Watch for when a jQuery object is passed as the selector if ( a.jquery ) return jQuery( jQuery.merge( a, [] ) ); // Watch for when a jQuery object is passed at the context if ( c && c.jquery ) return jQuery( c ).find(a); // If the context is global, return a new object if ( window == this ) return new jQuery(a,c); // Handle HTML strings if ( a.constructor == String ) { var m = /^[^<]*(<.+>)[^>]*$/.exec(a); if ( m ) a = jQuery.clean( [ m[1] ] ); } // Watch for when an array is passed in this.get( a.constructor == Array || a.length && !a.nodeType && a[0] != undefined && a[0].nodeType ? // Assume that it is an array of DOM Elements jQuery.merge( a, [] ) : // Find the matching elements and save them for later jQuery.find( a, c ) ); // See if an extra function was provided var fn = arguments[ arguments.length - 1 ]; // If so, execute it in context if ( fn && typeof fn == "function" ) this.each(fn); return this; }; // Map over the $ in case of overwrite if ( typeof $ != "undefined" ) jQuery._$ = $; /** * This function accepts a string containing a CSS selector, * basic XPath, or raw HTML, which is then used to match a set of elements. * The HTML string is different from the traditional selectors in that * it creates the DOM elements representing that HTML string, on the fly, * to be (assumedly) inserted into the document later. * * The core functionality of jQuery centers around this function. * Everything in jQuery is based upon this, or uses this in some way. * The most basic use of this function is to pass in an expression * (usually consisting of CSS or XPath), which then finds all matching * elements and remembers them for later use. * * By default, $() looks for DOM elements within the context of the * current HTML document. * * @example $("div > p") * @desc This finds all p elements that are children of a div element. * @before <p>one</p> <div><p>two</p></div> <p>three</p> * @result [ <p>two</p> ] * * @example $("<div><p>Hello</p></div>").appendTo("#body") * @desc Creates a div element (and all of its contents) dynamically, * and appends it to the element with the ID of body. Internally, an * element is created and it's innerHTML property set to the given markup. * It is therefore both quite flexible and limited. * * @name $ * @param String expr An expression to search with, or a string of HTML to create on the fly. * @cat Core * @type jQuery */ /** * This function accepts a string containing a CSS selector, or * basic XPath, which is then used to match a set of elements with the * context of the specified DOM element, or document * * @example $("div", xml.responseXML) * @desc This finds all div elements within the specified XML document. * * @name $ * @param String expr An expression to search with. * @param Element context A DOM Element, or Document, representing the base context. * @cat Core * @type jQuery */ /** * Wrap jQuery functionality around a specific DOM Element. * This function also accepts XML Documents and Window objects * as valid arguments (even though they are not DOM Elements). * * @example $(document).find("div > p") * @before <p>one</p> <div><p>two</p></div> <p>three</p> * @result [ <p>two</p> ] * * @example $(document.body).background( "black" ); * @desc Sets the background color of the page to black. * * @name $ * @param Element elem A DOM element to be encapsulated by a jQuery object. * @cat Core * @type jQuery */ /** * Wrap jQuery functionality around a set of DOM Elements. * * @example $( myForm.elements ).hide() * @desc Hides all the input elements within a form * * @name $ * @param Array<Element> elems An array of DOM elements to be encapsulated by a jQuery object. * @cat Core * @type jQuery */ /** * A shorthand for $(document).ready(), allowing you to bind a function * to be executed when the DOM document has finished loading. This function * behaves just like $(document).ready(), in that it should be used to wrap * all of the other $() operations on your page. While this function is, * technically, chainable - there really isn't much use for chaining against it. * You can have as many $(document).ready events on your page as you like. * * @example $(function(){ * // Document is ready * }); * @desc Executes the function when the DOM is ready to be used. * * @name $ * @param Function fn The function to execute when the DOM is ready. * @cat Core * @type jQuery */ /** * A means of creating a cloned copy of a jQuery object. This function * copies the set of matched elements from one jQuery object and creates * another, new, jQuery object containing the same elements. * * @example var div = $("div"); * $( div ).find("p"); * @desc Locates all p elements with all div elements, without disrupting the original jQuery object contained in 'div' (as would normally be the case if a simple div.find("p") was done). * * @name $ * @param jQuery obj The jQuery object to be cloned. * @cat Core * @type jQuery */ // Map the jQuery namespace to the '$' one var $ = jQuery; jQuery.fn = jQuery.prototype = { /** * The current version of jQuery. * * @private * @property * @name jquery * @type String * @cat Core */ jquery: "@VERSION", /** * The number of elements currently matched. * * @example $("img").length; * @before <img src="test1.jpg"/> <img src="test2.jpg"/> * @result 2 * * @test ok( $("div").length == 2, "Get Number of Elements Found" ); * * @property * @name length * @type Number * @cat Core */ /** * The number of elements currently matched. * * @example $("img").size(); * @before <img src="test1.jpg"/> <img src="test2.jpg"/> * @result 2 * * @test ok( $("div").size() == 2, "Get Number of Elements Found" ); * * @name size * @type Number * @cat Core */ size: function() { return this.length; }, /** * Access all matched elements. This serves as a backwards-compatible * way of accessing all matched elements (other than the jQuery object * itself, which is, in fact, an array of elements). * * @example $("img").get(); * @before <img src="test1.jpg"/> <img src="test2.jpg"/> * @result [ <img src="test1.jpg"/> <img src="test2.jpg"/> ] * * @test isSet( $("div").get(), q("main","foo"), "Get All Elements" ); * * @name get * @type Array<Element> * @cat Core */ /** * Access a single matched element. num is used to access the * Nth element matched. * * @example $("img").get(1); * @before <img src="test1.jpg"/> <img src="test2.jpg"/> * @result [ <img src="test1.jpg"/> ] * * @test ok( $("div").get(0) == document.getElementById("main"), "Get A Single Element" ); * * @name get * @type Element * @param Number num Access the element in the Nth position. * @cat Core */ /** * Set the jQuery object to an array of elements. * * @example $("img").get([ document.body ]); * @result $("img").get() == [ document.body ] * * @private * @name get * @type jQuery * @param Elements elems An array of elements * @cat Core */ get: function( num ) { // Watch for when an array (of elements) is passed in if ( num && num.constructor == Array ) { // Use a tricky hack to make the jQuery object // look and feel like an array this.length = 0; [].push.apply( this, num ); return this; } else return num == undefined ? // Return a 'clean' array jQuery.merge( this, [] ) : // Return just the object this[num]; }, /** * Execute a function within the context of every matched element. * This means that every time the passed-in function is executed * (which is once for every element matched) the 'this' keyword * points to the specific element. * * Additionally, the function, when executed, is passed a single * argument representing the position of the element in the matched * set. * * @example $("img").each(function(){ * this.src = "test.jpg"; * }); * @before <img/> <img/> * @result <img src="test.jpg"/> <img src="test.jpg"/> * * @example $("img").each(function(i){ * alert( "Image #" + i + " is " + this ); * }); * @before <img/> <img/> * @result <img src="test.jpg"/> <img src="test.jpg"/> * * @test var div = $("div"); * div.each(function(){this.foo = 'zoo';}); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).foo != "zoo" ) pass = false; * } * ok( pass, "Execute a function, Relative" ); * * @name each * @type jQuery * @param Function fn A function to execute * @cat Core */ each: function( fn, args ) { return jQuery.each( this, fn, args ); }, /** * Searches every matched element for the object and returns * the index of the element, if found, starting with zero. * Returns -1 if the object wasn't found. * * @example $("*").index(document.getElementById('foobar')) * @before <div id="foobar"></div><b></b><span id="foo"></span> * @result 0 * * @example $("*").index(document.getElementById('foo')) * @before <div id="foobar"></div><b></b><span id="foo"></span> * @result 2 * * @example $("*").index(document.getElementById('bar')) * @before <div id="foobar"></div><b></b><span id="foo"></span> * @result -1 * * @test ok( $([window, document]).index(window) == 0, "Check for index of elements" ); * ok( $([window, document]).index(document) == 1, "Check for index of elements" ); * var inputElements = $('#radio1,#radio2,#check1,#check2'); * ok( inputElements.index(document.getElementById('radio1')) == 0, "Check for index of elements" ); * ok( inputElements.index(document.getElementById('radio2')) == 1, "Check for index of elements" ); * ok( inputElements.index(document.getElementById('check1')) == 2, "Check for index of elements" ); * ok( inputElements.index(document.getElementById('check2')) == 3, "Check for index of elements" ); * ok( inputElements.index(window) == -1, "Check for not found index" ); * ok( inputElements.index(document) == -1, "Check for not found index" ); * * @name index * @type Number * @param Object obj Object to search for * @cat Core */ index: function( obj ) { var pos = -1; this.each(function(i){ if ( this == obj ) pos = i; }); return pos; }, /** * Access a property on the first matched element. * This method makes it easy to retrieve a property value * from the first matched element. * * @example $("img").attr("src"); * @before <img src="test.jpg"/> * @result test.jpg * * @test ok( $('#text1').attr('value') == "Test", 'Check for value attribute' ); * ok( $('#text1').attr('type') == "text", 'Check for type attribute' ); * ok( $('#radio1').attr('type') == "radio", 'Check for type attribute' ); * ok( $('#check1').attr('type') == "checkbox", 'Check for type attribute' ); * ok( $('#simon1').attr('rel') == "bookmark", 'Check for rel attribute' ); * ok( $('#google').attr('title') == "Google!", 'Check for title attribute' ); * ok( $('#mark').attr('hreflang') == "en", 'Check for hreflang attribute' ); * ok( $('#en').attr('lang') == "en", 'Check for lang attribute' ); * ok( $('#simon').attr('class') == "blog link", 'Check for class attribute' ); * ok( $('#name').attr('name') == "name", 'Check for name attribute' ); * ok( $('#text1').attr('name') == "action", 'Check for name attribute' ); * ok( $('#form').attr('action').indexOf("formaction") >= 0, 'Check for action attribute' ); * * @name attr * @type Object * @param String name The name of the property to access. * @cat DOM */ /** * Set a hash of key/value object properties to all matched elements. * This serves as the best way to set a large number of properties * on all matched elements. * * @example $("img").attr({ src: "test.jpg", alt: "Test Image" }); * @before <img/> * @result <img src="test.jpg" alt="Test Image"/> * * @test var pass = true; * $("div").attr({foo: 'baz', zoo: 'ping'}).each(function(){ * if ( this.getAttribute('foo') != "baz" && this.getAttribute('zoo') != "ping" ) pass = false; * }); * ok( pass, "Set Multiple Attributes" ); * * @name attr * @type jQuery * @param Hash prop A set of key/value pairs to set as object properties. * @cat DOM */ /** * Set a single property to a value, on all matched elements. * * @example $("img").attr("src","test.jpg"); * @before <img/> * @result <img src="test.jpg"/> * * @test var div = $("div"); * div.attr("foo", "bar"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).getAttribute('foo') != "bar" ) pass = false; * } * ok( pass, "Set Attribute" ); * * $("#name").attr('name', 'something'); * ok( $("#name").name() == 'something', 'Set name attribute' ); * $("#check2").attr('checked', true); * ok( document.getElementById('check2').checked == true, 'Set checked attribute' ); * $("#check2").attr('checked', false); * ok( document.getElementById('check2').checked == false, 'Set checked attribute' ); * $("#text1").attr('readonly', true); * ok( document.getElementById('text1').readOnly == true, 'Set readonly attribute' ); * $("#text1").attr('readonly', false); * ok( document.getElementById('text1').readOnly == false, 'Set readonly attribute' ); * * @test stop(); * $.get('data/dashboard.xml', function(xml) { * var titles = []; * $('tab', xml).each(function() { * titles.push($(this).attr('title')); * }); * ok( titles[0] == 'Location', 'attr() in XML context: Check first title' ); * ok( titles[1] == 'Users', 'attr() in XML context: Check second title' ); * start(); * }); * * @name attr * @type jQuery * @param String key The name of the property to set. * @param Object value The value to set the property to. * @cat DOM */ attr: function( key, value, type ) { // Check to see if we're setting style values return key.constructor != String || value != undefined ? this.each(function(){ // See if we're setting a hash of styles if ( value == undefined ) // Set all the styles for ( var prop in key ) jQuery.attr( type ? this.style : this, prop, key[prop] ); // See if we're setting a single key/value style else jQuery.attr( type ? this.style : this, key, value ); }) : // Look for the case where we're accessing a style value jQuery[ type || "attr" ]( this[0], key ); }, /** * Access a style property on the first matched element. * This method makes it easy to retrieve a style property value * from the first matched element. * * @example $("p").css("color"); * @before <p style="color:red;">Test Paragraph.</p> * @result red * @desc Retrieves the color style of the first paragraph * * @example $("p").css("fontWeight"); * @before <p style="font-weight: bold;">Test Paragraph.</p> * @result bold * @desc Retrieves the font-weight style of the first paragraph. * Note that for all style properties with a dash (like 'font-weight'), you have to * write it in camelCase. In other words: Every time you have a '-' in a * property, remove it and replace the next character with an uppercase * representation of itself. Eg. fontWeight, fontSize, fontFamily, borderWidth, * borderStyle, borderBottomWidth etc. * * @test ok( $('#main').css("display") == 'none', 'Check for css property "display"'); * * @name css * @type Object * @param String name The name of the property to access. * @cat CSS */ /** * Set a hash of key/value style properties to all matched elements. * This serves as the best way to set a large number of style properties * on all matched elements. * * @example $("p").css({ color: "red", background: "blue" }); * @before <p>Test Paragraph.</p> * @result <p style="color:red; background:blue;">Test Paragraph.</p> * * @test ok( $('#foo').is(':visible'), 'Modifying CSS display: Assert element is visible'); * $('#foo').css({display: 'none'}); * ok( !$('#foo').is(':visible'), 'Modified CSS display: Assert element is hidden'); * $('#foo').css({display: 'block'}); * ok( $('#foo').is(':visible'), 'Modified CSS display: Assert element is visible'); * $('#floatTest').css({styleFloat: 'right'}); * ok( $('#floatTest').css('styleFloat') == 'right', 'Modified CSS float using "styleFloat": Assert float is right'); * $('#floatTest').css({cssFloat: 'left'}); * ok( $('#floatTest').css('cssFloat') == 'left', 'Modified CSS float using "cssFloat": Assert float is left'); * $('#floatTest').css({'float': 'right'}); * ok( $('#floatTest').css('float') == 'right', 'Modified CSS float using "float": Assert float is right'); * $('#floatTest').css({'font-size': '30px'}); * ok( $('#floatTest').css('font-size') == '30px', 'Modified CSS font-size: Assert font-size is 30px'); * * @name css * @type jQuery * @param Hash prop A set of key/value pairs to set as style properties. * @cat CSS */ /** * Set a single style property to a value, on all matched elements. * * @example $("p").css("color","red"); * @before <p>Test Paragraph.</p> * @result <p style="color:red;">Test Paragraph.</p> * @desc Changes the color of all paragraphs to red * * * @test ok( $('#foo').is(':visible'), 'Modifying CSS display: Assert element is visible'); * $('#foo').css('display', 'none'); * ok( !$('#foo').is(':visible'), 'Modified CSS display: Assert element is hidden'); * $('#foo').css('display', 'block'); * ok( $('#foo').is(':visible'), 'Modified CSS display: Assert element is visible'); * $('#floatTest').css('styleFloat', 'left'); * ok( $('#floatTest').css('styleFloat') == 'left', 'Modified CSS float using "styleFloat": Assert float is left'); * $('#floatTest').css('cssFloat', 'right'); * ok( $('#floatTest').css('cssFloat') == 'right', 'Modified CSS float using "cssFloat": Assert float is right'); * $('#floatTest').css('float', 'left'); * ok( $('#floatTest').css('float') == 'left', 'Modified CSS float using "float": Assert float is left'); * $('#floatTest').css('font-size', '20px'); * ok( $('#floatTest').css('font-size') == '20px', 'Modified CSS font-size: Assert font-size is 20px'); * * @name css * @type jQuery * @param String key The name of the property to set. * @param Object value The value to set the property to. * @cat CSS */ css: function( key, value ) { return this.attr( key, value, "curCSS" ); }, /** * Retrieve the text contents of all matched elements. The result is * a string that contains the combined text contents of all matched * elements. This method works on both HTML and XML documents. * * @example $("p").text(); * @before <p>Test Paragraph.</p> * @result Test Paragraph. * * @test var expected = "This link has class=\"blog\": Simon Willison's Weblog"; * ok( $('#sap').text() == expected, 'Check for merged text of more then one element.' ); * * @name text * @type String * @cat DOM */ text: function(e) { e = e || this; var t = ""; for ( var j = 0; j < e.length; j++ ) { var r = e[j].childNodes; for ( var i = 0; i < r.length; i++ ) if ( r[i].nodeType != 8 ) t += r[i].nodeType != 1 ? r[i].nodeValue : jQuery.fn.text([ r[i] ]); } return t; }, /** * Wrap all matched elements with a structure of other elements. * This wrapping process is most useful for injecting additional * stucture into a document, without ruining the original semantic * qualities of a document. * * This works by going through the first element * provided (which is generated, on the fly, from the provided HTML) * and finds the deepest ancestor element within its * structure - it is that element that will en-wrap everything else. * * This does not work with elements that contain text. Any necessary text * must be added after the wrapping is done. * * @example $("p").wrap("<div class='wrap'></div>"); * @before <p>Test Paragraph.</p> * @result <div class='wrap'><p>Test Paragraph.</p></div> * * @test var defaultText = 'Try them out:' * var result = $('#first').wrap('<div class="red"><span></span></div>').text(); * ok( defaultText == result, 'Check for wrapping of on-the-fly html' ); * ok( $('#first').parent().parent().is('.red'), 'Check if wrapper has class "red"' ); * * @name wrap * @type jQuery * @param String html A string of HTML, that will be created on the fly and wrapped around the target. * @cat DOM/Manipulation */ /** * Wrap all matched elements with a structure of other elements. * This wrapping process is most useful for injecting additional * stucture into a document, without ruining the original semantic * qualities of a document. * * This works by going through the first element * provided and finding the deepest ancestor element within its * structure - it is that element that will en-wrap everything else. * * This does not work with elements that contain text. Any necessary text * must be added after the wrapping is done. * * @example $("p").wrap( document.getElementById('content') ); * @before <p>Test Paragraph.</p><div id="content"></div> * @result <div id="content"><p>Test Paragraph.</p></div> * * @test var defaultText = 'Try them out:' * var result = $('#first').wrap(document.getElementById('empty')).parent(); * ok( result.is('ol'), 'Check for element wrapping' ); * ok( result.text() == defaultText, 'Check for element wrapping' ); * * @name wrap * @type jQuery * @param Element elem A DOM element that will be wrapped. * @cat DOM/Manipulation */ wrap: function() { // The elements to wrap the target around var a = jQuery.clean(arguments); // Wrap each of the matched elements individually return this.each(function(){ // Clone the structure that we're using to wrap var b = a[0].cloneNode(true); // Insert it before the element to be wrapped this.parentNode.insertBefore( b, this ); // Find the deepest point in the wrap structure while ( b.firstChild ) b = b.firstChild; // Move the matched element to within the wrap structure b.appendChild( this ); }); }, /** * Append any number of elements to the inside of every matched elements, * generated from the provided HTML. * This operation is similar to doing an appendChild to all the * specified elements, adding them into the document. * * @example $("p").append("<b>Hello</b>"); * @before <p>I would like to say: </p> * @result <p>I would like to say: <b>Hello</b></p> * * @test var defaultText = 'Try them out:' * var result = $('#first').append('<b>buga</b>'); * ok( result.text() == defaultText + 'buga', 'Check if text appending works' ); * ok( $('#select3').append('<option value="appendTest">Append Test</option>').find('option:last-child').attr('value') == 'appendTest', 'Appending html options to select element'); * * @name append * @type jQuery * @param String html A string of HTML, that will be created on the fly and appended to the target. * @cat DOM/Manipulation */ /** * Append an element to the inside of all matched elements. * This operation is similar to doing an appendChild to all the * specified elements, adding them into the document. * * @example $("p").append( $("#foo")[0] ); * @before <p>I would like to say: </p><b id="foo">Hello</b> * @result <p>I would like to say: <b id="foo">Hello</b></p> * * @test var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:"; * $('#sap').append(document.getElementById('first')); * ok( expected == $('#sap').text(), "Check for appending of element" ); * * @name append * @type jQuery * @param Element elem A DOM element that will be appended. * @cat DOM/Manipulation */ /** * Append any number of elements to the inside of all matched elements. * This operation is similar to doing an appendChild to all the * specified elements, adding them into the document. * * @example $("p").append( $("b") ); * @before <p>I would like to say: </p><b>Hello</b> * @result <p>I would like to say: <b>Hello</b></p> * * @test var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo"; * $('#sap').append([document.getElementById('first'), document.getElementById('yahoo')]); * ok( expected == $('#sap').text(), "Check for appending of array of elements" ); * * @name append * @type jQuery * @param Array<Element> elems An array of elements, all of which will be appended. * @cat DOM/Manipulation */ append: function() { return this.domManip(arguments, true, 1, function(a){ this.appendChild( a ); }); }, /** * Prepend any number of elements to the inside of every matched elements, * generated from the provided HTML. * This operation is the best way to insert dynamically created elements * inside, at the beginning, of all the matched element. * * @example $("p").prepend("<b>Hello</b>"); * @before <p>I would like to say: </p> * @result <p><b>Hello</b>I would like to say: </p> * * @test var defaultText = 'Try them out:' * var result = $('#first').prepend('<b>buga</b>'); * ok( result.text() == 'buga' + defaultText, 'Check if text prepending works' ); * ok( $('#select3').prepend('<option value="prependTest">Prepend Test</option>').find('option:first-child').attr('value') == 'prependTest', 'Prepending html options to select element'); * * @name prepend * @type jQuery * @param String html A string of HTML, that will be created on the fly and appended to the target. * @cat DOM/Manipulation */ /** * Prepend an element to the inside of all matched elements. * This operation is the best way to insert an element inside, at the * beginning, of all the matched element. * * @example $("p").prepend( $("#foo")[0] ); * @before <p>I would like to say: </p><b id="foo">Hello</b> * @result <p><b id="foo">Hello</b>I would like to say: </p> * * @test var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog"; * $('#sap').prepend(document.getElementById('first')); * ok( expected == $('#sap').text(), "Check for prepending of element" ); * * @name prepend * @type jQuery * @param Element elem A DOM element that will be appended. * @cat DOM/Manipulation */ /** * Prepend any number of elements to the inside of all matched elements. * This operation is the best way to insert a set of elements inside, at the * beginning, of all the matched element. * * @example $("p").prepend( $("b") ); * @before <p>I would like to say: </p><b>Hello</b> * @result <p><b>Hello</b>I would like to say: </p> * * @test var expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog"; * $('#sap').prepend([document.getElementById('first'), document.getElementById('yahoo')]); * ok( expected == $('#sap').text(), "Check for prepending of array of elements" ); * * @name prepend * @type jQuery * @param Array<Element> elems An array of elements, all of which will be appended. * @cat DOM/Manipulation */ prepend: function() { return this.domManip(arguments, true, -1, function(a){ this.insertBefore( a, this.firstChild ); }); }, /** * Insert any number of dynamically generated elements before each of the * matched elements. * * @example $("p").before("<b>Hello</b>"); * @before <p>I would like to say: </p> * @result <b>Hello</b><p>I would like to say: </p> * * @test var expected = 'This is a normal link: bugaYahoo'; * $('#yahoo').before('<b>buga</b>'); * ok( expected == $('#en').text(), 'Insert String before' ); * * @name before * @type jQuery * @param String html A string of HTML, that will be created on the fly and appended to the target. * @cat DOM/Manipulation */ /** * Insert an element before each of the matched elements. * * @example $("p").before( $("#foo")[0] ); * @before <p>I would like to say: </p><b id="foo">Hello</b> * @result <b id="foo">Hello</b><p>I would like to say: </p> * * @test var expected = "This is a normal link: Try them out:Yahoo"; * $('#yahoo').before(document.getElementById('first')); * ok( expected == $('#en').text(), "Insert element before" ); * * @name before * @type jQuery * @param Element elem A DOM element that will be appended. * @cat DOM/Manipulation */ /** * Insert any number of elements before each of the matched elements. * * @example $("p").before( $("b") ); * @before <p>I would like to say: </p><b>Hello</b> * @result <b>Hello</b><p>I would like to say: </p> * * @test var expected = "This is a normal link: Try them out:diveintomarkYahoo"; * $('#yahoo').before([document.getElementById('first'), document.getElementById('mark')]); * ok( expected == $('#en').text(), "Insert array of elements before" ); * * @name before * @type jQuery * @param Array<Element> elems An array of elements, all of which will be appended. * @cat DOM/Manipulation */ before: function() { return this.domManip(arguments, false, 1, function(a){ this.parentNode.insertBefore( a, this ); }); }, /** * Insert any number of dynamically generated elements after each of the * matched elements. * * @example $("p").after("<b>Hello</b>"); * @before <p>I would like to say: </p> * @result <p>I would like to say: </p><b>Hello</b> * * @test var expected = 'This is a normal link: Yahoobuga'; * $('#yahoo').after('<b>buga</b>'); * ok( expected == $('#en').text(), 'Insert String after' ); * * @name after * @type jQuery * @param String html A string of HTML, that will be created on the fly and appended to the target. * @cat DOM/Manipulation */ /** * Insert an element after each of the matched elements. * * @example $("p").after( $("#foo")[0] ); * @before <b id="foo">Hello</b><p>I would like to say: </p> * @result <p>I would like to say: </p><b id="foo">Hello</b> * * @test var expected = "This is a normal link: YahooTry them out:"; * $('#yahoo').after(document.getElementById('first')); * ok( expected == $('#en').text(), "Insert element after" ); * * @name after * @type jQuery * @param Element elem A DOM element that will be appended. * @cat DOM/Manipulation */ /** * Insert any number of elements after each of the matched elements. * * @example $("p").after( $("b") ); * @before <b>Hello</b><p>I would like to say: </p> * @result <p>I would like to say: </p><b>Hello</b> * * @test var expected = "This is a normal link: YahooTry them out:diveintomark"; * $('#yahoo').after([document.getElementById('first'), document.getElementById('mark')]); * ok( expected == $('#en').text(), "Insert array of elements after" ); * * @name after * @type jQuery * @param Array<Element> elems An array of elements, all of which will be appended. * @cat DOM/Manipulation */ after: function() { return this.domManip(arguments, false, -1, function(a){ this.parentNode.insertBefore( a, this.nextSibling ); }); }, /** * End the most recent 'destructive' operation, reverting the list of matched elements * back to its previous state. After an end operation, the list of matched elements will * revert to the last state of matched elements. * * @example $("p").find("span").end(); * @before <p><span>Hello</span>, how are you?</p> * @result $("p").find("span").end() == [ <p>...</p> ] * * @test ok( 'Yahoo' == $('#yahoo').parent().end().text(), 'Check for end' ); * * @name end * @type jQuery * @cat DOM/Traversing */ end: function() { return this.get( this.stack.pop() ); }, /** * Searches for all elements that match the specified expression. * This method is the optimal way of finding additional descendant * elements with which to process. * * All searching is done using a jQuery expression. The expression can be * written using CSS 1-3 Selector syntax, or basic XPath. * * @example $("p").find("span"); * @before <p><span>Hello</span>, how are you?</p> * @result $("p").find("span") == [ <span>Hello</span> ] * * @test ok( 'Yahoo' == $('#foo').find('.blogTest').text(), 'Check for find' ); * * @name find * @type jQuery * @param String expr An expression to search with. * @cat DOM/Traversing */ find: function(t) { return this.pushStack( jQuery.map( this, function(a){ return jQuery.find(t,a); }), arguments ); }, /** * Create cloned copies of all matched DOM Elements. This does * not create a cloned copy of this particular jQuery object, * instead it creates duplicate copies of all DOM Elements. * This is useful for moving copies of the elements to another * location in the DOM. * * @example $("b").clone().prependTo("p"); * @before <b>Hello</b><p>, how are you?</p> * @result <b>Hello</b><p><b>Hello</b>, how are you?</p> * * @test ok( 'This is a normal link: Yahoo' == $('#en').text(), 'Assert text for #en' ); * var clone = $('#yahoo').clone(); * ok( 'Try them out:Yahoo' == $('#first').append(clone).text(), 'Check for clone' ); * ok( 'This is a normal link: Yahoo' == $('#en').text(), 'Reassert text for #en' ); * * @name clone * @type jQuery * @cat DOM/Manipulation */ clone: function(deep) { return this.pushStack( jQuery.map( this, function(a){ return a.cloneNode( deep != undefined ? deep : true ); }), arguments ); }, /** * Removes all elements from the set of matched elements that do not * match the specified expression. This method is used to narrow down * the results of a search. * * All searching is done using a jQuery expression. The expression * can be written using CSS 1-3 Selector syntax, or basic XPath. * * @example $("p").filter(".selected") * @before <p class="selected">Hello</p><p>How are you?</p> * @result $("p").filter(".selected") == [ <p class="selected">Hello</p> ] * * @test isSet( $("input").filter(":checked").get(), q("radio2", "check1"), "Filter elements" ); * @test $("input").filter(":checked",function(i){ * ok( this == q("radio2", "check1")[i], "Filter elements, context" ); * }); * @test $("#main > p#ap > a").filter("#foobar",function(){},function(i){ * ok( this == q("google","groups", "mark")[i], "Filter elements, else context" ); * }); * * @name filter * @type jQuery * @param String expr An expression to search with. * @cat DOM/Traversing */ /** * Removes all elements from the set of matched elements that do not * match at least one of the expressions passed to the function. This * method is used when you want to filter the set of matched elements * through more than one expression. * * Elements will be retained in the jQuery object if they match at * least one of the expressions passed. * * @example $("p").filter([".selected", ":first"]) * @before <p>Hello</p><p>Hello Again</p><p class="selected">And Again</p> * @result $("p").filter([".selected", ":first"]) == [ <p>Hello</p>, <p class="selected">And Again</p> ] * * @name filter * @type jQuery * @param Array<String> exprs A set of expressions to evaluate against * @cat DOM/Traversing */ filter: function(t) { return this.pushStack( t.constructor == Array && jQuery.map(this,function(a){ for ( var i = 0; i < t.length; i++ ) if ( jQuery.filter(t[i],[a]).r.length ) return a; return false; }) || t.constructor == Boolean && ( t ? this.get() : [] ) || typeof t == "function" && jQuery.grep( this, t ) || jQuery.filter(t,this).r, arguments ); }, /** * Removes the specified Element from the set of matched elements. This * method is used to remove a single Element from a jQuery object. * * @example $("p").not( document.getElementById("selected") ) * @before <p>Hello</p><p id="selected">Hello Again</p> * @result [ <p>Hello</p> ] * * @name not * @type jQuery * @param Element el An element to remove from the set * @cat DOM/Traversing */ /** * Removes elements matching the specified expression from the set * of matched elements. This method is used to remove one or more * elements from a jQuery object. * * @example $("p").not("#selected") * @before <p>Hello</p><p id="selected">Hello Again</p> * @result [ <p>Hello</p> ] * * @test ok($("#main > p#ap > a").not("#google").length == 2, ".not") * * @name not * @type jQuery * @param String expr An expression with which to remove matching elements * @cat DOM/Traversing */ not: function(t) { return this.pushStack( t.constructor == String ? jQuery.filter(t,this,false).r : jQuery.grep(this,function(a){ return a != t; }), arguments ); }, /** * Adds the elements matched by the expression to the jQuery object. This * can be used to concatenate the result sets of two expressions. * * @example $("p").add("span") * @before <p>Hello</p><p><span>Hello Again</span></p> * @result [ <p>Hello</p>, <span>Hello Again</span> ] * * @name add * @type jQuery * @param String expr An expression whose matched elements are added * @cat DOM/Traversing */ /** * Adds each of the Elements in the array to the set of matched elements. * This is used to add a set of Elements to a jQuery object. * * @example $("p").add([document.getElementById("a"), document.getElementById("b")]) * @before <p>Hello</p><p><span id="a">Hello Again</span><span id="b">And Again</span></p> * @result [ <p>Hello</p>, <span id="a">Hello Again</span>, <span id="b">And Again</span> ] * * @name add * @type jQuery * @param Array<Element> els An array of Elements to add * @cat DOM/Traversing */ /** * Adds a single Element to the set of matched elements. This is used to * add a single Element to a jQuery object. * * @example $("p").add( document.getElementById("a") ) * @before <p>Hello</p><p><span id="a">Hello Again</span></p> * @result [ <p>Hello</p>, <span id="a">Hello Again</span> ] * * @name add * @type jQuery * @param Element el An Element to add * @cat DOM/Traversing */ add: function(t) { return this.pushStack( jQuery.merge( this, t.constructor == String ? jQuery.find(t) : t.constructor == Array ? t : [t] ), arguments ); }, /** * Checks the current selection against an expression and returns true, * if the selection fits the given expression. Does return false, if the * selection does not fit or the expression is not valid. * * @example $("input[@type='checkbox']").parent().is("form") * @before <form><input type="checkbox" /></form> * @result true * @desc Returns true, because the parent of the input is a form element * * @example $("input[@type='checkbox']").parent().is("form") * @before <form><p><input type="checkbox" /></p></form> * @result false * @desc Returns false, because the parent of the input is a p element * * @example $("form").is(null) * @before <form></form> * @result false * @desc An invalid expression always returns false. * * @test ok( $('#form').is('form'), 'Check for element: A form must be a form' ); * ok( !$('#form').is('div'), 'Check for element: A form is not a div' ); * ok( $('#mark').is('.blog'), 'Check for class: Expected class "blog"' ); * ok( !$('#mark').is('.link'), 'Check for class: Did not expect class "link"' ); * ok( $('#simon').is('.blog.link'), 'Check for multiple classes: Expected classes "blog" and "link"' ); * ok( !$('#simon').is('.blogTest'), 'Check for multiple classes: Expected classes "blog" and "link", but not "blogTest"' ); * ok( $('#en').is('[@lang="en"]'), 'Check for attribute: Expected attribute lang to be "en"' ); * ok( !$('#en').is('[@lang="de"]'), 'Check for attribute: Expected attribute lang to be "en", not "de"' ); * ok( $('#text1').is('[@type="text"]'), 'Check for attribute: Expected attribute type to be "text"' ); * ok( !$('#text1').is('[@type="radio"]'), 'Check for attribute: Expected attribute type to be "text", not "radio"' ); * ok( $('#text2').is(':disabled'), 'Check for pseudoclass: Expected to be disabled' ); * ok( !$('#text1').is(':disabled'), 'Check for pseudoclass: Expected not disabled' ); * ok( $('#radio2').is(':checked'), 'Check for pseudoclass: Expected to be checked' ); * ok( !$('#radio1').is(':checked'), 'Check for pseudoclass: Expected not checked' ); * ok( $('#foo').is('[p]'), 'Check for child: Expected a child "p" element' ); * ok( !$('#foo').is('[ul]'), 'Check for child: Did not expect "ul" element' ); * ok( $('#foo').is('[p][a][code]'), 'Check for childs: Expected "p", "a" and "code" child elements' ); * ok( !$('#foo').is('[p][a][code][ol]'), 'Check for childs: Expected "p", "a" and "code" child elements, but no "ol"' ); * ok( !$('#foo').is(0), 'Expected false for an invalid expression - 0' ); * ok( !$('#foo').is(null), 'Expected false for an invalid expression - null' ); * ok( !$('#foo').is(''), 'Expected false for an invalid expression - ""' ); * ok( !$('#foo').is(undefined), 'Expected false for an invalid expression - undefined' ); * * @name is * @type Boolean * @param String expr The expression with which to filter * @cat DOM/Traversing */ is: function(expr) { return expr ? jQuery.filter(expr,this).r.length > 0 : false; }, /** * * * @private * @name domManip * @param Array args * @param Boolean table * @param Number int * @param Function fn The function doing the DOM manipulation. * @type jQuery * @cat Core */ domManip: function(args, table, dir, fn){ var clone = this.size() > 1; var a = jQuery.clean(args); return this.each(function(){ var obj = this; if ( table && this.nodeName.toUpperCase() == "TABLE" && a[0].nodeName.toUpperCase() != "THEAD" ) { var tbody = this.getElementsByTagName("tbody"); if ( !tbody.length ) { obj = document.createElement("tbody"); this.appendChild( obj ); } else obj = tbody[0]; } for ( var i = ( dir < 0 ? a.length - 1 : 0 ); i != ( dir < 0 ? dir : a.length ); i += dir ) { fn.apply( obj, [ clone ? a[i].cloneNode(true) : a[i] ] ); } }); }, /** * * * @private * @name pushStack * @param Array a * @param Array args * @type jQuery * @cat Core */ pushStack: function(a,args) { var fn = args && args[args.length-1]; var fn2 = args && args[args.length-2]; if ( fn && fn.constructor != Function ) fn = null; if ( fn2 && fn2.constructor != Function ) fn2 = null; if ( !fn ) { if ( !this.stack ) this.stack = []; this.stack.push( this.get() ); this.get( a ); } else { var old = this.get(); this.get( a ); if ( fn2 && a.length || !fn2 ) this.each( fn2 || fn ).get( old ); else this.get( old ).each( fn ); } return this; } }; /** * Extends the jQuery object itself. Can be used to add both static * functions and plugin methods. * * @example $.fn.extend({ * check: function() { * this.each(function() { this.checked = true; }); * ), * uncheck: function() { * this.each(function() { this.checked = false; }); * } * }); * $("input[@type=checkbox]").check(); * $("input[@type=radio]").uncheck(); * @desc Adds two plugin methods. * * @private * @name extend * @param Object obj * @type Object * @cat Core */ /** * Extend one object with another, returning the original, * modified, object. This is a great utility for simple inheritance. * * @example var settings = { validate: false, limit: 5, name: "foo" }; * var options = { validate: true, name: "bar" }; * jQuery.extend(settings, options); * @result settings == { validate: true, limit: 5, name: "bar" } * * @test var settings = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" }; * var options = { xnumber2: 1, xstring2: "x", xxx: "newstring" }; * var optionsCopy = { xnumber2: 1, xstring2: "x", xxx: "newstring" }; * var merged = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "x", xxx: "newstring" }; * jQuery.extend(settings, options); * isSet( settings, merged, "Check if extended: settings must be extended" ); * isSet ( options, optionsCopy, "Check if not modified: options must not be modified" ); * * @name $.extend * @param Object obj The object to extend * @param Object prop The object that will be merged into the first. * @type Object * @cat Javascript */ jQuery.extend = jQuery.fn.extend = function(obj,prop) { // Watch for the case where null or undefined gets passed in by accident if ( arguments.length > 1 && (prop === null || prop == undefined) ) return obj; // If no property object was provided, then we're extending jQuery if ( !prop ) { prop = obj; obj = this; } // Extend the base object for ( var i in prop ) obj[i] = prop[i]; // Return the modified object return obj; }; jQuery.extend({ /** * @private * @name init * @type undefined * @cat Core */ init: function(){ jQuery.initDone = true; jQuery.each( jQuery.macros.axis, function(i,n){ jQuery.fn[ i ] = function(a) { var ret = jQuery.map(this,n); if ( a && a.constructor == String ) ret = jQuery.filter(a,ret).r; return this.pushStack( ret, arguments ); }; }); jQuery.each( jQuery.macros.to, function(i,n){ jQuery.fn[ i ] = function(){ var a = arguments; return this.each(function(){ for ( var j = 0; j < a.length; j++ ) jQuery(a[j])[n]( this ); }); }; }); jQuery.each( jQuery.macros.each, function(i,n){ jQuery.fn[ i ] = function() { return this.each( n, arguments ); }; }); jQuery.each( jQuery.macros.filter, function(i,n){ jQuery.fn[ n ] = function(num,fn) { return this.filter( ":" + n + "(" + num + ")", fn ); }; }); jQuery.each( jQuery.macros.attr, function(i,n){ n = n || i; jQuery.fn[ i ] = function(h) { return h == undefined ? this.length ? this[0][n] : null : this.attr( n, h ); }; }); jQuery.each( jQuery.macros.css, function(i,n){ jQuery.fn[ n ] = function(h) { return h == undefined ? ( this.length ? jQuery.css( this[0], n ) : null ) : this.css( n, h ); }; }); }, /** * A generic iterator function, which can be used to seemlessly * iterate over both objects and arrays. This function is not the same * as $().each() - which is used to iterate, exclusively, over a jQuery * object. This function can be used to iterate over anything. * * @example $.each( [0,1,2], function(i){ * alert( "Item #" + i + ": " + this ); * }); * @desc This is an example of iterating over the items in an array, accessing both the current item and its index. * * @example $.each( { name: "John", lang: "JS" }, function(i){ * alert( "Name: " + i + ", Value: " + this ); * }); * @desc This is an example of iterating over the properties in an Object, accessing both the current item and its key. * * @name $.each * @param Object obj The object, or array, to iterate over. * @param Function fn The function that will be executed on every object. * @type Object * @cat Javascript */ each: function( obj, fn, args ) { if ( obj.length == undefined ) for ( var i in obj ) fn.apply( obj[i], args || [i, obj[i]] ); else for ( var i = 0; i < obj.length; i++ ) if ( fn.apply( obj[i], args || [i, obj[i]] ) === false ) break; return obj; }, className: { add: function(o,c){ if (jQuery.className.has(o,c)) return; o.className += ( o.className ? " " : "" ) + c; }, remove: function(o,c){ if( !c ) { o.className = ""; } else { var classes = o.className.split(" "); for(var i=0; i<classes.length; i++) { if(classes[i] == c) { classes.splice(i, 1); break; } } o.className = classes.join(' '); } }, has: function(e,a) { if ( e.className != undefined ) e = e.className; return new RegExp("(^|\\s)" + a + "(\\s|$)").test(e); } }, /** * Swap in/out style options. * @private */ swap: function(e,o,f) { for ( var i in o ) { e.style["old"+i] = e.style[i]; e.style[i] = o[i]; } f.apply( e, [] ); for ( var i in o ) e.style[i] = e.style["old"+i]; }, css: function(e,p) { if ( p == "height" || p == "width" ) { var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"]; for ( var i in d ) { old["padding" + d[i]] = 0; old["border" + d[i] + "Width"] = 0; } jQuery.swap( e, old, function() { if (jQuery.css(e,"display") != "none") { oHeight = e.offsetHeight; oWidth = e.offsetWidth; } else { e = jQuery(e.cloneNode(true)) .find(":radio").removeAttr("checked").end() .css({ visibility: "hidden", position: "absolute", display: "block", right: "0", left: "0" }).appendTo(e.parentNode)[0]; var parPos = jQuery.css(e.parentNode,"position"); if ( parPos == "" || parPos == "static" ) e.parentNode.style.position = "relative"; oHeight = e.clientHeight; oWidth = e.clientWidth; if ( parPos == "" || parPos == "static" ) e.parentNode.style.position = "static"; e.parentNode.removeChild(e); } }); return p == "height" ? oHeight : oWidth; } return jQuery.curCSS( e, p ); }, curCSS: function(elem, prop, force) { var ret; if (prop == 'opacity' && jQuery.browser.msie) return jQuery.attr(elem.style, 'opacity'); if (prop == "float" || prop == "cssFloat") prop = jQuery.browser.msie ? "styleFloat" : "cssFloat"; if (!force && elem.style[prop]) { ret = elem.style[prop]; } else if (elem.currentStyle) { var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();}); ret = elem.currentStyle[prop] || elem.currentStyle[newProp]; } else if (document.defaultView && document.defaultView.getComputedStyle) { if (prop == "cssFloat" || prop == "styleFloat") prop = "float"; prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase(); var cur = document.defaultView.getComputedStyle(elem, null); if ( cur ) ret = cur.getPropertyValue(prop); else if ( prop == 'display' ) ret = 'none'; else jQuery.swap(elem, { display: 'block' }, function() { ret = document.defaultView.getComputedStyle(this,null).getPropertyValue(prop); }); } return ret; }, clean: function(a) { var r = []; for ( var i = 0; i < a.length; i++ ) { var arg = a[i]; if ( arg.constructor == String ) { // Convert html string into DOM nodes // Trim whitespace, otherwise indexOf won't work as expected var s = jQuery.trim(arg), div = document.createElement("div"), wrap = [0,"",""]; if ( !s.indexOf("<opt") ) // option or optgroup wrap = [1, "<select>", "</select>"]; else if ( !s.indexOf("<thead") || !s.indexOf("<tbody") ) wrap = [1, "<table>", "</table>"]; else if ( !s.indexOf("<tr") ) wrap = [2, "<table>", "</table>"]; // tbody auto-inserted else if ( !s.indexOf("<td") || !s.indexOf("<th") ) wrap = [3, "<table><tbody><tr>", "</tr></tbody></table>"]; // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + s + wrap[2]; while ( wrap[0]-- ) div = div.firstChild; // Have to loop through the childNodes here to // prevent a Safari crash with text nodes and /n characters for ( var j = 0; j < div.childNodes.length; j++ ) r.push( div.childNodes[j] ); } else if ( arg.length != undefined && !arg.nodeType ) // Handles Array, jQuery, DOM NodeList collections for ( var n = 0; n < arg.length; n++ ) r.push(arg[n]); else r.push( arg.nodeType ? arg : document.createTextNode(arg.toString()) ); } return r; }, expr: { "": "m[2]== '*'||a.nodeName.toUpperCase()==m[2].toUpperCase()", "#": "a.getAttribute('id')&&a.getAttribute('id')==m[2]", ":": { // Position Checks lt: "i<m[3]-0", gt: "i>m[3]-0", nth: "m[3]-0==i", eq: "m[3]-0==i", first: "i==0", last: "i==r.length-1", even: "i%2==0", odd: "i%2", // Child Checks "nth-child": "jQuery.sibling(a,m[3]).cur", "first-child": "jQuery.sibling(a,0).cur", "last-child": "jQuery.sibling(a,0).last", "only-child": "jQuery.sibling(a).length==1", // Parent Checks parent: "a.childNodes.length", empty: "!a.childNodes.length", // Text Check contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0", // Visibility visible: "a.type!='hidden'&&jQuery.css(a,'display')!='none'&&jQuery.css(a,'visibility')!='hidden'", hidden: "a.type=='hidden'||jQuery.css(a,'display')=='none'||jQuery.css(a,'visibility')=='hidden'", // Form attributes enabled: "!a.disabled", disabled: "a.disabled", checked: "a.checked", selected: "a.selected || jQuery.attr(a, 'selected')", // Form elements text: "a.type=='text'", radio: "a.type=='radio'", checkbox: "a.type=='checkbox'", file: "a.type=='file'", password: "a.type=='password'", submit: "a.type=='submit'", image: "a.type=='image'", reset: "a.type=='reset'", button: "a.type=='button'", input: "a.nodeName.toLowerCase().match(/input|select|textarea|button/)" }, ".": "jQuery.className.has(a,m[2])", "@": { "=": "z==m[4]", "!=": "z!=m[4]", "^=": "z && !z.indexOf(m[4])", "$=": "z && z.substr(z.length - m[4].length,m[4].length)==m[4]", "*=": "z && z.indexOf(m[4])>=0", "": "z" }, "[": "jQuery.find(m[2],a).length" }, token: [ "\\.\\.|/\\.\\.", "a.parentNode", ">|/", "jQuery.sibling(a.firstChild)", "\\+", "jQuery.sibling(a).next", "~", function(a){ var r = []; var s = jQuery.sibling(a); if ( s.n > 0 ) for ( var i = s.n; i < s.length; i++ ) r.push( s[i] ); return r; } ], /** * * @test t( "Element Selector", "div", ["main","foo"] ); * t( "Element Selector", "body", ["body"] ); * t( "Element Selector", "html", ["html"] ); * ok( $("*").size() >= 30, "Element Selector" ); * t( "Parent Element", "div div", ["foo"] ); * * t( "ID Selector", "#body", ["body"] ); * t( "ID Selector w/ Element", "body#body", ["body"] ); * t( "ID Selector w/ Element", "ul#first", [] ); * * t( "Class Selector", ".blog", ["mark","simon"] ); * t( "Class Selector", ".blog.link", ["simon"] ); * t( "Class Selector w/ Element", "a.blog", ["mark","simon"] ); * t( "Parent Class Selector", "p .blog", ["mark","simon"] ); * * t( "Comma Support", "a.blog, div", ["mark","simon","main","foo"] ); * t( "Comma Support", "a.blog , div", ["mark","simon","main","foo"] ); * t( "Comma Support", "a.blog ,div", ["mark","simon","main","foo"] ); * t( "Comma Support", "a.blog,div", ["mark","simon","main","foo"] ); * * t( "Child", "p > a", ["simon1","google","groups","mark","yahoo","simon"] ); * t( "Child", "p> a", ["simon1","google","groups","mark","yahoo","simon"] ); * t( "Child", "p >a", ["simon1","google","groups","mark","yahoo","simon"] ); * t( "Child", "p>a", ["simon1","google","groups","mark","yahoo","simon"] ); * t( "Child w/ Class", "p > a.blog", ["mark","simon"] ); * t( "All Children", "code > *", ["anchor1","anchor2"] ); * t( "All Grandchildren", "p > * > *", ["anchor1","anchor2"] ); * t( "Adjacent", "a + a", ["groups"] ); * t( "Adjacent", "a +a", ["groups"] ); * t( "Adjacent", "a+ a", ["groups"] ); * t( "Adjacent", "a+a", ["groups"] ); * t( "Adjacent", "p + p", ["ap","en","sap"] ); * t( "Comma, Child, and Adjacent", "a + a, code > a", ["groups","anchor1","anchor2"] ); * t( "First Child", "p:first-child", ["firstp","sndp"] ); * t( "Attribute Exists", "a[@title]", ["google"] ); * t( "Attribute Exists", "*[@title]", ["google"] ); * t( "Attribute Exists", "[@title]", ["google"] ); * * t( "Non-existing part of attribute", "[@name*=bla]", [] ); * t( "Non-existing start of attribute", "[@name^=bla]", [] ); * t( "Non-existing end of attribute", "[@name$=bla]", [] ); * * t( "Attribute Equals", "a[@rel='bookmark']", ["simon1"] ); * t( "Attribute Equals", 'a[@rel="bookmark"]', ["simon1"] ); * t( "Attribute Equals", "a[@rel=bookmark]", ["simon1"] ); * t( "Multiple Attribute Equals", "input[@type='hidden'],input[@type='radio']", ["hidden1","radio1","radio2"] ); * t( "Multiple Attribute Equals", "input[@type=\"hidden\"],input[@type='radio']", ["hidden1","radio1","radio2"] ); * t( "Multiple Attribute Equals", "input[@type=hidden],input[@type=radio]", ["hidden1","radio1","radio2"] ); * * t( "Attribute Begins With", "a[@href ^= 'http://www']", ["google","yahoo"] ); * t( "Attribute Ends With", "a[@href $= 'org/']", ["mark"] ); * t( "Attribute Contains", "a[@href *= 'google']", ["google","groups"] ); * t( "First Child", "p:first-child", ["firstp","sndp"] ); * t( "Last Child", "p:last-child", ["sap"] ); * t( "Only Child", "a:only-child", ["simon1","anchor1","yahoo","anchor2"] ); * t( "Empty", "ul:empty", ["firstUL"] ); * t( "Enabled UI Element", "input:enabled", ["text1","radio1","radio2","check1","check2","hidden1","hidden2","name"] ); * t( "Disabled UI Element", "input:disabled", ["text2"] ); * t( "Checked UI Element", "input:checked", ["radio2","check1"] ); * t( "Selected Option Element", "option:selected", ["option1a","option2d","option3b","option3c"] ); * t( "Text Contains", "a:contains('Google')", ["google","groups"] ); * t( "Text Contains", "a:contains('Google Groups')", ["groups"] ); * t( "Element Preceded By", "p ~ div", ["foo"] ); * t( "Not", "a.blog:not(.link)", ["mark"] ); * * ok( jQuery.find("//*").length >= 30, "All Elements (//*)" ); * t( "All Div Elements", "//div", ["main","foo"] ); * t( "Absolute Path", "/html/body", ["body"] ); * t( "Absolute Path w/ *", "/* /body", ["body"] ); * t( "Long Absolute Path", "/html/body/dl/div/div/p", ["sndp","en","sap"] ); * t( "Absolute and Relative Paths", "/html//div", ["main","foo"] ); * t( "All Children, Explicit", "//code/*", ["anchor1","anchor2"] ); * t( "All Children, Implicit", "//code/", ["anchor1","anchor2"] ); * t( "Attribute Exists", "//a[@title]", ["google"] ); * t( "Attribute Equals", "//a[@rel='bookmark']", ["simon1"] ); * t( "Parent Axis", "//p/..", ["main","foo"] ); * t( "Sibling Axis", "//p/../", ["firstp","ap","foo","first","firstUL","empty","form","sndp","en","sap"] ); * t( "Sibling Axis", "//p/../*", ["firstp","ap","foo","first","firstUL","empty","form","sndp","en","sap"] ); * t( "Has Children", "//p[a]", ["firstp","ap","en","sap"] ); * * t( "nth Element", "p:nth(1)", ["ap"] ); * t( "First Element", "p:first", ["firstp"] ); * t( "Last Element", "p:last", ["first"] ); * t( "Even Elements", "p:even", ["firstp","sndp","sap"] ); * t( "Odd Elements", "p:odd", ["ap","en","first"] ); * t( "Position Equals", "p:eq(1)", ["ap"] ); * t( "Position Greater Than", "p:gt(0)", ["ap","sndp","en","sap","first"] ); * t( "Position Less Than", "p:lt(3)", ["firstp","ap","sndp"] ); * t( "Is A Parent", "p:parent", ["firstp","ap","sndp","en","sap","first"] ); * t( "Is Visible", "input:visible", ["text1","text2","radio1","radio2","check1","check2","name"] ); * t( "Is Hidden", "input:hidden", ["hidden1","hidden2"] ); * * t( "Grouped Form Elements", "input[@name='foo[bar]']", ["hidden2"] ); * * t( "All Children of ID", "#foo/*", ["sndp", "en", "sap"] ); * t( "All Children of ID with no children", "#firstUL/*", [] ); * * t( "Form element :input", ":input", ["text1", "text2", "radio1", "radio2", "check1", "check2", "hidden1", "hidden2", "name", "button", "area1", "select1", "select2", "select3"] ); * t( "Form element :radio", ":radio", ["radio1", "radio2"] ); * t( "Form element :checkbox", ":checkbox", ["check1", "check2"] ); * t( "Form element :text", ":text", ["text1", "text2", "hidden2", "name"] ); * t( "Form element :radio:checked", ":radio:checked", ["radio2"] ); * t( "Form element :checkbox:checked", ":checkbox:checked", ["check1"] ); * t( "Form element :checkbox:checked, :radio:checked", ":checkbox:checked, :radio:checked", ["check1", "radio2"] ); * * t( ":not() Existing attribute", "select:not([@multiple])", ["select1", "select2"]); * t( ":not() Equals attribute", "select:not([@name=select1])", ["select2", "select3"]); * t( ":not() Equals quoted attribute", "select:not([@name='select1'])", ["select2", "select3"]); * * @name $.find * @type Array<Element> * @private * @cat Core */ find: function( t, context ) { // Make sure that the context is a DOM Element if ( context && context.nodeType == undefined ) context = null; // Set the correct context (if none is provided) context = context || jQuery.context || document; if ( t.constructor != String ) return [t]; if ( !t.indexOf("//") ) { context = context.documentElement; t = t.substr(2,t.length); } else if ( !t.indexOf("/") ) { context = context.documentElement; t = t.substr(1,t.length); // FIX Assume the root element is right :( if ( t.indexOf("/") >= 1 ) t = t.substr(t.indexOf("/"),t.length); } var ret = [context]; var done = []; var last = null; while ( t.length > 0 && last != t ) { var r = []; last = t; t = jQuery.trim(t).replace( /^\/\//i, "" ); var foundToken = false; for ( var i = 0; i < jQuery.token.length; i += 2 ) { if ( foundToken ) continue; var re = new RegExp("^(" + jQuery.token[i] + ")"); var m = re.exec(t); if ( m ) { r = ret = jQuery.map( ret, jQuery.token[i+1] ); t = jQuery.trim( t.replace( re, "" ) ); foundToken = true; } } if ( !foundToken ) { if ( !t.indexOf(",") || !t.indexOf("|") ) { if ( ret[0] == context ) ret.shift(); done = jQuery.merge( done, ret ); r = ret = [context]; t = " " + t.substr(1,t.length); } else { var re2 = /^([#.]?)([a-z0-9\\*_-]*)/i; var m = re2.exec(t); if ( m[1] == "#" ) { // Ummm, should make this work in all XML docs var oid = document.getElementById(m[2]); r = ret = oid ? [oid] : []; t = t.replace( re2, "" ); } else { if ( !m[2] || m[1] == "." ) m[2] = "*"; for ( var i = 0; i < ret.length; i++ ) r = jQuery.merge( r, m[2] == "*" ? jQuery.getAll(ret[i]) : ret[i].getElementsByTagName(m[2]) ); } } } if ( t ) { var val = jQuery.filter(t,r); ret = r = val.r; t = jQuery.trim(val.t); } } if ( ret && ret[0] == context ) ret.shift(); done = jQuery.merge( done, ret ); return done; }, getAll: function(o,r) { r = r || []; var s = o.childNodes; for ( var i = 0; i < s.length; i++ ) if ( s[i].nodeType == 1 ) { r.push( s[i] ); jQuery.getAll( s[i], r ); } return r; }, attr: function(elem, name, value){ var fix = { "for": "htmlFor", "class": "className", "float": jQuery.browser.msie ? "styleFloat" : "cssFloat", cssFloat: jQuery.browser.msie ? "styleFloat" : "cssFloat", innerHTML: "innerHTML", className: "className", value: "value", disabled: "disabled", checked: "checked", readonly: "readOnly" }; // IE actually uses filters for opacity ... elem is actually elem.style if (name == "opacity" && jQuery.browser.msie && value != undefined) { // IE has trouble with opacity if it does not have layout // Would prefer to check element.hasLayout first but don't have access to the element here elem['zoom'] = 1; if (value == 1) // Remove filter to avoid more IE weirdness return elem["filter"] = elem["filter"].replace(/alpha\([^\)]*\)/gi,""); else return elem["filter"] = elem["filter"].replace(/alpha\([^\)]*\)/gi,"") + "alpha(opacity=" + value * 100 + ")"; } else if (name == "opacity" && jQuery.browser.msie) { return elem["filter"] ? parseFloat( elem["filter"].match(/alpha\(opacity=(.*)\)/)[1] )/100 : 1; } // Mozilla doesn't play well with opacity 1 if (name == "opacity" && jQuery.browser.mozilla && value == 1) value = 0.9999; if ( fix[name] ) { if ( value != undefined ) elem[fix[name]] = value; return elem[fix[name]]; } else if( value == undefined && jQuery.browser.msie && elem.nodeName && elem.nodeName.toUpperCase() == 'FORM' && (name == 'action' || name == 'method') ) { return elem.getAttributeNode(name).nodeValue; } else if ( elem.getAttribute != undefined && elem.tagName ) { // IE elem.getAttribute passes even for style if ( value != undefined ) elem.setAttribute( name, value ); return elem.getAttribute( name ); } else { name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();}); if ( value != undefined ) elem[name] = value; return elem[name]; } }, // The regular expressions that power the parsing engine parse: [ // Match: [@value='test'], [@foo] "\\[ *(@)S *([!*$^=]*) *('?\"?)(.*?)\\4 *\\]", // Match: [div], [div p] "(\\[)\s*(.*?)\s*\\]", // Match: :contains('foo') "(:)S\\(\"?'?([^\\)]*?)\"?'?\\)", // Match: :even, :last-chlid "([:.#]*)S" ], filter: function(t,r,not) { // Figure out if we're doing regular, or inverse, filtering var g = not !== false ? jQuery.grep : function(a,f) {return jQuery.grep(a,f,true);}; while ( t && /^[a-z[({<*:.#]/i.test(t) ) { var p = jQuery.parse; for ( var i = 0; i < p.length; i++ ) { // Look for, and replace, string-like sequences // and finally build a regexp out of it var re = new RegExp( "^" + p[i].replace("S", "([a-z*_-][a-z0-9_-]*)"), "i" ); var m = re.exec( t ); if ( m ) { // Re-organize the first match if ( !i ) m = ["",m[1], m[3], m[2], m[5]]; // Remove what we just matched t = t.replace( re, "" ); break; } } // :not() is a special case that can be optimized by // keeping it out of the expression list if ( m[1] == ":" && m[2] == "not" ) r = jQuery.filter(m[3],r,false).r; // Otherwise, find the expression to execute else { var f = jQuery.expr[m[1]]; if ( f.constructor != String ) f = jQuery.expr[m[1]][m[2]]; // Build a custom macro to enclose it eval("f = function(a,i){" + ( m[1] == "@" ? "z=jQuery.attr(a,m[3]);" : "" ) + "return " + f + "}"); // Execute it against the current filter r = g( r, f ); } } // Return an array of filtered elements (r) // and the modified expression string (t) return { r: r, t: t }; }, /** * Remove the whitespace from the beginning and end of a string. * * @example $.trim(" hello, how are you? "); * @result "hello, how are you?" * * @name $.trim * @type String * @param String str The string to trim. * @cat Javascript */ trim: function(t){ return t.replace(/^\s+|\s+$/g, ""); }, /** * All ancestors of a given element. * * @private * @name $.parents * @type Array<Element> * @param Element elem The element to find the ancestors of. * @cat DOM/Traversing */ parents: function( elem ){ var matched = []; var cur = elem.parentNode; while ( cur && cur != document ) { matched.push( cur ); cur = cur.parentNode; } return matched; }, /** * All elements on a specified axis. * * @private * @name $.sibling * @type Array * @param Element elem The element to find all the siblings of (including itself). * @cat DOM/Traversing */ sibling: function(elem, pos, not) { var elems = []; if(elem) { var siblings = elem.parentNode.childNodes; for ( var i = 0; i < siblings.length; i++ ) { if ( not === true && siblings[i] == elem ) continue; if ( siblings[i].nodeType == 1 ) elems.push( siblings[i] ); if ( siblings[i] == elem ) elems.n = elems.length - 1; } } return jQuery.extend( elems, { last: elems.n == elems.length - 1, cur: pos == "even" && elems.n % 2 == 0 || pos == "odd" && elems.n % 2 || elems[pos] == elem, prev: elems[elems.n - 1], next: elems[elems.n + 1] }); }, /** * Merge two arrays together, removing all duplicates. The final order * or the new array is: All the results from the first array, followed * by the unique results from the second array. * * @example $.merge( [0,1,2], [2,3,4] ) * @result [0,1,2,3,4] * * @example $.merge( [3,2,1], [4,3,2] ) * @result [3,2,1,4] * * @name $.merge * @type Array * @param Array first The first array to merge. * @param Array second The second array to merge. * @cat Javascript */ merge: function(first, second) { var result = []; // Move b over to the new array (this helps to avoid // StaticNodeList instances) for ( var k = 0; k < first.length; k++ ) result[k] = first[k]; // Now check for duplicates between a and b and only // add the unique items for ( var i = 0; i < second.length; i++ ) { var noCollision = true; // The collision-checking process for ( var j = 0; j < first.length; j++ ) if ( second[i] == first[j] ) noCollision = false; // If the item is unique, add it if ( noCollision ) result.push( second[i] ); } return result; }, /** * Filter items out of an array, by using a filter function. * The specified function will be passed two arguments: The * current array item and the index of the item in the array. The * function should return 'true' if you wish to keep the item in * the array, false if it should be removed. * * @example $.grep( [0,1,2], function(i){ * return i > 0; * }); * @result [1, 2] * * @name $.grep * @type Array * @param Array array The Array to find items in. * @param Function fn The function to process each item against. * @param Boolean inv Invert the selection - select the opposite of the function. * @cat Javascript */ grep: function(elems, fn, inv) { // If a string is passed in for the function, make a function // for it (a handy shortcut) if ( fn.constructor == String ) fn = new Function("a","i","return " + fn); var result = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0; i < elems.length; i++ ) if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) ) result.push( elems[i] ); return result; }, /** * Translate all items in an array to another array of items. * The translation function that is provided to this method is * called for each item in the array and is passed one argument: * The item to be translated. The function can then return: * The translated value, 'null' (to remove the item), or * an array of values - which will be flattened into the full array. * * @example $.map( [0,1,2], function(i){ * return i + 4; * }); * @result [4, 5, 6] * * @example $.map( [0,1,2], function(i){ * return i > 0 ? i + 1 : null; * }); * @result [2, 3] * * @example $.map( [0,1,2], function(i){ * return [ i, i + 1 ]; * }); * @result [0, 1, 1, 2, 2, 3] * * @name $.map * @type Array * @param Array array The Array to translate. * @param Function fn The function to process each item against. * @cat Javascript */ map: function(elems, fn) { // If a string is passed in for the function, make a function // for it (a handy shortcut) if ( fn.constructor == String ) fn = new Function("a","return " + fn); var result = []; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0; i < elems.length; i++ ) { var val = fn(elems[i],i); if ( val !== null && val != undefined ) { if ( val.constructor != Array ) val = [val]; result = jQuery.merge( result, val ); } } return result; }, /* * A number of helper functions used for managing events. * Many of the ideas behind this code orignated from Dean Edwards' addEvent library. */ event: { // Bind an event to an element // Original by Dean Edwards add: function(element, type, handler) { // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.browser.msie && element.setInterval != undefined ) element = window; // Make sure that the function being executed has a unique ID if ( !handler.guid ) handler.guid = this.guid++; // Init the element's event structure if (!element.events) element.events = {}; // Get the current list of functions bound to this event var handlers = element.events[type]; // If it hasn't been initialized yet if (!handlers) { // Init the event handler queue handlers = element.events[type] = {}; // Remember an existing handler, if it's already there if (element["on" + type]) handlers[0] = element["on" + type]; } // Add the function to the element's handler list handlers[handler.guid] = handler; // And bind the global event handler to the element element["on" + type] = this.handle; // Remember the function in a global list (for triggering) if (!this.global[type]) this.global[type] = []; this.global[type].push( element ); }, guid: 1, global: {}, // Detach an event or set of events from an element remove: function(element, type, handler) { if (element.events) if (type && element.events[type]) if ( handler ) delete element.events[type][handler.guid]; else for ( var i in element.events[type] ) delete element.events[type][i]; else for ( var j in element.events ) this.remove( element, j ); }, trigger: function(type,data,element) { // Touch up the incoming data data = data || []; // Handle a global trigger if ( !element ) { var g = this.global[type]; if ( g ) for ( var i = 0; i < g.length; i++ ) this.trigger( type, data, g[i] ); // Handle triggering a single element } else if ( element["on" + type] ) { // Pass along a fake event data.unshift( this.fix({ type: type, target: element }) ); // Trigger the event element["on" + type].apply( element, data ); } }, handle: function(event) { if ( typeof jQuery == "undefined" ) return false; event = event || jQuery.event.fix( window.event ); // If no correct event was found, fail if ( !event ) return false; var returnValue = true; var c = this.events[event.type]; var args = [].slice.call( arguments, 1 ); args.unshift( event ); for ( var j in c ) { if ( c[j].apply( this, args ) === false ) { event.preventDefault(); event.stopPropagation(); returnValue = false; } } return returnValue; }, fix: function(event) { // check IE if(jQuery.browser.msie) { // get real event from window.event event = window.event; // fix target property event.target = event.srcElement; // check safari and if target is a textnode } else if(jQuery.browser.safari && event.target.nodeType == 3) { // target is readonly, clone the event object event = jQuery.extend({}, event); // get parentnode from textnode event.target = event.target.parentNode; } // fix preventDefault and stopPropagation event.preventDefault = function() { this.returnValue = false; }; event.stopPropagation = function() { this.cancelBubble = true; }; return event; } } }); /** * Contains flags for the useragent, read from navigator.userAgent. * Available flags are: safari, opera, msie, mozilla * This property is available before the DOM is ready, therefore you can * use it to add ready events only for certain browsers. * * See <a href="http://davecardwell.co.uk/geekery/javascript/jquery/jqbrowser/"> * jQBrowser plugin</a> for advanced browser detection: * * @example $.browser.msie * @desc returns true if the current useragent is some version of microsoft's internet explorer * * @example if($.browser.safari) { $( function() { alert("this is safari!"); } ); } * @desc Alerts "this is safari!" only for safari browsers * * @name $.browser * @type Boolean * @cat Javascript */ new function() { var b = navigator.userAgent.toLowerCase(); // Figure out what browser is being used jQuery.browser = { safari: /webkit/.test(b), opera: /opera/.test(b), msie: /msie/.test(b) && !/opera/.test(b), mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b) }; // Check to see if the W3C box model is being used jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat"; }; jQuery.macros = { to: { /** * Append all of the matched elements to another, specified, set of elements. * This operation is, essentially, the reverse of doing a regular * $(A).append(B), in that instead of appending B to A, you're appending * A to B. * * @example $("p").appendTo("#foo"); * @before <p>I would like to say: </p><div id="foo"></div> * @result <div id="foo"><p>I would like to say: </p></div> * * @name appendTo * @type jQuery * @param String expr A jQuery expression of elements to match. * @cat DOM/Manipulation */ appendTo: "append", /** * Prepend all of the matched elements to another, specified, set of elements. * This operation is, essentially, the reverse of doing a regular * $(A).prepend(B), in that instead of prepending B to A, you're prepending * A to B. * * @example $("p").prependTo("#foo"); * @before <p>I would like to say: </p><div id="foo"><b>Hello</b></div> * @result <div id="foo"><p>I would like to say: </p><b>Hello</b></div> * * @name prependTo * @type jQuery * @param String expr A jQuery expression of elements to match. * @cat DOM/Manipulation */ prependTo: "prepend", /** * Insert all of the matched elements before another, specified, set of elements. * This operation is, essentially, the reverse of doing a regular * $(A).before(B), in that instead of inserting B before A, you're inserting * A before B. * * @example $("p").insertBefore("#foo"); * @before <div id="foo">Hello</div><p>I would like to say: </p> * @result <p>I would like to say: </p><div id="foo">Hello</div> * * @name insertBefore * @type jQuery * @param String expr A jQuery expression of elements to match. * @cat DOM/Manipulation */ insertBefore: "before", /** * Insert all of the matched elements after another, specified, set of elements. * This operation is, essentially, the reverse of doing a regular * $(A).after(B), in that instead of inserting B after A, you're inserting * A after B. * * @example $("p").insertAfter("#foo"); * @before <p>I would like to say: </p><div id="foo">Hello</div> * @result <div id="foo">Hello</div><p>I would like to say: </p> * * @name insertAfter * @type jQuery * @param String expr A jQuery expression of elements to match. * @cat DOM/Manipulation */ insertAfter: "after" }, /** * Get the current CSS width of the first matched element. * * @example $("p").width(); * @before <p>This is just a test.</p> * @result "300px" * * @name width * @type String * @cat CSS */ /** * Set the CSS width of every matched element. Be sure to include * the "px" (or other unit of measurement) after the number that you * specify, otherwise you might get strange results. * * @example $("p").width("20px"); * @before <p>This is just a test.</p> * @result <p style="width:20px;">This is just a test.</p> * * @name width * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS height of the first matched element. * * @example $("p").height(); * @before <p>This is just a test.</p> * @result "14px" * * @name height * @type String * @cat CSS */ /** * Set the CSS height of every matched element. Be sure to include * the "px" (or other unit of measurement) after the number that you * specify, otherwise you might get strange results. * * @example $("p").height("20px"); * @before <p>This is just a test.</p> * @result <p style="height:20px;">This is just a test.</p> * * @name height * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS top of the first matched element. * * @example $("p").top(); * @before <p>This is just a test.</p> * @result "0px" * * @name top * @type String * @cat CSS */ /** * Set the CSS top of every matched element. Be sure to include * the "px" (or other unit of measurement) after the number that you * specify, otherwise you might get strange results. * * @example $("p").top("20px"); * @before <p>This is just a test.</p> * @result <p style="top:20px;">This is just a test.</p> * * @name top * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS left of the first matched element. * * @example $("p").left(); * @before <p>This is just a test.</p> * @result "0px" * * @name left * @type String * @cat CSS */ /** * Set the CSS left of every matched element. Be sure to include * the "px" (or other unit of measurement) after the number that you * specify, otherwise you might get strange results. * * @example $("p").left("20px"); * @before <p>This is just a test.</p> * @result <p style="left:20px;">This is just a test.</p> * * @name left * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS position of the first matched element. * * @example $("p").position(); * @before <p>This is just a test.</p> * @result "static" * * @name position * @type String * @cat CSS */ /** * Set the CSS position of every matched element. * * @example $("p").position("relative"); * @before <p>This is just a test.</p> * @result <p style="position:relative;">This is just a test.</p> * * @name position * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS float of the first matched element. * * @example $("p").float(); * @before <p>This is just a test.</p> * @result "none" * * @name float * @type String * @cat CSS */ /** * Set the CSS float of every matched element. * * @example $("p").float("left"); * @before <p>This is just a test.</p> * @result <p style="float:left;">This is just a test.</p> * * @name float * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS overflow of the first matched element. * * @example $("p").overflow(); * @before <p>This is just a test.</p> * @result "none" * * @name overflow * @type String * @cat CSS */ /** * Set the CSS overflow of every matched element. * * @example $("p").overflow("auto"); * @before <p>This is just a test.</p> * @result <p style="overflow:auto;">This is just a test.</p> * * @name overflow * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS color of the first matched element. * * @example $("p").color(); * @before <p>This is just a test.</p> * @result "black" * * @name color * @type String * @cat CSS */ /** * Set the CSS color of every matched element. * * @example $("p").color("blue"); * @before <p>This is just a test.</p> * @result <p style="color:blue;">This is just a test.</p> * * @name color * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ /** * Get the current CSS background of the first matched element. * * @example $("p").background(); * @before <p style="background:blue;">This is just a test.</p> * @result "blue" * * @name background * @type String * @cat CSS */ /** * Set the CSS background of every matched element. * * @example $("p").background("blue"); * @before <p>This is just a test.</p> * @result <p style="background:blue;">This is just a test.</p> * * @name background * @type jQuery * @param String val Set the CSS property to the specified value. * @cat CSS */ css: "width,height,top,left,position,float,overflow,color,background".split(","), /** * Reduce the set of matched elements to a single element. * The position of the element in the set of matched elements * starts at 0 and goes to length - 1. * * @example $("p").eq(1) * @before <p>This is just a test.</p><p>So is this</p> * @result [ <p>So is this</p> ] * * @name eq * @type jQuery * @param Number pos The index of the element that you wish to limit to. * @cat Core */ /** * Reduce the set of matched elements to all elements before a given position. * The position of the element in the set of matched elements * starts at 0 and goes to length - 1. * * @example $("p").lt(1) * @before <p>This is just a test.</p><p>So is this</p> * @result [ <p>This is just a test.</p> ] * * @name lt * @type jQuery * @param Number pos Reduce the set to all elements below this position. * @cat Core */ /** * Reduce the set of matched elements to all elements after a given position. * The position of the element in the set of matched elements * starts at 0 and goes to length - 1. * * @example $("p").gt(0) * @before <p>This is just a test.</p><p>So is this</p> * @result [ <p>So is this</p> ] * * @name gt * @type jQuery * @param Number pos Reduce the set to all elements after this position. * @cat Core */ /** * Filter the set of elements to those that contain the specified text. * * @example $("p").contains("test") * @before <p>This is just a test.</p><p>So is this</p> * @result [ <p>This is just a test.</p> ] * * @name contains * @type jQuery * @param String str The string that will be contained within the text of an element. * @cat DOM/Traversing */ filter: [ "eq", "lt", "gt", "contains" ], attr: { /** * Get the current value of the first matched element. * * @example $("input").val(); * @before <input type="text" value="some text"/> * @result "some text" * * @test ok( $("#text1").val() == "Test", "Check for value of input element" ); * ok( !$("#text1").val() == "", "Check for value of input element" ); * * @name val * @type String * @cat DOM/Attributes */ /** * Set the value of every matched element. * * @example $("input").val("test"); * @before <input type="text" value="some text"/> * @result <input type="text" value="test"/> * * @test document.getElementById('text1').value = "bla"; * ok( $("#text1").val() == "bla", "Check for modified value of input element" ); * $("#text1").val('test'); * ok ( document.getElementById('text1').value == "test", "Check for modified (via val(String)) value of input element" ); * * @name val * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ val: "value", /** * Get the html contents of the first matched element. * * @example $("div").html(); * @before <div><input/></div> * @result <input/> * * @name html * @type String * @cat DOM/Attributes */ /** * Set the html contents of every matched element. * * @example $("div").html("<b>new stuff</b>"); * @before <div><input/></div> * @result <div><b>new stuff</b></div> * * @test var div = $("div"); * div.html("<b>test</b>"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).childNodes.length == 0 ) pass = false; * } * ok( pass, "Set HTML" ); * * @name html * @type jQuery * @param String val Set the html contents to the specified value. * @cat DOM/Attributes */ html: "innerHTML", /** * Get the current id of the first matched element. * * @example $("input").id(); * @before <input type="text" id="test" value="some text"/> * @result "test" * * @test ok( $(document.getElementById('main')).id() == "main", "Check for id" ); * ok( $("#foo").id() == "foo", "Check for id" ); * ok( !$("head").id(), "Check for id" ); * * @name id * @type String * @cat DOM/Attributes */ /** * Set the id of every matched element. * * @example $("input").id("newid"); * @before <input type="text" id="test" value="some text"/> * @result <input type="text" id="newid" value="some text"/> * * @name id * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ id: null, /** * Get the current title of the first matched element. * * @example $("img").title(); * @before <img src="test.jpg" title="my image"/> * @result "my image" * * @test ok( $(document.getElementById('google')).title() == "Google!", "Check for title" ); * ok( !$("#yahoo").title(), "Check for title" ); * * @name title * @type String * @cat DOM/Attributes */ /** * Set the title of every matched element. * * @example $("img").title("new title"); * @before <img src="test.jpg" title="my image"/> * @result <img src="test.jpg" title="new image"/> * * @name title * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ title: null, /** * Get the current name of the first matched element. * * @example $("input").name(); * @before <input type="text" name="username"/> * @result "username" * * @test ok( $(document.getElementById('text1')).name() == "action", "Check for name" ); * ok( $("#hidden1").name() == "hidden", "Check for name" ); * ok( !$("#area1").name(), "Check for name" ); * * @name name * @type String * @cat DOM/Attributes */ /** * Set the name of every matched element. * * @example $("input").name("user"); * @before <input type="text" name="username"/> * @result <input type="text" name="user"/> * * @name name * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ name: null, /** * Get the current href of the first matched element. * * @example $("a").href(); * @before <a href="test.html">my link</a> * @result "test.html" * * @name href * @type String * @cat DOM/Attributes */ /** * Set the href of every matched element. * * @example $("a").href("test2.html"); * @before <a href="test.html">my link</a> * @result <a href="test2.html">my link</a> * * @name href * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ href: null, /** * Get the current src of the first matched element. * * @example $("img").src(); * @before <img src="test.jpg" title="my image"/> * @result "test.jpg" * * @name src * @type String * @cat DOM/Attributes */ /** * Set the src of every matched element. * * @example $("img").src("test2.jpg"); * @before <img src="test.jpg" title="my image"/> * @result <img src="test2.jpg" title="my image"/> * * @name src * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ src: null, /** * Get the current rel of the first matched element. * * @example $("a").rel(); * @before <a href="test.html" rel="nofollow">my link</a> * @result "nofollow" * * @name rel * @type String * @cat DOM/Attributes */ /** * Set the rel of every matched element. * * @example $("a").rel("nofollow"); * @before <a href="test.html">my link</a> * @result <a href="test.html" rel="nofollow">my link</a> * * @name rel * @type jQuery * @param String val Set the property to the specified value. * @cat DOM/Attributes */ rel: null }, axis: { /** * Get a set of elements containing the unique parents of the matched * set of elements. * * @example $("p").parent() * @before <div><p>Hello</p><p>Hello</p></div> * @result [ <div><p>Hello</p><p>Hello</p></div> ] * * @name parent * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique parents of the matched * set of elements, and filtered by an expression. * * @example $("p").parent(".selected") * @before <div><p>Hello</p></div><div class="selected"><p>Hello Again</p></div> * @result [ <div class="selected"><p>Hello Again</p></div> ] * * @name parent * @type jQuery * @param String expr An expression to filter the parents with * @cat DOM/Traversing */ parent: "a.parentNode", /** * Get a set of elements containing the unique ancestors of the matched * set of elements (except for the root element). * * @example $("span").ancestors() * @before <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html> * @result [ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ] * * @name ancestors * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique ancestors of the matched * set of elements, and filtered by an expression. * * @example $("span").ancestors("p") * @before <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html> * @result [ <p><span>Hello</span></p> ] * * @name ancestors * @type jQuery * @param String expr An expression to filter the ancestors with * @cat DOM/Traversing */ ancestors: jQuery.parents, /** * Get a set of elements containing the unique ancestors of the matched * set of elements (except for the root element). * * @example $("span").ancestors() * @before <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html> * @result [ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ] * * @name parents * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique ancestors of the matched * set of elements, and filtered by an expression. * * @example $("span").ancestors("p") * @before <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html> * @result [ <p><span>Hello</span></p> ] * * @name parents * @type jQuery * @param String expr An expression to filter the ancestors with * @cat DOM/Traversing */ parents: jQuery.parents, /** * Get a set of elements containing the unique next siblings of each of the * matched set of elements. * * It only returns the very next sibling, not all next siblings. * * @example $("p").next() * @before <p>Hello</p><p>Hello Again</p><div><span>And Again</span></div> * @result [ <p>Hello Again</p>, <div><span>And Again</span></div> ] * * @name next * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique next siblings of each of the * matched set of elements, and filtered by an expression. * * It only returns the very next sibling, not all next siblings. * * @example $("p").next(".selected") * @before <p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div> * @result [ <p class="selected">Hello Again</p> ] * * @name next * @type jQuery * @param String expr An expression to filter the next Elements with * @cat DOM/Traversing */ next: "jQuery.sibling(a).next", /** * Get a set of elements containing the unique previous siblings of each of the * matched set of elements. * * It only returns the immediately previous sibling, not all previous siblings. * * @example $("p").prev() * @before <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p> * @result [ <div><span>Hello Again</span></div> ] * * @name prev * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing the unique previous siblings of each of the * matched set of elements, and filtered by an expression. * * It only returns the immediately previous sibling, not all previous siblings. * * @example $("p").previous(".selected") * @before <div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p> * @result [ <div><span>Hello</span></div> ] * * @name prev * @type jQuery * @param String expr An expression to filter the previous Elements with * @cat DOM/Traversing */ prev: "jQuery.sibling(a).prev", /** * Get a set of elements containing all of the unique siblings of each of the * matched set of elements. * * @example $("div").siblings() * @before <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p> * @result [ <p>Hello</p>, <p>And Again</p> ] * * @test isSet( $("#en").siblings().get(), q("sndp", "sap"), "Check for siblings" ); * * @name siblings * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing all of the unique siblings of each of the * matched set of elements, and filtered by an expression. * * @example $("div").siblings(".selected") * @before <div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p> * @result [ <p class="selected">Hello Again</p> ] * * @test isSet( $("#sndp").siblings("[code]").get(), q("sap"), "Check for filtered siblings (has code child element)" ); * isSet( $("#sndp").siblings("[a]").get(), q("en", "sap"), "Check for filtered siblings (has anchor child element)" ); * * @name siblings * @type jQuery * @param String expr An expression to filter the sibling Elements with * @cat DOM/Traversing */ siblings: "jQuery.sibling(a, null, true)", /** * Get a set of elements containing all of the unique children of each of the * matched set of elements. * * @example $("div").children() * @before <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p> * @result [ <span>Hello Again</span> ] * * @test isSet( $("#foo").children().get(), q("sndp", "en", "sap"), "Check for children" ); * * @name children * @type jQuery * @cat DOM/Traversing */ /** * Get a set of elements containing all of the unique children of each of the * matched set of elements, and filtered by an expression. * * @example $("div").children(".selected") * @before <div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div> * @result [ <p class="selected">Hello Again</p> ] * * @test isSet( $("#foo").children("[code]").get(), q("sndp", "sap"), "Check for filtered children" ); * * @name children * @type jQuery * @param String expr An expression to filter the child Elements with * @cat DOM/Traversing */ children: "jQuery.sibling(a.firstChild)" }, each: { /** * Remove an attribute from each of the matched elements. * * @example $("input").removeAttr("disabled") * @before <input disabled="disabled"/> * @result <input/> * * @name removeAttr * @type jQuery * @param String name The name of the attribute to remove. * @cat DOM */ removeAttr: function( key ) { this.removeAttribute( key ); }, /** * Displays each of the set of matched elements if they are hidden. * * @example $("p").show() * @before <p style="display: none">Hello</p> * @result [ <p style="display: block">Hello</p> ] * * @test var pass = true, div = $("div"); * div.show().each(function(){ * if ( this.style.display == "none" ) pass = false; * }); * ok( pass, "Show" ); * * @name show * @type jQuery * @cat Effects */ show: function(){ this.style.display = this.oldblock ? this.oldblock : ""; if ( jQuery.css(this,"display") == "none" ) this.style.display = "block"; }, /** * Hides each of the set of matched elements if they are shown. * * @example $("p").hide() * @before <p>Hello</p> * @result [ <p style="display: none">Hello</p> ] * * var pass = true, div = $("div"); * div.hide().each(function(){ * if ( this.style.display != "none" ) pass = false; * }); * ok( pass, "Hide" ); * * @name hide * @type jQuery * @cat Effects */ hide: function(){ this.oldblock = this.oldblock || jQuery.css(this,"display"); if ( this.oldblock == "none" ) this.oldblock = "block"; this.style.display = "none"; }, /** * Toggles each of the set of matched elements. If they are shown, * toggle makes them hidden. If they are hidden, toggle * makes them shown. * * @example $("p").toggle() * @before <p>Hello</p><p style="display: none">Hello Again</p> * @result [ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ] * * @name toggle * @type jQuery * @cat Effects */ toggle: function(){ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ].apply( jQuery(this), arguments ); }, /** * Adds the specified class to each of the set of matched elements. * * @example $("p").addClass("selected") * @before <p>Hello</p> * @result [ <p class="selected">Hello</p> ] * * @test var div = $("div"); * div.addClass("test"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).className.indexOf("test") == -1 ) pass = false; * } * ok( pass, "Add Class" ); * * @name addClass * @type jQuery * @param String class A CSS class to add to the elements * @cat DOM */ addClass: function(c){ jQuery.className.add(this,c); }, /** * Removes the specified class from the set of matched elements. * * @example $("p").removeClass("selected") * @before <p class="selected">Hello</p> * @result [ <p>Hello</p> ] * * @test var div = $("div").addClass("test"); * div.removeClass("test"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).className.indexOf("test") != -1 ) pass = false; * } * ok( pass, "Remove Class" ); * * reset(); * * var div = $("div").addClass("test").addClass("foo").addClass("bar"); * div.removeClass("test").removeClass("bar").removeClass("foo"); * var pass = true; * for ( var i = 0; i < div.size(); i++ ) { * if ( div.get(i).className.match(/test|bar|foo/) ) pass = false; * } * ok( pass, "Remove multiple classes" ); * * @name removeClass * @type jQuery * @param String class A CSS class to remove from the elements * @cat DOM */ removeClass: function(c){ jQuery.className.remove(this,c); }, /** * Adds the specified class if it is present, removes it if it is * not present. * * @example $("p").toggleClass("selected") * @before <p>Hello</p><p class="selected">Hello Again</p> * @result [ <p class="selected">Hello</p>, <p>Hello Again</p> ] * * @name toggleClass * @type jQuery * @param String class A CSS class with which to toggle the elements * @cat DOM */ toggleClass: function( c ){ jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this,c); }, /** * Removes all matched elements from the DOM. This does NOT remove them from the * jQuery object, allowing you to use the matched elements further. * * @example $("p").remove(); * @before <p>Hello</p> how are <p>you?</p> * @result how are * * @name remove * @type jQuery * @cat DOM/Manipulation */ /** * Removes only elements (out of the list of matched elements) that match * the specified jQuery expression. This does NOT remove them from the * jQuery object, allowing you to use the matched elements further. * * @example $("p").remove(".hello"); * @before <p class="hello">Hello</p> how are <p>you?</p> * @result how are <p>you?</p> * * @name remove * @type jQuery * @param String expr A jQuery expression to filter elements by. * @cat DOM/Manipulation */ remove: function(a){ if ( !a || jQuery.filter( a, [this] ).r ) this.parentNode.removeChild( this ); }, /** * Removes all child nodes from the set of matched elements. * * @example $("p").empty() * @before <p>Hello, <span>Person</span> <a href="#">and person</a></p> * @result [ <p></p> ] * * @name empty * @type jQuery * @cat DOM/Manipulation */ empty: function(){ while ( this.firstChild ) this.removeChild( this.firstChild ); }, /** * Binds a handler to a particular event (like click) for each matched element. * The event handler is passed an event object that you can use to prevent * default behaviour. To stop both default action and event bubbling, your handler * has to return false. * * @example $("p").bind( "click", function() { * alert( $(this).text() ); * } ) * @before <p>Hello</p> * @result alert("Hello") * * @example $("form").bind( "submit", function() { return false; } ) * @desc Cancel a default action and prevent it from bubbling by returning false * from your function. * * @example $("form").bind( "submit", function(event) { * event.preventDefault(); * } ); * @desc Cancel only the default action by using the preventDefault method. * * * @example $("form").bind( "submit", function(event) { * event.stopPropagation(); * } ) * @desc Stop only an event from bubbling by using the stopPropagation method. * * @name bind * @type jQuery * @param String type An event type * @param Function fn A function to bind to the event on each of the set of matched elements * @cat Events */ bind: function( type, fn ) { if ( fn.constructor == String ) fn = new Function("e", ( !fn.indexOf(".") ? "jQuery(this)" : "return " ) + fn); jQuery.event.add( this, type, fn ); }, /** * The opposite of bind, removes a bound event from each of the matched * elements. You must pass the identical function that was used in the original * bind method. * * @example $("p").unbind( "click", function() { alert("Hello"); } ) * @before <p onclick="alert('Hello');">Hello</p> * @result [ <p>Hello</p> ] * * @name unbind * @type jQuery * @param String type An event type * @param Function fn A function to unbind from the event on each of the set of matched elements * @cat Events */ /** * Removes all bound events of a particular type from each of the matched * elements. * * @example $("p").unbind( "click" ) * @before <p onclick="alert('Hello');">Hello</p> * @result [ <p>Hello</p> ] * * @name unbind * @type jQuery * @param String type An event type * @cat Events */ /** * Removes all bound events from each of the matched elements. * * @example $("p").unbind() * @before <p onclick="alert('Hello');">Hello</p> * @result [ <p>Hello</p> ] * * @name unbind * @type jQuery * @cat Events */ unbind: function( type, fn ) { jQuery.event.remove( this, type, fn ); }, /** * Trigger a type of event on every matched element. * * @example $("p").trigger("click") * @before <p click="alert('hello')">Hello</p> * @result alert('hello') * * @name trigger * @type jQuery * @param String type An event type to trigger. * @cat Events */ trigger: function( type, data ) { jQuery.event.trigger( type, data, this ); } } }; jQuery.init();
Fixed previous() in docs git-svn-id: a6f3e0ffc78e78789c45711e92f8046af3fcb362@501 c715fcbe-d12f-0410-84c4-316a508785bb
src/jquery/jquery.js
Fixed previous() in docs
<ide><path>rc/jquery/jquery.js <ide> * <ide> * It only returns the immediately previous sibling, not all previous siblings. <ide> * <del> * @example $("p").previous(".selected") <add> * @example $("p").prev(".selected") <ide> * @before <div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p> <ide> * @result [ <div><span>Hello</span></div> ] <ide> *
Java
epl-1.0
57e626a3d86276b2c248450f272e3615422895df
0
codenvy/che,davidfestal/che,jonahkichwacoders/che,akervern/che,TypeFox/che,sleshchenko/che,TypeFox/che,akervern/che,akervern/che,jonahkichwacoders/che,TypeFox/che,codenvy/che,davidfestal/che,akervern/che,codenvy/che,akervern/che,sleshchenko/che,Patricol/che,davidfestal/che,Patricol/che,davidfestal/che,jonahkichwacoders/che,TypeFox/che,davidfestal/che,akervern/che,Patricol/che,jonahkichwacoders/che,Patricol/che,sleshchenko/che,Patricol/che,jonahkichwacoders/che,Patricol/che,sleshchenko/che,jonahkichwacoders/che,Patricol/che,codenvy/che,sleshchenko/che,jonahkichwacoders/che,TypeFox/che,TypeFox/che,sleshchenko/che,davidfestal/che,jonahkichwacoders/che,sleshchenko/che,davidfestal/che,TypeFox/che,davidfestal/che,Patricol/che,TypeFox/che,akervern/che,sleshchenko/che,TypeFox/che,davidfestal/che,sleshchenko/che,akervern/che,sleshchenko/che,Patricol/che,davidfestal/che,Patricol/che,jonahkichwacoders/che,akervern/che,jonahkichwacoders/che,TypeFox/che
/* * Copyright (c) 2012-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.factory; import static org.eclipse.che.ide.api.action.IdeActions.GROUP_PROJECT; import static org.eclipse.che.ide.api.action.IdeActions.GROUP_WORKSPACE; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.ide.api.action.ActionManager; import org.eclipse.che.ide.api.action.DefaultActionGroup; import org.eclipse.che.ide.api.extension.Extension; import org.eclipse.che.ide.factory.accept.AcceptFactoryHandler; import org.eclipse.che.ide.factory.action.CreateFactoryAction; import org.eclipse.che.ide.factory.json.ImportFromConfigAction; import org.eclipse.che.ide.factory.welcome.OpenWelcomePageAction; /** @author Vladyslav Zhukovskii */ @Singleton @Extension(title = "Factory", version = "3.0.0") public class FactoryExtension { @Inject public FactoryExtension( AcceptFactoryHandler acceptFactoryHandler, ActionManager actionManager, FactoryResources resources, CreateFactoryAction configureFactoryAction, ImportFromConfigAction importFromConfigAction, OpenWelcomePageAction openWelcomePageAction) { acceptFactoryHandler.process(); resources.factoryCSS().ensureInjected(); DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction("openWelcomePage", openWelcomePageAction); actionManager.registerAction("importProjectFromCodenvyConfigAction", importFromConfigAction); actionManager.registerAction("configureFactoryAction", configureFactoryAction); projectGroup.add(importFromConfigAction); workspaceGroup.add(configureFactoryAction); } }
ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/factory/FactoryExtension.java
/* * Copyright (c) 2012-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.factory; import static com.google.gwt.core.client.ScriptInjector.TOP_WINDOW; import static org.eclipse.che.ide.api.action.IdeActions.GROUP_PROJECT; import static org.eclipse.che.ide.api.action.IdeActions.GROUP_WORKSPACE; import com.google.gwt.core.client.Callback; import com.google.gwt.core.client.ScriptInjector; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.ide.api.action.ActionManager; import org.eclipse.che.ide.api.action.DefaultActionGroup; import org.eclipse.che.ide.api.extension.Extension; import org.eclipse.che.ide.factory.accept.AcceptFactoryHandler; import org.eclipse.che.ide.factory.action.CreateFactoryAction; import org.eclipse.che.ide.factory.json.ImportFromConfigAction; import org.eclipse.che.ide.factory.welcome.OpenWelcomePageAction; /** @author Vladyslav Zhukovskii */ @Singleton @Extension(title = "Factory", version = "3.0.0") public class FactoryExtension { @Inject public FactoryExtension( AcceptFactoryHandler acceptFactoryHandler, ActionManager actionManager, FactoryResources resources, CreateFactoryAction configureFactoryAction, ImportFromConfigAction importFromConfigAction, OpenWelcomePageAction openWelcomePageAction) { acceptFactoryHandler.process(); /* * Inject resources and js */ ScriptInjector.fromUrl("https://apis.google.com/js/client:plusone.js?parsetags=explicit") .setWindow(TOP_WINDOW) .inject(); ScriptInjector.fromUrl("https://connect.facebook.net/en_US/sdk.js") .setWindow(TOP_WINDOW) .setCallback( new Callback<Void, Exception>() { @Override public void onSuccess(Void result) { init(); } @Override public void onFailure(Exception reason) {} private native void init() /*-{ $wnd.FB.init({ appId: "318167898391385", xfbml: true, version: "v2.1" }); }-*/; }) .inject(); resources.factoryCSS().ensureInjected(); DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction("openWelcomePage", openWelcomePageAction); actionManager.registerAction("importProjectFromCodenvyConfigAction", importFromConfigAction); actionManager.registerAction("configureFactoryAction", configureFactoryAction); projectGroup.add(importFromConfigAction); workspaceGroup.add(configureFactoryAction); } }
Remove unused legacy parts (#6351)
ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/factory/FactoryExtension.java
Remove unused legacy parts (#6351)
<ide><path>de/che-core-ide-app/src/main/java/org/eclipse/che/ide/factory/FactoryExtension.java <ide> */ <ide> package org.eclipse.che.ide.factory; <ide> <del>import static com.google.gwt.core.client.ScriptInjector.TOP_WINDOW; <ide> import static org.eclipse.che.ide.api.action.IdeActions.GROUP_PROJECT; <ide> import static org.eclipse.che.ide.api.action.IdeActions.GROUP_WORKSPACE; <ide> <del>import com.google.gwt.core.client.Callback; <del>import com.google.gwt.core.client.ScriptInjector; <ide> import com.google.inject.Inject; <ide> import com.google.inject.Singleton; <ide> import org.eclipse.che.ide.api.action.ActionManager; <ide> OpenWelcomePageAction openWelcomePageAction) { <ide> acceptFactoryHandler.process(); <ide> <del> /* <del> * Inject resources and js <del> */ <del> ScriptInjector.fromUrl("https://apis.google.com/js/client:plusone.js?parsetags=explicit") <del> .setWindow(TOP_WINDOW) <del> .inject(); <del> <del> ScriptInjector.fromUrl("https://connect.facebook.net/en_US/sdk.js") <del> .setWindow(TOP_WINDOW) <del> .setCallback( <del> new Callback<Void, Exception>() { <del> @Override <del> public void onSuccess(Void result) { <del> init(); <del> } <del> <del> @Override <del> public void onFailure(Exception reason) {} <del> <del> private native void init() /*-{ <del> $wnd.FB.init({ <del> appId: "318167898391385", <del> xfbml: true, <del> version: "v2.1" <del> }); <del> }-*/; <del> }) <del> .inject(); <del> <ide> resources.factoryCSS().ensureInjected(); <ide> <ide> DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT);
Java
bsd-2-clause
43a444a22c775a2ae509ab39f2ce19c0369d5a86
0
KorAP/Koral
import static org.junit.Assert.*; import de.ids_mannheim.korap.query.serialize.CollectionQueryTree; import de.ids_mannheim.korap.util.QueryException; import org.junit.Test; public class CollectionQueryTreeTest { CollectionQueryTree cqt; String map; private String query; private String expected; private boolean equalsQueryContent(String res, String query) throws QueryException { res = res.replaceAll(" ", ""); cqt = new CollectionQueryTree(); cqt.process(query); String queryMap = cqt.getRequestMap().get("query").toString().replaceAll(" ", ""); return res.equals(queryMap); } @Test public void testSimple() throws QueryException { query = "textClass=Sport"; // String regex1 = "{@type=korap:filter, filter={@type=korap:doc, attribute=textClass, key=Sport, match=match:eq}}"; expected = "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "textClass!=Sport"; // String regex1 = "{@type=korap:filter, filter={@type=korap:doc, attribute=textClass, key=Sport, match=match:eq}}"; expected = "{@type=korap:doc, key=textClass, value=Sport, match=match:ne}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testTwoConjuncts() throws QueryException { query = "textClass=Sport & year=2014"; expected = "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=year, value=2014, match=match:eq}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testThreeConjuncts() throws QueryException { query = "textClass=Sport & year=2014 & corpusID=WPD"; expected = "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=year, value=2014, match=match:eq}," + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + "]}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testTwoDisjuncts() throws QueryException { query = "textClass=Sport | year=2014"; expected = "{@type=korap:group, operation=operation:or, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=year, value=2014, match=match:eq}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testThreeDisjuncts() throws QueryException { query = "textClass=Sport | year=2014 | corpusID=WPD"; expected = "{@type=korap:group, operation=operation:or, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:group, operation=operation:or, operands=[" + "{@type=korap:doc, key=year, value=2014, match=match:eq}," + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + "]}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testMixed() throws QueryException { query = "(textClass=Sport | textClass=ausland) & corpusID=WPD"; expected = "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:group, operation=operation:or, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + "]}," + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "(textClass=Sport & textClass=ausland) & corpusID=WPD"; expected = "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + "]}," + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "(textClass=Sport & textClass=ausland) | (corpusID=WPD & author=White)"; expected = "{@type=korap:group, operation=operation:or, operands=[" + "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + "]}," + "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}," + "{@type=korap:doc, key=author, value=White, match=match:eq}" + "]}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "(textClass=Sport & textClass=ausland) | (corpusID=WPD & author=White & year=2010)"; expected = "{@type=korap:group, operation=operation:or, operands=[" + "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + "]}," + "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}," + "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=author, value=White, match=match:eq}," + "{@type=korap:doc, key=year, value=2010, match=match:eq}" + "]}" + "]}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testDate() throws QueryException { // search for pubDate between 1990 and 2010! query = "1990<pubDate<2010"; expected = "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=pubDate, value=1990, match=match:gt}," + "{@type=korap:doc, key=pubDate, value=2010, match=match:lt}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "pubDate>=1990"; expected = "{@type=korap:doc, key=pubDate, value=1990, match=match:geq}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "pubDate>=1990-05"; expected = "{@type=korap:doc, key=pubDate, value=1990-05, match=match:geq}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "pubDate>=1990-05-01"; expected = "{@type=korap:doc, key=pubDate, value=1990-05-01, match=match:geq}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testRegex() throws QueryException { query = "author=/Go.*he/"; expected = "{@type=korap:doc, key=author, value=Go.*he, type=type:regex, match=match:eq}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testContentFilter() throws QueryException { query = "[base=Schwalbe]"; expected = "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:eq}}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "[cnx/base=Schwalbe]"; expected = "{@type=korap:token, wrap={@type=korap:term, foundry=cnx, layer=lemma, key=Schwalbe, match=match:eq}}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "[base!=Schwalbe]"; expected = "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:ne}}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "[base=Schwalbe] & [orth=Foul]"; expected = "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:eq}}," + "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Foul, match=match:eq}}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testContentMetaMixed() throws QueryException { query = "textClass=Sport & [base=Schwalbe]"; expected = "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:eq}}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "[base=Schwalbe] & textClass=Sport"; expected = "{@type=korap:group, operation=operation:and, operands=[" + "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:eq}}," + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}" + "]}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } }
src/test/java/CollectionQueryTreeTest.java
import de.ids_mannheim.korap.query.serialize.CollectionQueryTree; import de.ids_mannheim.korap.util.QueryException; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CollectionQueryTreeTest { CollectionQueryTree cqt; String map; private String query; private String expected; private boolean equalsQueryContent(String res, String query) throws QueryException { res = res.replaceAll(" ", ""); cqt = new CollectionQueryTree(); cqt.process(query); String queryMap = cqt.getRequestMap().get("query").toString().replaceAll(" ", ""); return res.equals(queryMap); } @Test public void testSimple() throws QueryException { query = "textClass=Sport"; // String regex1 = "{@type=korap:filter, filter={@type=korap:doc, attribute=textClass, key=Sport, match=match:eq}}"; expected = "{@type=korap:filter, filter={@type=korap:doc, key=textClass, value=Sport, match=match:eq}}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "textClass!=Sport"; // String regex1 = "{@type=korap:filter, filter={@type=korap:doc, attribute=textClass, key=Sport, match=match:eq}}"; expected = "{@type=korap:filter, filter={@type=korap:doc, key=textClass, value=Sport, match=match:ne}}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testTwoConjuncts() throws QueryException { query = "textClass=Sport & year=2014"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=year, value=2014, match=match:eq}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testThreeConjuncts() throws QueryException { query = "textClass=Sport & year=2014 & corpusID=WPD"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=year, value=2014, match=match:eq}," + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + "]}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testTwoDisjuncts() throws QueryException { query = "textClass=Sport | year=2014"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:or, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=year, value=2014, match=match:eq}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testThreeDisjuncts() throws QueryException { query = "textClass=Sport | year=2014 | corpusID=WPD"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:or, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:docGroup, relation=relation:or, operands=[" + "{@type=korap:doc, key=year, value=2014, match=match:eq}," + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + "]}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testMixed() throws QueryException { query = "(textClass=Sport | textClass=ausland) & corpusID=WPD"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:docGroup, relation=relation:or, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + "]}," + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "(textClass=Sport & textClass=ausland) & corpusID=WPD"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + "]}," + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "(textClass=Sport & textClass=ausland) | (corpusID=WPD & author=White)"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:or, operands=[" + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + "]}," + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}," + "{@type=korap:doc, key=author, value=White, match=match:eq}" + "]}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "(textClass=Sport & textClass=ausland) | (corpusID=WPD & author=White & year=2010)"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:or, operands=[" + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + "]}," + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}," + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=author, value=White, match=match:eq}," + "{@type=korap:doc, key=year, value=2010, match=match:eq}" + "]}" + "]}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testDate() throws QueryException { // search for pubDate between 1990 and 2010! query = "1990<pubDate<2010"; expected = "{@type=korap:filter, filter=" + "{@type=korap:docGroup, relation=relation:and, operands=[" + "{@type=korap:doc, key=pubDate, value=1990, match=match:gt}," + "{@type=korap:doc, key=pubDate, value=2010, match=match:lt}" + "]}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "pubDate>=1990"; expected = "{@type=korap:filter, filter=" + "{@type=korap:doc, key=pubDate, value=1990, match=match:geq}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "pubDate>=1990-05"; expected = "{@type=korap:filter, filter=" + "{@type=korap:doc, key=pubDate, value=1990-05, match=match:geq}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); query = "pubDate>=1990-05-01"; expected = "{@type=korap:filter, filter=" + "{@type=korap:doc, key=pubDate, value=1990-05-01, match=match:geq}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } @Test public void testRegex() throws QueryException { query = "author=/Go.*he/"; expected = "{@type=korap:filter, filter=" + "{@type=korap:doc, key=author, value=Go.*he, type=type:regex, match=match:eq}" + "}"; cqt = new CollectionQueryTree(); cqt.process(query); map = cqt.getRequestMap().toString(); assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); } }
test content queries
src/test/java/CollectionQueryTreeTest.java
test content queries
<ide><path>rc/test/java/CollectionQueryTreeTest.java <add>import static org.junit.Assert.*; <ide> import de.ids_mannheim.korap.query.serialize.CollectionQueryTree; <ide> import de.ids_mannheim.korap.util.QueryException; <ide> import org.junit.Test; <del> <del>import static org.junit.Assert.assertEquals; <ide> <ide> public class CollectionQueryTreeTest { <ide> <ide> public void testSimple() throws QueryException { <ide> query = "textClass=Sport"; <ide> // String regex1 = "{@type=korap:filter, filter={@type=korap:doc, attribute=textClass, key=Sport, match=match:eq}}"; <del> expected = "{@type=korap:filter, filter={@type=korap:doc, key=textClass, value=Sport, match=match:eq}}"; <add> expected = "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> <ide> query = "textClass!=Sport"; <ide> // String regex1 = "{@type=korap:filter, filter={@type=korap:doc, attribute=textClass, key=Sport, match=match:eq}}"; <del> expected = "{@type=korap:filter, filter={@type=korap:doc, key=textClass, value=Sport, match=match:ne}}"; <add> expected = "{@type=korap:doc, key=textClass, value=Sport, match=match:ne}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> public void testTwoConjuncts() throws QueryException { <ide> query = "textClass=Sport & year=2014"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <add> "{@type=korap:group, operation=operation:and, operands=[" + <ide> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <ide> "{@type=korap:doc, key=year, value=2014, match=match:eq}" + <del> "]}" + <del> "}"; <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> public void testThreeConjuncts() throws QueryException { <ide> query = "textClass=Sport & year=2014 & corpusID=WPD"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <del> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <add> "{@type=korap:group, operation=operation:and, operands=[" + <add> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <add> "{@type=korap:group, operation=operation:and, operands=[" + <ide> "{@type=korap:doc, key=year, value=2014, match=match:eq}," + <ide> "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + <ide> "]}" + <del> "]}" + <del> "}"; <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> public void testTwoDisjuncts() throws QueryException { <ide> query = "textClass=Sport | year=2014"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:or, operands=[" + <add> "{@type=korap:group, operation=operation:or, operands=[" + <ide> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <ide> "{@type=korap:doc, key=year, value=2014, match=match:eq}" + <del> "]}" + <del> "}"; <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> public void testThreeDisjuncts() throws QueryException { <ide> query = "textClass=Sport | year=2014 | corpusID=WPD"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:or, operands=[" + <del> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <del> "{@type=korap:docGroup, relation=relation:or, operands=[" + <add> "{@type=korap:group, operation=operation:or, operands=[" + <add> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <add> "{@type=korap:group, operation=operation:or, operands=[" + <ide> "{@type=korap:doc, key=year, value=2014, match=match:eq}," + <ide> "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + <ide> "]}" + <del> "]}" + <del> "}"; <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> public void testMixed() throws QueryException { <ide> query = "(textClass=Sport | textClass=ausland) & corpusID=WPD"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <del> "{@type=korap:docGroup, relation=relation:or, operands=[" + <add> <add> "{@type=korap:group, operation=operation:and, operands=[" + <add> "{@type=korap:group, operation=operation:or, operands=[" + <ide> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <ide> "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + <ide> "]}," + <ide> "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + <del> "]}" + <del> "}"; <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> <ide> query = "(textClass=Sport & textClass=ausland) & corpusID=WPD"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <add> <add> "{@type=korap:group, operation=operation:and, operands=[" + <add> "{@type=korap:group, operation=operation:and, operands=[" + <ide> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <ide> "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + <ide> "]}," + <ide> "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}" + <del> "]}" + <del> "}"; <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> <ide> query = "(textClass=Sport & textClass=ausland) | (corpusID=WPD & author=White)"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:or, operands=[" + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <del> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <del> "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + <del> "]}," + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <add> <add> "{@type=korap:group, operation=operation:or, operands=[" + <add> "{@type=korap:group, operation=operation:and, operands=[" + <add> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <add> "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + <add> "]}," + <add> "{@type=korap:group, operation=operation:and, operands=[" + <ide> "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}," + <ide> "{@type=korap:doc, key=author, value=White, match=match:eq}" + <ide> "]}" + <del> "]}" + <del> "}"; <del> cqt = new CollectionQueryTree(); <del> cqt.process(query); <del> map = cqt.getRequestMap().toString(); <del> assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); <del> <del> query = "(textClass=Sport & textClass=ausland) | (corpusID=WPD & author=White & year=2010)"; <del> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:or, operands=[" + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <del> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <del> "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + <del> "]}," + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <add> "]}"; <add> cqt = new CollectionQueryTree(); <add> cqt.process(query); <add> map = cqt.getRequestMap().toString(); <add> assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); <add> <add> query = "(textClass=Sport & textClass=ausland) | (corpusID=WPD & author=White & year=2010)"; <add> expected = <add> "{@type=korap:group, operation=operation:or, operands=[" + <add> "{@type=korap:group, operation=operation:and, operands=[" + <add> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <add> "{@type=korap:doc, key=textClass, value=ausland, match=match:eq}" + <add> "]}," + <add> "{@type=korap:group, operation=operation:and, operands=[" + <ide> "{@type=korap:doc, key=corpusID, value=WPD, match=match:eq}," + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <add> "{@type=korap:group, operation=operation:and, operands=[" + <ide> "{@type=korap:doc, key=author, value=White, match=match:eq}," + <ide> "{@type=korap:doc, key=year, value=2010, match=match:eq}" + <ide> "]}" + <ide> "]}" + <del> "]}" + <del> "}"; <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> // search for pubDate between 1990 and 2010! <ide> query = "1990<pubDate<2010"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:docGroup, relation=relation:and, operands=[" + <add> "{@type=korap:group, operation=operation:and, operands=[" + <ide> "{@type=korap:doc, key=pubDate, value=1990, match=match:gt}," + <ide> "{@type=korap:doc, key=pubDate, value=2010, match=match:lt}" + <del> "]}" + <del> "}"; <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> <ide> query = "pubDate>=1990"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:doc, key=pubDate, value=1990, match=match:geq}" + <del> "}"; <add> "{@type=korap:doc, key=pubDate, value=1990, match=match:geq}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> <ide> query = "pubDate>=1990-05"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:doc, key=pubDate, value=1990-05, match=match:geq}" + <del> "}"; <add> "{@type=korap:doc, key=pubDate, value=1990-05, match=match:geq}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> <ide> query = "pubDate>=1990-05-01"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:doc, key=pubDate, value=1990-05-01, match=match:geq}" + <del> "}"; <add> "{@type=korap:doc, key=pubDate, value=1990-05-01, match=match:geq}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString(); <ide> public void testRegex() throws QueryException { <ide> query = "author=/Go.*he/"; <ide> expected = <del> "{@type=korap:filter, filter=" + <del> "{@type=korap:doc, key=author, value=Go.*he, type=type:regex, match=match:eq}" + <del> "}"; <add> "{@type=korap:doc, key=author, value=Go.*he, type=type:regex, match=match:eq}"; <add> cqt = new CollectionQueryTree(); <add> cqt.process(query); <add> map = cqt.getRequestMap().toString(); <add> assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); <add> } <add> <add> @Test <add> public void testContentFilter() throws QueryException { <add> query = "[base=Schwalbe]"; <add> expected = <add> "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:eq}}"; <add> cqt = new CollectionQueryTree(); <add> cqt.process(query); <add> map = cqt.getRequestMap().toString(); <add> assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); <add> <add> query = "[cnx/base=Schwalbe]"; <add> expected = <add> "{@type=korap:token, wrap={@type=korap:term, foundry=cnx, layer=lemma, key=Schwalbe, match=match:eq}}"; <add> cqt = new CollectionQueryTree(); <add> cqt.process(query); <add> map = cqt.getRequestMap().toString(); <add> assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); <add> <add> query = "[base!=Schwalbe]"; <add> expected = <add> "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:ne}}"; <add> cqt = new CollectionQueryTree(); <add> cqt.process(query); <add> map = cqt.getRequestMap().toString(); <add> assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); <add> <add> query = "[base=Schwalbe] & [orth=Foul]"; <add> expected = <add> "{@type=korap:group, operation=operation:and, operands=[" + <add> "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:eq}}," + <add> "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Foul, match=match:eq}}" + <add> "]}"; <add> cqt = new CollectionQueryTree(); <add> cqt.process(query); <add> map = cqt.getRequestMap().toString(); <add> assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); <add> } <add> <add> @Test <add> public void testContentMetaMixed() throws QueryException { <add> query = "textClass=Sport & [base=Schwalbe]"; <add> expected = <add> "{@type=korap:group, operation=operation:and, operands=[" + <add> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}," + <add> "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:eq}}" + <add> "]}"; <add> cqt = new CollectionQueryTree(); <add> cqt.process(query); <add> map = cqt.getRequestMap().toString(); <add> assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", "")); <add> <add> query = "[base=Schwalbe] & textClass=Sport"; <add> expected = <add> "{@type=korap:group, operation=operation:and, operands=[" + <add> "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schwalbe, match=match:eq}}," + <add> "{@type=korap:doc, key=textClass, value=Sport, match=match:eq}" + <add> "]}"; <ide> cqt = new CollectionQueryTree(); <ide> cqt.process(query); <ide> map = cqt.getRequestMap().toString();
Java
lgpl-2.1
bcd25b514df37b5b5eff26b5e9dc330073b736f5
0
svartika/ccnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,ebollens/ccnmp,cawka/ndnx,svartika/ccnx,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,cawka/ndnx,cawka/ndnx,svartika/ccnx,svartika/ccnx
package com.parc.ccn.data; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.data.util.DataUtils; import com.parc.ccn.data.util.GenericXMLEncodable; import com.parc.ccn.data.util.XMLDecoder; import com.parc.ccn.data.util.XMLEncodable; import com.parc.ccn.data.util.XMLEncoder; import com.sun.org.apache.xerces.internal.util.URI.MalformedURIException; public class ContentName extends GenericXMLEncodable implements XMLEncodable, Comparable<ContentName> { public static final String SCHEME = "ccn:"; public static final String SEPARATOR = "/"; public static final ContentName ROOT = new ContentName(0, (ArrayList<byte []>)null); public static final String CONTENT_NAME_ELEMENT = "Name"; private static final String COMPONENT_ELEMENT = "Component"; protected ArrayList<byte []> _components; public static class DotDotComponent extends Exception { // Need to strip off a component private static final long serialVersionUID = 4667513234636853164L; }; // Constructors // ContentNames consist of a sequence of byte[] components which may not // be assumed to follow any string encoding, or any other particular encoding. // The constructors therefore provide for creation only from byte[]s. // To create a ContentName from Strings, a client must call one of the static // methods that implements a conversion. public ContentName() { this(0, (ArrayList<byte[]>)null); } public ContentName(byte components[][]) { if (null == components) { _components = null; } else { _components = new ArrayList<byte []>(components.length); for (int i=0; i < components.length; ++i) { _components.add(components[i].clone()); } } } public ContentName(ContentName parent, byte [] name) { this(parent.count() + ((null != name) ? 1 : 0), parent.components()); if (null != name) { byte [] c = new byte[name.length]; System.arraycopy(name,0,c,0,name.length); _components.add(c); } } public ContentName(ContentName parent, byte [][] childComponents) { this(parent.count() + ((null != childComponents) ? childComponents.length : 0), parent.components()); if (null != childComponents) { for (byte [] b : childComponents) { if (null == b) continue; byte [] c = new byte[b.length]; System.arraycopy(b,0,c,0,b.length); _components.add(c); } } } public ContentName(ContentName parent, byte[] name1, byte[] name2) { this (parent.count() + ((null != name1) ? 1 : 0) + ((null != name2) ? 1 : 0), parent.components()); if (null != name1) { byte [] c = new byte[name1.length]; System.arraycopy(name1,0,c,0,name1.length); _components.add(c); } if (null != name2) { byte [] c = new byte[name2.length]; System.arraycopy(name2,0,c,0,name2.length); _components.add(c); } } /** * Basic constructor for extending or contracting names. * @param count * @param components */ public ContentName(int count, byte components[][]) { if (0 >= count) { _components = new ArrayList<byte []>(0); } else { int max = (null == components) ? 0 : ((count > components.length) ? components.length : count); _components = new ArrayList<byte []>(max); for (int i=0; i < max; ++i) { byte [] c = new byte[components[i].length]; System.arraycopy(components[i],0,c,0,components[i].length); _components.add(c); } } } /** * Basic constructor for extending or contracting names. * Shallow copy, as we don't tend to alter name components * once created. * @param count Only this number of name components are copied into the new name. * @param components These are the name components to be copied. Can be null, empty, or longer or shorter than count. */ public ContentName(int count, ArrayList<byte []>components) { if (0 >= count) { _components = new ArrayList<byte[]>(0); } else { int max = (null == components) ? 0 : ((count > components.size()) ? components.size() : count); _components = new ArrayList<byte []>(max); for (int i=0; i < max; ++i) { _components.add(components.get(i)); } } } /** * Copy constructor, also used by subclasses merely wanting a different * name in encoding/decoding. * @param otherName */ public ContentName(ContentName otherName) { this(((null == otherName) ? 0 : otherName.count()), ((null == otherName) ? null : otherName.components())); } /** * Return the <code>ContentName</code> represented by the given URI. * A CCN <code>ContentName</code> consists of a sequence of binary components * of any length (including 0), which allows such things as encrypted * name components. It is often convenient to work with string * representations of names in various forms. * <p> * The canonical String representation of a CCN <code>ContentName</code> is a * URI encoding of the name according to RFC 3986 with the addition * of special treatment for name components of 0 length or containing * only one or more of the byte value 0x2E, which is the US-ASCII * encoding of '.'. The major features of the URI encoding are the * use of a limited set of characters and the use of percent-encoding * to encode all other byte values. The combination of percent-encoding * and special treatment for certain name components allows the * canonical CCN string representation to encode all possible CCN names. * <p> * The legal characters in the URI are limited to the <i>unreserved</i> characters * "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "~" * plus the <i>reserved</i> delimiters "!", "$" "&", "'", "(", ")", * "*", "+", ",", ";", "=". * The reserved delimiter "/" is a special case interpreted as component separator and so * may not be used within a component unescaped. * Any query (starting '?') or fragment (starting '#') is ignored which means that these * reserved delimiters must be percent-encoded if they are to be part of the name. * <p> * The URI must begin with either the "/" delimiter or the scheme specification "ccn:" * plus delimiter to make URI absolute. * <p> * The decoding from a URI String to a ContentName translates each legal * character to its US-ASCII byte encoding, except for the "." which is subject * to special handling described below. Any other byte value in a component * (including those corresponding to "/" and ":") must be percent-encoded in * the URI. Any character sequence starting with "?" or "#" is discarded (to the * end of the component). * <p> * The resolution rules for relative references are applied in this * decoding: * <ul> * <li> "//" in the URI is interpreted as "/" * <li> "/./" and "/." in the URI are interpreted as "/" and "" * <li> "/../" and "/.." in the URI are interpreted as removing the preceding component * </ul> * <p> * Any component of 0 length, or containing only one or more of the byte * value 0x2E ("."), is represented in the URI by one "." per byte plus the * suffix "..." which provides unambiguous representation of all possible name * components in conjunction with the use of the resolution rules given above. * Thus the decoding from URI String to ContentName makes conversions such as: * <ul> * <li> "/.../" in the URI is converted to a 0-length name component * <li> "/..../" in the URI is converted to the name component {0x2E} * <li> "/...../" in the URI is converted to the name component {0x2E, 0x2E} * <li> "/....../" in the URI is converted to the name component {0x2E, 0x2E, 0x2E} * </ul> * <p> * Note that this URI encoding is very similar to but not the same as the * application/x-www-form-urlencoded MIME format that is used by the Java * {@link java.net.URLDecoder}. * * TODO: Inconsistent with C lib in that it does not strip authority part * TODO: Inconsistent with C lib in that it does not fully strip query and fragment parts (within component only) * @param name * @return * @throws MalformedContentNameStringException */ public static ContentName fromURI(String name) throws MalformedContentNameStringException { try { ContentName result = new ContentName(); if((name == null) || (name.length() == 0)) { result._components = null; } else { String[] parts; String justname = name; if (!name.startsWith(SEPARATOR)){ if (!name.startsWith(SCHEME + SEPARATOR)) { throw new MalformedContentNameStringException("ContentName strings must begin with " + SEPARATOR + " or " + SCHEME + SEPARATOR); } justname = name.substring(SCHEME.length()); } parts = justname.split(SEPARATOR); if (parts.length == 0) { // We've been asked to parse the root name. result._components = new ArrayList<byte []>(0); } else { result._components = new ArrayList<byte []>(parts.length - 1); } // Leave off initial empty component for (int i=1; i < parts.length; ++i) { try { byte[] component = componentParseURI(parts[i]); if (null != component) { result._components.add(component); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName string contains too many .. components: " + name); } else { result._components.remove(result._components.size()-1); } } } } return result; } catch (MalformedURIException e) { throw new MalformedContentNameStringException(e.getMessage()); } } public static ContentName fromURI(String parts[]) throws MalformedContentNameStringException { try { ContentName result = new ContentName(); if ((parts == null) || (parts.length == 0)) { result._components = null; } else { result._components = new ArrayList<byte []>(parts.length); for (int i=0; i < parts.length; ++i) { try { byte[] component = componentParseURI(parts[i]); if (null != component) { result._components.add(component); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName parts contains too many .. components"); } else { result._components.remove(result._components.size()-1); } } } } return result; } catch (MalformedURIException e) { throw new MalformedContentNameStringException(e.getMessage()); } } /** * Return the <code>ContentName</code> created by appending one component * to the supplied parent. The new component is converted from URI * string encoding. * @param parent * @param name * @return * @throws MalformedContentNameStringException */ public static ContentName fromURI(ContentName parent, String name) throws MalformedContentNameStringException { try { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name) { try { byte[] decodedName = componentParseURI(name); if (null != decodedName) { result._components.add(decodedName); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName parts contains too many .. components"); } else { result._components.remove(result._components.size()-1); } } } return result; } catch (MalformedURIException e) { throw new MalformedContentNameStringException(e.getMessage()); } } /** * Return the <code>ContentName</code> created from a native Java String. * In native strings only "/" is special, interpreted as component delimiter, * while all other characters will be encoded as UTF-8 in the output <code>ContentName</code> * Native String representations do not incorporate a URI scheme, and so must * begin with the component delimiter "/". * TODO use Java string escaping rules? * @param parent * @param name * @return * @throws MalformedContentNameStringException if name does not start with "/" */ public static ContentName fromNative(String name) throws MalformedContentNameStringException { ContentName result = new ContentName(); if (!name.startsWith(SEPARATOR)){ throw new MalformedContentNameStringException("ContentName native strings must begin with " + SEPARATOR); } if((name == null) || (name.length() == 0)) { result._components = null; } else { String[] parts; parts = name.split(SEPARATOR); if (parts.length == 0) { // We've been asked to parse the root name. result._components = new ArrayList<byte []>(0); } else { result._components = new ArrayList<byte []>(parts.length - 1); } // Leave off initial empty component for (int i=1; i < parts.length; ++i) { byte[] component = componentParseNative(parts[i]); if (null != component) { result._components.add(component); } } } return result; } /** * Return the <code>ContentName</code> created by appending one component * to the supplied parent. The new component is specified by a native * Java String which will be encoded as UTF-8 in the output <code>ContentName</code> * This method intentionally throws no declared exceptions * so you can be confident in encoding any native Java String * @param parent * @param name * @return */ public static ContentName fromNative(ContentName parent, String name) { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name) { byte[] decodedName = componentParseNative(name); if (null != decodedName) { result._components.add(decodedName); } } return result; } public static ContentName fromNative(ContentName parent, byte [] name) { ContentName result = new ContentName(parent.count(), parent.components()); result._components.add(name); return result; } public static ContentName fromNative(ContentName parent, String name1, String name2) { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name1) { byte[] decodedName = componentParseNative(name1); if (null != decodedName) { result._components.add(decodedName); } } if (null != name2) { byte[] decodedName = componentParseNative(name2); if (null != decodedName) { result._components.add(decodedName); } } return result; } public static ContentName fromNative(String parts[]) { ContentName result = new ContentName(); if ((parts == null) || (parts.length == 0)) { result._components = null; } else { result._components = new ArrayList<byte []>(parts.length); for (int i=0; i < parts.length; ++i) { byte[] component = componentParseNative(parts[i]); if (null != component) { result._components.add(component); } } } return result; } public ContentName clone() { return new ContentName(count(), components()); } /** * Returns a new name with the last component removed. */ public ContentName parent() { return new ContentName(count()-1, components()); } public String toString() { if (null == _components) return null; // toString of root name is "/" if (0 == _components.size()) return SEPARATOR; StringBuffer nameBuf = new StringBuffer(); for (int i=0; i < _components.size(); ++i) { nameBuf.append(SEPARATOR); nameBuf.append(componentPrintURI(_components.get(i))); } return nameBuf.toString(); } /** * Print bytes in the URI Generic Syntax of RFC 3986 * including byte sequences that are not legal character * encodings in any character set and byte sequences that have special * meaning for URI resolution per RFC 3986. This is designed to match * the C library URI encoding. * * This method must be invertible by parseComponent() so * for any input sequence of bytes it must be the case * that parseComponent(printComponent(input)) == input. * * All bytes that are unreserved characters per RFC 3986 are left unescaped. * Other bytes are percent encoded. * * Empty path components and path components "." and ".." have special * meaning for relative URI resolution per RFC 3986. To guarantee * these component variations are preserved and recovered exactly when * the URI is parsed by parseComponent() we use a convention that * components that are empty or consist entirely of '.' characters will * have "..." appended. This is intended to be consistent with the CCN C * library handling of URI representation of names. * @param bs input byte array. * @return */ public static String componentPrintURI(byte[] bs, int offset, int length) { if (null == bs || bs.length == 0) { // Empty component represented by three '.' return "..."; } // To get enough control over the encoding, we use // our own loop and NOT simply new String(bs) (or java.net.URLEncoder) because // the String constructor will decode illegal UTF-8 sub-sequences // with Unicode "Replacement Character" U+FFFD. We could use a CharsetDecoder // to detect the illegal UTF-8 sub-sequences and handle them separately, // except that this is almost certainly less efficient and some versions of Java // have bugs that prevent flagging illegal overlong UTF-8 encodings (CVE-2008-2938). // Also, it is much easier to verify what this is doing and compare to the C library implementation. StringBuffer result = new StringBuffer(); for (int i = 0; i < bs.length; i++) { byte ch = bs[i]; if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '-' || ch == '.' || ch == '_' || ch == '~') // Since these are all BMP characters, the can be represented in one Java Character result.append(Character.toChars(ch)[0]); else result.append(String.format("%%%02X", ch)); } int i = 0; for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) { continue; } if (i == result.length()) { // all dots result.append("..."); } return result.toString(); } public static String componentPrintURI(byte [] bs) { return componentPrintURI(bs, 0, bs.length); } public static String componentPrintNative(byte[] bs) { // Native string print is the one place where we can just use // Java native platform decoding. Note that this is not // necessarily invertible, since there may be byte sequences // that do not correspond to any legal native character encoding // that may be converted to e.g. Unicode "Replacement Character" U+FFFD. return new String(bs); } // UrlEncoded in case we want variant compatible with java.net.URLEncoder // again in future // protected static String componentPrintUrlEncoded(byte[] bs) { // // NHB: Van is expecting the URI encoding rules // if (null == bs || bs.length == 0) { // // Empty component represented by three '.' // return "..."; // } // try { // // Note that this would probably be more efficient as simple loop: // // In order to use the URLEncoder class to handle the // // parts that are UTF-8 already, we decode the bytes into Java String // // as though they were UTF-8. Wherever that fails // // (i.e. where byte sub-sequences are NOT legal UTF-8) // // we directly convert those bytes to the %xy output format. // // To get enough control over the decoding, we must use // // the charset decoder and NOT simply new String(bs) because // // the String constructor will decode illegal UTF-8 sub-sequences // // with Unicode "Replacement Character" U+FFFD. // StringBuffer result = new StringBuffer(); // Charset charset = Charset.forName("UTF-8"); // CharsetDecoder decoder = charset.newDecoder(); // // Leave nothing to defaults: we want to be notified on anything illegal // decoder.onMalformedInput(CodingErrorAction.REPORT); // decoder.onUnmappableCharacter(CodingErrorAction.REPORT); // ByteBuffer input = ByteBuffer.wrap(bs); // CharBuffer output = CharBuffer.allocate(((int)decoder.maxCharsPerByte()*bs.length)+1); // while (input.remaining() > 0) { // CoderResult cr = decoder.decode(input, output, true); // assert(!cr.isOverflow()); // // URLEncode whatever was successfully decoded from UTF-8 // output.flip(); // result.append(URLEncoder.encode(output.toString(), "UTF-8")); // output.clear(); // if (cr.isError()) { // for (int i=0; i<cr.length(); i++) { // result.append(String.format("%%%02X", input.get())); // } // } // } // int i = 0; // for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) { // continue; // } // if (i == result.length()) { // // all dots // result.append("..."); // } // return result.toString(); // } catch (UnsupportedCharsetException e) { // throw new RuntimeException("UTF-8 not supported charset", e); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException("UTF-8 not supported", e); // } // } public static String hexPrint(byte [] bs) { if (null == bs) return new String(); BigInteger bi = new BigInteger(1,bs); return bi.toString(16); } /* * Parse the URI Generic Syntax of RFC 3986 * including handling percent encoding of sequences that are not legal character * encodings in any character set. This method is the inverse of * printComponent() and for any input sequence of bytes it must be the case * that parseComponent(printComponent(input)) == input. Note that the inverse * is NOT true printComponent(parseComponent(input)) != input in general. * * Please see fromURI() documentation for more detail. * * Note in particular that this method interprets sequences of more than * two dots ('.') as representing an empty component or dot component value * as encoded by componentPrint. That is, the component value will be * the value obtained by removing three dots. * @param name a single component of a name * @return */ public static byte[] componentParseURI(String name) throws DotDotComponent, MalformedURIException { byte[] decodedName = null; boolean alldots = true; // does this component contain only dots after unescaping? boolean quitEarly = false; try { ByteBuffer result = ByteBuffer.allocate(name.length()); for (int i = 0; i < name.length() && !quitEarly; i++) { char ch = name.charAt(i); switch (ch) { case '%': // This is a byte string %xy where xy are hex digits // Since the input string must be compatible with the output // of componentPrint(), we may convert the byte values directly. // There is no need to go through a character representation. if (name.length()-1 < i+2) { throw new MalformedURIException("malformed %xy byte representation: too short"); } if (name.charAt(i+1) == '-') { throw new MalformedURIException("malformed %xy byte representation: negative value not permitted"); } try { result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue()); } catch (NumberFormatException e) { throw new MalformedURIException("malformed %xy byte representation: not legal hex number: " + name.substring(i+1, i+3)); } i+=2; // for loop will increment by one more to get net +3 so past byte string break; // Note in C lib case 0 is handled like the two general delimiters below that terminate processing // but that case should never arise in Java which uses real unicode characters. case '/': case '?': case '#': quitEarly = true; // early exit from containing loop break; case ':': case '[': case ']': case '@': case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': // Permit unescaped reserved characters result.put(name.substring(i, i+1).getBytes("UTF-8")); break; default: if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '-' || ch == '.' || ch == '_' || ch == '~') { // This character remains the same result.put(name.substring(i, i+1).getBytes("UTF-8")); } else { throw new MalformedURIException("Illegal characters in URI: " + name); } break; } if (!quitEarly && result.get(result.position()-1) != '.') { alldots = false; } } result.flip(); if (alldots) { if (result.limit() <= 1) { return null; } else if (result.limit() == 2) { throw new DotDotComponent(); } else { // Remove the three '.' extra result.limit(result.limit()-3); } } decodedName = new byte[result.limit()]; System.arraycopy(result.array(), 0, decodedName, 0, result.limit()); } catch (UnsupportedEncodingException e) { Library.logger().severe("UTF-8 not supported."); throw new RuntimeException("UTF-8 not supported", e); } return decodedName; } /** * Parse native string component: just UTF-8 encode * For full names in native strings only "/" is special * but for an individual component we will even allow that. * This method intentionally throws no declared exceptions * so you can be confident in encoding any native Java String * TODO make this use Java string escaping rules? * @param name * @return */ public static byte[] componentParseNative(String name) { try { return name.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { Library.logger().severe("UTF-8 not supported."); throw new RuntimeException("UTF-8 not supported", e); } } // UrlEncoded in case we want to enable it again // protected static byte[] componentParseUrlEncoded(String name) throws DotDotComponent { // byte[] decodedName = null; // boolean alldots = true; // does this component contain only dots after unescaping? // try { // ByteBuffer result = ByteBuffer.allocate(name.length()); // for (int i = 0; i < name.length(); i++) { // if (name.charAt(i) == '%') { // // This is a byte string %xy where xy are hex digits // // Since the input string must be compatible with the output // // of componentPrint(), we may convert the byte values directly. // // There is no need to go through a character representation. // if (name.length()-1 < i+2) { // throw new IllegalArgumentException("malformed %xy byte representation: too short"); // } // if (name.charAt(i+1) == '-') { // throw new IllegalArgumentException("malformed %xy byte representation: negative value not permitted"); // } // try { // result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue()); // } catch (NumberFormatException e) { // throw new IllegalArgumentException("malformed %xy byte representation: not legal hex number",e); // } // i+=2; // for loop will increment by one more to get net +3 so past byte string // } else if (name.charAt(i) == '+') { // // This is the one character translated to a different one // result.put(" ".getBytes("UTF-8")); // } else { // // This character remains the same // result.put(name.substring(i, i+1).getBytes("UTF-8")); // } // if (result.get(result.position()-1) != '.') { // alldots = false; // } // } // result.flip(); // if (alldots) { // if (result.limit() <= 1) { // return null; // } else if (result.limit() == 2) { // throw new DotDotComponent(); // } else { // // Remove the three '.' extra // result.limit(result.limit()-3); // } // } // decodedName = new byte[result.limit()]; // System.arraycopy(result.array(), 0, decodedName, 0, result.limit()); // } catch (UnsupportedEncodingException e) { // Library.logger().severe("UTF-8 not supported."); // throw new RuntimeException("UTF-8 not supported", e); // } // return decodedName; // } public ArrayList<byte[]> components() { return _components; } /** * @return The number of components in the name. */ public int count() { if (null == _components) return 0; return _components.size(); } /** * Get the i'th component, indexed from 0. * @param i * @return */ public final byte[] component(int i) { if ((null == _components) || (i >= _components.size())) return null; return _components.get(i); } public final byte [] lastComponent() { if (null == _components || _components.size() == 0) return null; return _components.get(_components.size()-1); } public String stringComponent(int i) { if ((null == _components) || (i >= _components.size())) return null; return componentPrintURI(_components.get(i)); } /** * Allow override to give different element name. * @return */ public String contentNameElement() { return CONTENT_NAME_ELEMENT; } public void decode(XMLDecoder decoder) throws XMLStreamException { decoder.readStartElement(contentNameElement()); _components = new ArrayList<byte []>(); while (decoder.peekStartElement(COMPONENT_ELEMENT)) { _components.add(decoder.readBinaryElement(COMPONENT_ELEMENT)); } decoder.readEndElement(); } /** * Test if this name is a prefix of another name - i.e. do all components in this name exist in the * name being compared with. Note there do not need to be any more components in the name * being compared with. * @param name name being compared with. * @return */ public boolean isPrefixOf(ContentName name) { return isPrefixOf(name, count()); } public boolean isPrefixOf(ContentName name, int count) { if (null == name) return false; if (count > name.count()) return false; for (int i=0; i < count; ++i) { if (!Arrays.equals(name.component(i), component(i))) return false; } return true; } /** * Compare our name to the name of the ContentObject. * If our name is 1 component longer than the ContentObject * and no prefix count is set, our name might contain a digest. * In that case, try matching the content to the last component as * a digest. * * @param other * @return */ public boolean isPrefixOf(ContentObject other) { return isPrefixOf(other, count()); } public boolean isPrefixOf(ContentObject other, int count) { boolean match = isPrefixOf(other.name(), count); if (match || count() != count) return match; if (count() == other.name().count() + 1) { if (DataUtils.compare(component(count() - 1), other.contentDigest()) == 0) { return true; } } return false; } /** * hashCode and equals not auto-generated, ArrayList does not do the right thing. */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ContentName other = (ContentName)obj; if (other.count() != this.count()) return false; for (int i=0; i < count(); ++i) { if (!Arrays.equals(other.component(i), this.component(i))) return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; for (int i=0; i < count(); ++i) { result = prime * result + Arrays.hashCode(component(i)); } return result; } /** * Parses the canonical URI representation. * @param str * @return * @throws MalformedContentNameStringException */ public static ContentName parse(String str) throws MalformedContentNameStringException { if(str == null) return null; if(str.length() == 0) return ROOT; return fromURI(str); } /** * Uses the canonical URI representation * @param str * @return */ public boolean contains(String str) throws MalformedURIException { try { byte[] parsed = componentParseURI(str); if (null == parsed) { return false; } else { return contains(parsed); } } catch (DotDotComponent c) { return false; } } public boolean contains(byte [] component) { return (containsWhere(component) > 0); } /** * Uses the canonical URI representation * @param str * @return * @throws MalformedURIException */ public int containsWhere(String str) throws MalformedURIException { try { byte[] parsed = componentParseURI(str); if (null == parsed) { return -1; } else { return containsWhere(parsed); } } catch (DotDotComponent c) { return -1; } } int containsWhere(byte [] component) { int i=0; boolean result = false; for (i=0; i < _components.size(); ++i) { if (Arrays.equals(_components.get(i),component)) { result = true; break; } } if (result) return i; return -1; } /** * Return the first componentNumber components of this name as a new name. * @param componentNumber * @return */ public ContentName cut(int componentCount) { if ((componentCount < 0) || (componentCount > count())) { throw new IllegalArgumentException("Illegal component count: " + componentCount); } if (componentCount == count()) return this; return new ContentName(componentCount, this.components()); } /** * Slice the name off right before the given component * @param name * @param component * @return */ public ContentName cut(byte [] component) { int offset = this.containsWhere(component); if (offset < 0) { // unfragmented return this; } // else need to cut it return new ContentName(offset, this.components()); } public ContentName cut(String component) throws MalformedURIException { try { byte[] parsed = componentParseURI(component); if (null == parsed) { return this; } else { return cut(parsed); } } catch (DotDotComponent c) { return this; } } public void encode(XMLEncoder encoder) throws XMLStreamException { if (!validate()) { throw new XMLStreamException("Cannot encode " + this.getClass().getName() + ": field values missing."); } encoder.writeStartElement(contentNameElement()); for (int i=0; i < count(); ++i) { encoder.writeElement(COMPONENT_ELEMENT, _components.get(i)); } encoder.writeEndElement(); } public boolean validate() { return (null != _components); } public ContentName copy(int nameComponentCount) { return new ContentName(nameComponentCount, this.components()); } public int compareTo(ContentName o) { if (this == o) return 0; int len = (this.count() > o.count()) ? this.count() : o.count(); int componentResult = 0; for (int i=0; i < len; ++i) { componentResult = DataUtils.compare(this.component(i), o.component(i)); if (0 != componentResult) return componentResult; } if (this.count() < o.count()) return -1; else if (this.count() > o.count()) return 1; return 0; } }
Java_CCN/com/parc/ccn/data/ContentName.java
package com.parc.ccn.data; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.data.util.DataUtils; import com.parc.ccn.data.util.GenericXMLEncodable; import com.parc.ccn.data.util.XMLDecoder; import com.parc.ccn.data.util.XMLEncodable; import com.parc.ccn.data.util.XMLEncoder; import com.sun.org.apache.xerces.internal.util.URI.MalformedURIException; public class ContentName extends GenericXMLEncodable implements XMLEncodable, Comparable<ContentName> { public static final String SCHEME = "ccn:"; public static final String SEPARATOR = "/"; public static final ContentName ROOT = new ContentName(0, (ArrayList<byte []>)null); public static final String CONTENT_NAME_ELEMENT = "Name"; private static final String COMPONENT_ELEMENT = "Component"; protected ArrayList<byte []> _components; public static class DotDotComponent extends Exception { // Need to strip off a component private static final long serialVersionUID = 4667513234636853164L; }; // Constructors // ContentNames consist of a sequence of byte[] components which may not // be assumed to follow any string encoding, or any other particular encoding. // The constructors therefore provide for creation only from byte[]s. // To create a ContentName from Strings, a client must call one of the static // methods that implements a conversion. public ContentName() { this(0, (ArrayList<byte[]>)null); } public ContentName(byte components[][]) { if (null == components) { _components = null; } else { _components = new ArrayList<byte []>(components.length); for (int i=0; i < components.length; ++i) { _components.add(components[i].clone()); } } } public ContentName(ContentName parent, byte [] name) { this(parent.count() + ((null != name) ? 1 : 0), parent.components()); if (null != name) { byte [] c = new byte[name.length]; System.arraycopy(name,0,c,0,name.length); _components.add(c); } } public ContentName(ContentName parent, byte [][] childComponents) { this(parent.count() + ((null != childComponents) ? childComponents.length : 0), parent.components()); if (null != childComponents) { for (byte [] b : childComponents) { if (null == b) continue; byte [] c = new byte[b.length]; System.arraycopy(b,0,c,0,b.length); _components.add(c); } } } public ContentName(ContentName parent, byte[] name1, byte[] name2) { this (parent.count() + ((null != name1) ? 1 : 0) + ((null != name2) ? 1 : 0), parent.components()); if (null != name1) { byte [] c = new byte[name1.length]; System.arraycopy(name1,0,c,0,name1.length); _components.add(c); } if (null != name2) { byte [] c = new byte[name2.length]; System.arraycopy(name2,0,c,0,name2.length); _components.add(c); } } /** * Basic constructor for extending or contracting names. * @param count * @param components */ public ContentName(int count, byte components[][]) { if (0 >= count) { _components = new ArrayList<byte []>(0); } else { int max = (null == components) ? 0 : ((count > components.length) ? components.length : count); _components = new ArrayList<byte []>(max); for (int i=0; i < max; ++i) { byte [] c = new byte[components[i].length]; System.arraycopy(components[i],0,c,0,components[i].length); _components.add(c); } } } /** * Basic constructor for extending or contracting names. * Shallow copy, as we don't tend to alter name components * once created. * @param count Only this number of name components are copied into the new name. * @param components These are the name components to be copied. Can be null, empty, or longer or shorter than count. */ public ContentName(int count, ArrayList<byte []>components) { if (0 >= count) { _components = new ArrayList<byte[]>(0); } else { int max = (null == components) ? 0 : ((count > components.size()) ? components.size() : count); _components = new ArrayList<byte []>(max); for (int i=0; i < max; ++i) { _components.add(components.get(i)); } } } /** * Copy constructor, also used by subclasses merely wanting a different * name in encoding/decoding. * @param otherName */ public ContentName(ContentName otherName) { this(((null == otherName) ? 0 : otherName.count()), ((null == otherName) ? null : otherName.components())); } /** * Return the <code>ContentName</code> represented by the given URI. * A CCN <code>ContentName</code> consists of a sequence of binary components * of any length (including 0), which allows such things as encrypted * name components. It is often convenient to work with string * representations of names in various forms. * <p> * The canonical String representation of a CCN <code>ContentName</code> is a * URI encoding of the name according to RFC 3986 with the addition * of special treatment for name components of 0 length or containing * only one or more of the byte value 0x2E, which is the US-ASCII * encoding of '.'. The major features of the URI encoding are the * use of a limited set of characters and the use of percent-encoding * to encode all other byte values. The combination of percent-encoding * and special treatment for certain name components allows the * canonical CCN string representation to encode all possible CCN names. * <p> * The legal characters in the URI are limited to the <i>unreserved</i> characters * "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "~" * plus the <i>reserved</i> delimiters "!", "$" "&", "'", "(", ")", * "*", "+", ",", ";", "=". * The reserved delimiter "/" is a special case interpreted as component separator and so * may not be used within a component unescaped. * Any query (starting '?') or fragment (starting '#') is ignored which means that these * reserved delimiters must be percent-encoded if they are to be part of the name. * <p> * The URI must begin with either the "/" delimiter or the scheme specification "ccn:" * plus delimiter to make URI absolute. * <p> * The decoding from a URI String to a ContentName translates each legal * character to its US-ASCII byte encoding, except for the "." which is subject * to special handling described below. Any other byte value in a component * (including those corresponding to "/" and ":") must be percent-encoded in * the URI. Any character sequence starting with "?" or "#" is discarded (to the * end of the component). * <p> * The resolution rules for relative references are applied in this * decoding: * <ul> * <li> "//" in the URI is interpreted as "/" * <li> "/./" and "/." in the URI are interpreted as "/" and "" * <li> "/../" and "/.." in the URI are interpreted as removing the preceding component * </ul> * <p> * Any component of 0 length, or containing only one or more of the byte * value 0x2E ("."), is represented in the URI by one "." per byte plus the * suffix "..." which provides unambiguous representation of all possible name * components in conjunction with the use of the resolution rules given above. * Thus the decoding from URI String to ContentName makes conversions such as: * <ul> * <li> "/.../" in the URI is converted to a 0-length name component * <li> "/..../" in the URI is converted to the name component {0x2E} * <li> "/...../" in the URI is converted to the name component {0x2E, 0x2E} * <li> "/....../" in the URI is converted to the name component {0x2E, 0x2E, 0x2E} * </ul> * <p> * Note that this URI encoding is very similar to but not the same as the * application/x-www-form-urlencoded MIME format that is used by the Java * {@link java.net.URLDecoder}. * * TODO: Inconsistent with C lib in that it does not strip authority part * TODO: Inconsistent with C lib in that it does not fully strip query and fragment parts (within component only) * @param name * @return * @throws MalformedContentNameStringException */ public static ContentName fromURI(String name) throws MalformedContentNameStringException { try { ContentName result = new ContentName(); if((name == null) || (name.length() == 0)) { result._components = null; } else { String[] parts; String justname = name; if (!name.startsWith(SEPARATOR)){ if (!name.startsWith(SCHEME + SEPARATOR)) { throw new MalformedContentNameStringException("ContentName strings must begin with " + SEPARATOR + " or " + SCHEME + SEPARATOR); } justname = name.substring(SCHEME.length()); } parts = justname.split(SEPARATOR); if (parts.length == 0) { // We've been asked to parse the root name. result._components = new ArrayList<byte []>(0); } else { result._components = new ArrayList<byte []>(parts.length - 1); } // Leave off initial empty component for (int i=1; i < parts.length; ++i) { try { byte[] component = componentParseURI(parts[i]); if (null != component) { result._components.add(component); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName string contains too many .. components: " + name); } else { result._components.remove(result._components.size()-1); } } } } return result; } catch (MalformedURIException e) { throw new MalformedContentNameStringException(e.getMessage()); } } public static ContentName fromURI(String parts[]) throws MalformedContentNameStringException { try { ContentName result = new ContentName(); if ((parts == null) || (parts.length == 0)) { result._components = null; } else { result._components = new ArrayList<byte []>(parts.length); for (int i=0; i < parts.length; ++i) { try { byte[] component = componentParseURI(parts[i]); if (null != component) { result._components.add(component); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName parts contains too many .. components"); } else { result._components.remove(result._components.size()-1); } } } } return result; } catch (MalformedURIException e) { throw new MalformedContentNameStringException(e.getMessage()); } } /** * Return the <code>ContentName</code> created by appending one component * to the supplied parent. The new component is converted from URI * string encoding. * @param parent * @param name * @return * @throws MalformedContentNameStringException */ public static ContentName fromURI(ContentName parent, String name) throws MalformedContentNameStringException { try { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name) { try { byte[] decodedName = componentParseURI(name); if (null != decodedName) { result._components.add(decodedName); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName parts contains too many .. components"); } else { result._components.remove(result._components.size()-1); } } } return result; } catch (MalformedURIException e) { throw new MalformedContentNameStringException(e.getMessage()); } } /** * Return the <code>ContentName</code> created from a native Java String. * In native strings only "/" is special, interpreted as component delimiter, * while all other characters will be encoded as UTF-8 in the output <code>ContentName</code> * Native String representations do not incorporate a URI scheme, and so must * begin with the component delimiter "/". * TODO use Java string escaping rules? * @param parent * @param name * @return * @throws MalformedContentNameStringException if name does not start with "/" */ public static ContentName fromNative(String name) throws MalformedContentNameStringException { ContentName result = new ContentName(); if (!name.startsWith(SEPARATOR)){ throw new MalformedContentNameStringException("ContentName native strings must begin with " + SEPARATOR); } if((name == null) || (name.length() == 0)) { result._components = null; } else { String[] parts; parts = name.split(SEPARATOR); if (parts.length == 0) { // We've been asked to parse the root name. result._components = new ArrayList<byte []>(0); } else { result._components = new ArrayList<byte []>(parts.length - 1); } // Leave off initial empty component for (int i=1; i < parts.length; ++i) { byte[] component = componentParseNative(parts[i]); if (null != component) { result._components.add(component); } } } return result; } /** * Return the <code>ContentName</code> created by appending one component * to the supplied parent. The new component is specified by a native * Java String which will be encoded as UTF-8 in the output <code>ContentName</code> * This method intentionally throws no declared exceptions * so you can be confident in encoding any native Java String * @param parent * @param name * @return */ public static ContentName fromNative(ContentName parent, String name) { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name) { byte[] decodedName = componentParseNative(name); if (null != decodedName) { result._components.add(decodedName); } } return result; } public static ContentName fromNative(ContentName parent, byte [] name) { ContentName result = new ContentName(parent.count(), parent.components()); result._components.add(name); return result; } public static ContentName fromNative(ContentName parent, String name1, String name2) { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name1) { byte[] decodedName = componentParseNative(name1); if (null != decodedName) { result._components.add(decodedName); } } if (null != name2) { byte[] decodedName = componentParseNative(name2); if (null != decodedName) { result._components.add(decodedName); } } return result; } public static ContentName fromNative(String parts[]) { ContentName result = new ContentName(); if ((parts == null) || (parts.length == 0)) { result._components = null; } else { result._components = new ArrayList<byte []>(parts.length); for (int i=0; i < parts.length; ++i) { byte[] component = componentParseNative(parts[i]); if (null != component) { result._components.add(component); } } } return result; } public ContentName clone() { return new ContentName(count(), components()); } /** * Returns a new name with the last component removed. */ public ContentName parent() { return new ContentName(count()-1, components()); } public String toString() { if (null == _components) return null; // toString of root name is "/" if (0 == _components.size()) return SEPARATOR; StringBuffer nameBuf = new StringBuffer(); for (int i=0; i < _components.size(); ++i) { nameBuf.append(SEPARATOR); nameBuf.append(componentPrintURI(_components.get(i))); } return nameBuf.toString(); } /** * Print bytes in the URI Generic Syntax of RFC 3986 * including byte sequences that are not legal character * encodings in any character set and byte sequences that have special * meaning for URI resolution per RFC 3986. This is designed to match * the C library URI encoding. * * This method must be invertible by parseComponent() so * for any input sequence of bytes it must be the case * that parseComponent(printComponent(input)) == input. * * All bytes that are unreserved characters per RFC 3986 are left unescaped. * Other bytes are percent encoded. * * Empty path components and path components "." and ".." have special * meaning for relative URI resolution per RFC 3986. To guarantee * these component variations are preserved and recovered exactly when * the URI is parsed by parseComponent() we use a convention that * components that are empty or consist entirely of '.' characters will * have "..." appended. This is intended to be consistent with the CCN C * library handling of URI representation of names. * @param bs input byte array. * @return */ public static String componentPrintURI(byte[] bs, int offset, int length) { if (null == bs || bs.length == 0) { // Empty component represented by three '.' return "..."; } // To get enough control over the encoding, we use // our own loop and NOT simply new String(bs) (or java.net.URLEncoder) because // the String constructor will decode illegal UTF-8 sub-sequences // with Unicode "Replacement Character" U+FFFD. We could use a CharsetDecoder // to detect the illegal UTF-8 sub-sequences and handle them separately, // except that this is almost certainly less efficient and some versions of Java // have bugs that prevent flagging illegal overlong UTF-8 encodings (CVE-2008-2938). // Also, it is much easier to verify what this is doing and compare to the C library implementation. StringBuffer result = new StringBuffer(); for (int i = 0; i < bs.length; i++) { byte ch = bs[i]; if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '-' || ch == '.' || ch == '_' || ch == '~') // Since these are all BMP characters, the can be represented in one Java Character result.append(Character.toChars(ch)[0]); else result.append(String.format("%%%02X", ch)); } int i = 0; for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) { continue; } if (i == result.length()) { // all dots result.append("..."); } return result.toString(); } public static String componentPrintURI(byte [] bs) { return componentPrintURI(bs, 0, bs.length); } public static String componentPrintNative(byte[] bs) { // Native string print is the one place where we can just use // Java native platform decoding. Note that this is not // necessarily invertible, since there may be byte sequences // that do not correspond to any legal native character encoding // that may be converted to e.g. Unicode "Replacement Character" U+FFFD. return new String(bs); } // UrlEncoded in case we want variant compatible with java.net.URLEncoder // again in future // protected static String componentPrintUrlEncoded(byte[] bs) { // // NHB: Van is expecting the URI encoding rules // if (null == bs || bs.length == 0) { // // Empty component represented by three '.' // return "..."; // } // try { // // Note that this would probably be more efficient as simple loop: // // In order to use the URLEncoder class to handle the // // parts that are UTF-8 already, we decode the bytes into Java String // // as though they were UTF-8. Wherever that fails // // (i.e. where byte sub-sequences are NOT legal UTF-8) // // we directly convert those bytes to the %xy output format. // // To get enough control over the decoding, we must use // // the charset decoder and NOT simply new String(bs) because // // the String constructor will decode illegal UTF-8 sub-sequences // // with Unicode "Replacement Character" U+FFFD. // StringBuffer result = new StringBuffer(); // Charset charset = Charset.forName("UTF-8"); // CharsetDecoder decoder = charset.newDecoder(); // // Leave nothing to defaults: we want to be notified on anything illegal // decoder.onMalformedInput(CodingErrorAction.REPORT); // decoder.onUnmappableCharacter(CodingErrorAction.REPORT); // ByteBuffer input = ByteBuffer.wrap(bs); // CharBuffer output = CharBuffer.allocate(((int)decoder.maxCharsPerByte()*bs.length)+1); // while (input.remaining() > 0) { // CoderResult cr = decoder.decode(input, output, true); // assert(!cr.isOverflow()); // // URLEncode whatever was successfully decoded from UTF-8 // output.flip(); // result.append(URLEncoder.encode(output.toString(), "UTF-8")); // output.clear(); // if (cr.isError()) { // for (int i=0; i<cr.length(); i++) { // result.append(String.format("%%%02X", input.get())); // } // } // } // int i = 0; // for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) { // continue; // } // if (i == result.length()) { // // all dots // result.append("..."); // } // return result.toString(); // } catch (UnsupportedCharsetException e) { // throw new RuntimeException("UTF-8 not supported charset", e); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException("UTF-8 not supported", e); // } // } public static String hexPrint(byte [] bs) { if (null == bs) return new String(); BigInteger bi = new BigInteger(1,bs); return bi.toString(16); } /* * Parse the URI Generic Syntax of RFC 3986 * including handling percent encoding of sequences that are not legal character * encodings in any character set. This method is the inverse of * printComponent() and for any input sequence of bytes it must be the case * that parseComponent(printComponent(input)) == input. Note that the inverse * is NOT true printComponent(parseComponent(input)) != input in general. * * Please see fromURI() documentation for more detail. * * Note in particular that this method interprets sequences of more than * two dots ('.') as representing an empty component or dot component value * as encoded by componentPrint. That is, the component value will be * the value obtained by removing three dots. * @param name a single component of a name * @return */ public static byte[] componentParseURI(String name) throws DotDotComponent, MalformedURIException { byte[] decodedName = null; boolean alldots = true; // does this component contain only dots after unescaping? boolean quitEarly = false; try { ByteBuffer result = ByteBuffer.allocate(name.length()); for (int i = 0; i < name.length() && !quitEarly; i++) { char ch = name.charAt(i); switch (ch) { case '%': // This is a byte string %xy where xy are hex digits // Since the input string must be compatible with the output // of componentPrint(), we may convert the byte values directly. // There is no need to go through a character representation. if (name.length()-1 < i+2) { throw new MalformedURIException("malformed %xy byte representation: too short"); } if (name.charAt(i+1) == '-') { throw new MalformedURIException("malformed %xy byte representation: negative value not permitted"); } try { result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue()); } catch (NumberFormatException e) { throw new MalformedURIException("malformed %xy byte representation: not legal hex number: " + name.substring(i+1, i+3)); } i+=2; // for loop will increment by one more to get net +3 so past byte string break; // Note in C lib case 0 is handled like the two general delimiters below that terminate processing // but that case should never arise in Java which uses real unicode characters. case '/': case '?': case '#': quitEarly = true; // early exit from containing loop break; case ':': case '[': case ']': case '@': case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': // Permit unescaped reserved characters result.put(name.substring(i, i+1).getBytes("UTF-8")); break; default: if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '-' || ch == '.' || ch == '_' || ch == '~') { // This character remains the same result.put(name.substring(i, i+1).getBytes("UTF-8")); } else { throw new MalformedURIException("Illegal characters in URI: " + name); } break; } if (!quitEarly && result.get(result.position()-1) != '.') { alldots = false; } } result.flip(); if (alldots) { if (result.limit() <= 1) { return null; } else if (result.limit() == 2) { throw new DotDotComponent(); } else { // Remove the three '.' extra result.limit(result.limit()-3); } } decodedName = new byte[result.limit()]; System.arraycopy(result.array(), 0, decodedName, 0, result.limit()); } catch (UnsupportedEncodingException e) { Library.logger().severe("UTF-8 not supported."); throw new RuntimeException("UTF-8 not supported", e); } return decodedName; } /** * Parse native string component: just UTF-8 encode * For full names in native strings only "/" is special * but for an individual component we will even allow that. * This method intentionally throws no declared exceptions * so you can be confident in encoding any native Java String * TODO make this use Java string escaping rules? * @param name * @return */ public static byte[] componentParseNative(String name) { try { return name.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { Library.logger().severe("UTF-8 not supported."); throw new RuntimeException("UTF-8 not supported", e); } } // UrlEncoded in case we want to enable it again // protected static byte[] componentParseUrlEncoded(String name) throws DotDotComponent { // byte[] decodedName = null; // boolean alldots = true; // does this component contain only dots after unescaping? // try { // ByteBuffer result = ByteBuffer.allocate(name.length()); // for (int i = 0; i < name.length(); i++) { // if (name.charAt(i) == '%') { // // This is a byte string %xy where xy are hex digits // // Since the input string must be compatible with the output // // of componentPrint(), we may convert the byte values directly. // // There is no need to go through a character representation. // if (name.length()-1 < i+2) { // throw new IllegalArgumentException("malformed %xy byte representation: too short"); // } // if (name.charAt(i+1) == '-') { // throw new IllegalArgumentException("malformed %xy byte representation: negative value not permitted"); // } // try { // result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue()); // } catch (NumberFormatException e) { // throw new IllegalArgumentException("malformed %xy byte representation: not legal hex number",e); // } // i+=2; // for loop will increment by one more to get net +3 so past byte string // } else if (name.charAt(i) == '+') { // // This is the one character translated to a different one // result.put(" ".getBytes("UTF-8")); // } else { // // This character remains the same // result.put(name.substring(i, i+1).getBytes("UTF-8")); // } // if (result.get(result.position()-1) != '.') { // alldots = false; // } // } // result.flip(); // if (alldots) { // if (result.limit() <= 1) { // return null; // } else if (result.limit() == 2) { // throw new DotDotComponent(); // } else { // // Remove the three '.' extra // result.limit(result.limit()-3); // } // } // decodedName = new byte[result.limit()]; // System.arraycopy(result.array(), 0, decodedName, 0, result.limit()); // } catch (UnsupportedEncodingException e) { // Library.logger().severe("UTF-8 not supported."); // throw new RuntimeException("UTF-8 not supported", e); // } // return decodedName; // } public ArrayList<byte[]> components() { return _components; } /** * @return The number of components in the name. */ public int count() { if (null == _components) return 0; return _components.size(); } /** * Get the i'th component, indexed from 0. * @param i * @return */ public final byte[] component(int i) { if ((null == _components) || (i >= _components.size())) return null; return _components.get(i); } public final byte [] lastComponent() { if (null == _components || _components.size() == 0) return null; return _components.get(_components.size()-1); } public String stringComponent(int i) { if ((null == _components) || (i >= _components.size())) return null; return componentPrintURI(_components.get(i)); } /** * Allow override to give different element name. * @return */ public String contentNameElement() { return CONTENT_NAME_ELEMENT; } public void decode(XMLDecoder decoder) throws XMLStreamException { decoder.readStartElement(contentNameElement()); _components = new ArrayList<byte []>(); while (decoder.peekStartElement(COMPONENT_ELEMENT)) { _components.add(decoder.readBinaryElement(COMPONENT_ELEMENT)); } decoder.readEndElement(); } /** * Test if this name is a prefix of another name - i.e. do all components in this name exist in the * name being compared with. Note there do not need to be any more components in the name * being compared with. * @param name name being compared with. * @return */ public boolean isPrefixOf(ContentName name) { return isPrefixOf(name, count()); } public boolean isPrefixOf(ContentName name, int count) { if (null == name) return false; if (count > name.count()) return false; for (int i=0; i < count; ++i) { if (!Arrays.equals(name.component(i), component(i))) return false; } return true; } /** * Compare our name to the name of the ContentObject. * If our name is 1 component longer than the ContentObject * and no prefix count is set, our name might contain a digest. * In that case, try matching the content to the last component as * a digest. * * @param other * @return */ public boolean isPrefixOf(ContentObject other) { return isPrefixOf(other, count()); } public boolean isPrefixOf(ContentObject other, int count) { boolean match = isPrefixOf(other.name(), count); if (match || count() != count) return match; if (count() == other.name().count() + 1) { if (DataUtils.compare(component(count() - 1), other.contentDigest()) == 0) { return true; } } return false; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ContentName other = (ContentName)obj; if (other.count() != this.count()) return false; for (int i=0; i < count(); ++i) { if (!Arrays.equals(other.component(i), this.component(i))) return false; } return true; } /** * Parses the canonical URI representation. * @param str * @return * @throws MalformedContentNameStringException */ public static ContentName parse(String str) throws MalformedContentNameStringException { if(str == null) return null; if(str.length() == 0) return ROOT; return fromURI(str); } /** * Uses the canonical URI representation * @param str * @return */ public boolean contains(String str) throws MalformedURIException { try { byte[] parsed = componentParseURI(str); if (null == parsed) { return false; } else { return contains(parsed); } } catch (DotDotComponent c) { return false; } } public boolean contains(byte [] component) { return (containsWhere(component) > 0); } /** * Uses the canonical URI representation * @param str * @return * @throws MalformedURIException */ public int containsWhere(String str) throws MalformedURIException { try { byte[] parsed = componentParseURI(str); if (null == parsed) { return -1; } else { return containsWhere(parsed); } } catch (DotDotComponent c) { return -1; } } int containsWhere(byte [] component) { int i=0; boolean result = false; for (i=0; i < _components.size(); ++i) { if (Arrays.equals(_components.get(i),component)) { result = true; break; } } if (result) return i; return -1; } /** * Return the first componentNumber components of this name as a new name. * @param componentNumber * @return */ public ContentName cut(int componentCount) { if ((componentCount < 0) || (componentCount > count())) { throw new IllegalArgumentException("Illegal component count: " + componentCount); } if (componentCount == count()) return this; return new ContentName(componentCount, this.components()); } /** * Slice the name off right before the given component * @param name * @param component * @return */ public ContentName cut(byte [] component) { int offset = this.containsWhere(component); if (offset < 0) { // unfragmented return this; } // else need to cut it return new ContentName(offset, this.components()); } public ContentName cut(String component) throws MalformedURIException { try { byte[] parsed = componentParseURI(component); if (null == parsed) { return this; } else { return cut(parsed); } } catch (DotDotComponent c) { return this; } } public void encode(XMLEncoder encoder) throws XMLStreamException { if (!validate()) { throw new XMLStreamException("Cannot encode " + this.getClass().getName() + ": field values missing."); } encoder.writeStartElement(contentNameElement()); for (int i=0; i < count(); ++i) { encoder.writeElement(COMPONENT_ELEMENT, _components.get(i)); } encoder.writeEndElement(); } public boolean validate() { return (null != _components); } public ContentName copy(int nameComponentCount) { return new ContentName(nameComponentCount, this.components()); } public int compareTo(ContentName o) { if (this == o) return 0; int len = (this.count() > o.count()) ? this.count() : o.count(); int componentResult = 0; for (int i=0; i < len; ++i) { componentResult = DataUtils.compare(this.component(i), o.component(i)); if (0 != componentResult) return componentResult; } if (this.count() < o.count()) return -1; else if (this.count() > o.count()) return 1; return 0; } }
Added working hashCode to ContentName.
Java_CCN/com/parc/ccn/data/ContentName.java
Added working hashCode to ContentName.
<ide><path>ava_CCN/com/parc/ccn/data/ContentName.java <ide> return false; <ide> } <ide> <add> /** <add> * hashCode and equals not auto-generated, ArrayList does not do the right thing. <add> */ <add> @Override <ide> public boolean equals(Object obj) { <ide> if (this == obj) <ide> return true; <ide> return true; <ide> } <ide> <add> @Override <add> public int hashCode() { <add> final int prime = 31; <add> int result = 1; <add> for (int i=0; i < count(); ++i) { <add> result = prime * result + Arrays.hashCode(component(i)); <add> } <add> return result; <add> } <add> <ide> /** <ide> * Parses the canonical URI representation. <ide> * @param str
Java
apache-2.0
fe26567b08e1bb595058ca4309e6de645194e2be
0
amygithub/vavr,amygithub/vavr,ummels/vavr,ummels/vavr,dx-pbuckley/vavr,dx-pbuckley/vavr
/* / \____ _ ______ _____ / \____ ____ _____ * / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang * _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014-2015 Daniel Dietrich * /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0 */ package javaslang; import javaslang.collection.*; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.StreamSupport; /** * A representation of value which may be either <em>defined</em> or <em>undefined</em>. If a value is undefined, we say * it is empty. * <p> * In a functional setting, a value can be seen as the result of a partial function application. Hence the result may * be undefined. * <p> * How the empty state is interpreted depends on the context, i.e. it may be <em>undefined</em>, <em>failed</em>, * <em>not yet defined</em>, etc. * * @param <T> The type of the wrapped value. * @since 2.0.0 */ public interface Value<T> extends MonadLike<T>, IterableLike<T>, ConversionOps<T> { /** * Gets the underlying value or throws if no value is present. * * @return the underlying value * @throws java.util.NoSuchElementException if no value is defined */ T get(); /** * Gets the underlying as Option. * * @return Some(value) if a value is present, None otherwise */ default Option<T> getOption() { return isEmpty() ? None.instance() : new Some<>(get()); } /** * A fluent if-expression for this value. If this is defined (i.e. not empty) trueVal is returned, * otherwise falseVal is returned. * * @param trueVal The result, if this is defined. * @param falseVal The result, if this is not defined. * @return trueVal if this.isDefined(), otherwise falseVal. */ default T ifDefined(T trueVal, T falseVal) { return isDefined() ? trueVal : falseVal; } /** * A fluent if-expression for this value. If this is defined (i.e. not empty) trueSupplier.get() is returned, * otherwise falseSupplier.get() is returned. * * @param trueSupplier The result, if this is defined. * @param falseSupplier The result, if this is not defined. * @return trueSupplier.get() if this.isDefined(), otherwise falseSupplier.get(). */ default T ifDefined(Supplier<? extends T> trueSupplier, Supplier<? extends T> falseSupplier) { return isDefined() ? trueSupplier.get() : falseSupplier.get(); } /** * A fluent if-expression for this value. If this is empty (i.e. not defined) trueVal is returned, * otherwise falseVal is returned. * * @param trueVal The result, if this is empty. * @param falseVal The result, if this is not empty. * @return trueVal if this.isEmpty(), otherwise falseVal. */ default T ifEmpty(T trueVal, T falseVal) { return isEmpty() ? trueVal : falseVal; } /** * A fluent if-expression for this value. If this is empty (i.e. not defined) trueSupplier.get() is returned, * otherwise falseSupplier.get() is returned. * * @param trueSupplier The result, if this is defined. * @param falseSupplier The result, if this is not defined. * @return trueSupplier.get() if this.isEmpty(), otherwise falseSupplier.get(). */ default T ifEmpty(Supplier<? extends T> trueSupplier, Supplier<? extends T> falseSupplier) { return isEmpty() ? trueSupplier.get() : falseSupplier.get(); } /** * Checks, this {@code Value} is empty, i.e. if the underlying value is absent. * * @return false, if no underlying value is present, true otherwise. */ boolean isEmpty(); /** * Checks, this {@code Value} is defined, i.e. if the underlying value is present. * * @return true, if an underlying value is present, false otherwise. */ default boolean isDefined() { return !isEmpty(); } /** * Returns the underlying value if present, otherwise {@code other}. * * @param other An alternative value. * @return A value of type {@code T} */ default T orElse(T other) { return isEmpty() ? other : get(); } /** * Returns the underlying value if present, otherwise {@code other}. * * @param supplier An alternative value. * @return A value of type {@code T} * @throws NullPointerException if supplier is null */ default T orElseGet(Supplier<? extends T> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return isEmpty() ? supplier.get() : get(); } /** * Returns the underlying value if present, otherwise throws {@code supplier.get()}. * * @param <X> a Throwable type * @param supplier An exception supplier. * @return A value of type {@code T} * @throws NullPointerException if supplier is null * @throws X if no value is present */ default <X extends Throwable> T orElseThrow(Supplier<X> supplier) throws X { Objects.requireNonNull(supplier, "supplier is null"); if (isEmpty()) { throw supplier.get(); } else { return get(); } } @Override Value<T> peek(Consumer<? super T> action); // TODO: // @Override // default Array<T> toArray() { // return isEmpty() ? Array.empty() : Array.ofAll(this); // } @Override default Lazy<T> toLazy() { if (this instanceof Lazy) { return (Lazy<T>) this; } else { return isEmpty() ? Lazy.empty() : Lazy.of(this::get); } } @Override default List<T> toList() { return isEmpty() ? List.empty() : List.ofAll(this); } @Override default <K, V> Map<K, V> toMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); Map<K, V> map = HashMap.empty(); for (T a : this) { final Tuple2<? extends K, ? extends V> entry = f.apply(a); map = map.put(entry._1, entry._2); } return map; } @Override default Option<T> toOption() { if (this instanceof Option) { return (Option<T>) this; } else { return isEmpty() ? None.instance() : new Some<>(get()); } } @Override default Queue<T> toQueue() { return isEmpty() ? Queue.empty() : Queue.ofAll(this); } @Override default Set<T> toSet() { return isEmpty() ? HashSet.empty() : HashSet.ofAll(this); } @Override default Stack<T> toStack() { return isEmpty() ? Stack.empty() : Stack.ofAll(this); } @Override default Stream<T> toStream() { return isEmpty() ? Stream.empty() : Stream.ofAll(this); } // TODO: // @Override // default Vector<T> toVector() { // return isEmpty() ? Vector.empty() : Vector.ofAll(this); // } @SuppressWarnings("unchecked") @Override default T[] toJavaArray(Class<T> componentType) { Objects.requireNonNull(componentType, "componentType is null"); final java.util.List<T> list = toJavaList(); return list.toArray((T[]) java.lang.reflect.Array.newInstance(componentType, list.size())); } @Override default java.util.List<T> toJavaList() { final java.util.List<T> result = new java.util.ArrayList<>(); for (T a : this) { result.add(a); } return result; } @Override default Optional<T> toJavaOptional() { return isEmpty() ? Optional.empty() : Optional.ofNullable(get()); } @Override default <K, V> java.util.Map<K, V> toJavaMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); final java.util.Map<K, V> map = new java.util.HashMap<>(); for (T a : this) { final Tuple2<? extends K, ? extends V> entry = f.apply(a); map.put(entry._1, entry._2); } return map; } @Override default java.util.Set<T> toJavaSet() { final java.util.Set<T> result = new java.util.HashSet<>(); for (T a : this) { result.add(a); } return result; } @Override default java.util.stream.Stream<T> toJavaStream() { return StreamSupport.stream(spliterator(), false); } } /** * Some essential operations for monad-like types. * The <code>flatMap</code> method is missing here in order to have only one generic type parameter. * <p> * Internal interface to reduce code duplication. Currently used by Value only. * * @param <T> Component type * @since 2.0.0 */ interface MonadLike<T> { /** * Filters this {@code Value} by testing a predicate. * <p> * The semantics may vary from class to class, e.g. for single-valued type (like Option) and multi-values types * (like Traversable). The commonality is, that filtered.isEmpty() will return true, if no element satisfied * the given predicate. * <p> * Also, an implementation may throw {@code NoSuchElementException}, if no element makes it through the filter * and this state cannot be reflected. E.g. this is the case for {@link javaslang.control.Either.LeftProjection} and * {@link javaslang.control.Either.RightProjection}. * * @param predicate A predicate * @return a new Value instance * @throws NullPointerException if {@code predicate} is null */ Value<T> filter(Predicate<? super T> predicate); /** * Flattens this {@code Value}. * <p> * The semantics may vary from class to class. The commonality is, * that some kind of wrapped state is recursively unwrapped. * <p> * Example: * <pre><code>(((1))).flatten() = (1)</code></pre> * * @return A flattened version of this {@code Value}. */ Value<Object> flatten(); /** * Maps this value to a new value with different component type. * * @param mapper A mapper. * @param <U> Component type of the mapped {@code Value} * @return a mapped {@code Value} * @throws NullPointerException if {@code mapper} is null */ <U> Value<U> map(Function<? super T, ? extends U> mapper); } /** * Some essential operations for iterable-like types. * <p> * Internal interface to reduce code duplication. Currently used by Value only. * * @param <T> Component type * @since 2.0.0 */ interface IterableLike<T> extends Iterable<T> { /** * Checks, if an element exists such that the predicate holds. * * @param predicate A Predicate * @return true, if predicate holds for one or more elements, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean exists(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (T t : this) { if (predicate.test(t)) { return true; } } return false; } /** * Checks, if the given predicate holds for all elements. * * @param predicate A Predicate * @return true, if the predicate holds for all elements, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean forAll(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return !exists(predicate.negate()); } /** * Performs an action on each element. * * @param action A {@code Consumer} * @throws NullPointerException if {@code action} is null */ default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); for (T t : this) { action.accept(t); } } /** * Performs the given {@code action} on the first element if this is an <em>eager</em> implementation. * Performs the given {@code action} on all elements (the first immediately, successive deferred), * if this is a <em>lazy</em> implementation. * * @param action The action the will be performed on the element(s). * @return this instance */ IterableLike<T> peek(Consumer<? super T> action); } /** * Inter-Javaslang type and to-Java type conversions. Currently used by Value only. * <p> * Internal interface to reduce code duplication. Currently used by Value only. * * @param <T> Component type * @since 2.0.0 */ interface ConversionOps<T> { // -- Javaslang types // TODO: // /** // * Converts this instance to a {@link Array}. // * // * @return A new {@link Array}. // */ // Array<T> toArray(); /** * Converts this instance to a {@link Lazy}. * * @return A new {@link Lazy}. */ Lazy<T> toLazy(); /** * Converts this instance to a {@link List}. * * @return A new {@link List}. */ List<T> toList(); /** * Converts this instance to a {@link Map}. * * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link HashMap}. */ <K, V> Map<K, V> toMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f); /** * Converts this instance to an {@link Option}. * * @return A new {@link Option}. */ Option<T> toOption(); /** * Converts this instance to a {@link Queue}. * * @return A new {@link Queue}. */ Queue<T> toQueue(); /** * Converts this instance to a {@link Set}. * * @return A new {@link HashSet}. */ Set<T> toSet(); /** * Converts this instance to a {@link Stack}. * * @return A new {@link List}, which is a {@link Stack}. */ Stack<T> toStack(); /** * Converts this instance to a {@link Stream}. * * @return A new {@link Stream}. */ Stream<T> toStream(); // TODO: // /** // * Converts this instance to a {@link Tree}. // * // * @return A new {@link Tree}. // */ // Tree<T> toTree(); // TODO: // /** // * Converts this instance to a {@link Vector}. // * // * @return A new {@link Vector}. // */ // Vector<T> toVector(); // -- Java types /** * Converts this instance to a Java array. * * @param componentType Component type of the array * @return A new Java array. * @throws NullPointerException if componentType is null */ T[] toJavaArray(Class<T> componentType); /** * Converts this instance to an {@link java.util.List}. * * @return A new {@link java.util.ArrayList}. */ java.util.List<T> toJavaList(); /** * Converts this instance to a {@link java.util.Map}. * * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link java.util.HashMap}. */ <K, V> java.util.Map<K, V> toJavaMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f); /** * Converts this instance to an {@link java.util.Optional}. * * @return A new {@link java.util.Optional}. */ Optional<T> toJavaOptional(); /** * Converts this instance to a {@link java.util.Set}. * * @return A new {@link java.util.HashSet}. */ java.util.Set<T> toJavaSet(); /** * Converts this instance to a {@link java.util.stream.Stream}. * * @return A new {@link java.util.stream.Stream}. */ java.util.stream.Stream<T> toJavaStream(); }
src/main/java/javaslang/Value.java
/* / \____ _ ______ _____ / \____ ____ _____ * / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang * _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014-2015 Daniel Dietrich * /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0 */ package javaslang; import javaslang.collection.*; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.StreamSupport; /** * A representation of value which may be either <em>defined</em> or <em>undefined</em>. If a value is undefined, we say * it is empty. * <p> * In a functional setting, a value can be seen as the result of a partial function application. Hence the result may * be undefined. * <p> * How the empty state is interpreted depends on the context, i.e. it may be <em>undefined</em>, <em>failed</em>, * <em>not yet defined</em>, etc. * * @param <T> The type of the wrapped value. * @since 2.0.0 */ public interface Value<T> extends MonadLike<T>, IterableLike<T>, ConversionOps<T> { /** * Gets the underlying value or throws if no value is present. * * @return the underlying value * @throws java.util.NoSuchElementException if no value is defined */ T get(); /** * Gets the underlying as Option. * * @return Some(value) if a value is present, None otherwise */ default Option<T> getOption() { return isEmpty() ? None.instance() : new Some<>(get()); } /** * A fluent if-expression for this value. If this is defined (i.e. not empty) trueVal is returned, * otherwise falseVal is returned. * * @param trueVal The result, if this is defined. * @param falseVal The result, if this is not defined. * @return trueVal if this.isDefined(), otherwise falseVal. */ default T ifDefined(T trueVal, T falseVal) { return isDefined() ? trueVal : falseVal; } /** * A fluent if-expression for this value. If this is defined (i.e. not empty) trueSupplier.get() is returned, * otherwise falseSupplier.get() is returned. * * @param trueSupplier The result, if this is defined. * @param falseSupplier The result, if this is not defined. * @return trueSupplier.get() if this.isDefined(), otherwise falseSupplier.get(). */ default T ifDefined(Supplier<? extends T> trueSupplier, Supplier<? extends T> falseSupplier) { return isDefined() ? trueSupplier.get() : falseSupplier.get(); } /** * A fluent if-expression for this value. If this is empty (i.e. not defined) trueVal is returned, * otherwise falseVal is returned. * * @param trueVal The result, if this is empty. * @param falseVal The result, if this is not empty. * @return trueVal if this.isEmpty(), otherwise falseVal. */ default T ifEmpty(T trueVal, T falseVal) { return isEmpty() ? trueVal : falseVal; } /** * A fluent if-expression for this value. If this is empty (i.e. not defined) trueSupplier.get() is returned, * otherwise falseSupplier.get() is returned. * * @param trueSupplier The result, if this is defined. * @param falseSupplier The result, if this is not defined. * @return trueSupplier.get() if this.isEmpty(), otherwise falseSupplier.get(). */ default T ifEmpty(Supplier<? extends T> trueSupplier, Supplier<? extends T> falseSupplier) { return isEmpty() ? trueSupplier.get() : falseSupplier.get(); } /** * Checks, this {@code Value} is empty, i.e. if the underlying value is absent. * * @return false, if no underlying value is present, true otherwise. */ boolean isEmpty(); /** * Checks, this {@code Value} is defined, i.e. if the underlying value is present. * * @return true, if an underlying value is present, false otherwise. */ default boolean isDefined() { return !isEmpty(); } /** * Returns the underlying value if present, otherwise {@code other}. * * @param other An alternative value. * @return A value of type {@code T} */ default T orElse(T other) { return isEmpty() ? other : get(); } /** * Returns the underlying value if present, otherwise {@code other}. * * @param supplier An alternative value. * @return A value of type {@code T} * @throws NullPointerException if supplier is null */ default T orElseGet(Supplier<? extends T> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return isEmpty() ? supplier.get() : get(); } /** * Returns the underlying value if present, otherwise throws {@code supplier.get()}. * * @param <X> a Throwable type * @param supplier An exception supplier. * @return A value of type {@code T} * @throws NullPointerException if supplier is null * @throws X if no value is present */ default <X extends Throwable> T orElseThrow(Supplier<X> supplier) throws X { Objects.requireNonNull(supplier, "supplier is null"); if (isEmpty()) { throw supplier.get(); } else { return get(); } } @Override Value<T> peek(Consumer<? super T> action); // TODO: // @Override // default Array<T> toArray() { // return isEmpty() ? Array.empty() : Array.ofAll(this); // } @Override default Lazy<T> toLazy() { if (this instanceof Lazy) { return (Lazy<T>) this; } else { return isEmpty() ? Lazy.empty() : Lazy.of(this::get); } } @Override default List<T> toList() { return isEmpty() ? List.empty() : List.ofAll(this); } @Override default <K, V> Map<K, V> toMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); Map<K, V> map = HashMap.empty(); for (T a : this) { final Tuple2<? extends K, ? extends V> entry = f.apply(a); map = map.put(entry._1, entry._2); } return map; } @Override default Option<T> toOption() { if (this instanceof Option) { return (Option<T>) this; } else { return isEmpty() ? None.instance() : new Some<>(get()); } } @Override default Queue<T> toQueue() { return isEmpty() ? Queue.empty() : Queue.ofAll(this); } @Override default Set<T> toSet() { return isEmpty() ? HashSet.empty() : HashSet.ofAll(this); } @Override default Stack<T> toStack() { return isEmpty() ? Stack.empty() : Stack.ofAll(this); } @Override default Stream<T> toStream() { return isEmpty() ? Stream.empty() : Stream.ofAll(this); } // TODO: // @Override // default Vector<T> toVector() { // return isEmpty() ? Vector.empty() : Vector.ofAll(this); // } @SuppressWarnings("unchecked") @Override default T[] toJavaArray(Class<T> componentType) { Objects.requireNonNull(componentType, "componentType is null"); final java.util.List<T> list = toJavaList(); return list.toArray((T[]) java.lang.reflect.Array.newInstance(componentType, list.size())); } @Override default java.util.List<T> toJavaList() { final java.util.List<T> result = new java.util.ArrayList<>(); for (T a : this) { result.add(a); } return result; } @Override default Optional<T> toJavaOptional() { return isEmpty() ? Optional.empty() : Optional.ofNullable(get()); } @Override default <K, V> java.util.Map<K, V> toJavaMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); final java.util.Map<K, V> map = new java.util.HashMap<>(); for (T a : this) { final Tuple2<? extends K, ? extends V> entry = f.apply(a); map.put(entry._1, entry._2); } return map; } @Override default java.util.Set<T> toJavaSet() { final java.util.Set<T> result = new java.util.HashSet<>(); for (T a : this) { result.add(a); } return result; } @Override default java.util.stream.Stream<T> toJavaStream() { return StreamSupport.stream(spliterator(), false); } } /** * Some essential operations for monad-like types. * The <code>flatMap</code> method is missing here in order to have only one generic type parameter. * <p> * Internal interface to reduce code duplication. Currently used by Value only. * * @param <T> Component type * @since 2.0.0 */ interface MonadLike<T> { /** * Filters this {@code Value} by testing a predicate. * <p> * The semantics may vary from class to class, e.g. for single-valued type (like Option) and multi-values types * (like Traversable). The commonality is, that filtered.isEmpty() will return true, if no element satisfied * the given predicate. * <p> * Also, an implementation may throw {@code NoSuchElementException}, if no element makes it through the filter * and this state cannot be reflected. E.g. this is the case for {@link javaslang.control.Either.LeftProjection} and * {@link javaslang.control.Either.RightProjection}. * * @param predicate A predicate * @return a new Value instance * @throws NullPointerException if {@code predicate} is null */ Value<T> filter(Predicate<? super T> predicate); /** * Flattens this {@code Value}. * <p> * The semantics may vary from class to class. The commonality is, * that some kind of wrapped state is recursively unwrapped. * <p> * Example: * <pre><code>(((1))).flatten() = (1)</code></pre> * * @return A flattened version of this {@code Value}. */ Value<Object> flatten(); /** * Maps this value to a new value with different component type. * * @param mapper A mapper. * @param <U> Component type of the mapped {@code Value} * @return a mapped {@code Value} * @throws NullPointerException if {@code mapper} is null */ <U> Value<U> map(Function<? super T, ? extends U> mapper); } /** * Some essential operations for iterable-like types. * <p> * Internal interface to reduce code duplication. Currently used by Value only. * * @param <T> Component type * @since 2.0.0 */ interface IterableLike<T> extends Iterable<T> { /** * Checks, if an element exists such that the predicate holds. * * @param predicate A Predicate * @return true, if predicate holds for one or more elements, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean exists(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (T t : this) { if (predicate.test(t)) { return true; } } return false; } /** * Checks, if the given predicate holds for all elements. * * @param predicate A Predicate * @return true, if the predicate holds for all elements, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean forAll(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return !exists(predicate.negate()); } /** * Performs an action on each element. * * @param action A {@code Consumer} * @throws NullPointerException if {@code action} is null */ default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); for (T t : this) { action.accept(t); } } /** * Performs the given {@code action} on the first element if this is an <em>eager</em> implementation. * Performs the given {@code action} on all elements (the first immediately, successive deferred), * if this is a <em>lazy</em> implementation. * * @param action The action the will be performed on the element(s). * @return this instance */ IterableLike<T> peek(Consumer<? super T> action); } /** * Inter-Javaslang type and to-Java type conversions. Currently used by Value only. * <p> * Internal interface to reduce code duplication. Currently used by Value only. * * @param <T> Component type * @since 2.0.0 */ interface ConversionOps<T> { // -- Javaslang types // TODO: // /** // * Converts this instance to a {@link Array}. // * // * @return A new {@link Array}. // */ // Array<T> toArray(); /** * Converts this instance to a {@link Lazy}. * * @return A new {@link Lazy}. */ Lazy<T> toLazy(); /** * Converts this instance to a {@link List}. * * @return A new {@link List}. */ List<T> toList(); /** * Converts this instance to a {@link Map}. * * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link HashMap}. */ <K, V> Map<K, V> toMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f); /** * Converts this instance to an {@link Option}. * * @return A new {@link Option}. */ Option<T> toOption(); /** * Converts this instance to a {@link Queue}. * * @return A new {@link Queue}. */ Queue<T> toQueue(); /** * Converts this instance to a {@link Set}. * * @return A new {@link HashSet}. */ Set<T> toSet(); /** * Converts this instance to a {@link Stack}. * * @return A new {@link List}, which is a {@link Stack}. */ Stack<T> toStack(); /** * Converts this instance to a {@link Stream}. * * @return A new {@link Stream}. */ Stream<T> toStream(); // TODO: // /** // * Converts this instance to a {@link Tree}. // * // * @return A new {@link Tree}. // */ // Tree<T> toTree(); // TODO: // /** // * Converts this instance to a {@link Vector}. // * // * @return A new {@link Vector}. // */ // Vector<T> toVector(); // -- Java types /** * Converts this instance to a Java array. * * @return A new Java array. * @throws NullPointerException if componentType is null */ T[] toJavaArray(Class<T> componentType); /** * Converts this instance to an {@link java.util.List}. * * @return A new {@link java.util.ArrayList}. */ java.util.List<T> toJavaList(); /** * Converts this instance to a {@link java.util.Map}. * * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link java.util.HashMap}. */ <K, V> java.util.Map<K, V> toJavaMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f); /** * Converts this instance to an {@link java.util.Optional}. * * @return A new {@link java.util.Optional}. */ Optional<T> toJavaOptional(); /** * Converts this instance to a {@link java.util.Set}. * * @return A new {@link java.util.HashSet}. */ java.util.Set<T> toJavaSet(); /** * Converts this instance to a {@link java.util.stream.Stream}. * * @return A new {@link java.util.stream.Stream}. */ java.util.stream.Stream<T> toJavaStream(); }
fixed javadoc
src/main/java/javaslang/Value.java
fixed javadoc
<ide><path>rc/main/java/javaslang/Value.java <ide> /** <ide> * Converts this instance to a Java array. <ide> * <add> * @param componentType Component type of the array <ide> * @return A new Java array. <ide> * @throws NullPointerException if componentType is null <ide> */
Java
mit
cdbcb1edc4053bf1cf37908081101fc49414f3d6
0
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
package leetcode; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * https://leetcode.com/problems/k-closest-points-to-origin/ */ public class Problem973 { public int[][] kClosest(int[][] points, int K) { List<PointDistance> list = new ArrayList<>(); for (int[] point : points) { double distance = Math.sqrt((Math.abs(point[0]) * Math.abs(point[0])) + (Math.abs(point[1]) * Math.abs(point[1]))); list.add(new PointDistance(point, distance)); } Collections.sort(list, (a, b) -> { if (a.distance < b.distance) { return -1; } else if (a.distance == b.distance) { return 0; } return 1; }); int[][] answer = new int[K][]; for (int i = 0; i < K; i++) { answer[i] = list.get(i).point; } return answer; } private static class PointDistance { private final int[] point; private final double distance; public PointDistance(int[] point, double distance) { this.point = point; this.distance = distance; } @Override public String toString() { return Arrays.toString(point) + " --> " + distance; } } private static void print(int[][] answer) { for (int[] i : answer) { System.out.print(Arrays.toString(i) + " "); } System.out.println(); } public static void main(String[] args) { Problem973 prob = new Problem973(); print(prob.kClosest(new int[][]{ {1, 3}, {-2, 2} }, 1)); // [[-2,2]] print(prob.kClosest(new int[][]{ {3, 3}, {5, -1}, {-2, 4} }, 2)); // [[3,3],[-2,4]] } }
src/main/java/leetcode/Problem973.java
package leetcode; /** * https://leetcode.com/problems/k-closest-points-to-origin/ */ public class Problem973 { public int[][] kClosest(int[][] points, int K) { // TODO return null; } public static void main(String[] args) { Problem973 prob = new Problem973(); } }
Update problem 973
src/main/java/leetcode/Problem973.java
Update problem 973
<ide><path>rc/main/java/leetcode/Problem973.java <ide> package leetcode; <add> <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.Collections; <add>import java.util.List; <ide> <ide> /** <ide> * https://leetcode.com/problems/k-closest-points-to-origin/ <ide> */ <ide> public class Problem973 { <ide> public int[][] kClosest(int[][] points, int K) { <del> // TODO <del> return null; <add> List<PointDistance> list = new ArrayList<>(); <add> for (int[] point : points) { <add> double distance = Math.sqrt((Math.abs(point[0]) * Math.abs(point[0])) + <add> (Math.abs(point[1]) * Math.abs(point[1]))); <add> list.add(new PointDistance(point, distance)); <add> } <add> Collections.sort(list, (a, b) -> { <add> if (a.distance < b.distance) { <add> return -1; <add> } else if (a.distance == b.distance) { <add> return 0; <add> } <add> return 1; <add> }); <add> int[][] answer = new int[K][]; <add> for (int i = 0; i < K; i++) { <add> answer[i] = list.get(i).point; <add> } <add> return answer; <add> } <add> <add> private static class PointDistance { <add> private final int[] point; <add> private final double distance; <add> <add> public PointDistance(int[] point, double distance) { <add> this.point = point; <add> this.distance = distance; <add> } <add> <add> @Override <add> public String toString() { <add> return Arrays.toString(point) + " --> " + distance; <add> } <add> } <add> <add> private static void print(int[][] answer) { <add> for (int[] i : answer) { <add> System.out.print(Arrays.toString(i) + " "); <add> } <add> System.out.println(); <ide> } <ide> <ide> public static void main(String[] args) { <ide> Problem973 prob = new Problem973(); <add> print(prob.kClosest(new int[][]{ <add> {1, 3}, {-2, 2} <add> }, 1)); // [[-2,2]] <add> print(prob.kClosest(new int[][]{ <add> {3, 3}, {5, -1}, {-2, 4} <add> }, 2)); // [[3,3],[-2,4]] <ide> } <ide> }
Java
apache-2.0
caa63ea2ca65b5fc40da14210a1dc752e48c369e
0
dimagi/javarosa,dimagi/javarosa,dimagi/javarosa
/* * Copyright (C) 2015 JavaRosa * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.javarosa.xpath.expr.test; import j2meunit.framework.Test; import j2meunit.framework.TestCase; import j2meunit.framework.TestMethod; import j2meunit.framework.TestSuite; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.util.Date; import java.util.Vector; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.condition.IFunctionHandler; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.IntegerData; import org.javarosa.core.model.data.StringData; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.model.xform.XPathReference; import org.javarosa.xpath.IExprDataType; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathParseTool; import org.javarosa.xpath.XPathTypeMismatchException; import org.javarosa.xpath.XPathUnhandledException; import org.javarosa.xpath.XPathUnsupportedException; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.expr.XPathFuncExpr; import org.javarosa.xpath.expr.XPathNumericLiteral; import org.javarosa.xpath.expr.XPathPathExpr; import org.javarosa.xpath.parser.XPathSyntaxException; import org.javarosa.xml.ElementParser; import org.javarosa.xml.TreeElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; /** * * @author Phillip Mates */ public class XPathPathExprTest extends TestCase { private static final String formPath = new String("/test_xpathpathexpr.xml"); // private static final String formPath = new String("/test_small_xml_example.xml"); public XPathPathExprTest(String name, TestMethod rTestMethod) { super(name, rTestMethod); } public XPathPathExprTest(String name) { super(name); } public XPathPathExprTest() { super(); } public Test suite() { TestSuite aSuite = new TestSuite(); aSuite.addTest(new XPathPathExprTest("XPath Path Expression Test", new TestMethod() { public void run(TestCase tc) { ((XPathPathExprTest) tc).doTests(); } })); return aSuite; } public void doTests() { TreeElement root = null; EvaluationContext ec = new EvaluationContext(null); TreeElementParser parser; // read in xml try { InputStream is = System.class.getResourceAsStream(formPath); parser = new TreeElementParser(ElementParser.instantiateParser(is), 0, "instance"); } catch (IOException e) { fail("Contents at filepath could not be loaded into parser: " + formPath); return; } // turn parsed xml into a form instance try { root = parser.parse(); } catch (Exception e) { fail("File couldn't be parsed into a TreeElement: " + formPath); return; } FormInstance instance = null; try { instance = new FormInstance(root, ""); } catch (Exception e) { fail("couldn't create form instance"); } // Used to reproduce bug where locations can't handle heterogeneous template paths // The following test will pass when this is fixed. testEval("/data/places/country[1]/state[0]/name", instance, null, "Utah"); // XXX: not sure why this test isn't passing testEval("/data/places/country[0]/name", instance, null, "Singapore"); } private void testEval(String expr, FormInstance model, EvaluationContext ec, Object expected) { testEval(expr, model, ec, expected, 1.0e-12); } private void testEval(String expr, FormInstance model, EvaluationContext ec, Object expected, double tolerance) { XPathExpression xpe = null; boolean exceptionExpected = (expected instanceof XPathException); if (ec == null) { ec = new EvaluationContext(model); } try { xpe = XPathParseTool.parseXPath(expr); } catch (XPathSyntaxException xpse) { } if (xpe == null) { fail("Null expression or syntax error " + expr); } try { Object result = XPathFuncExpr.unpack(xpe.eval(model, ec)); if (tolerance != XPathFuncExpr.DOUBLE_TOLERANCE) { System.out.println(expr + " = " + result); } if (exceptionExpected) { fail("Expected exception, expression : " + expr); } else if ((result instanceof Double && expected instanceof Double)) { Double o = ((Double) result).doubleValue(); Double t = ((Double) expected).doubleValue(); if (Math.abs(o - t) > tolerance) { fail("Doubles outside of tolerance: got " + o + ", expected " + t); } } else if (!expected.equals(result)) { fail("Expected " + expected + ", got " + result); } } catch (XPathException xpex) { if (!exceptionExpected) { fail("Did not expect " + xpex.getClass() + " exception"); } else if (xpex.getClass() != expected.getClass()) { fail("Did not get expected exception type"); } } } }
core/test/org/javarosa/xpath/expr/test/XPathPathExprTest.java
/* * Copyright (C) 2015 JavaRosa * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.javarosa.xpath.expr.test; import j2meunit.framework.Test; import j2meunit.framework.TestCase; import j2meunit.framework.TestMethod; import j2meunit.framework.TestSuite; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.util.Date; import java.util.Vector; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.condition.IFunctionHandler; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.IntegerData; import org.javarosa.core.model.data.StringData; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.model.xform.XPathReference; import org.javarosa.xpath.IExprDataType; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathParseTool; import org.javarosa.xpath.XPathTypeMismatchException; import org.javarosa.xpath.XPathUnhandledException; import org.javarosa.xpath.XPathUnsupportedException; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.expr.XPathFuncExpr; import org.javarosa.xpath.expr.XPathNumericLiteral; import org.javarosa.xpath.expr.XPathPathExpr; import org.javarosa.xpath.parser.XPathSyntaxException; import org.javarosa.xml.ElementParser; import org.javarosa.xml.TreeElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; /** * * @author Phillip Mates */ public class XPathPathExprTest extends TestCase { private static final String formPath = new String("/test_xpathpathexpr.xml"); // private static final String formPath = new String("/test_small_xml_example.xml"); public XPathPathExprTest(String name, TestMethod rTestMethod) { super(name, rTestMethod); } public XPathPathExprTest(String name) { super(name); } public XPathPathExprTest() { super(); } public Test suite() { TestSuite aSuite = new TestSuite(); aSuite.addTest(new XPathPathExprTest("XPath Path Expression Test", new TestMethod() { public void run(TestCase tc) { ((XPathPathExprTest) tc).doTests(); } })); return aSuite; } public void doTests() { TreeElement root = null; EvaluationContext ec = new EvaluationContext(null); TreeElementParser parser; // read in xml try { InputStream is = System.class.getResourceAsStream(formPath); parser = new TreeElementParser(ElementParser.instantiateParser(is), 0, "data"); } catch (IOException e) { fail("Contents at filepath could not be parsed as XML: " + formPath); return; } // turn parsed xml into a form instance try { root = parser.parse(); } catch (Exception e) { fail("File couldn't be parsed into a TreeElement: " + formPath); return; } FormInstance instance = null; try { instance = new FormInstance(root, "data"); } catch (Exception e) { fail("couldn't create form instance"); } testEval("count(/data/places/country/state)", instance, null, new Double(2)); } private void testEval(String expr, FormInstance model, EvaluationContext ec, Object expected) { testEval(expr, model, ec, expected, 1.0e-12); } private void testEval(String expr, FormInstance model, EvaluationContext ec, Object expected, double tolerance) { XPathExpression xpe = null; boolean exceptionExpected = (expected instanceof XPathException); if (ec == null) { ec = new EvaluationContext(model); } try { xpe = XPathParseTool.parseXPath(expr); } catch (XPathSyntaxException xpse) { } if (xpe == null) { fail("Null expression or syntax error " + expr); } try { Object result = XPathFuncExpr.unpack(xpe.eval(model, ec)); if (tolerance != XPathFuncExpr.DOUBLE_TOLERANCE) { System.out.println(expr + " = " + result); } if (exceptionExpected) { fail("Expected exception, expression : " + expr); } else if ((result instanceof Double && expected instanceof Double)) { Double o = ((Double) result).doubleValue(); Double t = ((Double) expected).doubleValue(); if (Math.abs(o - t) > tolerance) { fail("Doubles outside of tolerance: got " + o + ", expected " + t); } } else if (!expected.equals(result)) { fail("Expected " + expected + ", got " + result); } } catch (XPathException xpex) { if (!exceptionExpected) { fail("Did not expect " + xpex.getClass() + " exception"); } else if (xpex.getClass() != expected.getClass()) { fail("Did not get expected exception type"); } } } }
added test that should pass once path template bug is fixed
core/test/org/javarosa/xpath/expr/test/XPathPathExprTest.java
added test that should pass once path template bug is fixed
<ide><path>ore/test/org/javarosa/xpath/expr/test/XPathPathExprTest.java <ide> // read in xml <ide> try { <ide> InputStream is = System.class.getResourceAsStream(formPath); <del> parser = new TreeElementParser(ElementParser.instantiateParser(is), 0, "data"); <add> parser = new TreeElementParser(ElementParser.instantiateParser(is), 0, "instance"); <ide> } catch (IOException e) { <del> fail("Contents at filepath could not be parsed as XML: " + formPath); <add> fail("Contents at filepath could not be loaded into parser: " + formPath); <ide> return; <ide> } <ide> <ide> } <ide> FormInstance instance = null; <ide> try { <del> instance = new FormInstance(root, "data"); <add> instance = new FormInstance(root, ""); <ide> } catch (Exception e) { <ide> fail("couldn't create form instance"); <ide> } <ide> <del> testEval("count(/data/places/country/state)", instance, null, new Double(2)); <add> // Used to reproduce bug where locations can't handle heterogeneous template paths <add> // The following test will pass when this is fixed. <add> testEval("/data/places/country[1]/state[0]/name", instance, null, "Utah"); <add> <add> // XXX: not sure why this test isn't passing <add> testEval("/data/places/country[0]/name", instance, null, "Singapore"); <ide> } <ide> <ide> private void testEval(String expr, FormInstance model, EvaluationContext ec, Object expected) {
Java
apache-2.0
c8df0d8cb66d2b02ea304121830a00c012b3bc3f
0
TonyChai24/cat,unidal/cat,jialinsun/cat,TonyChai24/cat,chqlb/cat,TonyChai24/cat,JacksonSha/cat,dadarom/cat,dianping/cat,wuqiangxjtu/cat,TonyChai24/cat,chinaboard/cat,xiaojiaqi/cat,itnihao/cat,dianping/cat,cdljsj/cat,howepeng/cat,xiaojiaqi/cat,michael8335/cat,chqlb/cat,xiaojiaqi/cat,ddviplinux/cat,chqlb/cat,JacksonSha/cat,chinaboard/cat,michael8335/cat,ddviplinux/cat,chinaboard/cat,jialinsun/cat,xiaojiaqi/cat,gspandy/cat,michael8335/cat,redbeans2015/cat,unidal/cat,howepeng/cat,wyzssw/cat,dadarom/cat,itnihao/cat,redbeans2015/cat,wyzssw/cat,itnihao/cat,redbeans2015/cat,javachengwc/cat,xiaojiaqi/cat,michael8335/cat,bryanchou/cat,dianping/cat,javachengwc/cat,gspandy/cat,howepeng/cat,JacksonSha/cat,ddviplinux/cat,bryanchou/cat,itnihao/cat,redbeans2015/cat,gspandy/cat,chinaboard/cat,cdljsj/cat,dadarom/cat,jialinsun/cat,xiaojiaqi/cat,dadarom/cat,javachengwc/cat,wyzssw/cat,chinaboard/cat,redbeans2015/cat,howepeng/cat,gspandy/cat,ddviplinux/cat,dianping/cat,javachengwc/cat,bryanchou/cat,JacksonSha/cat,itnihao/cat,gspandy/cat,ddviplinux/cat,unidal/cat,dadarom/cat,redbeans2015/cat,JacksonSha/cat,itnihao/cat,bryanchou/cat,chinaboard/cat,chqlb/cat,howepeng/cat,wuqiangxjtu/cat,dianping/cat,dianping/cat,wuqiangxjtu/cat,wuqiangxjtu/cat,javachengwc/cat,howepeng/cat,wuqiangxjtu/cat,gspandy/cat,jialinsun/cat,JacksonSha/cat,chqlb/cat,bryanchou/cat,unidal/cat,michael8335/cat,cdljsj/cat,cdljsj/cat,wyzssw/cat,michael8335/cat,jialinsun/cat,wyzssw/cat,javachengwc/cat,wyzssw/cat,TonyChai24/cat,unidal/cat,dianping/cat,TonyChai24/cat,cdljsj/cat,unidal/cat,dadarom/cat,cdljsj/cat,chqlb/cat,ddviplinux/cat,bryanchou/cat,wuqiangxjtu/cat,jialinsun/cat
package com.dianping.cat.report.service; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; import org.unidal.dal.jdbc.DalException; import org.unidal.dal.jdbc.DalNotFoundException; import org.unidal.lookup.annotation.Inject; import com.dianping.cat.Cat; import com.dianping.cat.core.dal.DailyReport; import com.dianping.cat.core.dal.DailyReportDao; import com.dianping.cat.core.dal.HourlyReport; import com.dianping.cat.core.dal.HourlyReportContent; import com.dianping.cat.core.dal.HourlyReportContentDao; import com.dianping.cat.core.dal.HourlyReportDao; import com.dianping.cat.core.dal.HourlyReportEntity; import com.dianping.cat.core.dal.MonthlyReport; import com.dianping.cat.core.dal.MonthlyReportDao; import com.dianping.cat.core.dal.MonthlyReportEntity; import com.dianping.cat.core.dal.WeeklyReport; import com.dianping.cat.core.dal.WeeklyReportDao; import com.dianping.cat.core.dal.WeeklyReportEntity; import com.dianping.cat.helper.TimeHelper; import com.dianping.cat.core.dal.DailyReportContent; import com.dianping.cat.core.dal.DailyReportContentDao; import com.dianping.cat.core.dal.MonthlyReportContent; import com.dianping.cat.core.dal.MonthlyReportContentDao; import com.dianping.cat.core.dal.WeeklyReportContent; import com.dianping.cat.core.dal.WeeklyReportContentDao; import com.dianping.cat.message.Event; public abstract class AbstractReportService<T> implements LogEnabled, ReportService<T> { @Inject protected HourlyReportDao m_hourlyReportDao; @Inject protected HourlyReportContentDao m_hourlyReportContentDao; @Inject protected DailyReportDao m_dailyReportDao; @Inject protected DailyReportContentDao m_dailyReportContentDao; @Inject protected WeeklyReportDao m_weeklyReportDao; @Inject protected WeeklyReportContentDao m_weeklyReportContentDao; @Inject protected MonthlyReportDao m_monthlyReportDao; @Inject protected MonthlyReportContentDao m_monthlyReportContentDao; @Override public boolean insertDailyReport(DailyReport report, byte[] content) { try { report.setCreationDate(new Date()); m_dailyReportDao.insert(report); int id = report.getId(); DailyReportContent proto = m_dailyReportContentDao.createLocal(); proto.setReportId(id); proto.setContent(content); m_dailyReportContentDao.insert(proto); return true; } catch (DalException e) { Cat.logError(e); return false; } } @Override public boolean insertHourlyReport(HourlyReport report, byte[] content) { try { report.setCreationDate(new Date()); m_hourlyReportDao.insert(report); int id = report.getId(); HourlyReportContent proto = m_hourlyReportContentDao.createLocal(); proto.setReportId(id); proto.setContent(content); m_hourlyReportContentDao.insert(proto); return true; } catch (DalException e) { Cat.logError(e); return false; } } @Override public boolean insertMonthlyReport(MonthlyReport report, byte[] content) { try { report.setCreationDate(new Date()); MonthlyReport monthReport = m_monthlyReportDao.findReportByDomainNamePeriod(report.getPeriod(), report.getDomain(), report.getName(), MonthlyReportEntity.READSET_FULL); if (monthReport != null) { MonthlyReportContent reportContent = m_monthlyReportContentDao.createLocal(); reportContent.setKeyReportId(monthReport.getId()); reportContent.setReportId(monthReport.getId()); m_monthlyReportDao.deleteReportByDomainNamePeriod(report); m_monthlyReportContentDao.deleteByPK(reportContent); } } catch (DalNotFoundException e) { } catch (Exception e) { Cat.logError(e); } try { m_monthlyReportDao.insert(report); int id = report.getId(); MonthlyReportContent proto = m_monthlyReportContentDao.createLocal(); proto.setReportId(id); proto.setContent(content); m_monthlyReportContentDao.insert(proto); return true; } catch (DalException e) { Cat.logError(e); return false; } } @Override public boolean insertWeeklyReport(WeeklyReport report, byte[] content) { try { report.setCreationDate(new Date()); WeeklyReport weeklyReport = m_weeklyReportDao.findReportByDomainNamePeriod(report.getPeriod(), report.getDomain(), report.getName(), WeeklyReportEntity.READSET_FULL); if (weeklyReport != null) { WeeklyReportContent reportContent = m_weeklyReportContentDao.createLocal(); reportContent.setKeyReportId(weeklyReport.getId()); reportContent.setReportId(weeklyReport.getId()); m_weeklyReportContentDao.deleteByPK(reportContent); m_weeklyReportDao.deleteReportByDomainNamePeriod(report); } } catch (DalNotFoundException e) { } catch (Exception e) { Cat.logError(e); } try { m_weeklyReportDao.insert(report); int id = report.getId(); WeeklyReportContent proto = m_weeklyReportContentDao.createLocal(); proto.setReportId(id); proto.setContent(content); m_weeklyReportContentDao.insert(proto); return true; } catch (DalException e) { Cat.logError(e); return false; } } private Map<String, Set<String>> m_domains = new LinkedHashMap<String, Set<String>>() { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Entry<String, Set<String>> eldest) { return size() > 1000; } }; protected Logger m_logger; public static final int s_hourly = 1; public static final int s_daily = 2; public static final int s_weekly = 3; public static final int s_monthly = 4; public static final int s_customer = 5; public int computeQueryType(Date start, Date end) { long duration = end.getTime() - start.getTime(); if (duration == TimeHelper.ONE_HOUR) { return s_hourly; } if (duration == TimeHelper.ONE_DAY) { return s_daily; } Calendar startCal = Calendar.getInstance(); startCal.setTime(start); if (duration == TimeHelper.ONE_WEEK && startCal.get(Calendar.DAY_OF_WEEK) == 7) { return s_weekly; } Calendar endCal = Calendar.getInstance(); endCal.setTime(end); if (startCal.get(Calendar.DAY_OF_MONTH) == 1 && endCal.get(Calendar.DAY_OF_MONTH) == 1) { return s_monthly; } return s_customer; } @Override public void enableLogging(Logger logger) { m_logger = logger; } public abstract T makeReport(String domain, Date start, Date end); public Set<String> queryAllDomainNames(Date start, Date end, String name) { Set<String> domains = new HashSet<String>(); long startTime = start.getTime(); long endTime = end.getTime(); for (; startTime < endTime; startTime = startTime + TimeHelper.ONE_HOUR) { domains.addAll(queryAllDomains(new Date(startTime), name)); } return domains; } private Set<String> queryAllDomains(Date date, String name) { String key = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date) + ":" + name; Set<String> domains = m_domains.get(key); if (domains == null) { domains = new HashSet<String>(); try { List<HourlyReport> reports = m_hourlyReportDao.findAllByPeriodName(date, name, HourlyReportEntity.READSET_DOMAIN_NAME); if (reports != null) { for (HourlyReport report : reports) { domains.add(report.getDomain()); } } Cat.logEvent("FindDomain", key, Event.SUCCESS, domains.toString()); m_domains.put(key, domains); } catch (DalException e) { Cat.logError(e); } } return domains; } @Override public abstract T queryDailyReport(String domain, Date start, Date end); @Override public abstract T queryHourlyReport(String domain, Date start, Date end); @Override public abstract T queryMonthlyReport(String domain, Date start); public T queryReport(String domain, Date start, Date end) { int type = computeQueryType(start, end); T report = null; if (type == s_hourly) { report = queryHourlyReport(domain, start, end); } else if (type == s_daily) { report = queryDailyReport(domain, start, end); } else if (type == s_weekly) { report = queryWeeklyReport(domain, start); } else if (type == s_monthly) { report = queryMonthlyReport(domain, start); } else { report = queryDailyReport(domain, start, end); } if (report == null) { report = makeReport(domain, start, end); } return report; } @Override public abstract T queryWeeklyReport(String domain, Date start); }
cat-core/src/main/java/com/dianping/cat/report/service/AbstractReportService.java
package com.dianping.cat.report.service; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; import org.unidal.dal.jdbc.DalException; import org.unidal.dal.jdbc.DalNotFoundException; import org.unidal.lookup.annotation.Inject; import com.dianping.cat.Cat; import com.dianping.cat.core.dal.DailyReport; import com.dianping.cat.core.dal.DailyReportDao; import com.dianping.cat.core.dal.HourlyReport; import com.dianping.cat.core.dal.HourlyReportContent; import com.dianping.cat.core.dal.HourlyReportContentDao; import com.dianping.cat.core.dal.HourlyReportDao; import com.dianping.cat.core.dal.HourlyReportEntity; import com.dianping.cat.core.dal.MonthlyReport; import com.dianping.cat.core.dal.MonthlyReportDao; import com.dianping.cat.core.dal.MonthlyReportEntity; import com.dianping.cat.core.dal.WeeklyReport; import com.dianping.cat.core.dal.WeeklyReportDao; import com.dianping.cat.core.dal.WeeklyReportEntity; import com.dianping.cat.helper.TimeHelper; import com.dianping.cat.core.dal.DailyReportContent; import com.dianping.cat.core.dal.DailyReportContentDao; import com.dianping.cat.core.dal.MonthlyReportContent; import com.dianping.cat.core.dal.MonthlyReportContentDao; import com.dianping.cat.core.dal.WeeklyReportContent; import com.dianping.cat.core.dal.WeeklyReportContentDao; import com.dianping.cat.message.Event; public abstract class AbstractReportService<T> implements LogEnabled, ReportService<T> { @Inject protected HourlyReportDao m_hourlyReportDao; @Inject protected HourlyReportContentDao m_hourlyReportContentDao; @Inject protected DailyReportDao m_dailyReportDao; @Inject protected DailyReportContentDao m_dailyReportContentDao; @Inject protected WeeklyReportDao m_weeklyReportDao; @Inject protected WeeklyReportContentDao m_weeklyReportContentDao; @Inject protected MonthlyReportDao m_monthlyReportDao; @Inject protected MonthlyReportContentDao m_monthlyReportContentDao; @Override public boolean insertDailyReport(DailyReport report, byte[] content) { try { m_dailyReportDao.insert(report); int id = report.getId(); DailyReportContent proto = m_dailyReportContentDao.createLocal(); proto.setReportId(id); proto.setContent(content); m_dailyReportContentDao.insert(proto); return true; } catch (DalException e) { Cat.logError(e); return false; } } @Override public boolean insertHourlyReport(HourlyReport report, byte[] content) { try { m_hourlyReportDao.insert(report); int id = report.getId(); HourlyReportContent proto = m_hourlyReportContentDao.createLocal(); proto.setReportId(id); proto.setContent(content); m_hourlyReportContentDao.insert(proto); return true; } catch (DalException e) { Cat.logError(e); return false; } } @Override public boolean insertMonthlyReport(MonthlyReport report, byte[] content) { try { MonthlyReport monthReport = m_monthlyReportDao.findReportByDomainNamePeriod(report.getPeriod(), report.getDomain(), report.getName(), MonthlyReportEntity.READSET_FULL); if (monthReport != null) { MonthlyReportContent reportContent = m_monthlyReportContentDao.createLocal(); reportContent.setKeyReportId(monthReport.getId()); reportContent.setReportId(monthReport.getId()); m_monthlyReportDao.deleteReportByDomainNamePeriod(report); m_monthlyReportContentDao.deleteByPK(reportContent); } } catch (DalNotFoundException e) { } catch (Exception e) { Cat.logError(e); } try { m_monthlyReportDao.insert(report); int id = report.getId(); MonthlyReportContent proto = m_monthlyReportContentDao.createLocal(); proto.setReportId(id); proto.setContent(content); m_monthlyReportContentDao.insert(proto); return true; } catch (DalException e) { Cat.logError(e); return false; } } @Override public boolean insertWeeklyReport(WeeklyReport report, byte[] content) { try { WeeklyReport weeklyReport = m_weeklyReportDao.findReportByDomainNamePeriod(report.getPeriod(), report.getDomain(), report.getName(), WeeklyReportEntity.READSET_FULL); if (weeklyReport != null) { WeeklyReportContent reportContent = m_weeklyReportContentDao.createLocal(); reportContent.setKeyReportId(weeklyReport.getId()); reportContent.setReportId(weeklyReport.getId()); m_weeklyReportContentDao.deleteByPK(reportContent); m_weeklyReportDao.deleteReportByDomainNamePeriod(report); } } catch (DalNotFoundException e) { } catch (Exception e) { Cat.logError(e); } try { m_weeklyReportDao.insert(report); int id = report.getId(); WeeklyReportContent proto = m_weeklyReportContentDao.createLocal(); proto.setReportId(id); proto.setContent(content); m_weeklyReportContentDao.insert(proto); return true; } catch (DalException e) { Cat.logError(e); return false; } } private Map<String, Set<String>> m_domains = new LinkedHashMap<String, Set<String>>() { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Entry<String, Set<String>> eldest) { return size() > 1000; } }; protected Logger m_logger; public static final int s_hourly = 1; public static final int s_daily = 2; public static final int s_weekly = 3; public static final int s_monthly = 4; public static final int s_customer = 5; public int computeQueryType(Date start, Date end) { long duration = end.getTime() - start.getTime(); if (duration == TimeHelper.ONE_HOUR) { return s_hourly; } if (duration == TimeHelper.ONE_DAY) { return s_daily; } Calendar startCal = Calendar.getInstance(); startCal.setTime(start); if (duration == TimeHelper.ONE_WEEK && startCal.get(Calendar.DAY_OF_WEEK) == 7) { return s_weekly; } Calendar endCal = Calendar.getInstance(); endCal.setTime(end); if (startCal.get(Calendar.DAY_OF_MONTH) == 1 && endCal.get(Calendar.DAY_OF_MONTH) == 1) { return s_monthly; } return s_customer; } @Override public void enableLogging(Logger logger) { m_logger = logger; } public abstract T makeReport(String domain, Date start, Date end); public Set<String> queryAllDomainNames(Date start, Date end, String name) { Set<String> domains = new HashSet<String>(); long startTime = start.getTime(); long endTime = end.getTime(); for (; startTime < endTime; startTime = startTime + TimeHelper.ONE_HOUR) { domains.addAll(queryAllDomains(new Date(startTime), name)); } return domains; } private Set<String> queryAllDomains(Date date, String name) { String key = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date) + ":" + name; Set<String> domains = m_domains.get(key); if (domains == null) { domains = new HashSet<String>(); try { List<HourlyReport> reports = m_hourlyReportDao.findAllByPeriodName(date, name, HourlyReportEntity.READSET_DOMAIN_NAME); if (reports != null) { for (HourlyReport report : reports) { domains.add(report.getDomain()); } } Cat.logEvent("FindDomain", key, Event.SUCCESS, domains.toString()); m_domains.put(key, domains); } catch (DalException e) { Cat.logError(e); } } return domains; } @Override public abstract T queryDailyReport(String domain, Date start, Date end); @Override public abstract T queryHourlyReport(String domain, Date start, Date end); @Override public abstract T queryMonthlyReport(String domain, Date start); public T queryReport(String domain, Date start, Date end) { int type = computeQueryType(start, end); T report = null; if (type == s_hourly) { report = queryHourlyReport(domain, start, end); } else if (type == s_daily) { report = queryDailyReport(domain, start, end); } else if (type == s_weekly) { report = queryWeeklyReport(domain, start); } else if (type == s_monthly) { report = queryMonthlyReport(domain, start); } else { report = queryDailyReport(domain, start, end); } if (report == null) { report = makeReport(domain, start, end); } return report; } @Override public abstract T queryWeeklyReport(String domain, Date start); }
modify the reportservice
cat-core/src/main/java/com/dianping/cat/report/service/AbstractReportService.java
modify the reportservice
<ide><path>at-core/src/main/java/com/dianping/cat/report/service/AbstractReportService.java <ide> @Override <ide> public boolean insertDailyReport(DailyReport report, byte[] content) { <ide> try { <add> report.setCreationDate(new Date()); <ide> m_dailyReportDao.insert(report); <ide> <ide> int id = report.getId(); <ide> @Override <ide> public boolean insertHourlyReport(HourlyReport report, byte[] content) { <ide> try { <add> report.setCreationDate(new Date()); <ide> m_hourlyReportDao.insert(report); <ide> <ide> int id = report.getId(); <ide> @Override <ide> public boolean insertMonthlyReport(MonthlyReport report, byte[] content) { <ide> try { <add> report.setCreationDate(new Date()); <add> <ide> MonthlyReport monthReport = m_monthlyReportDao.findReportByDomainNamePeriod(report.getPeriod(), <ide> report.getDomain(), report.getName(), MonthlyReportEntity.READSET_FULL); <ide> <ide> @Override <ide> public boolean insertWeeklyReport(WeeklyReport report, byte[] content) { <ide> try { <add> report.setCreationDate(new Date()); <add> <ide> WeeklyReport weeklyReport = m_weeklyReportDao.findReportByDomainNamePeriod(report.getPeriod(), <ide> report.getDomain(), report.getName(), WeeklyReportEntity.READSET_FULL); <ide>
Java
mpl-2.0
e2bca4ea8e7aa7e1bdfaef7197e015194edb5fd4
0
phase/sbhs,phase/sbhs,phase/sbhs
package xyz.jadonfowler.sbse; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.RandomAccessFile; import java.util.HashMap; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; /** * @author https://github.com/phase */ public class SBHS { public static String gameLocation = "res/sonic.gba"; public static RandomAccessFile raf; public static final int SpritesStart = 0x47B800 + (64 * (12 / 2)); public static final int SpritesEnd = 0xA8C600; public static JFrame frame; public static HashMap<String, String[]> PALETTES = new HashMap<String, String[]>() { { String[] g = { "Background (useless)", "Eye color and shoe/glove reflection", "Above the eye, shoe/glove color", "Outside of shoe/glove", "Outline of shoe/glove", "In-ball shine", "Primary fur color", "Secondary fur color", "Third fur color/outline", "Primary skin color", "Secondary skin color", "Third skin color", "Primary shoe color", "Secondary shoe color", "Third shoe color", "Eye Color" }; put("Sonic", g); put("Knuckles", g); } }; public static void main(String[] args) throws Exception { frame = new JFrame("Sonic Battle Hack Suite"); frame.setSize(700, 600); // frame.setResizable(false); gameLocation = getFile(); raf = new RandomAccessFile(gameLocation, "rw"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTabbedPane tp = new JTabbedPane(); addTab(tp, "Sonic", 0x47AFB8); addTab(tp, "Tails", 0x5283F8); addTab(tp, "Knuckles", 0x4CADD8); addTab(tp, "Amy", 0x636458); addTab(tp, "Shadow", 0x58D818); addTab(tp, "Rouge", 0x5F3E38); addTab(tp, "E-102", 0x681A78); addTab(tp, "Chaos", 0x7336B8); addTab(tp, "Emerl", 0x787CFA); addTab(tp, "Fake Emerl", 0x47AB78); addTab(tp, "Eggman", 0x7822D8); frame.getContentPane().add(tp); frame.setVisible(true); // frame.pack(); } public static void addTab(JTabbedPane pane, String name, int offset) throws Exception { pane.addTab(name, null, createPalettePanel(name, offset), "Edit " + name + " Palette"); } public static JPanel createPalettePanel(String name, int hex) throws Exception { String[] colors = new String[16]; int color = 0; String f = ""; for (int i = hex; i <= hex + 32; i++) { raf.seek(i); int value = raf.read(); // System.out.print(Integer.toHexString(value)); if (f.length() == 4) { f = f.split("(?<=\\G.{2})")[1] + f.split("(?<=\\G.{2})")[0]; colors[color++] = f; f = (value < 16 ? "0" : "") + Integer.toHexString(value); } else { f += (value < 16 ? "0" : "") + Integer.toHexString(value); } } // System.out.println(Arrays.toString(colors)); int i = 0; JPanel jp = new JPanel(); jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS)); for (String s : colors) { i++; JButton jb = new JButton(name + " color " + i + ": " + (PALETTES.get(name) == null ? "Something?" : PALETTES.get(name).length < i ? "Something?" : PALETTES.get(name)[i - 1])); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name = jb.getText(); int i = -1 + (Integer.parseInt(name.split(" ")[2].replace(":", ""))); colors[i] = GBAColor.toGBA(getColorInput(GBAColor.fromGBA(colors[i]))); try { int h1 = Integer.parseInt(colors[i].split("(?<=\\G.{2})")[0], 16); int h2 = Integer.parseInt(colors[i].split("(?<=\\G.{2})")[1], 16); // colors[i] = Integer.toHexString(h2) + // Integer.toHexString(h1) + ""; raf.seek(hex + (i * 2)); raf.write(h2); raf.seek(hex + (i * 2) + 1); raf.write(h1); } catch (IOException e1) { e1.printStackTrace(); } // System.out.println(Arrays.toString(colors)); } }); jp.add(jb); } return jp; } public static String getFile() { JFileChooser fc = new JFileChooser(); return (fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) ? fc.getSelectedFile().toString() : ""; } public static Color getColorInput(Color previousColor) { Color c = JColorChooser.showDialog(frame, "Pick Color", previousColor); return c == null ? previousColor : c; } public static void spriteTest() throws Exception { RandomAccessFile raf = new RandomAccessFile(gameLocation, "r"); // for (int i = SpritesStart, j = 0; i <= SpritesEnd; i++) { String f = ""; for (int i = SpritesStart, j = 1, k = 0, size = 4, rows = 8; i < SpritesStart + (size * rows * 2); i++) { if (j == 1) System.out.print(hex(i) + ": "); raf.seek(i); int value = raf.read(); f += (char) (value <= 20 ? '.' : value); System.out.print(spaceout(reverse(hex(value)))); if (j < size) j++; else { j = 1; System.out.println(f); f = ""; } if (k < (size * rows) - 1) k++; else { k = 0; System.out.println("========"); } } raf.close(); } public static String hex(int i) { return (i < 10 ? "0" : "") + Integer.toHexString(i); } public static String reverse(String s) { return new StringBuilder().append(s).reverse().toString(); } public static String spaceout(String s) { String f = ""; for (char c : s.toCharArray()) f += c + " "; return f; } }
src/xyz/jadonfowler/sbse/SBHS.java
package xyz.jadonfowler.sbse; import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JFrame; import javax.swing.JPanel; /** * @author https://github.com/phase */ public class SBHS { public static final int SpritesStart = 0x47B800 + (64 * (12 / 2)); public static final int SpritesEnd = 0xA8C600; public static JFrame frame; public static final String gameLocation = "res/sonic.gba"; public static void main(String[] args) throws Exception { frame = new JFrame("Sonic Battle Hack Suite"); frame.setSize(700, 600); frame.setResizable(false); frame.setVisible(true); final Container contentPane = frame.getContentPane(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RandomAccessFile raf = new RandomAccessFile(gameLocation, "rw"); String[] colors = new String[16]; int color = 0; String f = ""; for (int i = 0x47AFB8; i <= 0x47AFB8 + 32; i++) { raf.seek(i); int value = raf.read(); // System.out.print(Integer.toHexString(value)); if (f.length() == 4) { colors[color++] = f; f = (value < 16 ? "0" : "") + Integer.toHexString(value); } else { f += (value < 16 ? "0" : "") + Integer.toHexString(value); } } System.out.println(Arrays.toString(colors)); int i = 0; JPanel jp = new JPanel(); jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS)); for (String s : colors) { i++; JButton jb = new JButton("Edit color " + i + " of Sonic"); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name = jb.getText(); int i = -1 + (Integer.parseInt(name.split(" ")[2])); colors[i] = GBAColor.toGBA(getColorInput(GBAColor.fromGBA(colors[i]))); try { int h1 = Integer.parseInt(colors[i].split("(?<=\\G.{2})")[0], 16); int h2 = Integer.parseInt(colors[i].split("(?<=\\G.{2})")[1], 16); //colors[i] = Integer.toHexString(h2) + Integer.toHexString(h1) + ""; raf.seek(0x47AFB8 + (i * 2)); raf.write(h2); raf.seek(0x47AFB8 + (i * 2) + 1); raf.write(h1); } catch (IOException e1) { e1.printStackTrace(); } System.out.println(Arrays.toString(colors)); } }); jp.add(jb); } contentPane.add(jp); frame.pack(); } public static Color getColorInput(Color previousColor) { Color c = JColorChooser.showDialog(frame, "Pick Color", previousColor); return c == null ? previousColor : c; } public static void spriteTest() throws Exception { RandomAccessFile raf = new RandomAccessFile(gameLocation, "r"); // for (int i = SpritesStart, j = 0; i <= SpritesEnd; i++) { String f = ""; for (int i = SpritesStart, j = 1, k = 0, size = 4, rows = 8; i < SpritesStart + (size * rows * 2); i++) { if (j == 1) System.out.print(hex(i) + ": "); raf.seek(i); int value = raf.read(); f += (char) (value <= 20 ? '.' : value); System.out.print(spaceout(reverse(hex(value)))); if (j < size) j++; else { j = 1; System.out.println(f); f = ""; } if (k < (size * rows) - 1) k++; else { k = 0; System.out.println("========"); } } raf.close(); } public static String hex(int i) { return (i < 10 ? "0" : "") + Integer.toHexString(i); } public static String reverse(String s) { return new StringBuilder().append(s).reverse().toString(); } public static String spaceout(String s) { String f = ""; for (char c : s.toCharArray()) f += c + " "; return f; } }
Finish Palette Editor
src/xyz/jadonfowler/sbse/SBHS.java
Finish Palette Editor
<ide><path>rc/xyz/jadonfowler/sbse/SBHS.java <ide> package xyz.jadonfowler.sbse; <ide> <ide> import java.awt.Color; <del>import java.awt.Container; <ide> import java.awt.event.ActionEvent; <ide> import java.awt.event.ActionListener; <ide> import java.io.IOException; <ide> import java.io.RandomAccessFile; <del>import java.util.Arrays; <add>import java.util.HashMap; <ide> import javax.swing.BoxLayout; <ide> import javax.swing.JButton; <ide> import javax.swing.JColorChooser; <add>import javax.swing.JFileChooser; <ide> import javax.swing.JFrame; <ide> import javax.swing.JPanel; <add>import javax.swing.JTabbedPane; <ide> <ide> /** <ide> * @author https://github.com/phase <ide> */ <ide> public class SBHS { <add> public static String gameLocation = "res/sonic.gba"; <add> public static RandomAccessFile raf; <ide> public static final int SpritesStart = 0x47B800 + (64 * (12 / 2)); <ide> public static final int SpritesEnd = 0xA8C600; <ide> public static JFrame frame; <del> public static final String gameLocation = "res/sonic.gba"; <add> public static HashMap<String, String[]> PALETTES = new HashMap<String, String[]>() { <add> { <add> String[] g = { "Background (useless)", "Eye color and shoe/glove reflection", <add> "Above the eye, shoe/glove color", "Outside of shoe/glove", "Outline of shoe/glove", <add> "In-ball shine", "Primary fur color", "Secondary fur color", "Third fur color/outline", <add> "Primary skin color", "Secondary skin color", "Third skin color", "Primary shoe color", <add> "Secondary shoe color", "Third shoe color", "Eye Color" }; <add> put("Sonic", g); <add> put("Knuckles", g); <add> } <add> }; <ide> <ide> public static void main(String[] args) throws Exception { <ide> frame = new JFrame("Sonic Battle Hack Suite"); <ide> frame.setSize(700, 600); <del> frame.setResizable(false); <add> // frame.setResizable(false); <add> gameLocation = getFile(); <add> raf = new RandomAccessFile(gameLocation, "rw"); <add> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); <add> JTabbedPane tp = new JTabbedPane(); <add> addTab(tp, "Sonic", 0x47AFB8); <add> addTab(tp, "Tails", 0x5283F8); <add> addTab(tp, "Knuckles", 0x4CADD8); <add> addTab(tp, "Amy", 0x636458); <add> addTab(tp, "Shadow", 0x58D818); <add> addTab(tp, "Rouge", 0x5F3E38); <add> addTab(tp, "E-102", 0x681A78); <add> addTab(tp, "Chaos", 0x7336B8); <add> addTab(tp, "Emerl", 0x787CFA); <add> addTab(tp, "Fake Emerl", 0x47AB78); <add> addTab(tp, "Eggman", 0x7822D8); <add> frame.getContentPane().add(tp); <ide> frame.setVisible(true); <del> final Container contentPane = frame.getContentPane(); <del> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); <del> RandomAccessFile raf = new RandomAccessFile(gameLocation, "rw"); <add> // frame.pack(); <add> } <add> <add> public static void addTab(JTabbedPane pane, String name, int offset) throws Exception { <add> pane.addTab(name, null, createPalettePanel(name, offset), "Edit " + name + " Palette"); <add> } <add> <add> public static JPanel createPalettePanel(String name, int hex) throws Exception { <ide> String[] colors = new String[16]; <ide> int color = 0; <ide> String f = ""; <del> for (int i = 0x47AFB8; i <= 0x47AFB8 + 32; i++) { <add> for (int i = hex; i <= hex + 32; i++) { <ide> raf.seek(i); <ide> int value = raf.read(); <ide> // System.out.print(Integer.toHexString(value)); <ide> if (f.length() == 4) { <add> f = f.split("(?<=\\G.{2})")[1] + f.split("(?<=\\G.{2})")[0]; <ide> colors[color++] = f; <ide> f = (value < 16 ? "0" : "") + Integer.toHexString(value); <ide> } <ide> f += (value < 16 ? "0" : "") + Integer.toHexString(value); <ide> } <ide> } <del> System.out.println(Arrays.toString(colors)); <add> // System.out.println(Arrays.toString(colors)); <ide> int i = 0; <ide> JPanel jp = new JPanel(); <ide> jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS)); <ide> for (String s : colors) { <ide> i++; <del> JButton jb = new JButton("Edit color " + i + " of Sonic"); <add> JButton jb = new JButton(name <add> + " color " <add> + i <add> + ": " <add> + (PALETTES.get(name) == null ? "Something?" : PALETTES.get(name).length < i ? "Something?" <add> : PALETTES.get(name)[i - 1])); <ide> jb.addActionListener(new ActionListener() { <ide> public void actionPerformed(ActionEvent e) { <ide> String name = jb.getText(); <del> int i = -1 + (Integer.parseInt(name.split(" ")[2])); <add> int i = -1 + (Integer.parseInt(name.split(" ")[2].replace(":", ""))); <ide> colors[i] = GBAColor.toGBA(getColorInput(GBAColor.fromGBA(colors[i]))); <ide> try { <ide> int h1 = Integer.parseInt(colors[i].split("(?<=\\G.{2})")[0], 16); <ide> int h2 = Integer.parseInt(colors[i].split("(?<=\\G.{2})")[1], 16); <del> //colors[i] = Integer.toHexString(h2) + Integer.toHexString(h1) + ""; <del> raf.seek(0x47AFB8 + (i * 2)); <add> // colors[i] = Integer.toHexString(h2) + <add> // Integer.toHexString(h1) + ""; <add> raf.seek(hex + (i * 2)); <ide> raf.write(h2); <del> raf.seek(0x47AFB8 + (i * 2) + 1); <add> raf.seek(hex + (i * 2) + 1); <ide> raf.write(h1); <ide> } <ide> catch (IOException e1) { <ide> e1.printStackTrace(); <ide> } <del> System.out.println(Arrays.toString(colors)); <add> // System.out.println(Arrays.toString(colors)); <ide> } <ide> }); <ide> jp.add(jb); <ide> } <del> contentPane.add(jp); <del> frame.pack(); <add> return jp; <add> } <add> <add> public static String getFile() { <add> JFileChooser fc = new JFileChooser(); <add> return (fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) ? fc.getSelectedFile().toString() : ""; <ide> } <ide> <ide> public static Color getColorInput(Color previousColor) {
Java
bsd-3-clause
5a572bba1e12099a9b89a1c4b9107650112342bb
0
tomcz/spring-stringtemplate
package com.watchitlater.spring; import org.antlr.stringtemplate.StringTemplateErrorListener; import org.apache.commons.lang.StringUtils; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.Ordered; import org.springframework.core.io.ResourceLoader; import org.springframework.web.context.ServletContextAware; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.view.UrlBasedViewResolver; import javax.servlet.ServletContext; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class StringTemplateViewResolver implements ViewResolver, ResourceLoaderAware, ServletContextAware, Ordered { // WebStringTemplateGroup protected Map<String, WebStringTemplateGroup> groupCache = new ConcurrentHashMap<String, WebStringTemplateGroup>(); protected boolean useGroupCache = false; protected StringTemplateErrorListener templateErrorListener; protected Integer refreshIntervalInSeconds; protected String sourceFileCharEncoding; protected ResourceLoader resourceLoader; protected String templateRoot = ""; protected String sharedRoot; // WebStringTemplate protected List<Renderer> renderers = Collections.emptyList(); protected WebFormat defaultFormat = WebFormat.html; // StringTemplateView protected ServletContext servletContext; protected String contentType = "text/html;charset=UTF-8"; protected boolean exposeRequestContext = true; protected boolean autoIndent = true; // Ordered protected int order = 1; public void setUseGroupCache(boolean useGroupCache) { this.useGroupCache = useGroupCache; } public void setTemplateErrorListener(StringTemplateErrorListener templateErrorListener) { this.templateErrorListener = templateErrorListener; } public void setRefreshIntervalInSeconds(Integer refreshIntervalInSeconds) { this.refreshIntervalInSeconds = refreshIntervalInSeconds; } public void setSourceFileCharEncoding(String sourceFileCharEncoding) { this.sourceFileCharEncoding = sourceFileCharEncoding; } public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public void setTemplateRoot(String templateRoot) { this.templateRoot = templateRoot; } public void setSharedRoot(String sharedRoot) { this.sharedRoot = sharedRoot; } public void setRenderers(List<Renderer> renderers) { this.renderers = renderers; } public void setDefaultFormat(String defaultFormat) { this.defaultFormat = WebFormat.fromName(defaultFormat); } public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } public void setContentType(String contentType) { this.contentType = contentType; } public void setExposeRequestContext(boolean exposeRequestContext) { this.exposeRequestContext = exposeRequestContext; } public void setAutoIndent(boolean autoIndent) { this.autoIndent = autoIndent; } public void setOrder(int order) { this.order = order; } public int getOrder() { return order; } public StringTemplateView resolveViewName(String viewName, Locale locale) { if (shouldNotResolve(viewName)) { return null; } try { WebStringTemplate tempate = createTemplate(viewName); StringTemplateView view = createView(); initView(view, tempate); return view; } catch (IllegalArgumentException e) { return null; } } protected boolean shouldNotResolve(String viewName) { return StringUtils.isBlank(viewName) || viewName.startsWith(UrlBasedViewResolver.FORWARD_URL_PREFIX) || viewName.startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX); } protected StringTemplateView createView() { return new StringTemplateView(); } protected void initView(StringTemplateView view, WebStringTemplate tempate) { view.setExposeRequestContext(exposeRequestContext); view.setServletContext(servletContext); view.setContentType(contentType); view.setAutoIndent(autoIndent); view.setTemplate(tempate); } protected WebStringTemplate createTemplate(String viewName) { WebStringTemplate template = createGroup(viewName).createTemplate(viewName); template.setDefaultFormat(defaultFormat); registerAttributeRenderers(template); return template; } protected void registerAttributeRenderers(WebStringTemplate template) { for (Renderer renderer : renderers) { template.register(renderer); } } protected WebStringTemplateGroup createGroup(String viewName) { return useGroupCache ? getCachedGroup(viewName) : createGroup(); } protected WebStringTemplateGroup getCachedGroup(String viewName) { WebStringTemplateGroup group = groupCache.get(viewName); if (group == null) { group = createGroup(); groupCache.put(viewName, group); } return group; } protected WebStringTemplateGroup createGroup() { WebStringTemplateGroup group = new WebStringTemplateGroup("main", templateRoot, resourceLoader); if (sharedRoot != null) { WebStringTemplateGroup shared = new WebStringTemplateGroup("shared", sharedRoot, resourceLoader); group.setSuperGroup(shared); initGroup(shared); } initGroup(group); return group; } protected void initGroup(WebStringTemplateGroup group) { if (refreshIntervalInSeconds != null) { group.setRefreshInterval(refreshIntervalInSeconds); } if (sourceFileCharEncoding != null) { group.setFileCharEncoding(sourceFileCharEncoding); } if (templateErrorListener != null) { group.setErrorListener(templateErrorListener); } } }
src/main/java/com/watchitlater/spring/StringTemplateViewResolver.java
package com.watchitlater.spring; import org.antlr.stringtemplate.StringTemplateErrorListener; import org.apache.commons.lang.StringUtils; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.Ordered; import org.springframework.core.io.ResourceLoader; import org.springframework.web.context.ServletContextAware; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.view.UrlBasedViewResolver; import javax.servlet.ServletContext; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class StringTemplateViewResolver implements ViewResolver, ResourceLoaderAware, ServletContextAware, Ordered { // WebStringTemplateGroup protected Map<String, WebStringTemplateGroup> groupCache = new ConcurrentHashMap<String, WebStringTemplateGroup>(); protected boolean useGroupCache = false; protected StringTemplateErrorListener templateErrorListener; protected Integer refreshIntervalInSeconds; protected String sourceFileCharEncoding; protected ResourceLoader resourceLoader; protected String templateRoot = ""; protected String sharedRoot; // WebStringTemplate protected List<Renderer> renderers = Collections.emptyList(); protected WebFormat defaultFormat = WebFormat.html; // StringTemplateView protected ServletContext servletContext; protected String contentType = "text/html;charset=UTF-8"; protected boolean exposeRequestContext = true; protected boolean autoIndent = true; // Ordered protected int order = 1; public void setUseGroupCache(boolean useGroupCache) { this.useGroupCache = useGroupCache; } public void setTemplateErrorListener(StringTemplateErrorListener templateErrorListener) { this.templateErrorListener = templateErrorListener; } public void setRefreshIntervalInSeconds(Integer refreshIntervalInSeconds) { this.refreshIntervalInSeconds = refreshIntervalInSeconds; } public void setSourceFileCharEncoding(String sourceFileCharEncoding) { this.sourceFileCharEncoding = sourceFileCharEncoding; } public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public void setTemplateRoot(String templateRoot) { this.templateRoot = templateRoot; } public void setSharedRoot(String sharedRoot) { this.sharedRoot = sharedRoot; } public void setRenderers(List<Renderer> renderers) { this.renderers = renderers; } public void setDefaultFormat(String defaultFormat) { this.defaultFormat = WebFormat.fromName(defaultFormat); } public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } public void setContentType(String contentType) { this.contentType = contentType; } public void setExposeRequestContext(boolean exposeRequestContext) { this.exposeRequestContext = exposeRequestContext; } public void setAutoIndent(boolean autoIndent) { this.autoIndent = autoIndent; } public void setOrder(int order) { this.order = order; } public int getOrder() { return order; } public StringTemplateView resolveViewName(String viewName, Locale locale) { if (shouldNotResolve(viewName)) { return null; } try { WebStringTemplate tempate = createTemplate(viewName); StringTemplateView view = createView(); initView(view, tempate); return view; } catch (IllegalArgumentException e) { return null; } } protected boolean shouldNotResolve(String viewName) { return StringUtils.isBlank(viewName) || StringUtils.startsWith(viewName, UrlBasedViewResolver.FORWARD_URL_PREFIX) || StringUtils.startsWith(viewName, UrlBasedViewResolver.REDIRECT_URL_PREFIX); } protected StringTemplateView createView() { return new StringTemplateView(); } protected void initView(StringTemplateView view, WebStringTemplate tempate) { view.setExposeRequestContext(exposeRequestContext); view.setServletContext(servletContext); view.setContentType(contentType); view.setAutoIndent(autoIndent); view.setTemplate(tempate); } protected WebStringTemplate createTemplate(String viewName) { WebStringTemplate template = createGroup(viewName).createTemplate(viewName); template.setDefaultFormat(defaultFormat); registerAttributeRenderers(template); return template; } protected void registerAttributeRenderers(WebStringTemplate template) { for (Renderer renderer : renderers) { template.register(renderer); } } protected WebStringTemplateGroup createGroup(String viewName) { return useGroupCache ? getCachedGroup(viewName) : createGroup(); } protected WebStringTemplateGroup getCachedGroup(String viewName) { WebStringTemplateGroup group = groupCache.get(viewName); if (group == null) { group = createGroup(); groupCache.put(viewName, group); } return group; } protected WebStringTemplateGroup createGroup() { WebStringTemplateGroup group = new WebStringTemplateGroup("main", templateRoot, resourceLoader); if (sharedRoot != null) { WebStringTemplateGroup shared = new WebStringTemplateGroup("shared", sharedRoot, resourceLoader); group.setSuperGroup(shared); initGroup(shared); } initGroup(group); return group; } protected void initGroup(WebStringTemplateGroup group) { if (refreshIntervalInSeconds != null) { group.setRefreshInterval(refreshIntervalInSeconds); } if (sourceFileCharEncoding != null) { group.setFileCharEncoding(sourceFileCharEncoding); } if (templateErrorListener != null) { group.setErrorListener(templateErrorListener); } } }
Don't try to resolve "forward:" or "redirect:" prefixes. Use an InternalResourceViewResolver for that.
src/main/java/com/watchitlater/spring/StringTemplateViewResolver.java
Don't try to resolve "forward:" or "redirect:" prefixes. Use an InternalResourceViewResolver for that.
<ide><path>rc/main/java/com/watchitlater/spring/StringTemplateViewResolver.java <ide> <ide> protected boolean shouldNotResolve(String viewName) { <ide> return StringUtils.isBlank(viewName) <del> || StringUtils.startsWith(viewName, UrlBasedViewResolver.FORWARD_URL_PREFIX) <del> || StringUtils.startsWith(viewName, UrlBasedViewResolver.REDIRECT_URL_PREFIX); <add> || viewName.startsWith(UrlBasedViewResolver.FORWARD_URL_PREFIX) <add> || viewName.startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX); <ide> } <ide> <ide> protected StringTemplateView createView() {
Java
mit
174b23d6752fddc6bae9c4e7de96f5703546d6c5
0
opengl-8080/Samples,opengl-8080/Samples,opengl-8080/Samples,opengl-8080/Samples,opengl-8080/Samples
package sample.javafx.property; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener.Change; import javafx.collections.ObservableList; public class Main { public static void main(String[] args) { ObservableList<String> list = FXCollections.observableArrayList("one", "two", "three"); list.addListener((Change<? extends String> change) -> { System.out.println("=========================================="); while (change.next()) { System.out.println("list=" + change.getList()); if (change.wasAdded()) { System.out.println("追加 : " + change); } if (change.wasRemoved()) { System.out.println("削除 : " + change); } if (change.wasPermutated()) { System.out.println("順序変更 : " + change); } if (change.wasReplaced()) { System.out.println("置換 : " + change); } } }); list.add("FOO"); list.remove("one"); FXCollections.sort(list); list.set(1, "hoge"); } }
java/javafx/src/main/java/sample/javafx/property/Main.java
package sample.javafx.property; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ReadOnlyDoubleProperty; import javafx.beans.property.SimpleDoubleProperty; public class Main { public static void main(String[] args) { MyClass myClass = new MyClass(); DoubleProperty readOnlyDoubleProperty = (DoubleProperty)myClass.valueProperty(); readOnlyDoubleProperty.set(20.0); System.out.println(myClass.getValue()); } }
JavaFX Collection
java/javafx/src/main/java/sample/javafx/property/Main.java
JavaFX Collection
<ide><path>ava/javafx/src/main/java/sample/javafx/property/Main.java <ide> package sample.javafx.property; <ide> <del>import javafx.beans.property.DoubleProperty; <del>import javafx.beans.property.ReadOnlyDoubleProperty; <del>import javafx.beans.property.SimpleDoubleProperty; <add>import javafx.collections.FXCollections; <add>import javafx.collections.ListChangeListener.Change; <add>import javafx.collections.ObservableList; <ide> <ide> public class Main { <ide> public static void main(String[] args) { <del> MyClass myClass = new MyClass(); <del> DoubleProperty readOnlyDoubleProperty = (DoubleProperty)myClass.valueProperty(); <del> readOnlyDoubleProperty.set(20.0); <add> ObservableList<String> list = FXCollections.observableArrayList("one", "two", "three"); <add> <add> list.addListener((Change<? extends String> change) -> { <add> System.out.println("=========================================="); <add> while (change.next()) { <add> System.out.println("list=" + change.getList()); <add> if (change.wasAdded()) { <add> System.out.println("追加 : " + change); <add> } <add> if (change.wasRemoved()) { <add> System.out.println("削除 : " + change); <add> } <add> if (change.wasPermutated()) { <add> System.out.println("順序変更 : " + change); <add> } <add> if (change.wasReplaced()) { <add> System.out.println("置換 : " + change); <add> } <add> } <add> }); <ide> <del> System.out.println(myClass.getValue()); <add> list.add("FOO"); <add> list.remove("one"); <add> FXCollections.sort(list); <add> list.set(1, "hoge"); <ide> } <ide> }
Java
mit
ebbed4aa40d49a4a96d240fb6ff99adff977301a
0
AlmasB/FXGL,AlmasB/FXGL,AlmasB/FXGL,AlmasB/FXGL
/* * The MIT License (MIT) * * FXGL - JavaFX Game Library * * Copyright (c) 2015-2016 AlmasB ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.almasb.fxgl.entity.component; import com.almasb.easyio.serialization.Bundle; import com.almasb.ents.CopyableComponent; import com.almasb.ents.component.ObjectComponent; import com.almasb.ents.serialization.SerializableComponent; import org.jetbrains.annotations.NotNull; import java.io.Serializable; /** * Represents an entity type. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ public class TypeComponent extends ObjectComponent<Serializable> implements SerializableComponent, CopyableComponent<TypeComponent> { /** * Constructs a component with no type. */ public TypeComponent() { this(new SObject()); } /** * Constructs a component with given type. * Note: although the type could be any object, it is recommended * that an enum is used to represent types. * * @param type entity type */ public TypeComponent(Serializable type) { super(type); } /** * <pre> * Example: * entity.getTypeComponent().isType(Type.PLAYER); * </pre> * * @param type entity type * @return true iff this type component is of given type */ public boolean isType(Object type) { return getValue().equals(type); } @Override public String toString() { return "Type(" + getValue() + ")"; } @Override public void write(@NotNull Bundle bundle) { bundle.put("value", getValue()); } @Override public void read(@NotNull Bundle bundle) { setValue(bundle.get("value")); } @Override public TypeComponent copy() { return new TypeComponent(getValue()); } private static class SObject implements Serializable { private static final long serialVersionUID = -1L; @Override public String toString() { return "NONE"; } } }
src/main/java/com/almasb/fxgl/entity/component/TypeComponent.java
/* * The MIT License (MIT) * * FXGL - JavaFX Game Library * * Copyright (c) 2015-2016 AlmasB ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.almasb.fxgl.entity.component; import com.almasb.easyio.serialization.Bundle; import com.almasb.ents.CopyableComponent; import com.almasb.ents.component.ObjectComponent; import com.almasb.ents.serialization.SerializableComponent; import org.jetbrains.annotations.NotNull; import java.io.Serializable; /** * Represents an entity type. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ public class TypeComponent extends ObjectComponent<Serializable> implements SerializableComponent, CopyableComponent<TypeComponent> { /** * Constructs a component with no type. */ public TypeComponent() { this(new SObject()); } /** * Constructs a component with given type. * Note: although the type could be any object, it is recommended * that an enum is used to represent types. * * @param type entity type */ public TypeComponent(Serializable type) { super(type); } /** * <pre> * Example: * entity.getTypeComponent().isType(Type.PLAYER); * </pre> * * @param type entity type * @return true iff this type component is of given type */ public boolean isType(Object type) { return getValue().equals(type); } @Override public String toString() { return "Type(" + getValue() + ")"; } @Override public void write(@NotNull Bundle bundle) { bundle.put("value", getValue()); } @Override public void read(@NotNull Bundle bundle) { setValue(bundle.get("value")); } @Override public TypeComponent copy() { return new TypeComponent(getValue()); } private static class SObject implements Serializable { private static final long serialVersionUID = -1L; } }
added toString to SObject for pretty print
src/main/java/com/almasb/fxgl/entity/component/TypeComponent.java
added toString to SObject for pretty print
<ide><path>rc/main/java/com/almasb/fxgl/entity/component/TypeComponent.java <ide> <ide> private static class SObject implements Serializable { <ide> private static final long serialVersionUID = -1L; <add> <add> @Override <add> public String toString() { <add> return "NONE"; <add> } <ide> } <ide> }
Java
lgpl-2.1
a4c69d2794fe031ce401b314c11bc99d892ad64e
0
viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.unizh.ini.jaer.projects.minliu; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import com.jogamp.opengl.util.awt.TextRenderer; import eu.seebetter.ini.chips.davis.imu.IMUSample; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.filter.Steadicam; import net.sf.jaer.eventprocessing.filter.TransformAtTime; import net.sf.jaer.util.filter.HighpassFilter; /** * Uses patch matching to measure local optical flow. <b>Not</b> gradient based, * but rather matches local features backwards in time. * * @author Tobi, Jan 2016 */ @Description("Computes true flow events with speed and vector direction using binary feature patch matching.") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements Observer { // These const values are for the fast implementation of the hamming weight calculation private final long m1 = 0x5555555555555555L; //binary: 0101... private final long m2 = 0x3333333333333333L; //binary: 00110011.. private final long m4 = 0x0f0f0f0f0f0f0f0fL; //binary: 4 zeros, 4 ones ... private final long m8 = 0x00ff00ff00ff00ffL; //binary: 8 zeros, 8 ones ... private final long m16 = 0x0000ffff0000ffffL; //binary: 16 zeros, 16 ones ... private final long m32 = 0x00000000ffffffffL; //binary: 32 zeros, 32 ones private final long hff = 0xffffffffffffffffL; //binary: all ones private final long h01 = 0x0101010101010101L; //the sum of 256 to the power of 0,1,2,3... private int[][][] histograms = null; private int numSlices = 3; private int sx, sy; private int tMinus2SliceIdx = 0, tMinus1SliceIdx = 1, currentSliceIdx = 2; private int[][] currentSlice = null, tMinus1Slice = null, tMinus2Slice = null; private ArrayList<Integer[]> [][] spikeTrans = null; private ArrayList<int[][]>[] histogramsAL = null; private ArrayList<int[][]> currentAL = null, previousAL = null, previousMinus1AL = null; // One is for current, the second is for previous, the third is for the one before previous one private BitSet[] histogramsBitSet = null; private BitSet currentSli = null, tMinus1Sli = null, tMinus2Sli = null; private int patchDimension = getInt("patchDimension", 8); protected boolean measurePerformance = getBoolean("measurePerformance", false); private boolean displayOutputVectors = getBoolean("displayOutputVectors", true); private int eventPatchDimension = getInt("eventPatchDimension", 3); private int forwardEventNum = getInt("forwardEventNum", 10); private float cost = getFloat("cost", 0.001f); private int thresholdTime = getInt("thresholdTime", 1000000); private int[][] lastFireIndex = new int[240][240]; private int[][] eventSeqStartTs = new int[240][240]; public enum PatchCompareMethod { JaccardDistance, HammingDistance, SAD, EventSqeDistance }; private PatchCompareMethod patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.HammingDistance.toString())); private int sliceDurationUs = getInt("sliceDurationUs", 1000); private int sliceEventCount = getInt("sliceEventCount", 1000); private String patchTT = "Patch matching"; private float sadSum = 0; private boolean rewindFlg = false; // The flag to indicate the rewind event. private TransformAtTime lastTransform = null, imageTransform = null; private FilterChain filterChain; private Steadicam cameraMotion; private int packetNum; private int sx2; private int sy2; private double panTranslationDeg; private double tiltTranslationDeg; private float rollDeg; private int lastImuTimestamp = 0; private float panRate = 0, tiltRate = 0, rollRate = 0; // in deg/sec private float panOffset = getFloat("panOffset", 0), tiltOffset = getFloat("tiltOffset", 0), rollOffset = getFloat("rollOffset", 0); private float panDC = 0, tiltDC = 0, rollDC = 0; private boolean showTransformRectangle = getBoolean("showTransformRectangle", true); private boolean removeCameraMotion = getBoolean("removeCameraMotion", true); // calibration private boolean calibrating = false; // used to flag calibration state private int calibrationSampleCount = 0; private int NUM_CALIBRATION_SAMPLES_DEFAULT = 800; // 400 samples /sec protected int numCalibrationSamples = getInt("numCalibrationSamples", NUM_CALIBRATION_SAMPLES_DEFAULT); private CalibrationFilter panCalibrator, tiltCalibrator, rollCalibrator; TextRenderer imuTextRenderer = null; private boolean showGrid = getBoolean("showGrid", true); private int flushCounter = 0; public enum SliceMethod { ConstantDuration, ConstantEventNumber, AdaptationDuration }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.ConstantDuration.toString())); private int eventCounter = 0; // private int sliceLastTs = Integer.MIN_VALUE; private int sliceLastTs = 0; HighpassFilter panTranslationFilter = new HighpassFilter(); HighpassFilter tiltTranslationFilter = new HighpassFilter(); HighpassFilter rollFilter = new HighpassFilter(); private float highpassTauMsTranslation = getFloat("highpassTauMsTranslation", 1000); private float highpassTauMsRotation = getFloat("highpassTauMsRotation", 1000); private boolean highPassFilterEn = getBoolean("highPassFilterEn", false); public PatchMatchFlow(AEChip chip) { super(chip); filterChain = new FilterChain(chip); cameraMotion = new Steadicam(chip); cameraMotion.setFilterEnabled(true); cameraMotion.setDisableRotation(true); cameraMotion.setDisableTranslation(true); // filterChain.add(cameraMotion); setEnclosedFilterChain(filterChain); String imu = "IMU"; chip.addObserver(this); // to allocate memory once chip size is known setPropertyTooltip(patchTT, "patchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches"); setPropertyTooltip(patchTT, "sliceDurationUs", "duration of patches in us"); setPropertyTooltip(patchTT, "sliceEventCount", "number of collected events in each bitmap"); setPropertyTooltip(patchTT, "eventPatchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "forwardEventNum", "forward events number"); setPropertyTooltip(patchTT, "cost", "The cost to translation one event to the other position"); setPropertyTooltip(patchTT, "thresholdTime", "The threshold value of interval time between the first event and the last event"); setPropertyTooltip(dispTT, "highpassTauMsTranslation", "highpass filter time constant in ms to relax transform back to zero for translation (pan, tilt) components"); setPropertyTooltip(dispTT, "highpassTauMsRotation", "highpass filter time constant in ms to relax transform back to zero for rotation (roll) component"); setPropertyTooltip(dispTT, "highPassFilterEn", "enable the high pass filter or not"); setPropertyTooltip(dispTT, "showTransformRectangle", "Disable to not show the red transform square and red cross hairs"); setPropertyTooltip(dispTT, "displayOutputVectors", "display the output motion vectors or not"); setPropertyTooltip(imu, "removeCameraMotion", "Remove the camera motion"); setPropertyTooltip(imu, "zeroGyro", "zeros the gyro output. Sensor should be stationary for period of 1-2 seconds during zeroing"); setPropertyTooltip(imu, "eraseGyroZero", "Erases the gyro zero values"); panCalibrator = new CalibrationFilter(); tiltCalibrator = new CalibrationFilter(); rollCalibrator = new CalibrationFilter(); rollFilter.setTauMs(highpassTauMsRotation); panTranslationFilter.setTauMs(highpassTauMsTranslation); tiltTranslationFilter.setTauMs(highpassTauMsTranslation); lastTransform = new TransformAtTime(ts, new Point2D.Float( (float)(0), (float)(0)), (float) (0)); } @Override public EventPacket filterPacket(EventPacket in) { setupFilter(in); sadSum = 0; packetNum++; ApsDvsEventPacket in2 = (ApsDvsEventPacket) in; Iterator itr = in2.fullIterator(); // Wfffsfe also need IMU data, so here we use the full iterator. while (itr.hasNext()) { Object ein = itr.next(); if (ein == null) { log.warning("null event passed in, returning input packet"); return in; } extractEventInfo(ein); ApsDvsEvent apsDvsEvent = (ApsDvsEvent) ein; if (apsDvsEvent.isImuSample()) { IMUSample s = apsDvsEvent.getImuSample(); lastTransform = updateTransform(s); continue; } // inItr = in.inputIterator; if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { imuFlowEstimator.calculateImuFlow((ApsDvsEvent) inItr.next()); setGroundTruth(); } if (xyFilter()) { continue; } countIn++; if(!removeCameraMotion) { showTransformRectangle = true; int nx = e.x - 120, ny = e.y - 90; e.x = (short) ((((lastTransform.cosAngle * nx) - (lastTransform.sinAngle * ny)) + lastTransform.translationPixels.x) + 120); e.y = (short) (((lastTransform.sinAngle * nx) + (lastTransform.cosAngle * ny) + lastTransform.translationPixels.y) + 90); e.address = chip.getEventExtractor().getAddressFromCell(e.x, e.y, e.getType()); // so event is logged properly to disk if ((e.x > 239) || (e.x < 0) || (e.y > 179) || (e.y < 0)) { e.setFilteredOut(true); // TODO this gradually fills the packet with filteredOut events, which are never seen afterwards because the iterator filters them outputPacket in the reused packet. continue; // discard events outside chip limits for now, because we can't render them presently, although they are valid events } else { e.setFilteredOut(false); } extractEventInfo(e); // Update x, y, ts and type } else { showTransformRectangle = false; } long startTime = 0; if (measurePerformance) { startTime = System.nanoTime(); } // compute flow SADResult result = new SADResult(0,0,0); int blockLocX = x/eventPatchDimension; int blockLocY = y/eventPatchDimension; // Build the spike trains of every block, every block is consist of 3*3 pixels. if(spikeTrans[blockLocX][blockLocY] == null) { spikeTrans[blockLocX][blockLocY] = new ArrayList(); } int spikeBlokcLength = spikeTrans[blockLocX][blockLocY].size(); int previousTsInterval = 0; if(spikeBlokcLength == 0) { previousTsInterval = ts; } else { previousTsInterval = ts - spikeTrans[blockLocX][blockLocY].get(spikeBlokcLength - 1)[0]; } spikeTrans[blockLocX][blockLocY].add(new Integer[]{ts, type}); switch(patchCompareMethod) { case HammingDistance: maybeRotateSlices(); accumulateEvent(); // There're enough events fire on the specific block now. if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; result = minHammingDistance(x, y, tMinus2Sli, tMinus1Sli); result.dx = result.dx/sliceDurationUs * 1000000; result.dy = result.dy/sliceDurationUs * 1000000; } break; case SAD: maybeRotateSlices(); accumulateEvent(); // There're enough events fire on the specific block now if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; result = minSad(x, y, tMinus2Slice, tMinus1Slice); result.dx = result.dx/sliceDurationUs * 1000000; result.dy = result.dy/sliceDurationUs * 1000000; } break; case JaccardDistance: maybeRotateSlices(); accumulateEvent(); // There're enough events fire on the specific block now if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; result = minJaccardDistance(x, y, tMinus2Sli, tMinus1Sli); result.dx = result.dx/sliceDurationUs * 1000000; result.dy = result.dy/sliceDurationUs * 1000000; } break; case EventSqeDistance: if(previousTsInterval < 0) { spikeTrans[blockLocX][blockLocY].remove(spikeTrans[blockLocX][blockLocY].size() - 1); continue; } if(previousTsInterval >= thresholdTime ) { if(blockLocX == 55 && blockLocY == 35) { int tmp = 0; } float maxDt = 0; float[][] dataPoint = new float[9][2]; if(blockLocX >= 1 && blockLocY >= 1 && blockLocX <= 238 && blockLocY <= 178 ) { for(int ii = -1; ii < 2; ii++) { for(int jj = -1; jj < 2; jj++) { float dt = ts - eventSeqStartTs[blockLocX + ii][blockLocY + jj]; // Remove the seq1 itself if(0 == ii && 0 == jj){ // continue; dt = 0; } // if(dt > 50000) { // continue; // } dataPoint[(ii + 1)*3 + (jj + 1)][0] = dt; if(dt > maxDt) { // maxDt = dt; // result.dx = -ii/dt * 1000000 * 0.2f * eventPatchDimension; // result.dy = -jj/dt * 1000000 * 0.2f * eventPatchDimension; } } } } // result = minVicPurDistance(blockLocX, blockLocY); eventSeqStartTs[blockLocX][blockLocY] = ts; boolean allZeroFlg = true; for(int mm = 0; mm < 9; mm ++) { for(int nn = 0; nn < 1; nn++) { if(dataPoint[mm][nn] != 0) { allZeroFlg = false; } } } if(allZeroFlg) { continue; } KMeans cluster = new KMeans(); cluster.setData(dataPoint); int[] initialValue = new int[3]; initialValue[0] = 0; initialValue[1] = 4; initialValue[2] = 8; cluster.setInitialByUser(initialValue); cluster.cluster(); ArrayList<ArrayList<Integer>> kmeansResult = cluster.getResult(); float[][] classData = cluster.getClassData(); int firstClusterIdx = -1, secondClusterIdx = -1, thirdClusterIdx = -1; for(int i = 0; i < 3; i ++) { if(kmeansResult.get(i).contains(0)) { firstClusterIdx = i; } if(kmeansResult.get(i).contains(4)) { secondClusterIdx = i; } if(kmeansResult.get(i).contains(8)) { thirdClusterIdx = i; } } if(kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).contains(1) && kmeansResult.get(firstClusterIdx).contains(2)){ result.dx = -1/(classData[secondClusterIdx][0] - classData[firstClusterIdx][0]) * 1000000* 0.2f * eventPatchDimension;; result.dy = 0; } if(kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(thirdClusterIdx).contains(2) && kmeansResult.get(thirdClusterIdx).contains(5)){ result.dy = -1/(classData[thirdClusterIdx][0] - classData[secondClusterIdx][0]) * 1000000* 0.2f * eventPatchDimension;; result.dx = 0; } } break; } vx = result.dx; vy = result.dy; v = (float) Math.sqrt(vx * vx + vy * vy); if (measurePerformance) { long dt = System.nanoTime() - startTime; float us = 1e-3f * dt; log.info(String.format("Per event processing time: %.1fus", us)); } // long[] testByteArray1 = tMinus1Sli.toLongArray(); // long[] testByteArray2 = tMinus2Sli.toLongArray(); // tMinus1Sli.andNot(tMinus2Sli); // long test1 = popcount_3((long) sadSum); // DavisChip apsDvsChip = (DavisChip) chip; // int frameStartTimestamp = apsDvsChip.getFrameExposureStartTimestampUs(); // int frameEndTimestamp = apsDvsChip.getFrameExposureEndTimestampUs(); // int frameCounter = apsDvsChip.getFrameCount(); // // if a frame has been read outputPacket, then save the last transform to apply to rendering this frame // imageTransform = lastTransform; // ChipRendererDisplayMethodRGBA displayMethod = (ChipRendererDisplayMethodRGBA) chip.getCanvas().getDisplayMethod(); // TODO not ideal (tobi) // displayMethod.setImageTransform(lastTransform.translationPixels, lastTransform.rotationRad); // reject values that are unreasonable if (accuracyTests()) { continue; } if(displayOutputVectors) { writeOutputEvent(); } if (measureAccuracy) { motionFlowStatistics.update(vx, vy, v, vxGT, vyGT, vGT); } } // if(cameraMotion.getLastTransform() != null) { // lastTransform = cameraMotion.getLastTransform(); // } // ChipRendererDisplayMethodRGBA displayMethod = (ChipRendererDisplayMethodRGBA) chip.getCanvas().getDisplayMethod(); // After the rewind event, restore sliceLastTs to 0 and rewindFlg to false. // displayMethod.getImageTransform(); // displayMethod.setImageTransform(lastTransform.translationPixels, lastTransform.rotationRad); if(rewindFlg) { rewindFlg = false; sliceLastTs = 0; flushCounter = 10; panDC = 0; tiltDC = 0; rollDC = 0; for(int i = 0; i < 240; i++) { for(int j = 0; j < 180; j++) { if(spikeTrans[i][j] != null) { spikeTrans[i][j] = null; } if(lastFireIndex != null) { lastFireIndex[i][j] = 0; } eventSeqStartTs[i][j] = 0; } } } motionFlowStatistics.updatePacket(countIn, countOut); return isShowRawInputEnabled() ? in : dirPacket; } @Override public synchronized void resetFilter() { super.resetFilter(); eventCounter = 0; lastTs = Integer.MIN_VALUE; if (histograms == null || histograms.length != subSizeX || histograms[0].length != subSizeY) { histograms = new int[numSlices][subSizeX][subSizeY]; } for (int[][] a : histograms) { for (int[] b : a) { Arrays.fill(b, 0); } } if (histogramsBitSet == null) { histogramsBitSet = new BitSet[numSlices]; } for(int ii = 0; ii < numSlices; ii ++) { histogramsBitSet[ii] = new BitSet(subSizeX*subSizeY); } // Initialize 3 ArrayList's histogram, every pixel has three patches: current, previous and previous-1 if(histogramsAL == null){ histogramsAL = new ArrayList[3]; } if (spikeTrans == null & subSizeX != 0 & subSizeY != 0) { spikeTrans = new ArrayList[subSizeX][subSizeY]; } if(patchDimension != 0) { int colPatchCnt = subSizeX/patchDimension; int rowPatchCnt = subSizeY/patchDimension; for(int ii = 0; ii < numSlices; ii ++) { histogramsAL[ii] = new ArrayList(); for(int jj = 0; jj < colPatchCnt*rowPatchCnt; jj ++) { int[][] patch = new int[patchDimension][patchDimension]; histogramsAL[ii].add(patch); } } } tMinus2SliceIdx = 0; tMinus1SliceIdx = 1; currentSliceIdx = 2; if(histograms.length != 0) { assignSliceReferences(); } sliceLastTs = 0; packetNum = 0; rewindFlg = true; } @Override public void update(Observable o, Object arg) { super.update(o, arg); if (!isFilterEnabled()) { return; } if (o instanceof AEChip && chip.getNumPixels() > 0) { resetFilter(); } } /** * Computes transform using current gyro outputs based on timestamp supplied * and returns a TransformAtTime object. * * @param timestamp the timestamp in us. * @return the transform object representing the camera rotationRad */ synchronized public TransformAtTime updateTransform(IMUSample imuSample) { int timestamp = imuSample.getTimestampUs(); float dtS = (timestamp - lastImuTimestamp) * 1e-6f; lastImuTimestamp = timestamp; if (flushCounter-- >= 0) { return new TransformAtTime(ts, new Point2D.Float( (float)(0),(float)(0)), (float) (0)); // flush some samples if the timestamps have been reset and we need to discard some samples here } panRate = imuSample.getGyroYawY(); tiltRate = imuSample.getGyroTiltX(); rollRate = imuSample.getGyroRollZ(); if (calibrating) { calibrationSampleCount++; if (calibrationSampleCount > numCalibrationSamples) { calibrating = false; panOffset = panCalibrator.computeAverage(); tiltOffset = tiltCalibrator.computeAverage(); rollOffset = rollCalibrator.computeAverage(); panDC = 0; tiltDC = 0; rollDC = 0; putFloat("panOffset", panOffset); putFloat("tiltOffset", tiltOffset); putFloat("rollOffset", rollOffset); log.info(String.format("calibration finished. %d samples averaged to (pan,tilt,roll)=(%.3f,%.3f,%.3f)", numCalibrationSamples, panOffset, tiltOffset, rollOffset)); } else { panCalibrator.addSample(panRate); tiltCalibrator.addSample(tiltRate); rollCalibrator.addSample(rollRate); } return new TransformAtTime(ts, new Point2D.Float( (float)(0),(float)(0)), (float) (0)); } panDC += getPanRate() * dtS; tiltDC += getTiltRate() * dtS; rollDC += getRollRate() * dtS; if(highPassFilterEn) { panTranslationDeg = panTranslationFilter.filter(panDC, timestamp); tiltTranslationDeg = tiltTranslationFilter.filter(tiltDC, timestamp); rollDeg = rollFilter.filter(rollDC, timestamp); } else { panTranslationDeg = panDC; tiltTranslationDeg = tiltDC; rollDeg = rollDC; } float radValPerPixel = (float) Math.atan(chip.getPixelWidthUm() / (1000 * getLensFocalLengthMm())); // Use the lens focal length and camera resolution. TransformAtTime tr = new TransformAtTime(timestamp, new Point2D.Float( (float) ((Math.PI / 180) * panTranslationDeg/radValPerPixel), (float) ((Math.PI / 180) * tiltTranslationDeg/radValPerPixel)), (-rollDeg * (float) Math.PI) / 180); return tr; } private class CalibrationFilter { int count = 0; float sum = 0; void reset() { count = 0; sum = 0; } void addSample(float sample) { sum += sample; count++; } float computeAverage() { return sum / count; } } /** * @return the panRate */ public float getPanRate() { return panRate - panOffset; } /** * @return the tiltRate */ public float getTiltRate() { return tiltRate - tiltOffset; } /** * @return the rollRate */ public float getRollRate() { return rollRate - rollOffset; } /** * uses the current event to maybe rotate the slices */ private void maybeRotateSlices() { int dt = ts - sliceLastTs; switch (sliceMethod) { case ConstantDuration: if(rewindFlg) { return; } if (dt < sliceDurationUs || dt < 0) { return; } break; case ConstantEventNumber: if (eventCounter++ < sliceEventCount) { return; } case AdaptationDuration: int x = e.x; int y = e.y; if(x < patchDimension || y < patchDimension || x > subSizeX - patchDimension || y > subSizeY - patchDimension) { return; } int positionX = x%(patchDimension + 1); int positionY = y%(patchDimension + 1); int centerX = x + (patchDimension - positionX); int centerY = y + (patchDimension - positionY); int count = 0; for (int row = -patchDimension; row <= patchDimension; row ++) { BitSet tmpRow = currentSli.get((centerX - patchDimension) + (centerY + row) * subSizeX, (centerX + patchDimension) + (centerY + row) * subSizeX); count += tmpRow.cardinality(); } if(count <= (patchDimension * 2 + 1) * (patchDimension * 2 + 1) / 2) { return; } int timestamp = e.timestamp; break; } /* The index cycle is " current idx -> t1 idx -> t2 idx -> current idx". Change the index, the change should like this: next t2 = previous t1 = histogram(previous t2 idx + 1); next t1 = previous current = histogram(previous t1 idx + 1); */ currentSliceIdx = (currentSliceIdx + 1) % numSlices; tMinus1SliceIdx = (tMinus1SliceIdx + 1) % numSlices; tMinus2SliceIdx = (tMinus2SliceIdx + 1) % numSlices; sliceEventCount = 0; sliceLastTs = ts; assignSliceReferences(); } private int updateAdaptDuration() { return 1000; } private void assignSliceReferences() { currentSlice = histograms[currentSliceIdx]; tMinus1Slice = histograms[tMinus1SliceIdx]; tMinus2Slice = histograms[tMinus2SliceIdx]; currentSli = histogramsBitSet[currentSliceIdx]; tMinus1Sli = histogramsBitSet[tMinus1SliceIdx]; tMinus2Sli = histogramsBitSet[tMinus2SliceIdx]; currentSli.clear(); } /** * Accumulates the current event to the current slice */ private void accumulateEvent() { currentSlice[x][y] += e.getPolaritySignum(); currentSli.set((x + 1) + y * subSizeX); // All evnets wheather 0 or 1 will be set in the BitSet Slice. } private void clearSlice(int idx) { for (int[] a : histograms[idx]) { Arrays.fill(a, 0); } } synchronized public void doEraseGyroZero() { panOffset = 0; tiltOffset = 0; rollOffset = 0; putFloat("panOffset", 0); putFloat("tiltOffset", 0); putFloat("rollOffset", 0); log.info("calibration erased"); } synchronized public void doZeroGyro() { calibrating = true; calibrationSampleCount = 0; panCalibrator.reset(); tiltCalibrator.reset(); rollCalibrator.reset(); log.info("calibration started"); // panOffset = panRate; // TODO offsets should really be some average over some samples // tiltOffset = tiltRate; // rollOffset = rollRate; } /** * Computes hamming eight around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { int minSum = Integer.MAX_VALUE, sum = 0; SADResult sadResult = new SADResult(0, 0, 0); for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { sum = hammingDistance(x, y, dx, dy, prevSlice, curSlice); if(sum <= minSum) { minSum = sum; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSum; } } } return sadResult; } /** * computes Hamming distance centered on x,y with patch of patchSize for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private int hammingDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { int retVal = 0; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension || y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) { return Integer.MAX_VALUE; } for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) { for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) { if(curSlice.get((xx + 1) + (yy) * subSizeX) != prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX)) { retVal += 1; } } } return retVal; } /** * Computes hamming eight around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { float minSum = Integer.MAX_VALUE, sum = 0; SADResult sadResult = new SADResult(0, 0, 0); for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice); if(sum <= minSum) { minSum = sum; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSum; } } } return sadResult; } /** * computes Hamming distance centered on x,y with patch of patchSize for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { float retVal = 0; float M01 = 0, M10 = 0, M11 = 0; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension || y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) { return Integer.MAX_VALUE; } for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) { for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) { if(curSlice.get((xx + 1) + (yy) * subSizeX) == true && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == true) { M11 += 1; } if(curSlice.get((xx + 1) + (yy) * subSizeX) == true && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == false) { M01 += 1; } if(curSlice.get((xx + 1) + (yy) * subSizeX) == false && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == true) { M10 += 1; } } } if(0 == M01 + M10 + M11) { retVal = 0; } else { retVal = M11/(M01 + M10 + M11); } retVal = 1 - retVal; return retVal; } private SADResult minVicPurDistance(int blockX, int blockY) { ArrayList<Integer[]> seq1 = new ArrayList(1); SADResult sadResult = new SADResult(0, 0, 0); int size = spikeTrans[blockX][blockY].size(); int lastTs = spikeTrans[blockX][blockY].get(size - forwardEventNum)[0]; for(int i = size - forwardEventNum; i < size; i++) { seq1.add(spikeTrans[blockX][blockY].get(i)); } // if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) { // return sadResult; // } double minium = Integer.MAX_VALUE; for(int i = -1; i < 2; i++){ for(int j = -1; j < 2; j++){ // Remove the seq1 itself if(0 == i && 0 == j){ continue; } ArrayList<Integer[]> seq2 = new ArrayList(1); if(blockX >= 2 && blockY >=2) { ArrayList<Integer[]> tmpSpikes = spikeTrans[blockX + i][blockY + j]; if(tmpSpikes != null) { for(int index = 0; index < tmpSpikes.size(); index++) { if(tmpSpikes.get(index)[0] >= lastTs) { seq2.add(tmpSpikes.get(index)); } } double dis = vicPurDistance(seq1, seq2); if(dis < minium) { minium = dis; sadResult.dx = -i; sadResult.dy = -j; } } } } } lastFireIndex[blockX][blockY] = spikeTrans[blockX][blockY].size() - 1; if(sadResult.dx != 1 || sadResult.dy != 0) { // sadResult = new SADResult(0, 0, 0); } return sadResult; } private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) { int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0; Iterator itr1 = seq1.iterator(); Iterator itr2 = seq2.iterator(); int length1 = seq1.size(); int length2 = seq2.size(); double[][] distanceMatrix = new double[length1 + 1][length2 + 1]; for(int h = 0; h <= length1; h++) { for(int k = 0; k <= length2; k++) { if(h == 0) { distanceMatrix[h][k] = k; continue; } if(k == 0) { distanceMatrix[h][k] = h; continue; } double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1); double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0]; double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0]; distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + cost*Math.abs(event1 - event2)); } } while(itr1.hasNext()){ Integer[] ii = (Integer[]) itr1.next(); if(ii[1] == 1) { sum1Plus += 1; } else{ sum1Minus += 1; } } while(itr2.hasNext()){ Integer[] ii = (Integer[]) itr2.next(); if(ii[1] == 1) { sum2Plus += 1; } else{ sum2Minus += 1; } } // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus); return distanceMatrix[length1][length2]; } /** * Computes min SAD shift around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minSad(int x, int y, int[][] prevSlice, int[][] curSlice) { // for now just do exhaustive search over all shifts up to +/-searchDistance SADResult sadResult = new SADResult(0, 0, 0); int minSad = Integer.MAX_VALUE, minDx = 0, minDy = 0; for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { int sad = sad(x, y, dx, dy, prevSlice, curSlice); if (sad <= minSad) { minSad = sad; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSad; } } } return sadResult; } /** * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param dx * @param dy * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private int sad(int x, int y, int dx, int dy, int[][] prevSlice, int[][] curSlice) { // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension || y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) { return Integer.MAX_VALUE; } int sad = 0; for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) { for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) { int d = curSlice[xx][yy] - prevSlice[xx - dx][yy - dy]; if (d <= 0) { d = -d; } sad += d; } } return sad; } //This uses fewer arithmetic operations than any other known //implementation on machines with fast multiplication. //It uses 12 arithmetic operations, one of which is a multiply. public long popcount_3(long x) { x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits return (x * h01)>>56; //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ... } private class SADResult { float dx, dy; float sadValue; public SADResult(float dx, float dy, float sadValue) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } @Override public String toString() { return String.format("dx,dy=%d,%5 SAD=%d",dx,dy,sadValue); } } /** * @return the patchDimension */ public int getPatchDimension() { return patchDimension; } /** * @param patchDimension the patchDimension to set */ public void setPatchDimension(int patchDimension) { this.patchDimension = patchDimension; putInt("patchDimension", patchDimension); } public int getEventPatchDimension() { return eventPatchDimension; } public void setEventPatchDimension(int eventPatchDimension) { this.eventPatchDimension = eventPatchDimension; putInt("eventPatchDimension", eventPatchDimension); } public int getForwardEventNum() { return forwardEventNum; } public void setForwardEventNum(int forwardEventNum) { this.forwardEventNum = forwardEventNum; putInt("forwardEventNum", forwardEventNum); } public float getCost() { return cost; } public void setCost(float cost) { this.cost = cost; putFloat("cost", cost); } public int getThresholdTime() { return thresholdTime; } public void setThresholdTime(int thresholdTime) { this.thresholdTime = thresholdTime; putInt("thresholdTime", thresholdTime); } /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ public void setSliceMethod(SliceMethod sliceMethod) { this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); } public PatchCompareMethod getPatchCompareMethod() { return patchCompareMethod; } public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) { this.patchCompareMethod = patchCompareMethod; putString("patchCompareMethod", patchCompareMethod.toString()); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { this.sliceDurationUs = sliceDurationUs; putInt("sliceDurationUs", sliceDurationUs); } public boolean isShowTransformRectangle() { return showTransformRectangle; } public void setShowTransformRectangle(boolean showTransformRectangle) { this.showTransformRectangle = showTransformRectangle; } public boolean isRemoveCameraMotion() { return removeCameraMotion; } public void setRemoveCameraMotion(boolean removeCameraMotion) { this.removeCameraMotion = removeCameraMotion; } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); } public float getHighpassTauMsTranslation() { return highpassTauMsTranslation; } public void setHighpassTauMsTranslation(float highpassTauMs) { this.highpassTauMsTranslation = highpassTauMs; putFloat("highpassTauMsTranslation", highpassTauMs); panTranslationFilter.setTauMs(highpassTauMs); tiltTranslationFilter.setTauMs(highpassTauMs); } public float getHighpassTauMsRotation() { return highpassTauMsRotation; } public void setHighpassTauMsRotation(float highpassTauMs) { this.highpassTauMsRotation = highpassTauMs; putFloat("highpassTauMsRotation", highpassTauMs); rollFilter.setTauMs(highpassTauMs); } public boolean isHighPassFilterEn() { return highPassFilterEn; } public void setHighPassFilterEn(boolean highPassFilterEn) { this.highPassFilterEn = highPassFilterEn; putBoolean("highPassFilterEn", highPassFilterEn); } public boolean isMeasurePerformance() { return measurePerformance; } public void setMeasurePerformance(boolean measurePerformance) { this.measurePerformance = measurePerformance; putBoolean("measurePerformance", measurePerformance); } public boolean isDisplayOutputVectors() { return displayOutputVectors; } public void setDisplayOutputVectors(boolean displayOutputVectors) { this.displayOutputVectors = displayOutputVectors; putBoolean("displayOutputVectors", measurePerformance); } }
src/ch/unizh/ini/jaer/projects/minliu/PatchMatchFlow.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.unizh.ini.jaer.projects.minliu; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import com.jogamp.opengl.util.awt.TextRenderer; import eu.seebetter.ini.chips.davis.imu.IMUSample; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.filter.Steadicam; import net.sf.jaer.eventprocessing.filter.TransformAtTime; import net.sf.jaer.util.filter.HighpassFilter; /** * Uses patch matching to measure local optical flow. <b>Not</b> gradient based, * but rather matches local features backwards in time. * * @author Tobi, Jan 2016 */ @Description("Computes true flow events with speed and vector direction using binary feature patch matching.") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements Observer { // These const values are for the fast implementation of the hamming weight calculation private final long m1 = 0x5555555555555555L; //binary: 0101... private final long m2 = 0x3333333333333333L; //binary: 00110011.. private final long m4 = 0x0f0f0f0f0f0f0f0fL; //binary: 4 zeros, 4 ones ... private final long m8 = 0x00ff00ff00ff00ffL; //binary: 8 zeros, 8 ones ... private final long m16 = 0x0000ffff0000ffffL; //binary: 16 zeros, 16 ones ... private final long m32 = 0x00000000ffffffffL; //binary: 32 zeros, 32 ones private final long hff = 0xffffffffffffffffL; //binary: all ones private final long h01 = 0x0101010101010101L; //the sum of 256 to the power of 0,1,2,3... private int[][][] histograms = null; private int numSlices = 3; private int sx, sy; private int tMinus2SliceIdx = 0, tMinus1SliceIdx = 1, currentSliceIdx = 2; private int[][] currentSlice = null, tMinus1Slice = null, tMinus2Slice = null; private ArrayList<Integer[]> [][] spikeTrans = null; private ArrayList<int[][]>[] histogramsAL = null; private ArrayList<int[][]> currentAL = null, previousAL = null, previousMinus1AL = null; // One is for current, the second is for previous, the third is for the one before previous one private BitSet[] histogramsBitSet = null; private BitSet currentSli = null, tMinus1Sli = null, tMinus2Sli = null; private int patchDimension = getInt("patchDimension", 8); protected boolean measurePerformance = getBoolean("measurePerformance", false); private boolean displayOutputVectors = getBoolean("displayOutputVectors", true); private int eventPatchDimension = getInt("eventPatchDimension", 3); private int forwardEventNum = getInt("forwardEventNum", 10); private float cost = getFloat("cost", 0.001f); private int thresholdTime = getInt("thresholdTime", 1000000); private int[][] lastFireIndex = new int[240][240]; private int[][] eventSeqStartTs = new int[240][240]; public enum PatchCompareMethod { JaccardDistance, HammingDistance, SAD, EventSqeDistance }; private PatchCompareMethod patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.HammingDistance.toString())); private int sliceDurationUs = getInt("sliceDurationUs", 1000); private int sliceEventCount = getInt("sliceEventCount", 1000); private String patchTT = "Patch matching"; private float sadSum = 0; private boolean rewindFlg = false; // The flag to indicate the rewind event. private TransformAtTime lastTransform = null, imageTransform = null; private FilterChain filterChain; private Steadicam cameraMotion; private int packetNum; private int sx2; private int sy2; private double panTranslationDeg; private double tiltTranslationDeg; private float rollDeg; private int lastImuTimestamp = 0; private float panRate = 0, tiltRate = 0, rollRate = 0; // in deg/sec private float panOffset = getFloat("panOffset", 0), tiltOffset = getFloat("tiltOffset", 0), rollOffset = getFloat("rollOffset", 0); private float panDC = 0, tiltDC = 0, rollDC = 0; private boolean showTransformRectangle = getBoolean("showTransformRectangle", true); private boolean removeCameraMotion = getBoolean("removeCameraMotion", true); // calibration private boolean calibrating = false; // used to flag calibration state private int calibrationSampleCount = 0; private int NUM_CALIBRATION_SAMPLES_DEFAULT = 800; // 400 samples /sec protected int numCalibrationSamples = getInt("numCalibrationSamples", NUM_CALIBRATION_SAMPLES_DEFAULT); private CalibrationFilter panCalibrator, tiltCalibrator, rollCalibrator; TextRenderer imuTextRenderer = null; private boolean showGrid = getBoolean("showGrid", true); private int flushCounter = 0; public enum SliceMethod { ConstantDuration, ConstantEventNumber, AdaptationDuration }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.ConstantDuration.toString())); private int eventCounter = 0; // private int sliceLastTs = Integer.MIN_VALUE; private int sliceLastTs = 0; HighpassFilter panTranslationFilter = new HighpassFilter(); HighpassFilter tiltTranslationFilter = new HighpassFilter(); HighpassFilter rollFilter = new HighpassFilter(); private float highpassTauMsTranslation = getFloat("highpassTauMsTranslation", 1000); private float highpassTauMsRotation = getFloat("highpassTauMsRotation", 1000); private boolean highPassFilterEn = getBoolean("highPassFilterEn", false); public PatchMatchFlow(AEChip chip) { super(chip); filterChain = new FilterChain(chip); cameraMotion = new Steadicam(chip); cameraMotion.setFilterEnabled(true); cameraMotion.setDisableRotation(true); cameraMotion.setDisableTranslation(true); // filterChain.add(cameraMotion); setEnclosedFilterChain(filterChain); String imu = "IMU"; chip.addObserver(this); // to allocate memory once chip size is known setPropertyTooltip(patchTT, "patchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches"); setPropertyTooltip(patchTT, "sliceDurationUs", "duration of patches in us"); setPropertyTooltip(patchTT, "sliceEventCount", "number of collected events in each bitmap"); setPropertyTooltip(patchTT, "eventPatchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "forwardEventNum", "forward events number"); setPropertyTooltip(patchTT, "cost", "The cost to translation one event to the other position"); setPropertyTooltip(patchTT, "thresholdTime", "The threshold value of interval time between the first event and the last event"); setPropertyTooltip(dispTT, "highpassTauMsTranslation", "highpass filter time constant in ms to relax transform back to zero for translation (pan, tilt) components"); setPropertyTooltip(dispTT, "highpassTauMsRotation", "highpass filter time constant in ms to relax transform back to zero for rotation (roll) component"); setPropertyTooltip(dispTT, "highPassFilterEn", "enable the high pass filter or not"); setPropertyTooltip(dispTT, "showTransformRectangle", "Disable to not show the red transform square and red cross hairs"); setPropertyTooltip(dispTT, "displayOutputVectors", "display the output motion vectors or not"); setPropertyTooltip(imu, "removeCameraMotion", "Remove the camera motion"); setPropertyTooltip(imu, "zeroGyro", "zeros the gyro output. Sensor should be stationary for period of 1-2 seconds during zeroing"); setPropertyTooltip(imu, "eraseGyroZero", "Erases the gyro zero values"); panCalibrator = new CalibrationFilter(); tiltCalibrator = new CalibrationFilter(); rollCalibrator = new CalibrationFilter(); rollFilter.setTauMs(highpassTauMsRotation); panTranslationFilter.setTauMs(highpassTauMsTranslation); tiltTranslationFilter.setTauMs(highpassTauMsTranslation); lastTransform = new TransformAtTime(ts, new Point2D.Float( (float)(0), (float)(0)), (float) (0)); } @Override public EventPacket filterPacket(EventPacket in) { setupFilter(in); sadSum = 0; packetNum++; ApsDvsEventPacket in2 = (ApsDvsEventPacket) in; Iterator itr = in2.fullIterator(); // Wfffsfe also need IMU data, so here we use the full iterator. while (itr.hasNext()) { Object ein = itr.next(); if (ein == null) { log.warning("null event passed in, returning input packet"); return in; } extractEventInfo(ein); ApsDvsEvent apsDvsEvent = (ApsDvsEvent) ein; if (apsDvsEvent.isImuSample()) { IMUSample s = apsDvsEvent.getImuSample(); lastTransform = updateTransform(s); continue; } // inItr = in.inputIterator; if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { imuFlowEstimator.calculateImuFlow((ApsDvsEvent) inItr.next()); setGroundTruth(); } if (xyFilter()) { continue; } countIn++; if(!removeCameraMotion) { showTransformRectangle = true; int nx = e.x - 120, ny = e.y - 90; e.x = (short) ((((lastTransform.cosAngle * nx) - (lastTransform.sinAngle * ny)) + lastTransform.translationPixels.x) + 120); e.y = (short) (((lastTransform.sinAngle * nx) + (lastTransform.cosAngle * ny) + lastTransform.translationPixels.y) + 90); e.address = chip.getEventExtractor().getAddressFromCell(e.x, e.y, e.getType()); // so event is logged properly to disk if ((e.x > 239) || (e.x < 0) || (e.y > 179) || (e.y < 0)) { e.setFilteredOut(true); // TODO this gradually fills the packet with filteredOut events, which are never seen afterwards because the iterator filters them outputPacket in the reused packet. continue; // discard events outside chip limits for now, because we can't render them presently, although they are valid events } else { e.setFilteredOut(false); } extractEventInfo(e); // Update x, y, ts and type } else { showTransformRectangle = false; } long startTime = 0; if (measurePerformance) { startTime = System.nanoTime(); } // compute flow SADResult result = new SADResult(0,0,0); int blockLocX = x/eventPatchDimension; int blockLocY = y/eventPatchDimension; // Build the spike trains of every block, every block is consist of 3*3 pixels. if(spikeTrans[blockLocX][blockLocY] == null) { spikeTrans[blockLocX][blockLocY] = new ArrayList(); } int spikeBlokcLength = spikeTrans[blockLocX][blockLocY].size(); int previousTsInterval = 0; if(spikeBlokcLength == 0) { previousTsInterval = ts; } else { previousTsInterval = ts - spikeTrans[blockLocX][blockLocY].get(spikeBlokcLength - 1)[0]; } spikeTrans[blockLocX][blockLocY].add(new Integer[]{ts, type}); switch(patchCompareMethod) { case HammingDistance: maybeRotateSlices(); accumulateEvent(); // There're enough events fire on the specific block now. if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; result = minHammingDistance(x, y, tMinus2Sli, tMinus1Sli); } break; case SAD: maybeRotateSlices(); accumulateEvent(); // There're enough events fire on the specific block now if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; result = minSad(x, y, tMinus2Slice, tMinus1Slice); } break; case JaccardDistance: maybeRotateSlices(); accumulateEvent(); // There're enough events fire on the specific block now if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; result = minJaccardDistance(x, y, tMinus2Sli, tMinus1Sli); } break; case EventSqeDistance: if(previousTsInterval < 0) { spikeTrans[blockLocX][blockLocY].remove(spikeTrans[blockLocX][blockLocY].size() - 1); continue; } if(previousTsInterval >= thresholdTime ) { if(blockLocX == 55 && blockLocY == 35) { int tmp = 0; } float maxDt = 0; float[][] dataPoint = new float[9][2]; if(blockLocX >= 1 && blockLocY >= 1 && blockLocX <= 238 && blockLocY <= 178 ) { for(int ii = -1; ii < 2; ii++) { for(int jj = -1; jj < 2; jj++) { float dt = ts - eventSeqStartTs[blockLocX + ii][blockLocY + jj]; // Remove the seq1 itself if(0 == ii && 0 == jj){ // continue; dt = 0; } // if(dt > 50000) { // continue; // } dataPoint[(ii + 1)*3 + (jj + 1)][0] = dt; if(dt > maxDt) { // maxDt = dt; // result.dx = -ii/dt * 1000000 * 0.2f * eventPatchDimension; // result.dy = -jj/dt * 1000000 * 0.2f * eventPatchDimension; } } } } // result = minVicPurDistance(blockLocX, blockLocY); eventSeqStartTs[blockLocX][blockLocY] = ts; boolean allZeroFlg = true; for(int mm = 0; mm < 9; mm ++) { for(int nn = 0; nn < 1; nn++) { if(dataPoint[mm][nn] != 0) { allZeroFlg = false; } } } if(allZeroFlg) { continue; } KMeans cluster = new KMeans(); cluster.setData(dataPoint); int[] initialValue = new int[3]; initialValue[0] = 0; initialValue[1] = 4; initialValue[2] = 8; cluster.setInitialByUser(initialValue); cluster.cluster(); ArrayList<ArrayList<Integer>> kmeansResult = cluster.getResult(); float[][] classData = cluster.getClassData(); int firstClusterIdx = -1, secondClusterIdx = -1, thirdClusterIdx = -1; for(int i = 0; i < 3; i ++) { if(kmeansResult.get(i).contains(0)) { firstClusterIdx = i; } if(kmeansResult.get(i).contains(4)) { secondClusterIdx = i; } if(kmeansResult.get(i).contains(8)) { thirdClusterIdx = i; } } if(kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).contains(1) && kmeansResult.get(firstClusterIdx).contains(2)){ result.dx = -1/(classData[secondClusterIdx][0] - classData[firstClusterIdx][0]) * 1000000* 0.2f * eventPatchDimension;; result.dy = 0; } if(kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(firstClusterIdx).size() == 3 && kmeansResult.get(thirdClusterIdx).contains(2) && kmeansResult.get(thirdClusterIdx).contains(5)){ result.dy = -1/(classData[thirdClusterIdx][0] - classData[secondClusterIdx][0]) * 1000000* 0.2f * eventPatchDimension;; result.dx = 0; } } break; } vx = result.dx * 5; vy = result.dy * 5; v = (float) Math.sqrt(vx * vx + vy * vy); if (measurePerformance) { long dt = System.nanoTime() - startTime; float us = 1e-3f * dt; log.info(String.format("Per event processing time: %.1fus", us)); } // long[] testByteArray1 = tMinus1Sli.toLongArray(); // long[] testByteArray2 = tMinus2Sli.toLongArray(); // tMinus1Sli.andNot(tMinus2Sli); // long test1 = popcount_3((long) sadSum); // DavisChip apsDvsChip = (DavisChip) chip; // int frameStartTimestamp = apsDvsChip.getFrameExposureStartTimestampUs(); // int frameEndTimestamp = apsDvsChip.getFrameExposureEndTimestampUs(); // int frameCounter = apsDvsChip.getFrameCount(); // // if a frame has been read outputPacket, then save the last transform to apply to rendering this frame // imageTransform = lastTransform; // ChipRendererDisplayMethodRGBA displayMethod = (ChipRendererDisplayMethodRGBA) chip.getCanvas().getDisplayMethod(); // TODO not ideal (tobi) // displayMethod.setImageTransform(lastTransform.translationPixels, lastTransform.rotationRad); // reject values that are unreasonable if (accuracyTests()) { continue; } if(displayOutputVectors) { writeOutputEvent(); } if (measureAccuracy) { motionFlowStatistics.update(vx, vy, v, vxGT, vyGT, vGT); } } // if(cameraMotion.getLastTransform() != null) { // lastTransform = cameraMotion.getLastTransform(); // } // ChipRendererDisplayMethodRGBA displayMethod = (ChipRendererDisplayMethodRGBA) chip.getCanvas().getDisplayMethod(); // After the rewind event, restore sliceLastTs to 0 and rewindFlg to false. // displayMethod.getImageTransform(); // displayMethod.setImageTransform(lastTransform.translationPixels, lastTransform.rotationRad); if(rewindFlg) { rewindFlg = false; sliceLastTs = 0; flushCounter = 10; panDC = 0; tiltDC = 0; rollDC = 0; for(int i = 0; i < 240; i++) { for(int j = 0; j < 180; j++) { if(spikeTrans[i][j] != null) { spikeTrans[i][j] = null; } if(lastFireIndex != null) { lastFireIndex[i][j] = 0; } eventSeqStartTs[i][j] = 0; } } } motionFlowStatistics.updatePacket(countIn, countOut); return isShowRawInputEnabled() ? in : dirPacket; } @Override public synchronized void resetFilter() { super.resetFilter(); eventCounter = 0; lastTs = Integer.MIN_VALUE; if (histograms == null || histograms.length != subSizeX || histograms[0].length != subSizeY) { histograms = new int[numSlices][subSizeX][subSizeY]; } for (int[][] a : histograms) { for (int[] b : a) { Arrays.fill(b, 0); } } if (histogramsBitSet == null) { histogramsBitSet = new BitSet[numSlices]; } for(int ii = 0; ii < numSlices; ii ++) { histogramsBitSet[ii] = new BitSet(subSizeX*subSizeY); } // Initialize 3 ArrayList's histogram, every pixel has three patches: current, previous and previous-1 if(histogramsAL == null){ histogramsAL = new ArrayList[3]; } if (spikeTrans == null & subSizeX != 0 & subSizeY != 0) { spikeTrans = new ArrayList[subSizeX][subSizeY]; } int colPatchCnt = subSizeX/patchDimension; int rowPatchCnt = subSizeY/patchDimension; for(int ii = 0; ii < numSlices; ii ++) { histogramsAL[ii] = new ArrayList(); for(int jj = 0; jj < colPatchCnt*rowPatchCnt; jj ++) { int[][] patch = new int[patchDimension][patchDimension]; histogramsAL[ii].add(patch); } } tMinus2SliceIdx = 0; tMinus1SliceIdx = 1; currentSliceIdx = 2; assignSliceReferences(); sliceLastTs = 0; packetNum = 0; rewindFlg = true; } // @Override // public void annotate(GLAutoDrawable drawable) { // GL2 gl = null; // if (showTransformRectangle) { // gl = drawable.getGL().getGL2(); // } // // if (gl == null) { // return; // } // // draw transform // gl.glPushMatrix(); // // // Use this blur rectangle to indicate where is the zero point position. // gl.glColor4f(.1f, .1f, 1f, .25f); // gl.glRectf(0, 0, 10, 10); // // gl.glLineWidth(1f); // gl.glColor3f(1, 0, 0); // // if(chip != null) { // sx2 = chip.getSizeX() / 2; // sy2 = chip.getSizeY() / 2; // } else { // sx2 = 0; // sy2 = 0; // } // // translate and rotate // if(lastTransform != null) { // gl.glTranslatef(lastTransform.translationPixels.x + sx2, lastTransform.translationPixels.y + sy2, 0); // gl.glRotatef((float) ((lastTransform.rotationRad * 180) / Math.PI), 0, 0, 1); // // // draw xhairs on frame to help show locations of objects and if they have moved. // gl.glBegin(GL.GL_LINES); // sequence of individual segments, in pairs of vertices // gl.glVertex2f(0, 0); // start at origin // gl.glVertex2f(sx2, 0); // outputPacket to right // gl.glVertex2f(0, 0); // origin // gl.glVertex2f(-sx2, 0); // outputPacket to left // gl.glVertex2f(0, 0); // origin // gl.glVertex2f(0, sy2); // up // gl.glVertex2f(0, 0); // origin // gl.glVertex2f(0, -sy2); // down // gl.glEnd(); // // // rectangle around transform // gl.glTranslatef(-sx2, -sy2, 0); // lower left corner // gl.glBegin(GL.GL_LINE_LOOP); // loop of vertices // gl.glVertex2f(0, 0); // lower left corner // gl.glVertex2f(sx2 * 2, 0); // lower right // gl.glVertex2f(2 * sx2, 2 * sy2); // upper right // gl.glVertex2f(0, 2 * sy2); // upper left // gl.glVertex2f(0, 0); // back of lower left // gl.glEnd(); // gl.glPopMatrix(); // } // } @Override public void update(Observable o, Object arg) { super.update(o, arg); if (!isFilterEnabled()) { return; } if (o instanceof AEChip && chip.getNumPixels() > 0) { resetFilter(); } } /** * Computes transform using current gyro outputs based on timestamp supplied * and returns a TransformAtTime object. * * @param timestamp the timestamp in us. * @return the transform object representing the camera rotationRad */ synchronized public TransformAtTime updateTransform(IMUSample imuSample) { int timestamp = imuSample.getTimestampUs(); float dtS = (timestamp - lastImuTimestamp) * 1e-6f; lastImuTimestamp = timestamp; if (flushCounter-- >= 0) { return new TransformAtTime(ts, new Point2D.Float( (float)(0),(float)(0)), (float) (0)); // flush some samples if the timestamps have been reset and we need to discard some samples here } panRate = imuSample.getGyroYawY(); tiltRate = imuSample.getGyroTiltX(); rollRate = imuSample.getGyroRollZ(); if (calibrating) { calibrationSampleCount++; if (calibrationSampleCount > numCalibrationSamples) { calibrating = false; panOffset = panCalibrator.computeAverage(); tiltOffset = tiltCalibrator.computeAverage(); rollOffset = rollCalibrator.computeAverage(); panDC = 0; tiltDC = 0; rollDC = 0; putFloat("panOffset", panOffset); putFloat("tiltOffset", tiltOffset); putFloat("rollOffset", rollOffset); log.info(String.format("calibration finished. %d samples averaged to (pan,tilt,roll)=(%.3f,%.3f,%.3f)", numCalibrationSamples, panOffset, tiltOffset, rollOffset)); } else { panCalibrator.addSample(panRate); tiltCalibrator.addSample(tiltRate); rollCalibrator.addSample(rollRate); } return new TransformAtTime(ts, new Point2D.Float( (float)(0),(float)(0)), (float) (0)); } panDC += getPanRate() * dtS; tiltDC += getTiltRate() * dtS; rollDC += getRollRate() * dtS; if(highPassFilterEn) { panTranslationDeg = panTranslationFilter.filter(panDC, timestamp); tiltTranslationDeg = tiltTranslationFilter.filter(tiltDC, timestamp); rollDeg = rollFilter.filter(rollDC, timestamp); } else { panTranslationDeg = panDC; tiltTranslationDeg = tiltDC; rollDeg = rollDC; } float radValPerPixel = (float) Math.atan(chip.getPixelWidthUm() / (1000 * getLensFocalLengthMm())); // Use the lens focal length and camera resolution. TransformAtTime tr = new TransformAtTime(timestamp, new Point2D.Float( (float) ((Math.PI / 180) * panTranslationDeg/radValPerPixel), (float) ((Math.PI / 180) * tiltTranslationDeg/radValPerPixel)), (-rollDeg * (float) Math.PI) / 180); return tr; } private class CalibrationFilter { int count = 0; float sum = 0; void reset() { count = 0; sum = 0; } void addSample(float sample) { sum += sample; count++; } float computeAverage() { return sum / count; } } /** * @return the panRate */ public float getPanRate() { return panRate - panOffset; } /** * @return the tiltRate */ public float getTiltRate() { return tiltRate - tiltOffset; } /** * @return the rollRate */ public float getRollRate() { return rollRate - rollOffset; } /** * uses the current event to maybe rotate the slices */ private void maybeRotateSlices() { int dt = ts - sliceLastTs; switch (sliceMethod) { case ConstantDuration: if(rewindFlg) { return; } if (dt < sliceDurationUs || dt < 0) { return; } break; case ConstantEventNumber: if (eventCounter++ < sliceEventCount) { return; } case AdaptationDuration: int x = e.x; int y = e.y; if(x < patchDimension || y < patchDimension || x > subSizeX - patchDimension || y > subSizeY - patchDimension) { return; } int positionX = x%(patchDimension + 1); int positionY = y%(patchDimension + 1); int centerX = x + (patchDimension - positionX); int centerY = y + (patchDimension - positionY); int count = 0; for (int row = -patchDimension; row <= patchDimension; row ++) { BitSet tmpRow = currentSli.get((centerX - patchDimension) + (centerY + row) * subSizeX, (centerX + patchDimension) + (centerY + row) * subSizeX); count += tmpRow.cardinality(); } if(count <= (patchDimension * 2 + 1) * (patchDimension * 2 + 1) / 2) { return; } int timestamp = e.timestamp; break; } /* The index cycle is " current idx -> t1 idx -> t2 idx -> current idx". Change the index, the change should like this: next t2 = previous t1 = histogram(previous t2 idx + 1); next t1 = previous current = histogram(previous t1 idx + 1); */ currentSliceIdx = (currentSliceIdx + 1) % numSlices; tMinus1SliceIdx = (tMinus1SliceIdx + 1) % numSlices; tMinus2SliceIdx = (tMinus2SliceIdx + 1) % numSlices; sliceEventCount = 0; sliceLastTs = ts; assignSliceReferences(); } private int updateAdaptDuration() { return 1000; } private void assignSliceReferences() { currentSlice = histograms[currentSliceIdx]; tMinus1Slice = histograms[tMinus1SliceIdx]; tMinus2Slice = histograms[tMinus2SliceIdx]; currentSli = histogramsBitSet[currentSliceIdx]; tMinus1Sli = histogramsBitSet[tMinus1SliceIdx]; tMinus2Sli = histogramsBitSet[tMinus2SliceIdx]; currentSli.clear(); } /** * Accumulates the current event to the current slice */ private void accumulateEvent() { currentSlice[x][y] += e.getPolaritySignum(); currentSli.set((x + 1) + y * subSizeX); // All evnets wheather 0 or 1 will be set in the BitSet Slice. } private void clearSlice(int idx) { for (int[] a : histograms[idx]) { Arrays.fill(a, 0); } } synchronized public void doEraseGyroZero() { panOffset = 0; tiltOffset = 0; rollOffset = 0; putFloat("panOffset", 0); putFloat("tiltOffset", 0); putFloat("rollOffset", 0); log.info("calibration erased"); } synchronized public void doZeroGyro() { calibrating = true; calibrationSampleCount = 0; panCalibrator.reset(); tiltCalibrator.reset(); rollCalibrator.reset(); log.info("calibration started"); // panOffset = panRate; // TODO offsets should really be some average over some samples // tiltOffset = tiltRate; // rollOffset = rollRate; } /** * Computes hamming eight around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { int minSum = Integer.MAX_VALUE, sum = 0; SADResult sadResult = new SADResult(0, 0, 0); for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { sum = hammingDistance(x, y, dx, dy, prevSlice, curSlice); if(sum <= minSum) { minSum = sum; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSum; } } } return sadResult; } /** * computes Hamming distance centered on x,y with patch of patchSize for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private int hammingDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { int retVal = 0; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension || y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) { return Integer.MAX_VALUE; } for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) { for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) { if(curSlice.get((xx + 1) + (yy) * subSizeX) != prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX)) { retVal += 1; } } } return retVal; } /** * Computes hamming eight around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { float minSum = Integer.MAX_VALUE, sum = 0; SADResult sadResult = new SADResult(0, 0, 0); for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice); if(sum <= minSum) { minSum = sum; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSum; } } } return sadResult; } /** * computes Hamming distance centered on x,y with patch of patchSize for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { float retVal = 0; float M01 = 0, M10 = 0, M11 = 0; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension || y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) { return Integer.MAX_VALUE; } for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) { for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) { if(curSlice.get((xx + 1) + (yy) * subSizeX) == true && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == true) { M11 += 1; } if(curSlice.get((xx + 1) + (yy) * subSizeX) == true && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == false) { M01 += 1; } if(curSlice.get((xx + 1) + (yy) * subSizeX) == false && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == true) { M10 += 1; } } } if(0 == M01 + M10 + M11) { retVal = 0; } else { retVal = M11/(M01 + M10 + M11); } retVal = 1 - retVal; return retVal; } private SADResult minVicPurDistance(int blockX, int blockY) { ArrayList<Integer[]> seq1 = new ArrayList(1); SADResult sadResult = new SADResult(0, 0, 0); int size = spikeTrans[blockX][blockY].size(); int lastTs = spikeTrans[blockX][blockY].get(size - forwardEventNum)[0]; for(int i = size - forwardEventNum; i < size; i++) { seq1.add(spikeTrans[blockX][blockY].get(i)); } // if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) { // return sadResult; // } double minium = Integer.MAX_VALUE; for(int i = -1; i < 2; i++){ for(int j = -1; j < 2; j++){ // Remove the seq1 itself if(0 == i && 0 == j){ continue; } ArrayList<Integer[]> seq2 = new ArrayList(1); if(blockX >= 2 && blockY >=2) { ArrayList<Integer[]> tmpSpikes = spikeTrans[blockX + i][blockY + j]; if(tmpSpikes != null) { for(int index = 0; index < tmpSpikes.size(); index++) { if(tmpSpikes.get(index)[0] >= lastTs) { seq2.add(tmpSpikes.get(index)); } } double dis = vicPurDistance(seq1, seq2); if(dis < minium) { minium = dis; sadResult.dx = -i; sadResult.dy = -j; } } } } } lastFireIndex[blockX][blockY] = spikeTrans[blockX][blockY].size() - 1; if(sadResult.dx != 1 || sadResult.dy != 0) { // sadResult = new SADResult(0, 0, 0); } return sadResult; } private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) { int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0; Iterator itr1 = seq1.iterator(); Iterator itr2 = seq2.iterator(); int length1 = seq1.size(); int length2 = seq2.size(); double[][] distanceMatrix = new double[length1 + 1][length2 + 1]; for(int h = 0; h <= length1; h++) { for(int k = 0; k <= length2; k++) { if(h == 0) { distanceMatrix[h][k] = k; continue; } if(k == 0) { distanceMatrix[h][k] = h; continue; } double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1); double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0]; double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0]; distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + cost*Math.abs(event1 - event2)); } } while(itr1.hasNext()){ Integer[] ii = (Integer[]) itr1.next(); if(ii[1] == 1) { sum1Plus += 1; } else{ sum1Minus += 1; } } while(itr2.hasNext()){ Integer[] ii = (Integer[]) itr2.next(); if(ii[1] == 1) { sum2Plus += 1; } else{ sum2Minus += 1; } } // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus); return distanceMatrix[length1][length2]; } /** * Computes min SAD shift around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minSad(int x, int y, int[][] prevSlice, int[][] curSlice) { // for now just do exhaustive search over all shifts up to +/-searchDistance SADResult sadResult = new SADResult(0, 0, 0); int minSad = Integer.MAX_VALUE, minDx = 0, minDy = 0; for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { int sad = sad(x, y, dx, dy, prevSlice, curSlice); if (sad <= minSad) { minSad = sad; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSad; } } } return sadResult; } /** * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param dx * @param dy * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private int sad(int x, int y, int dx, int dy, int[][] prevSlice, int[][] curSlice) { // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension || y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) { return Integer.MAX_VALUE; } int sad = 0; for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) { for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) { int d = curSlice[xx][yy] - prevSlice[xx - dx][yy - dy]; if (d <= 0) { d = -d; } sad += d; } } return sad; } //This uses fewer arithmetic operations than any other known //implementation on machines with fast multiplication. //It uses 12 arithmetic operations, one of which is a multiply. public long popcount_3(long x) { x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits return (x * h01)>>56; //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ... } private class SADResult { float dx, dy; float sadValue; public SADResult(float dx, float dy, float sadValue) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } @Override public String toString() { return String.format("dx,dy=%d,%5 SAD=%d",dx,dy,sadValue); } } /** * @return the patchDimension */ public int getPatchDimension() { return patchDimension; } /** * @param patchDimension the patchDimension to set */ public void setPatchDimension(int patchDimension) { this.patchDimension = patchDimension; putInt("patchDimension", patchDimension); } public int getEventPatchDimension() { return eventPatchDimension; } public void setEventPatchDimension(int eventPatchDimension) { this.eventPatchDimension = eventPatchDimension; putInt("eventPatchDimension", eventPatchDimension); } public int getForwardEventNum() { return forwardEventNum; } public void setForwardEventNum(int forwardEventNum) { this.forwardEventNum = forwardEventNum; putInt("forwardEventNum", forwardEventNum); } public float getCost() { return cost; } public void setCost(float cost) { this.cost = cost; putFloat("cost", cost); } public int getThresholdTime() { return thresholdTime; } public void setThresholdTime(int thresholdTime) { this.thresholdTime = thresholdTime; putInt("thresholdTime", thresholdTime); } /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ public void setSliceMethod(SliceMethod sliceMethod) { this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); } public PatchCompareMethod getPatchCompareMethod() { return patchCompareMethod; } public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) { this.patchCompareMethod = patchCompareMethod; putString("patchCompareMethod", patchCompareMethod.toString()); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { this.sliceDurationUs = sliceDurationUs; putInt("sliceDurationUs", sliceDurationUs); } public boolean isShowTransformRectangle() { return showTransformRectangle; } public void setShowTransformRectangle(boolean showTransformRectangle) { this.showTransformRectangle = showTransformRectangle; } public boolean isRemoveCameraMotion() { return removeCameraMotion; } public void setRemoveCameraMotion(boolean removeCameraMotion) { this.removeCameraMotion = removeCameraMotion; } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); } public float getHighpassTauMsTranslation() { return highpassTauMsTranslation; } public void setHighpassTauMsTranslation(float highpassTauMs) { this.highpassTauMsTranslation = highpassTauMs; putFloat("highpassTauMsTranslation", highpassTauMs); panTranslationFilter.setTauMs(highpassTauMs); tiltTranslationFilter.setTauMs(highpassTauMs); } public float getHighpassTauMsRotation() { return highpassTauMsRotation; } public void setHighpassTauMsRotation(float highpassTauMs) { this.highpassTauMsRotation = highpassTauMs; putFloat("highpassTauMsRotation", highpassTauMs); rollFilter.setTauMs(highpassTauMs); } public boolean isHighPassFilterEn() { return highPassFilterEn; } public void setHighPassFilterEn(boolean highPassFilterEn) { this.highPassFilterEn = highPassFilterEn; putBoolean("highPassFilterEn", highPassFilterEn); } public boolean isMeasurePerformance() { return measurePerformance; } public void setMeasurePerformance(boolean measurePerformance) { this.measurePerformance = measurePerformance; putBoolean("measurePerformance", measurePerformance); } public boolean isDisplayOutputVectors() { return displayOutputVectors; } public void setDisplayOutputVectors(boolean displayOutputVectors) { this.displayOutputVectors = displayOutputVectors; putBoolean("displayOutputVectors", measurePerformance); } }
Fixed the problem that setAccuracy can't run normally. git-svn-id: fe6b3b33f0410f5f719dcd9e0c58b92353e7a5d3@9227 b7f4320f-462c-0410-a916-d9f35bb82d52
src/ch/unizh/ini/jaer/projects/minliu/PatchMatchFlow.java
Fixed the problem that setAccuracy can't run normally.
<ide><path>rc/ch/unizh/ini/jaer/projects/minliu/PatchMatchFlow.java <ide> // There're enough events fire on the specific block now. <ide> if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { <ide> lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; <del> result = minHammingDistance(x, y, tMinus2Sli, tMinus1Sli); <add> result = minHammingDistance(x, y, tMinus2Sli, tMinus1Sli); <add> result.dx = result.dx/sliceDurationUs * 1000000; <add> result.dy = result.dy/sliceDurationUs * 1000000; <ide> } <ide> <ide> break; <ide> if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { <ide> lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; <ide> result = minSad(x, y, tMinus2Slice, tMinus1Slice); <add> result.dx = result.dx/sliceDurationUs * 1000000; <add> result.dy = result.dy/sliceDurationUs * 1000000; <add> <ide> } <ide> break; <ide> case JaccardDistance: <ide> if(spikeTrans[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY] >= forwardEventNum ) { <ide> lastFireIndex[blockLocX][blockLocY] = spikeTrans[blockLocX][blockLocY].size() - 1; <ide> result = minJaccardDistance(x, y, tMinus2Sli, tMinus1Sli); <add> result.dx = result.dx/sliceDurationUs * 1000000; <add> result.dy = result.dy/sliceDurationUs * 1000000; <ide> } <ide> break; <ide> case EventSqeDistance: <ide> } <ide> break; <ide> } <del> vx = result.dx * 5; <del> vy = result.dy * 5; <add> vx = result.dx; <add> vy = result.dy; <ide> v = (float) Math.sqrt(vx * vx + vy * vy); <ide> <ide> if (measurePerformance) { <ide> if (spikeTrans == null & subSizeX != 0 & subSizeY != 0) { <ide> spikeTrans = new ArrayList[subSizeX][subSizeY]; <ide> } <del> <del> int colPatchCnt = subSizeX/patchDimension; <del> int rowPatchCnt = subSizeY/patchDimension; <del> <del> for(int ii = 0; ii < numSlices; ii ++) { <del> histogramsAL[ii] = new ArrayList(); <del> for(int jj = 0; jj < colPatchCnt*rowPatchCnt; jj ++) { <del> int[][] patch = new int[patchDimension][patchDimension]; <del> histogramsAL[ii].add(patch); <del> } <del> } <add> if(patchDimension != 0) { <add> int colPatchCnt = subSizeX/patchDimension; <add> int rowPatchCnt = subSizeY/patchDimension; <add> <add> for(int ii = 0; ii < numSlices; ii ++) { <add> histogramsAL[ii] = new ArrayList(); <add> for(int jj = 0; jj < colPatchCnt*rowPatchCnt; jj ++) { <add> int[][] patch = new int[patchDimension][patchDimension]; <add> histogramsAL[ii].add(patch); <add> } <add> } <add> } <add> <ide> <ide> tMinus2SliceIdx = 0; <ide> tMinus1SliceIdx = 1; <ide> currentSliceIdx = 2; <del> assignSliceReferences(); <add> if(histograms.length != 0) { <add> assignSliceReferences(); <add> } <ide> <ide> sliceLastTs = 0; <ide> packetNum = 0; <ide> rewindFlg = true; <ide> } <del> <del>// @Override <del>// public void annotate(GLAutoDrawable drawable) { <del>// GL2 gl = null; <del>// if (showTransformRectangle) { <del>// gl = drawable.getGL().getGL2(); <del>// } <del>// <del>// if (gl == null) { <del>// return; <del>// } <del>// // draw transform <del>// gl.glPushMatrix(); <del>// <del>// // Use this blur rectangle to indicate where is the zero point position. <del>// gl.glColor4f(.1f, .1f, 1f, .25f); <del>// gl.glRectf(0, 0, 10, 10); <del>// <del>// gl.glLineWidth(1f); <del>// gl.glColor3f(1, 0, 0); <del>// <del>// if(chip != null) { <del>// sx2 = chip.getSizeX() / 2; <del>// sy2 = chip.getSizeY() / 2; <del>// } else { <del>// sx2 = 0; <del>// sy2 = 0; <del>// } <del>// // translate and rotate <del>// if(lastTransform != null) { <del>// gl.glTranslatef(lastTransform.translationPixels.x + sx2, lastTransform.translationPixels.y + sy2, 0); <del>// gl.glRotatef((float) ((lastTransform.rotationRad * 180) / Math.PI), 0, 0, 1); <del>// <del>// // draw xhairs on frame to help show locations of objects and if they have moved. <del>// gl.glBegin(GL.GL_LINES); // sequence of individual segments, in pairs of vertices <del>// gl.glVertex2f(0, 0); // start at origin <del>// gl.glVertex2f(sx2, 0); // outputPacket to right <del>// gl.glVertex2f(0, 0); // origin <del>// gl.glVertex2f(-sx2, 0); // outputPacket to left <del>// gl.glVertex2f(0, 0); // origin <del>// gl.glVertex2f(0, sy2); // up <del>// gl.glVertex2f(0, 0); // origin <del>// gl.glVertex2f(0, -sy2); // down <del>// gl.glEnd(); <del>// <del>// // rectangle around transform <del>// gl.glTranslatef(-sx2, -sy2, 0); // lower left corner <del>// gl.glBegin(GL.GL_LINE_LOOP); // loop of vertices <del>// gl.glVertex2f(0, 0); // lower left corner <del>// gl.glVertex2f(sx2 * 2, 0); // lower right <del>// gl.glVertex2f(2 * sx2, 2 * sy2); // upper right <del>// gl.glVertex2f(0, 2 * sy2); // upper left <del>// gl.glVertex2f(0, 0); // back of lower left <del>// gl.glEnd(); <del>// gl.glPopMatrix(); <del>// } <del>// } <ide> <ide> @Override <ide> public void update(Observable o, Object arg) {
Java
bsd-3-clause
f25aa3b5c1734bd05764df7e3fa6e236a46dfd67
0
exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.experience; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import javax.inject.Inject; import com.amplitude.api.Amplitude; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactRootView; import org.json.JSONException; import org.json.JSONObject; import de.greenrobot.event.EventBus; import host.exp.exponent.analytics.Analytics; import host.exp.exponent.Constants; import host.exp.exponent.LauncherActivity; import host.exp.exponent.di.NativeModuleDepsProvider; import host.exp.expoview.Exponent; import host.exp.expoview.R; import host.exp.exponent.analytics.EXL; import host.exp.exponent.kernel.Kernel; import host.exp.exponent.storage.ExponentSharedPreferences; import host.exp.exponent.utils.JSONBundleConverter; public class ErrorActivity extends MultipleVersionReactNativeActivity { private static final String TAG = ErrorActivity.class.getSimpleName(); public static final String IS_HOME_KEY = "isHome"; public static final String MANIFEST_URL_KEY = "manifestUrl"; public static final String USER_ERROR_MESSAGE_KEY = "userErrorMessage"; public static final String DEVELOPER_ERROR_MESSAGE_KEY = "developerErrorMessage"; public static final String DEBUG_MODE_KEY = "isDebugModeEnabled"; private static final String ERROR_MODULE_NAME = "ErrorScreenApp"; private static ErrorActivity sVisibleActivity; TextView mErrorMessageView; View mHomeButton; ImageButton mReloadButton; private boolean mShouldShowJSErrorScreen; private String mManifestUrl; private ReactRootView mReactRootView; private String mUserErrorMessage; private String mDeveloperErrorMessage; private String mDefaultErrorMessage; private boolean mIsShellApp; @Inject Kernel mKernel; public static ErrorActivity getVisibleActivity() { return sVisibleActivity; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mShouldDestroyRNInstanceOnExit = false; setContentView(R.layout.error_activity); mErrorMessageView = (TextView) findViewById(R.id.error_message); mHomeButton = findViewById(R.id.home_button); mReloadButton = (ImageButton) findViewById(R.id.reload_button); mHomeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickHome(); } }); mReloadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickReload(); } }); NativeModuleDepsProvider.getInstance().inject(ErrorActivity.class, this); ExperienceActivity.removeNotification(this); Bundle bundle = getIntent().getExtras(); mUserErrorMessage = bundle.getString(USER_ERROR_MESSAGE_KEY); mDeveloperErrorMessage = bundle.getString(DEVELOPER_ERROR_MESSAGE_KEY); mDefaultErrorMessage = mUserErrorMessage; if (mDefaultErrorMessage == null || mDefaultErrorMessage.length() == 0) { mDefaultErrorMessage = mDeveloperErrorMessage; } Boolean isDebugModeEnabled = bundle.getBoolean(DEBUG_MODE_KEY); mManifestUrl = bundle.getString(MANIFEST_URL_KEY); boolean isHomeError = bundle.getBoolean(IS_HOME_KEY, false); mIsShellApp = mManifestUrl != null && mManifestUrl.equals(Constants.INITIAL_URL); mShouldShowJSErrorScreen = mKernel.isRunning(); try { JSONObject eventProperties = new JSONObject(); eventProperties.put(Analytics.USER_ERROR_MESSAGE, mUserErrorMessage); eventProperties.put(Analytics.DEVELOPER_ERROR_MESSAGE, mDeveloperErrorMessage); eventProperties.put(Analytics.MANIFEST_URL, mManifestUrl); Amplitude.getInstance().logEvent(Analytics.ERROR_SCREEN, eventProperties); } catch (Exception e) { EXL.e(TAG, e.getMessage()); } if (isHomeError || mManifestUrl == null || mManifestUrl.equals(Constants.INITIAL_URL)) { // Kernel is probably dead. mHomeButton.setVisibility(View.GONE); mErrorMessageView.setText(mDefaultErrorMessage); } else { if (mShouldShowJSErrorScreen) { // Show JS error screen. if (!isDebugModeEnabled) { mErrorMessageView.setText(this.getString(R.string.error_unable_to_load_experience)); } } else { mErrorMessageView.setText(mDefaultErrorMessage); } } EventBus.getDefault().registerSticky(this); EXL.e(TAG, "ErrorActivity message: " + mDefaultErrorMessage); if (!mKernel.isStarted()) { // Might not be started if the Experience crashed immediately. // ONLY start it if it hasn't been started already, don't want to retry immediately // if there was an error in the kernel. mKernel.startJSKernel(); } } @Override protected void onResume() { super.onResume(); sVisibleActivity = this; Analytics.logEventWithManifestUrl(Analytics.ERROR_APPEARED, mManifestUrl); } @Override protected void onPause() { super.onPause(); if (sVisibleActivity == this) { sVisibleActivity = null; } } public void onEventMainThread(Kernel.KernelStartedRunningEvent event) { if (!mKernel.isRunning()) { return; } JSONObject props = new JSONObject(); try { props.put("isShellApp", mIsShellApp); props.put("userErrorMessage", mUserErrorMessage); props.put("developerErrorMessage", mDeveloperErrorMessage); } catch (JSONException e) { EXL.e(TAG, e); } Bundle bundle = JSONBundleConverter.JSONToBundle(props); mReactInstanceManager.assign(mKernel.getReactInstanceManager()); mReactRootView = new ReactRootView(this); mReactRootView.startReactApplication( (ReactInstanceManager) mReactInstanceManager.get(), ERROR_MODULE_NAME, bundle ); mReactInstanceManager.onHostResume(this, this); setContentView(mReactRootView); } @Override public void onBackPressed() { if (mReactInstanceManager.isNotNull() && !mIsCrashed) { mReactInstanceManager.call("onBackPressed"); } else { mKernel.killActivityStack(this); } } @Override public void invokeDefaultOnBackPressed() { mKernel.killActivityStack(this); } public void onClickHome() { if (!mKernel.isRunning()) { mKernel.reloadJSBundle(); } Intent intent = new Intent(this, LauncherActivity.class); startActivity(intent); // Mark as not visible so that any new errors go to a new activity. if (sVisibleActivity == this) { sVisibleActivity = null; } mKernel.killActivityStack(this); } public void onClickReload() { if (!mKernel.isRunning()) { mKernel.reloadJSBundle(); } if (mManifestUrl != null) { // Mark as not visible so that any new errors go to a new activity. if (sVisibleActivity == this) { sVisibleActivity = null; } mKernel.killActivityStack(this); mKernel.reloadVisibleExperience(mManifestUrl); } else { // Mark as not visible so that any new errors go to a new activity. if (sVisibleActivity == this) { sVisibleActivity = null; } finish(); } } }
android/expoview/src/main/java/host/exp/exponent/experience/ErrorActivity.java
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.experience; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import javax.inject.Inject; import com.amplitude.api.Amplitude; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactRootView; import org.json.JSONException; import org.json.JSONObject; import de.greenrobot.event.EventBus; import host.exp.exponent.analytics.Analytics; import host.exp.exponent.Constants; import host.exp.exponent.LauncherActivity; import host.exp.exponent.di.NativeModuleDepsProvider; import host.exp.expoview.Exponent; import host.exp.expoview.R; import host.exp.exponent.analytics.EXL; import host.exp.exponent.kernel.Kernel; import host.exp.exponent.storage.ExponentSharedPreferences; import host.exp.exponent.utils.JSONBundleConverter; public class ErrorActivity extends MultipleVersionReactNativeActivity { private static final String TAG = ErrorActivity.class.getSimpleName(); public static final String IS_HOME_KEY = "isHome"; public static final String MANIFEST_URL_KEY = "manifestUrl"; public static final String USER_ERROR_MESSAGE_KEY = "userErrorMessage"; public static final String DEVELOPER_ERROR_MESSAGE_KEY = "developerErrorMessage"; public static final String DEBUG_MODE_KEY = "isDebugModeEnabled"; private static final String ERROR_MODULE_NAME = "ErrorScreenApp"; private static ErrorActivity sVisibleActivity; TextView mErrorMessageView; View mHomeButton; ImageButton mReloadButton; private boolean mShouldShowJSErrorScreen; private String mManifestUrl; private ReactRootView mReactRootView; private String mUserErrorMessage; private String mDeveloperErrorMessage; private String mDefaultErrorMessage; private boolean mIsShellApp; @Inject Kernel mKernel; public static ErrorActivity getVisibleActivity() { return sVisibleActivity; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mShouldDestroyRNInstanceOnExit = false; setContentView(R.layout.error_activity); mErrorMessageView = (TextView) findViewById(R.id.error_message); mHomeButton = findViewById(R.id.home_button); mReloadButton = (ImageButton) findViewById(R.id.reload_button); mHomeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickHome(); } }); mReloadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickReload(); } }); NativeModuleDepsProvider.getInstance().inject(ErrorActivity.class, this); ExperienceActivity.removeNotification(this); Bundle bundle = getIntent().getExtras(); mUserErrorMessage = bundle.getString(USER_ERROR_MESSAGE_KEY); mDeveloperErrorMessage = bundle.getString(DEVELOPER_ERROR_MESSAGE_KEY); mDefaultErrorMessage = mUserErrorMessage; if (mDefaultErrorMessage == null || mDefaultErrorMessage.length() == 0) { mDefaultErrorMessage = mDeveloperErrorMessage; } Boolean isDebugModeEnabled = bundle.getBoolean(DEBUG_MODE_KEY); mManifestUrl = bundle.getString(MANIFEST_URL_KEY); boolean isHomeError = bundle.getBoolean(IS_HOME_KEY, false); mIsShellApp = mManifestUrl != null && mManifestUrl.equals(Constants.INITIAL_URL); mShouldShowJSErrorScreen = mKernel.isRunning(); try { JSONObject eventProperties = new JSONObject(); eventProperties.put(Analytics.USER_ERROR_MESSAGE, mUserErrorMessage); eventProperties.put(Analytics.DEVELOPER_ERROR_MESSAGE, mDeveloperErrorMessage); eventProperties.put(Analytics.MANIFEST_URL, mManifestUrl); Amplitude.getInstance().logEvent(Analytics.ERROR_SCREEN, eventProperties); } catch (Exception e) { EXL.e(TAG, e.getMessage()); } if (isHomeError || mManifestUrl == null || mManifestUrl.equals(Constants.INITIAL_URL)) { // Kernel is probably dead. mHomeButton.setVisibility(View.GONE); mErrorMessageView.setText(mDefaultErrorMessage); } else { if (mShouldShowJSErrorScreen) { // Show JS error screen. if (!isDebugModeEnabled) { mErrorMessageView.setText(this.getString(R.string.error_unable_to_load_experience)); } } else { mErrorMessageView.setText(mDefaultErrorMessage); } } EventBus.getDefault().registerSticky(this); EXL.e(TAG, "ErrorActivity message: " + mDefaultErrorMessage); if (!mKernel.isStarted()) { // Might not be started if the Experience crashed immediately. // ONLY start it if it hasn't been started already, don't want to retry immediately // if there was an error in the kernel. mKernel.startJSKernel(); } } @Override protected void onResume() { super.onResume(); sVisibleActivity = this; Analytics.logEventWithManifestUrl(Analytics.ERROR_APPEARED, mManifestUrl); } @Override protected void onPause() { super.onPause(); if (sVisibleActivity == this) { sVisibleActivity = null; } } public void onEventMainThread(Kernel.KernelStartedRunningEvent event) { if (!mKernel.isRunning()) { return; } JSONObject props = new JSONObject(); try { props.put("isShellApp", mIsShellApp); props.put("userErrorMessage", mUserErrorMessage); props.put("developerErrorMessage", mDeveloperErrorMessage); } catch (JSONException e) { EXL.e(TAG, e); } Bundle bundle = JSONBundleConverter.JSONToBundle(props); mReactInstanceManager.assign(mKernel.getReactInstanceManager()); mReactRootView = new ReactRootView(this); mReactRootView.startReactApplication( (ReactInstanceManager) mReactInstanceManager.get(), ERROR_MODULE_NAME, bundle ); mReactInstanceManager.onHostResume(this, this); setContentView(mReactRootView); } @Override public void onBackPressed() { if (mReactInstanceManager.isNotNull() && !mIsCrashed) { mReactInstanceManager.call("onBackPressed"); } else { mKernel.killActivityStack(this); } } @Override public void invokeDefaultOnBackPressed() { mKernel.killActivityStack(this); } public void onClickHome() { if (!mKernel.isRunning()) { mKernel.reloadJSBundle(); } Intent intent = new Intent(this, LauncherActivity.class); startActivity(intent); // Mark as not visible so that any new errors go to a new activity. if (sVisibleActivity == this) { sVisibleActivity = null; } mKernel.killActivityStack(this); } public void onClickReload() { if (!mKernel.isRunning()) { mKernel.reloadJSBundle(); } if (mManifestUrl != null) { mKernel.reloadVisibleExperience(mManifestUrl); // Mark as not visible so that any new errors go to a new activity. if (sVisibleActivity == this) { sVisibleActivity = null; } mKernel.killActivityStack(this); } else { // Mark as not visible so that any new errors go to a new activity. if (sVisibleActivity == this) { sVisibleActivity = null; } finish(); } } }
fix timing issue with reloading from error on android fbshipit-source-id: 3d33a44
android/expoview/src/main/java/host/exp/exponent/experience/ErrorActivity.java
fix timing issue with reloading from error on android
<ide><path>ndroid/expoview/src/main/java/host/exp/exponent/experience/ErrorActivity.java <ide> } <ide> <ide> if (mManifestUrl != null) { <del> mKernel.reloadVisibleExperience(mManifestUrl); <del> <ide> // Mark as not visible so that any new errors go to a new activity. <ide> if (sVisibleActivity == this) { <ide> sVisibleActivity = null; <ide> } <ide> <ide> mKernel.killActivityStack(this); <add> mKernel.reloadVisibleExperience(mManifestUrl); <ide> } else { <ide> // Mark as not visible so that any new errors go to a new activity. <ide> if (sVisibleActivity == this) {
Java
apache-2.0
156fa09288f583ddb6f3e38a4a84da184e54bdd2
0
javers/javers,javers/javers
package org.javers.spring.boot.sql; import org.hibernate.SessionFactory; import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.javers.common.exception.JaversException; import org.javers.common.reflection.ReflectionUtil; import org.javers.core.Javers; import org.javers.hibernate.integration.HibernateUnproxyObjectAccessHook; import org.javers.repository.sql.ConnectionProvider; import org.javers.repository.sql.DialectName; import org.javers.repository.sql.JaversSqlRepository; import org.javers.repository.sql.SqlRepositoryBuilder; import org.javers.spring.auditable.*; import org.javers.spring.auditable.aspect.JaversAuditableAspect; import org.javers.spring.auditable.aspect.springdatajpa.JaversSpringDataJpaAuditableRepositoryAspect; import org.javers.spring.jpa.JpaHibernateConnectionProvider; import org.javers.spring.jpa.TransactionalJaversBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.transaction.PlatformTransactionManager; import javax.persistence.EntityManagerFactory; /** * @author pawelszymczyk */ @Configuration @EnableAspectJAutoProxy @EnableConfigurationProperties(value = {JaversSqlProperties.class, JpaProperties.class}) @AutoConfigureAfter(HibernateJpaAutoConfiguration.class) public class JaversSqlAutoConfiguration { private static final Logger logger = LoggerFactory.getLogger(JaversSqlAutoConfiguration.class); private final DialectMapper dialectMapper = new DialectMapper(); @Autowired private JaversSqlProperties javersSqlProperties; @Autowired private EntityManagerFactory entityManagerFactory; @Bean public DialectName javersSqlDialectName() { SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) entityManagerFactory.unwrap(SessionFactory.class); Dialect hibernateDialect = sessionFactory.getDialect(); logger.info("detected Hibernate dialect: " + hibernateDialect.getClass().getSimpleName()); return dialectMapper.map(hibernateDialect); } @Bean(name = "JaversSqlRepositoryFromStarter") @ConditionalOnMissingBean public JaversSqlRepository javersSqlRepository(ConnectionProvider connectionProvider) { return SqlRepositoryBuilder .sqlRepository() .withSchema(javersSqlProperties.getSqlSchema()) .withConnectionProvider(connectionProvider) .withDialect(javersSqlDialectName()) .withSchemaManagementEnabled(javersSqlProperties.isSqlSchemaManagementEnabled()) .build(); } @Bean(name = "JaversFromStarter") @ConditionalOnMissingBean public Javers javers(JaversSqlRepository sqlRepository, PlatformTransactionManager transactionManager) { final HibernateUnproxyObjectAccessHook objectAccessHook = createClassObject(javersSqlProperties.getObjectAccessHook()); return TransactionalJaversBuilder .javers() .withTxManager(transactionManager) .registerJaversRepository(sqlRepository) .withObjectAccessHook(objectAccessHook) .withProperties(javersSqlProperties) .build(); } private HibernateUnproxyObjectAccessHook createClassObject(String accessHookClassName) { try { final Class<?> aClass = ReflectionUtil.classForName(accessHookClassName); return (HibernateUnproxyObjectAccessHook) aClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new JaversException(e); } } @Bean(name = "SpringSecurityAuthorProvider") @ConditionalOnMissingBean @ConditionalOnClass(name = {"org.springframework.security.core.context.SecurityContextHolder"}) public AuthorProvider springSecurityAuthorProvider() { return new SpringSecurityAuthorProvider(); } @Bean(name = "MockAuthorProvider") @ConditionalOnMissingBean @ConditionalOnMissingClass({"org.springframework.security.core.context.SecurityContextHolder"}) public AuthorProvider unknownAuthorProvider() { return new MockAuthorProvider(); } @Bean(name = "EmptyPropertiesProvider") @ConditionalOnMissingBean public CommitPropertiesProvider commitPropertiesProvider() { return new EmptyPropertiesProvider(); } @Bean(name = "JpaHibernateConnectionProvider") @ConditionalOnMissingBean public ConnectionProvider jpaConnectionProvider() { return new JpaHibernateConnectionProvider(); } @Bean @ConditionalOnProperty(name = "javers.auditableAspectEnabled", havingValue = "true", matchIfMissing = true) public JaversAuditableAspect javersAuditableAspect(Javers javers, AuthorProvider authorProvider, CommitPropertiesProvider commitPropertiesProvider) { return new JaversAuditableAspect(javers, authorProvider, commitPropertiesProvider); } @Bean @ConditionalOnProperty(name = "javers.springDataAuditableRepositoryAspectEnabled", havingValue = "true", matchIfMissing = true) public JaversSpringDataJpaAuditableRepositoryAspect javersSpringDataAuditableAspect(Javers javers, AuthorProvider authorProvider, CommitPropertiesProvider commitPropertiesProvider) { return new JaversSpringDataJpaAuditableRepositoryAspect(javers, authorProvider, commitPropertiesProvider); } }
javers-spring-boot-starter-sql/src/main/java/org/javers/spring/boot/sql/JaversSqlAutoConfiguration.java
package org.javers.spring.boot.sql; import org.hibernate.SessionFactory; import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.javers.common.exception.JaversException; import org.javers.common.reflection.ReflectionUtil; import org.javers.core.Javers; import org.javers.hibernate.integration.HibernateUnproxyObjectAccessHook; import org.javers.repository.sql.ConnectionProvider; import org.javers.repository.sql.DialectName; import org.javers.repository.sql.JaversSqlRepository; import org.javers.repository.sql.SqlRepositoryBuilder; import org.javers.spring.auditable.*; import org.javers.spring.auditable.aspect.JaversAuditableAspect; import org.javers.spring.auditable.aspect.springdatajpa.JaversSpringDataJpaAuditableRepositoryAspect; import org.javers.spring.jpa.JpaHibernateConnectionProvider; import org.javers.spring.jpa.TransactionalJaversBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.transaction.PlatformTransactionManager; import javax.persistence.EntityManagerFactory; /** * @author pawelszymczyk */ @Configuration @EnableAspectJAutoProxy @EnableConfigurationProperties(value = {JaversSqlProperties.class, JpaProperties.class}) @AutoConfigureAfter(HibernateJpaAutoConfiguration.class) public class JaversSqlAutoConfiguration { private static final Logger logger = LoggerFactory.getLogger(JaversSqlAutoConfiguration.class); private final DialectMapper dialectMapper = new DialectMapper(); @Autowired private JaversSqlProperties javersSqlProperties; @Autowired private EntityManagerFactory entityManagerFactory; @Bean public DialectName javersSqlDialectName() { SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) entityManagerFactory.unwrap(SessionFactory.class); Dialect hibernateDialect = sessionFactory.getDialect(); logger.info("detected Hibernate dialect: " + hibernateDialect.getClass().getSimpleName()); return dialectMapper.map(hibernateDialect); } @Bean(name = "JaversSqlRepositoryFromStarter") @ConditionalOnMissingBean public JaversSqlRepository javersSqlRepository(ConnectionProvider connectionProvider) { return SqlRepositoryBuilder .sqlRepository() .withSchema(javersSqlProperties.getSqlSchema()) .withConnectionProvider(connectionProvider) .withDialect(javersSqlDialectName()) .withSchemaManagementEnabled(javersSqlProperties.isSqlSchemaManagementEnabled()) .build(); } @Bean(name = "JaversFromStarter") @ConditionalOnMissingBean public Javers javers(JaversSqlRepository sqlRepository, PlatformTransactionManager transactionManager) { final HibernateUnproxyObjectAccessHook objectAccessHook = createClassObject(javersSqlProperties.getObjectAccessHook()); return TransactionalJaversBuilder .javers() .withTxManager(transactionManager) .registerJaversRepository(sqlRepository) .withObjectAccessHook(objectAccessHook) .withProperties(javersSqlProperties) .build(); } private HibernateUnproxyObjectAccessHook createClassObject(String accessHookClassName) { try { final Class<?> aClass = ReflectionUtil.classForName(accessHookClassName); return (HibernateUnproxyObjectAccessHook) aClass.newInstance(); } catch (Exception e) { throw new JaversException(e); } } @Bean(name = "SpringSecurityAuthorProvider") @ConditionalOnMissingBean @ConditionalOnClass(name = {"org.springframework.security.core.context.SecurityContextHolder"}) public AuthorProvider springSecurityAuthorProvider() { return new SpringSecurityAuthorProvider(); } @Bean(name = "MockAuthorProvider") @ConditionalOnMissingBean @ConditionalOnMissingClass({"org.springframework.security.core.context.SecurityContextHolder"}) public AuthorProvider unknownAuthorProvider() { return new MockAuthorProvider(); } @Bean(name = "EmptyPropertiesProvider") @ConditionalOnMissingBean public CommitPropertiesProvider commitPropertiesProvider() { return new EmptyPropertiesProvider(); } @Bean(name = "JpaHibernateConnectionProvider") @ConditionalOnMissingBean public ConnectionProvider jpaConnectionProvider() { return new JpaHibernateConnectionProvider(); } @Bean @ConditionalOnProperty(name = "javers.auditableAspectEnabled", havingValue = "true", matchIfMissing = true) public JaversAuditableAspect javersAuditableAspect(Javers javers, AuthorProvider authorProvider, CommitPropertiesProvider commitPropertiesProvider) { return new JaversAuditableAspect(javers, authorProvider, commitPropertiesProvider); } @Bean @ConditionalOnProperty(name = "javers.springDataAuditableRepositoryAspectEnabled", havingValue = "true", matchIfMissing = true) public JaversSpringDataJpaAuditableRepositoryAspect javersSpringDataAuditableAspect(Javers javers, AuthorProvider authorProvider, CommitPropertiesProvider commitPropertiesProvider) { return new JaversSpringDataJpaAuditableRepositoryAspect(javers, authorProvider, commitPropertiesProvider); } }
https://github.com/javers/javers/issues/708 - small fix for creating class instance
javers-spring-boot-starter-sql/src/main/java/org/javers/spring/boot/sql/JaversSqlAutoConfiguration.java
https://github.com/javers/javers/issues/708 - small fix for creating class instance
<ide><path>avers-spring-boot-starter-sql/src/main/java/org/javers/spring/boot/sql/JaversSqlAutoConfiguration.java <ide> private HibernateUnproxyObjectAccessHook createClassObject(String accessHookClassName) { <ide> try { <ide> final Class<?> aClass = ReflectionUtil.classForName(accessHookClassName); <del> return (HibernateUnproxyObjectAccessHook) aClass.newInstance(); <add> return (HibernateUnproxyObjectAccessHook) aClass.getDeclaredConstructor().newInstance(); <ide> } catch (Exception e) { <ide> throw new JaversException(e); <ide> }
Java
apache-2.0
a94189cd8984c3971d405422460a6216566cbdae
0
apache/commons-imaging,apache/commons-imaging
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.imaging.formats.tiff; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.imaging.ImageFormats; import org.apache.commons.imaging.ImageReadException; import org.apache.commons.imaging.ImageWriteException; import org.apache.commons.imaging.Imaging; import org.apache.commons.imaging.formats.tiff.constants.TiffConstants; import org.junit.jupiter.api.Test; public class TiffSubImageTest extends TiffBaseTest { final List<File> imageFileList; TiffSubImageTest() throws IOException, ImageReadException{ imageFileList = getTiffImages(); } @Test public void testSubImage() throws ImageReadException, ImageWriteException, IOException { final BufferedImage src = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); final byte[] imageBytes = Imaging.writeImageToBytes(src, ImageFormats.TIFF, null); final Map<String, Object> params = new TreeMap<>(); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, 0); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, 0); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, 2); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, 3); final BufferedImage image = Imaging.getBufferedImage(imageBytes, params); assertEquals(image.getWidth(), 2); assertEquals(image.getHeight(), 3); } @Test public void testBadSubImage() throws ImageReadException, IOException{ File target = imageFileList.get(0); final BufferedImage referenceImage = Imaging.getBufferedImage(target); int width = referenceImage.getWidth(); int height = referenceImage.getHeight(); final Map<String, Object> params = new HashMap<>(); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, 0); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, 0); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, width); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, height); BufferedImage image = Imaging.getBufferedImage(target, params); assertEquals(image.getWidth(), width, "Improper width when sub-imaging entire image"); assertEquals(image.getHeight(), height, "Improper height when sub-imaging entire image"); processBadParams(target, -1, 0, width, height, "negative x position"); processBadParams(target, 0, -1, width, height, "negative y position"); processBadParams(target, 0, 0, 0, height, "zero width"); processBadParams(target, 0, 0, width, 0, "zero height"); processBadParams(target, 1, 0, width, height, "sub-image width extends beyond bounds"); processBadParams(target, 0, 1, width, height, "sub-image height extends beyond bounds"); } private void processBadParams(File target, int x, int y, int width, int height, String comment) throws IOException{ try{ final Map<String, Object> params = new HashMap<>(); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, x); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, y); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, width); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, height); BufferedImage image = Imaging.getBufferedImage(target, params); fail("Reading TIFF sub-image failed to detect bad parameter: "+comment); }catch(ImageReadException ire){ // the test passed } } @Test public void testSubImageCorrectness() throws ImageReadException, IOException { for(File target: imageFileList){ final BufferedImage referenceImage = Imaging.getBufferedImage(target); int rW = referenceImage.getWidth(); int rH = referenceImage.getHeight(); if(rW<3 || rH<3){ continue; } int []rArgb = new int[rW*rH]; referenceImage.getRGB(0, 0, rW, rH, rArgb, 0, rW); final Map<String, Object> params = new HashMap<>(); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, 1); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, 1); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, rW-2); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, rH-2); BufferedImage image = Imaging.getBufferedImage(target, params); int iW = image.getWidth(); int iH = image.getHeight(); assertEquals(iW, rW-2, "Invalid subimage width"); assertEquals(iH, rH-2, "Invalid subimage height"); int []iArgb= new int[iW*iH]; image.getRGB(0, 0, iW, iH, iArgb, 0, iW); for(int i=0; i<iH; i++){ for(int j=0; j<iW; j++){ int rTest = rArgb[(i+1)*rW+j+1]; int iTest = iArgb[i*iW+j]; assertEquals(iTest, rTest, "Invalid pixel lookup for "+target.getName()+" at "+i+", "+j); } } } } }
src/test/java/org/apache/commons/imaging/formats/tiff/TiffSubImageTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.imaging.formats.tiff; import static org.junit.jupiter.api.Assertions.assertEquals; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import org.apache.commons.imaging.ImageFormats; import org.apache.commons.imaging.ImageReadException; import org.apache.commons.imaging.ImageWriteException; import org.apache.commons.imaging.Imaging; import org.apache.commons.imaging.formats.tiff.constants.TiffConstants; import org.junit.jupiter.api.Test; public class TiffSubImageTest extends TiffBaseTest { @Test public void testSubImage() throws ImageReadException, ImageWriteException, IOException { final BufferedImage src = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); final byte[] imageBytes = Imaging.writeImageToBytes(src, ImageFormats.TIFF, null); final Map<String, Object> params = new TreeMap<>(); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, 0); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, 0); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, 2); params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, 3); final BufferedImage image = Imaging.getBufferedImage(imageBytes, params); assertEquals(image.getWidth(), 2); assertEquals(image.getHeight(), 3); } }
Added parameter and correctness tests
src/test/java/org/apache/commons/imaging/formats/tiff/TiffSubImageTest.java
Added parameter and correctness tests
<ide><path>rc/test/java/org/apache/commons/imaging/formats/tiff/TiffSubImageTest.java <ide> package org.apache.commons.imaging.formats.tiff; <ide> <ide> import static org.junit.jupiter.api.Assertions.assertEquals; <add>import static org.junit.jupiter.api.Assertions.fail; <ide> <ide> import java.awt.image.BufferedImage; <add>import java.io.File; <ide> import java.io.IOException; <add>import java.util.HashMap; <add>import java.util.List; <ide> import java.util.Map; <ide> import java.util.TreeMap; <ide> <ide> import org.junit.jupiter.api.Test; <ide> <ide> public class TiffSubImageTest extends TiffBaseTest { <add> final List<File> imageFileList; <add> <add> TiffSubImageTest() throws IOException, ImageReadException{ <add> imageFileList = getTiffImages(); <add> } <ide> <ide> @Test <ide> public void testSubImage() throws ImageReadException, ImageWriteException, IOException { <ide> assertEquals(image.getWidth(), 2); <ide> assertEquals(image.getHeight(), 3); <ide> } <add> <add> @Test <add> public void testBadSubImage() throws ImageReadException, IOException{ <add> File target = imageFileList.get(0); <add> final BufferedImage referenceImage = Imaging.getBufferedImage(target); <add> int width = referenceImage.getWidth(); <add> int height = referenceImage.getHeight(); <add> <add> final Map<String, Object> params = new HashMap<>(); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, 0); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, 0); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, width); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, height); <add> <add> BufferedImage image = Imaging.getBufferedImage(target, params); <add> assertEquals(image.getWidth(), width, "Improper width when sub-imaging entire image"); <add> assertEquals(image.getHeight(), height, "Improper height when sub-imaging entire image"); <add> <add> processBadParams(target, -1, 0, width, height, "negative x position"); <add> processBadParams(target, 0, -1, width, height, "negative y position"); <add> processBadParams(target, 0, 0, 0, height, "zero width"); <add> processBadParams(target, 0, 0, width, 0, "zero height"); <add> processBadParams(target, 1, 0, width, height, "sub-image width extends beyond bounds"); <add> processBadParams(target, 0, 1, width, height, "sub-image height extends beyond bounds"); <add> } <add> <add> private void processBadParams(File target, int x, int y, int width, int height, String comment) throws IOException{ <add> try{ <add> final Map<String, Object> params = new HashMap<>(); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, x); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, y); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, width); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, height); <add> BufferedImage image = Imaging.getBufferedImage(target, params); <add> fail("Reading TIFF sub-image failed to detect bad parameter: "+comment); <add> }catch(ImageReadException ire){ <add> // the test passed <add> } <add> } <add> <add> @Test <add> public void testSubImageCorrectness() throws ImageReadException, IOException { <add> for(File target: imageFileList){ <add> final BufferedImage referenceImage = Imaging.getBufferedImage(target); <add> int rW = referenceImage.getWidth(); <add> int rH = referenceImage.getHeight(); <add> if(rW<3 || rH<3){ <add> continue; <add> } <add> int []rArgb = new int[rW*rH]; <add> referenceImage.getRGB(0, 0, rW, rH, rArgb, 0, rW); <add> final Map<String, Object> params = new HashMap<>(); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, 1); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, 1); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, rW-2); <add> params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, rH-2); <add> BufferedImage image = Imaging.getBufferedImage(target, params); <add> int iW = image.getWidth(); <add> int iH = image.getHeight(); <add> assertEquals(iW, rW-2, "Invalid subimage width"); <add> assertEquals(iH, rH-2, "Invalid subimage height"); <add> int []iArgb= new int[iW*iH]; <add> image.getRGB(0, 0, iW, iH, iArgb, 0, iW); <add> for(int i=0; i<iH; i++){ <add> for(int j=0; j<iW; j++){ <add> int rTest = rArgb[(i+1)*rW+j+1]; <add> int iTest = iArgb[i*iW+j]; <add> assertEquals(iTest, rTest, "Invalid pixel lookup for "+target.getName()+" at "+i+", "+j); <add> } <add> } <add> } <add> } <add> <add> <ide> }
Java
mit
445411722d8134806e7d6c0a1dcfc54ae336ffdc
0
RoboEagles4828/2017Robot,RoboEagles4828/ACE
package org.usfirst.frc.team4828.vision; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.nio.charset.Charset; import org.usfirst.frc.team4828.Ultrasonic; public class Pixy implements Runnable { private static final String HOST = "pixyco.local"; private static final int PORT = 5800; private static final int PIXY_SIDE = 1; //-1 for right, 1 for left private boolean enabled; private boolean connected; private boolean blocksDetected; private volatile Frame currentFrame; private volatile Frame lastFrame; private BufferedReader in; private Socket soc; private Ultrasonic us; private String line; /** * loops while it's alive * Create object encapsulating the last frame and ultrasonic data. */ public Pixy(Ultrasonic ultra) { System.out.println("Constructing pixy thread"); String[] temp = {"0 1 2 3 4 5 6"}; currentFrame = new Frame(temp, .5); lastFrame = new Frame(temp, .5); enabled = false; blocksDetected = false; connected = false; us = ultra; } public boolean blocksDetected() { return blocksDetected; } public double horizontalOffset() { //if two blocks are detected return position of peg if (currentFrame.numBlocks() == 2) { return lastFrame.getRealDistance(((lastFrame.getFrameData().get(0).getX() + lastFrame.getFrameData().get(1).getX()) / 2) - Block.X_CENTER); } //if only one vision target is detected guess position of peg else if (currentFrame.numBlocks() == 1) { blocksDetected = false; double pegPos = ((currentFrame.getFrameData().get(0).getX() - Block.X_CENTER) > 0) ? 4.125 : -4.125; return currentFrame.getRealDistance(currentFrame.getFrameData().get(0).getX() - Block.X_CENTER) + pegPos; } //if no vision targets are detected blocksDetected = false; return 4828; } @Override public void run() { System.out.println("Searching for socket connection..."); enabled = true; while (enabled) { try { soc = new Socket(HOST, PORT); in = new BufferedReader(new InputStreamReader(soc.getInputStream(), Charset.forName("UTF-8"))); System.out.print("Socket connection established on ip: " + soc.getInetAddress()); break; } catch (IOException e) { System.out.println("Connect failed, waiting and trying again"); try { Thread.sleep(1000); } catch (InterruptedException ie) { ie.printStackTrace(); } } } connected = true; while (enabled) { try { line = in.readLine(); assert line != null; currentFrame = new Frame(line.split(","), us.getDist()); } catch (IOException e) { e.printStackTrace(); } if (currentFrame.numBlocks() >= 2 || (lastFrame == null && currentFrame.numBlocks() == 1)) { blocksDetected = true; lastFrame = currentFrame; } edu.wpi.first.wpilibj.Timer.delay(0.01); } } public void terminate() { System.out.println("DISABLING THREAD"); if (enabled && connected) { try { in.close(); soc.close(); } catch (IOException e) { e.printStackTrace(); } } blocksDetected = false; connected = false; enabled = false; } public int getWidth() { return lastFrame.getFrameData().get(0).getWidth(); } public Frame getLastFrame() { if (lastFrame != null) { return lastFrame; } return currentFrame; } @Override public String toString() { if (lastFrame != null) { return lastFrame.toString(); } else { return currentFrame.toString(); } } }
src/main/java/org/usfirst/frc/team4828/vision/Pixy.java
package org.usfirst.frc.team4828.vision; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.nio.charset.Charset; import org.usfirst.frc.team4828.Ultrasonic; public class Pixy implements Runnable { private static final String HOST = "pixyco.local"; private static final int PORT = 5800; private static final int PIXY_SIDE = 1; //-1 for right, 1 for left private boolean enabled; private boolean connected; private boolean blocksDetected; private volatile Frame currentFrame; private volatile Frame lastFrame; private BufferedReader in; private Socket soc; private Ultrasonic us; private String line; /** * loops while it's alive * Create object encapsulating the last frame and ultrasonic data. */ public Pixy(Ultrasonic ultra) { System.out.println("Constructing pixy thread"); String[] temp = {"0 1 2 3 4 5 6"}; currentFrame = new Frame(temp, .5); lastFrame = new Frame(temp, .5); enabled = false; blocksDetected = false; connected = false; us = ultra; } public boolean blocksDetected() { return blocksDetected; } public double horizontalOffset() { //if two blocks are detected return position of peg if (currentFrame.numBlocks() == 2) { return lastFrame.getRealDistance(((lastFrame.getFrameData().get(0).getX() + lastFrame.getFrameData().get(1).getX()) / 2) - Block.X_CENTER); } //if only one vision target is detected guess position of peg else if (currentFrame.numBlocks() == 1) { blocksDetected = false; double pegPos = ((currentFrame.getFrameData().get(0).getX() - Block.X_CENTER) > 0) ? 4.125 : -4.125; return currentFrame.getRealDistance(currentFrame.getFrameData().get(0).getX() - Block.X_CENTER) + pegPos; } //if no vision targets are detected blocksDetected = false; return 4828; } @Override public void run() { System.out.println("Searching for socket connection..."); enabled = true; while (enabled) { try { soc = new Socket(HOST, PORT); in = new BufferedReader(new InputStreamReader(soc.getInputStream(), Charset.forName("UTF-8"))); System.out.print("Socket connection established on ip: " + soc.getInetAddress()); break; } catch (IOException e) { System.out.println("Connect failed, waiting and trying again"); try { Thread.sleep(1000); } catch (InterruptedException ie) { ie.printStackTrace(); } } } connected = true; while (enabled) { try { line = in.readLine(); //assert line != null; currentFrame = new Frame(line.split(","), us.getDist()); } catch (IOException e) { e.printStackTrace(); } if (currentFrame.numBlocks() >= 2 || (lastFrame == null && currentFrame.numBlocks() == 1)) { blocksDetected = true; lastFrame = currentFrame; } edu.wpi.first.wpilibj.Timer.delay(0.01); } } public void terminate() { System.out.println("DISABLING THREAD"); if (enabled && connected) { try { in.close(); soc.close(); } catch (IOException e) { e.printStackTrace(); } } blocksDetected = false; connected = false; enabled = false; } public int getWidth() { return lastFrame.getFrameData().get(0).getWidth(); } public Frame getLastFrame() { if (lastFrame != null) { return lastFrame; } return currentFrame; } @Override public String toString() { if (lastFrame != null) { return lastFrame.toString(); } else { return currentFrame.toString(); } } }
Fix Test Bug
src/main/java/org/usfirst/frc/team4828/vision/Pixy.java
Fix Test Bug
<ide><path>rc/main/java/org/usfirst/frc/team4828/vision/Pixy.java <ide> while (enabled) { <ide> try { <ide> line = in.readLine(); <del> //assert line != null; <add> assert line != null; <ide> currentFrame = new Frame(line.split(","), us.getDist()); <ide> } catch (IOException e) { <ide> e.printStackTrace();
Java
mit
7a46209a3ad5952193a5124c5048d93757ef413c
0
CS2103AUG2016-T09-C4/main
package seedu.unburden.testutil; import seedu.unburden.model.tag.UniqueTagList; import seedu.unburden.model.task.*; /** * A mutable person object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private TaskDescription taskD; private Date date; private Time startTime; private Time endTime; private UniqueTagList tags; private boolean done; public TestTask() { tags = new UniqueTagList(); } public void setName(Name name) { this.name = name; } @Override public Name getName() { return name; } @Override public TaskDescription getTaskDescription() { return taskD; } @Override public Date getDate() { return date; } @Override public Time getStartTime() { return startTime; } @Override public Time getEndTime() { return endTime; } @Override public UniqueTagList getTags() { return tags; } @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().fullName + " "); this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " ")); return sb.toString(); } @Override public boolean getDone() { return done; } @Override public String getDoneString() { if(done == true){ return "Task Done!"; } else{ return "Task unDone!"; } } }
src/test/java/seedu/unburden/testutil/TestTask.java
package seedu.unburden.testutil; import seedu.unburden.model.tag.UniqueTagList; import seedu.unburden.model.task.*; /** * A mutable person object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private TaskDescription taskD; private Date date; private Time startTime; private Time endTime; private UniqueTagList tags; public TestTask() { tags = new UniqueTagList(); } public void setName(Name name) { this.name = name; } @Override public Name getName() { return name; } @Override public TaskDescription getTaskDescription() { return taskD; } @Override public Date getDate() { return date; } @Override public Time getStartTime() { return startTime; } @Override public Time getEndTime() { return endTime; } @Override public UniqueTagList getTags() { return tags; } @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().fullName + " "); this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " ")); return sb.toString(); } }
Updated TestTask for done command
src/test/java/seedu/unburden/testutil/TestTask.java
Updated TestTask for done command
<ide><path>rc/test/java/seedu/unburden/testutil/TestTask.java <ide> private Time startTime; <ide> private Time endTime; <ide> private UniqueTagList tags; <add> private boolean done; <ide> <ide> public TestTask() { <ide> tags = new UniqueTagList(); <ide> this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " ")); <ide> return sb.toString(); <ide> } <add> <add> @Override <add> public boolean getDone() { <add> return done; <add> } <add> <add> @Override <add> public String getDoneString() { <add> if(done == true){ <add> return "Task Done!"; <add> } <add> else{ <add> return "Task unDone!"; <add> } <add> } <ide> }
Java
apache-2.0
2a137a2d8a680fc28ca58387b508e6090512e0f6
0
Buzzardo/spring-boot,mdeinum/spring-boot,Buzzardo/spring-boot,scottfrederick/spring-boot,vpavic/spring-boot,dreis2211/spring-boot,wilkinsona/spring-boot,vpavic/spring-boot,scottfrederick/spring-boot,mdeinum/spring-boot,jxblum/spring-boot,michael-simons/spring-boot,chrylis/spring-boot,Buzzardo/spring-boot,aahlenst/spring-boot,mdeinum/spring-boot,aahlenst/spring-boot,vpavic/spring-boot,Buzzardo/spring-boot,mbenson/spring-boot,htynkn/spring-boot,mbenson/spring-boot,philwebb/spring-boot,wilkinsona/spring-boot,philwebb/spring-boot,htynkn/spring-boot,htynkn/spring-boot,dreis2211/spring-boot,michael-simons/spring-boot,mdeinum/spring-boot,chrylis/spring-boot,aahlenst/spring-boot,shakuzen/spring-boot,shakuzen/spring-boot,dreis2211/spring-boot,chrylis/spring-boot,htynkn/spring-boot,dreis2211/spring-boot,michael-simons/spring-boot,jxblum/spring-boot,jxblum/spring-boot,scottfrederick/spring-boot,spring-projects/spring-boot,vpavic/spring-boot,Buzzardo/spring-boot,htynkn/spring-boot,wilkinsona/spring-boot,spring-projects/spring-boot,chrylis/spring-boot,michael-simons/spring-boot,scottfrederick/spring-boot,htynkn/spring-boot,spring-projects/spring-boot,spring-projects/spring-boot,spring-projects/spring-boot,jxblum/spring-boot,vpavic/spring-boot,aahlenst/spring-boot,wilkinsona/spring-boot,mdeinum/spring-boot,spring-projects/spring-boot,michael-simons/spring-boot,philwebb/spring-boot,shakuzen/spring-boot,Buzzardo/spring-boot,shakuzen/spring-boot,jxblum/spring-boot,shakuzen/spring-boot,shakuzen/spring-boot,chrylis/spring-boot,mbenson/spring-boot,philwebb/spring-boot,dreis2211/spring-boot,chrylis/spring-boot,wilkinsona/spring-boot,wilkinsona/spring-boot,jxblum/spring-boot,philwebb/spring-boot,scottfrederick/spring-boot,philwebb/spring-boot,dreis2211/spring-boot,scottfrederick/spring-boot,michael-simons/spring-boot,mbenson/spring-boot,mdeinum/spring-boot,aahlenst/spring-boot,mbenson/spring-boot,mbenson/spring-boot,aahlenst/spring-boot,vpavic/spring-boot
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.loader.jar; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.security.Permission; import java.util.EnumSet; import java.util.Enumeration; import java.util.Set; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.jar.JarFileWrapperTests.SpyJarFile.Call; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link JarFileWrapper}. * * @author Phillip Webb */ class JarFileWrapperTests { private SpyJarFile parent; private JarFileWrapper wrapper; @BeforeEach void setup(@TempDir File temp) throws IOException { this.parent = new SpyJarFile(createTempJar(temp)); this.wrapper = new JarFileWrapper(this.parent); } private File createTempJar(File temp) throws IOException { File file = new File(temp, "temp.jar"); new JarOutputStream(new FileOutputStream(file)).close(); return file; } @Test void getUrlDelegatesToParent() throws MalformedURLException { this.wrapper.getUrl(); this.parent.verify(Call.GET_URL); } @Test void getTypeDelegatesToParent() { this.wrapper.getType(); this.parent.verify(Call.GET_TYPE); } @Test void getPermissionDelegatesToParent() { this.wrapper.getPermission(); this.parent.verify(Call.GET_PERMISSION); } @Test void getManifestDelegatesToParent() throws IOException { this.wrapper.getManifest(); this.parent.verify(Call.GET_MANIFEST); } @Test void entriesDelegatesToParent() { this.wrapper.entries(); this.parent.verify(Call.ENTRIES); } @Test void getJarEntryDelegatesToParent() { this.wrapper.getJarEntry("test"); this.parent.verify(Call.GET_JAR_ENTRY); } @Test void getEntryDelegatesToParent() { this.wrapper.getEntry("test"); this.parent.verify(Call.GET_ENTRY); } @Test void getInputStreamDelegatesToParent() throws IOException { this.wrapper.getInputStream(); this.parent.verify(Call.GET_INPUT_STREAM); } @Test void getEntryInputStreamDelegatesToParent() throws IOException { ZipEntry entry = new ZipEntry("test"); this.wrapper.getInputStream(entry); this.parent.verify(Call.GET_ENTRY_INPUT_STREAM); } @Test void getCommentDelegatesToParent() { this.wrapper.getComment(); this.parent.verify(Call.GET_COMMENT); } @Test void sizeDelegatesToParent() { this.wrapper.size(); this.parent.verify(Call.SIZE); } @Test void toStringDelegatesToParent() { assertThat(this.wrapper.toString()).endsWith("/temp.jar"); } @Test // gh-22991 void wrapperMustNotImplementClose() { // If the wrapper overrides close then on Java 11 a FinalizableResource // instance will be used to perform cleanup. This can result in a lot // of additional memory being used since cleanup only occurs when the // finalizer thread runs. See gh-22991 assertThatExceptionOfType(NoSuchMethodException.class) .isThrownBy(() -> JarFileWrapper.class.getDeclaredMethod("close")); } /** * {@link JarFile} that we can spy (even on Java 11+) */ static class SpyJarFile extends JarFile { private final Set<Call> calls = EnumSet.noneOf(Call.class); SpyJarFile(File file) throws IOException { super(file); } @Override Permission getPermission() { mark(Call.GET_PERMISSION); return super.getPermission(); } @Override public Manifest getManifest() throws IOException { mark(Call.GET_MANIFEST); return super.getManifest(); } @Override public Enumeration<java.util.jar.JarEntry> entries() { mark(Call.ENTRIES); return super.entries(); } @Override public JarEntry getJarEntry(String name) { mark(Call.GET_JAR_ENTRY); return super.getJarEntry(name); } @Override public ZipEntry getEntry(String name) { mark(Call.GET_ENTRY); return super.getEntry(name); } @Override InputStream getInputStream() throws IOException { mark(Call.GET_INPUT_STREAM); return super.getInputStream(); } @Override InputStream getInputStream(String name) throws IOException { mark(Call.GET_ENTRY_INPUT_STREAM); return super.getInputStream(name); } @Override public String getComment() { mark(Call.GET_COMMENT); return super.getComment(); } @Override public int size() { mark(Call.SIZE); return super.size(); } @Override public URL getUrl() throws MalformedURLException { mark(Call.GET_URL); return super.getUrl(); } @Override JarFileType getType() { mark(Call.GET_TYPE); return super.getType(); } private void mark(Call call) { this.calls.add(call); } void verify(Call call) { assertThat(call).matches(this.calls::contains); } enum Call { GET_URL, GET_TYPE, GET_PERMISSION, GET_MANIFEST, ENTRIES, GET_JAR_ENTRY, GET_ENTRY, GET_INPUT_STREAM, GET_ENTRY_INPUT_STREAM, GET_COMMENT, SIZE } } }
spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.loader.jar; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * Tests for {@link JarFileWrapper}. * * @author Phillip Webb */ class JarFileWrapperTests { private JarFile parent; private JarFileWrapper wrapper; @BeforeEach void setup(@TempDir File temp) throws IOException { this.parent = spy(new JarFile(createTempJar(temp))); this.wrapper = new JarFileWrapper(this.parent); } private File createTempJar(File temp) throws IOException { File file = new File(temp, "temp.jar"); new JarOutputStream(new FileOutputStream(file)).close(); return file; } @Test void getUrlDelegatesToParent() throws MalformedURLException { this.wrapper.getUrl(); verify(this.parent).getUrl(); } @Test void getTypeDelegatesToParent() { this.wrapper.getType(); verify(this.parent).getType(); } @Test void getPermissionDelegatesToParent() { this.wrapper.getPermission(); verify(this.parent).getPermission(); } @Test void getManifestDelegatesToParent() throws IOException { this.wrapper.getManifest(); verify(this.parent).getManifest(); } @Test void entriesDelegatesToParent() { this.wrapper.entries(); verify(this.parent).entries(); } @Test void getJarEntryDelegatesToParent() { this.wrapper.getJarEntry("test"); verify(this.parent).getJarEntry("test"); } @Test void getEntryDelegatesToParent() { this.wrapper.getEntry("test"); verify(this.parent).getEntry("test"); } @Test void getInputStreamDelegatesToParent() throws IOException { this.wrapper.getInputStream(); verify(this.parent).getInputStream(); } @Test void getEntryInputStreamDelegatesToParent() throws IOException { ZipEntry entry = new ZipEntry("test"); this.wrapper.getInputStream(entry); verify(this.parent).getInputStream(entry); } @Test void getCommentDelegatesToParent() { this.wrapper.getComment(); verify(this.parent).getComment(); } @Test void sizeDelegatesToParent() { this.wrapper.size(); verify(this.parent).size(); } @Test void toStringDelegatesToParent() { assertThat(this.wrapper.toString()).endsWith("/temp.jar"); } @Test // gh-22991 void wrapperMustNotImplementClose() { // If the wrapper overrides close then on Java 11 a FinalizableResource // instance will be used to perform cleanup. This can result in a lot // of additional memory being used since cleanup only occurs when the // finalizer thread runs. See gh-22991 assertThatExceptionOfType(NoSuchMethodException.class) .isThrownBy(() -> JarFileWrapper.class.getDeclaredMethod("close")); } }
Remove Mockito from JarFileWrapperTests Remove Mockto from JarFileWrapperTests since it seems to be failing on later versions of Java. See gh-22991
spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java
Remove Mockito from JarFileWrapperTests
<ide><path>pring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java <ide> import java.io.File; <ide> import java.io.FileOutputStream; <ide> import java.io.IOException; <add>import java.io.InputStream; <ide> import java.net.MalformedURLException; <add>import java.net.URL; <add>import java.security.Permission; <add>import java.util.EnumSet; <add>import java.util.Enumeration; <add>import java.util.Set; <ide> import java.util.jar.JarOutputStream; <add>import java.util.jar.Manifest; <ide> import java.util.zip.ZipEntry; <ide> <ide> import org.junit.jupiter.api.BeforeEach; <ide> import org.junit.jupiter.api.Test; <ide> import org.junit.jupiter.api.io.TempDir; <ide> <add>import org.springframework.boot.loader.jar.JarFileWrapperTests.SpyJarFile.Call; <add> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <del>import static org.mockito.Mockito.spy; <del>import static org.mockito.Mockito.verify; <ide> <ide> /** <ide> * Tests for {@link JarFileWrapper}. <ide> */ <ide> class JarFileWrapperTests { <ide> <del> private JarFile parent; <add> private SpyJarFile parent; <ide> <ide> private JarFileWrapper wrapper; <ide> <ide> @BeforeEach <ide> void setup(@TempDir File temp) throws IOException { <del> this.parent = spy(new JarFile(createTempJar(temp))); <add> this.parent = new SpyJarFile(createTempJar(temp)); <ide> this.wrapper = new JarFileWrapper(this.parent); <ide> } <ide> <ide> @Test <ide> void getUrlDelegatesToParent() throws MalformedURLException { <ide> this.wrapper.getUrl(); <del> verify(this.parent).getUrl(); <add> this.parent.verify(Call.GET_URL); <ide> } <ide> <ide> @Test <ide> void getTypeDelegatesToParent() { <ide> this.wrapper.getType(); <del> verify(this.parent).getType(); <add> this.parent.verify(Call.GET_TYPE); <ide> } <ide> <ide> @Test <ide> void getPermissionDelegatesToParent() { <ide> this.wrapper.getPermission(); <del> verify(this.parent).getPermission(); <add> this.parent.verify(Call.GET_PERMISSION); <ide> } <ide> <ide> @Test <ide> void getManifestDelegatesToParent() throws IOException { <ide> this.wrapper.getManifest(); <del> verify(this.parent).getManifest(); <add> this.parent.verify(Call.GET_MANIFEST); <ide> } <ide> <ide> @Test <ide> void entriesDelegatesToParent() { <ide> this.wrapper.entries(); <del> verify(this.parent).entries(); <add> this.parent.verify(Call.ENTRIES); <ide> } <ide> <ide> @Test <ide> void getJarEntryDelegatesToParent() { <ide> this.wrapper.getJarEntry("test"); <del> verify(this.parent).getJarEntry("test"); <add> this.parent.verify(Call.GET_JAR_ENTRY); <ide> } <ide> <ide> @Test <ide> void getEntryDelegatesToParent() { <ide> this.wrapper.getEntry("test"); <del> verify(this.parent).getEntry("test"); <add> this.parent.verify(Call.GET_ENTRY); <ide> } <ide> <ide> @Test <ide> void getInputStreamDelegatesToParent() throws IOException { <ide> this.wrapper.getInputStream(); <del> verify(this.parent).getInputStream(); <add> this.parent.verify(Call.GET_INPUT_STREAM); <ide> } <ide> <ide> @Test <ide> void getEntryInputStreamDelegatesToParent() throws IOException { <ide> ZipEntry entry = new ZipEntry("test"); <ide> this.wrapper.getInputStream(entry); <del> verify(this.parent).getInputStream(entry); <add> this.parent.verify(Call.GET_ENTRY_INPUT_STREAM); <ide> } <ide> <ide> @Test <ide> void getCommentDelegatesToParent() { <ide> this.wrapper.getComment(); <del> verify(this.parent).getComment(); <add> this.parent.verify(Call.GET_COMMENT); <ide> } <ide> <ide> @Test <ide> void sizeDelegatesToParent() { <ide> this.wrapper.size(); <del> verify(this.parent).size(); <add> this.parent.verify(Call.SIZE); <ide> } <ide> <ide> @Test <ide> .isThrownBy(() -> JarFileWrapper.class.getDeclaredMethod("close")); <ide> } <ide> <add> /** <add> * {@link JarFile} that we can spy (even on Java 11+) <add> */ <add> static class SpyJarFile extends JarFile { <add> <add> private final Set<Call> calls = EnumSet.noneOf(Call.class); <add> <add> SpyJarFile(File file) throws IOException { <add> super(file); <add> } <add> <add> @Override <add> Permission getPermission() { <add> mark(Call.GET_PERMISSION); <add> return super.getPermission(); <add> } <add> <add> @Override <add> public Manifest getManifest() throws IOException { <add> mark(Call.GET_MANIFEST); <add> return super.getManifest(); <add> } <add> <add> @Override <add> public Enumeration<java.util.jar.JarEntry> entries() { <add> mark(Call.ENTRIES); <add> return super.entries(); <add> } <add> <add> @Override <add> public JarEntry getJarEntry(String name) { <add> mark(Call.GET_JAR_ENTRY); <add> return super.getJarEntry(name); <add> } <add> <add> @Override <add> public ZipEntry getEntry(String name) { <add> mark(Call.GET_ENTRY); <add> return super.getEntry(name); <add> } <add> <add> @Override <add> InputStream getInputStream() throws IOException { <add> mark(Call.GET_INPUT_STREAM); <add> return super.getInputStream(); <add> } <add> <add> @Override <add> InputStream getInputStream(String name) throws IOException { <add> mark(Call.GET_ENTRY_INPUT_STREAM); <add> return super.getInputStream(name); <add> } <add> <add> @Override <add> public String getComment() { <add> mark(Call.GET_COMMENT); <add> return super.getComment(); <add> } <add> <add> @Override <add> public int size() { <add> mark(Call.SIZE); <add> return super.size(); <add> } <add> <add> @Override <add> public URL getUrl() throws MalformedURLException { <add> mark(Call.GET_URL); <add> return super.getUrl(); <add> } <add> <add> @Override <add> JarFileType getType() { <add> mark(Call.GET_TYPE); <add> return super.getType(); <add> } <add> <add> private void mark(Call call) { <add> this.calls.add(call); <add> } <add> <add> void verify(Call call) { <add> assertThat(call).matches(this.calls::contains); <add> } <add> <add> enum Call { <add> <add> GET_URL, <add> <add> GET_TYPE, <add> <add> GET_PERMISSION, <add> <add> GET_MANIFEST, <add> <add> ENTRIES, <add> <add> GET_JAR_ENTRY, <add> <add> GET_ENTRY, <add> <add> GET_INPUT_STREAM, <add> <add> GET_ENTRY_INPUT_STREAM, <add> <add> GET_COMMENT, <add> <add> SIZE <add> <add> } <add> <add> } <add> <ide> }
JavaScript
mit
e831d30577a8d020e6a3f22dd81b117bb5637efc
0
jxmono/web-sockets
/* * Init * */ exports.init = function (link) { // console.log(M.app.server); // TODO link.send(200, { op: "init", data: link.data }); }; /* * Listen * */ exports.listen = function (link) { // TODO link.send(200, { op: "listen" }); }; /* * Emit * */ exports.emit = function (link) { // TODO link.send(200, { op: "emit" }); };
operations.js
/* * Init * */ exports.init = function (link) { // TODO link.send(200, { op: "init", data: link.data }); }; /* * Listen * */ exports.listen = function (link) { // TODO link.send(200, { op: "listen" }); }; /* * Emit * */ exports.emit = function (link) { // TODO link.send(200, { op: "emit" }); };
trying to get the server
operations.js
trying to get the server
<ide><path>perations.js <ide> * Init <ide> * */ <ide> exports.init = function (link) { <add> // console.log(M.app.server); <ide> // TODO <ide> link.send(200, { op: "init", data: link.data }); <ide> };
Java
apache-2.0
d23bc3f698f21471fdd6f5e6c4f3cd966c8349f6
0
rbccps-iisc/streamprocessing
package robertbosch.utils; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.concurrent.TimeoutException; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; public class Testclass { static int ctr=0; public static void main(String[] args) { System.out.println("test rabbitmq subscriber..."); subscriberabbitMQ(Integer.parseInt(args[0])); System.out.println("done with test proto code..."); } private static void subscriberabbitMQ(final int datapoint) { //String subscribefile = "/Users/sahiltyagi/Desktop/subscribe.txt"; String subscribefile = "/home/etl_subsystem/subscribe.txt"; RobertBoschUtils rb = new RobertBoschUtils(); try { final BufferedWriter subscriber = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(subscribefile))); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(RobertBoschUtils.props.getProperty("host")); factory.setPort(Integer.parseInt(RobertBoschUtils.props.getProperty("port"))); factory.setUsername(RobertBoschUtils.props.getProperty("username")); factory.setPassword(RobertBoschUtils.props.getProperty("password")); factory.setVirtualHost(RobertBoschUtils.props.getProperty("virtualhost")); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); channel.queueDeclare("sahil", false, false, false, null); Consumer consumer = new DefaultConsumer(channel) { public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //RabbitMQSpout.nbqueue.add(body); String message = new String(body, "UTF-8"); //System.out.println(" [x] Received '" + message + "'"); JSONParser parser = new JSONParser(); try { Object ob = parser.parse(message); JSONObject jsonob = (JSONObject)ob; //System.out.println(jsonob.get("devEUI")); subscriber.write(System.currentTimeMillis() + "," + jsonob.get("devEUI") + "\n"); ctr++; if(ctr == datapoint) { subscriber.close(); System.out.println("completed index...."); } } catch (ParseException e) { e.printStackTrace(); } } }; channel.basicConsume("sahil", true, consumer); } catch(IOException e) { e.printStackTrace(); } catch(TimeoutException t) { t.printStackTrace(); } } }
src/main/java/robertbosch/utils/Testclass.java
package robertbosch.utils; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.concurrent.TimeoutException; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; public class Testclass { static int ctr=0; public static void main(String[] args) { System.out.println("test rabbitmq subscriber..."); subscriberabbitMQ(Integer.parseInt(args[0])); System.out.println("done with test proto code..."); } private static void subscriberabbitMQ(final int datapoint) { //String subscribefile = "/Users/sahiltyagi/Desktop/subscribe.txt"; String subscribefile = "/home/etl_subsystem/subscribe.txt"; RobertBoschUtils rb = new RobertBoschUtils(); try { final BufferedWriter subscriber = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(subscribefile))); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(RobertBoschUtils.props.getProperty("host")); factory.setPort(Integer.parseInt(RobertBoschUtils.props.getProperty("port"))); factory.setUsername(RobertBoschUtils.props.getProperty("username")); factory.setPassword(RobertBoschUtils.props.getProperty("password")); factory.setVirtualHost(RobertBoschUtils.props.getProperty("virtualhost")); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); channel.queueDeclare("sahil", false, false, false, null); Consumer consumer = new DefaultConsumer(channel) { public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //RabbitMQSpout.nbqueue.add(body); String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); JSONParser parser = new JSONParser(); try { Object ob = parser.parse(message); JSONObject jsonob = (JSONObject)ob; System.out.println(jsonob.get("devEUI")); subscriber.write(System.currentTimeMillis() + "," + jsonob.get("devEUI") + "\n"); ctr++; if(ctr == datapoint) { subscriber.close(); System.out.println("completed index...."); } } catch (ParseException e) { e.printStackTrace(); } } }; channel.basicConsume("sahil", true, consumer); } catch(IOException e) { e.printStackTrace(); } catch(TimeoutException t) { t.printStackTrace(); } } }
calculating latency in broker for energy meter data
src/main/java/robertbosch/utils/Testclass.java
calculating latency in broker for energy meter data
<ide><path>rc/main/java/robertbosch/utils/Testclass.java <ide> <ide> //RabbitMQSpout.nbqueue.add(body); <ide> String message = new String(body, "UTF-8"); <del> System.out.println(" [x] Received '" + message + "'"); <add> //System.out.println(" [x] Received '" + message + "'"); <ide> JSONParser parser = new JSONParser(); <ide> <ide> try { <ide> Object ob = parser.parse(message); <ide> JSONObject jsonob = (JSONObject)ob; <del> System.out.println(jsonob.get("devEUI")); <add> //System.out.println(jsonob.get("devEUI")); <ide> subscriber.write(System.currentTimeMillis() + "," + jsonob.get("devEUI") + "\n"); <ide> ctr++; <ide> if(ctr == datapoint) {
JavaScript
mit
c47d003b5cfc3840fbd95b1c5a1787252cdf4271
0
gscplanning/cell-towers,gscplanning/cell-towers
var map = L.map('map', { maxZoom: 19, minZoom: 12 }).setView([38.317236, -84.564147], 12); var info = L.control(); info.onAdd = function (map) { this._div = L.DomUtil.create('div','info'); this.update(); return this._div; }; info.update = function (props) { this._div.innerHTML = (props ? '<h3>' + props.location + '</h3><br>' + '<b>Status: </b> ' + props.status2 + '<br>' + '<b>Owner: </b> ' + props.owner + '<br>' + '<b><a href="http://wireless2.fcc.gov/UlsApp/AsrSearch/asrRegistration.jsp?callingSystem=AS&amp;regKey=' + props.page + '" target="_blank">View Application</a></b><br>' : 'Click icon for more info' ) } info.addTo(map); function clicky(e) { var layer = e.target; cellTowers.setStyle({ color: '#fff' }) layer.setStyle({ color: 'yellow' }) info.update(layer.feature.properties); } function onEachFeature(feature, layer) { layer.on({ click: clicky }) } function getColor(d) { return d=="C" ? '#4CAF50': d=="G" ? '#2196F3': d=="A" ? '#FFC107': d=="I" ? '#212121': d=="T" ? '#f44336': '#ecf0f1'; } function style(feature){ return getColor(feature.properties.status) } L.esri.tiledMapLayer({ url: 'https://gis.gscplanning.com/arcgis/rest/services/basemaps/gscbase_streets/MapServer', attribution: 'GSCPC', // Dealing with broken blank tiles: https://github.com/Esri/esri-leaflet/issues/759 errorTileUrl: './errorTile256.png' }).addTo(map); var cellTowers = L.esri.featureLayer({ url: 'https://services1.arcgis.com/dpmGqj7FxlwlvK0y/arcgis/rest/services/Scott_County_Cell_Towers/FeatureServer/0', pointToLayer: function (geojson, latlng) { return L.circleMarker(latlng,{ fillColor: style(geojson), fillOpacity: 1, color: '#fff', weight: 4, radius:10 } )}, onEachFeature: onEachFeature }).addTo(map); var tower = document.getElementById('appStatus'); tower.addEventListener('change', function(){ cellTowers.setWhere(tower.status); });
app.js
var map = L.map('map', { maxZoom: 19, minZoom: 12 }).setView([38.317236, -84.564147], 12); var info = L.control(); info.onAdd = function (map) { this._div = L.DomUtil.create('div','info'); this.update(); return this._div; }; info.update = function (props) { this._div.innerHTML = (props ? '<h3>' + props.location + '</h3><br>' + '<b>Status: </b> ' + props.status2 + '<br>' + '<b>Owner: </b> ' + props.owner + '<br>' + '<b><a href="http://wireless2.fcc.gov/UlsApp/AsrSearch/asrRegistration.jsp?callingSystem=AS&amp;regKey=' + props.page + '" target="_blank">View Application</a></b><br>' : 'Click icon for more info' ) } info.addTo(map); function clicky(e) { var layer = e.target; cellTowers.setStyle({ color: '#fff' }) layer.setStyle({ color: 'yellow' }) info.update(layer.feature.properties); } function onEachFeature(feature, layer) { layer.on({ click: clicky }) } function getColor(d) { return d=="C" ? '#4CAF50': d=="G" ? '#2196F3': d=="A" ? '#FFC107': d=="I" ? '#212121': d=="T" ? '#f44336': '#ecf0f1'; } function style(feature){ return getColor(feature.properties.status) } L.esri.tiledMapLayer({ url: 'http://gis.gscplanning.com/arcgis/rest/services/basemaps/gscbase_streets/MapServer', attribution: 'GSCPC', // Dealing with broken blank tiles: https://github.com/Esri/esri-leaflet/issues/759 errorTileUrl: './errorTile256.png' }).addTo(map); var cellTowers = L.esri.featureLayer({ url: 'http://services1.arcgis.com/dpmGqj7FxlwlvK0y/arcgis/rest/services/Scott_County_Cell_Towers/FeatureServer/0', pointToLayer: function (geojson, latlng) { return L.circleMarker(latlng,{ fillColor: style(geojson), fillOpacity: 1, color: '#fff', weight: 4, radius:10 } )}, onEachFeature: onEachFeature }).addTo(map); var tower = document.getElementById('appStatus'); tower.addEventListener('change', function(){ cellTowers.setWhere(tower.status); });
https-ify data sources Maybe this will let it work...
app.js
https-ify data sources
<ide><path>pp.js <ide> } <ide> <ide> L.esri.tiledMapLayer({ <del> url: 'http://gis.gscplanning.com/arcgis/rest/services/basemaps/gscbase_streets/MapServer', <add> url: 'https://gis.gscplanning.com/arcgis/rest/services/basemaps/gscbase_streets/MapServer', <ide> attribution: 'GSCPC', <ide> // Dealing with broken blank tiles: https://github.com/Esri/esri-leaflet/issues/759 <ide> errorTileUrl: './errorTile256.png' <ide> }).addTo(map); <ide> <ide> var cellTowers = L.esri.featureLayer({ <del> url: 'http://services1.arcgis.com/dpmGqj7FxlwlvK0y/arcgis/rest/services/Scott_County_Cell_Towers/FeatureServer/0', <add> url: 'https://services1.arcgis.com/dpmGqj7FxlwlvK0y/arcgis/rest/services/Scott_County_Cell_Towers/FeatureServer/0', <ide> pointToLayer: function (geojson, latlng) { <ide> return L.circleMarker(latlng,{ <ide> fillColor: style(geojson),
Java
apache-2.0
13483d9afc50c2b1daef3e1d404dc803a312d6cc
0
dkelmer/splunk-sdk-java,splunk/splunk-sdk-java,dkelmer/splunk-sdk-java,dkelmer/splunk-sdk-java,splunk/splunk-sdk-java,splunk/splunk-sdk-java,splunk/splunk-sdk-java,splunk/splunk-sdk-java,splunk/splunk-sdk-java,dkelmer/splunk-sdk-java,dkelmer/splunk-sdk-java
/* * Copyright 2012 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.splunk; import junit.framework.AssertionFailedError; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.*; import java.net.Socket; public class IndexTest extends SDKTestCase { private String indexName; private Index index; @Before @Override public void setUp() throws Exception { super.setUp(); indexName = createTemporaryName(); index = service.getIndexes().create(indexName); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return service.getIndexes().containsKey(indexName); } }); } @After @Override public void tearDown() throws Exception { if (service.versionIsAtLeast("5.0.0")) { if (service.getIndexes().containsKey(indexName)) { index.remove(); } } else { // Can't delete indexes via the REST API. Just let them build up. } super.tearDown(); } @Test public void testAttachWithCookieHeader() throws IOException { if (service.versionIsEarlierThan("6.2")) { // Cookies not implemented before version 6.2 return; } Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); Assert.assertTrue(service.hasCookies()); String validCookie = service.stringifyCookies(); Args args = new Args(); args.put("cookie", (String) validCookie); Service s = new Service(args); Index localIndex = s.getIndexes().get(indexName); Socket socket = localIndex.attach(); OutputStream ostream = socket.getOutputStream(); Writer out = new OutputStreamWriter(ostream, "UTF-8"); out.write(createTimestamp() + " Hello world!\u0150\r\n"); out.write(createTimestamp() + " Goodbye world!\u0150\r\n"); out.flush(); socket.close(); localIndex.refresh(); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { index.refresh(); return getResultCountOfIndex() == 2; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 2); } }); } @Test public void testDeletion() { if (service.versionIsEarlierThan("5.0.0")) { // Can't delete indexes via the REST API. return; } Assert.assertTrue(service.getIndexes().containsKey(indexName)); index.remove(); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return !service.getIndexes().containsKey(indexName); } }); } @Test public void testDeletionFromCollection() { if (service.versionIsEarlierThan("5.0.0")) { // Can't delete indexes via the REST API. return; } Assert.assertTrue(service.getIndexes().containsKey(indexName)); service.getIndexes().remove(indexName); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return !service.getIndexes().containsKey(indexName); } }); } @Test public void testAttachWith() throws IOException { final int originalEventCount = index.getTotalEventCount(); index.attachWith(new ReceiverBehavior() { public void run(OutputStream stream) throws IOException { String s = createTimestamp() + " Boris the mad baboon!\r\n"; stream.write(s.getBytes("UTF-8")); } }); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { index.refresh(); return index.getTotalEventCount() == originalEventCount + 1; } }); } @Test @SuppressWarnings("deprecation") public void testIndexGettersThrowNoErrors() { index.getAssureUTF8(); index.getBlockSignatureDatabase(); index.getBlockSignSize(); index.getBloomfilterTotalSizeKB(); index.getColdPath(); index.getColdPathExpanded(); index.getColdToFrozenDir(); index.getColdToFrozenScript(); index.getCompressRawdata(); index.getCurrentDBSizeMB(); index.getDefaultDatabase(); index.getEnableRealtimeSearch(); index.getFrozenTimePeriodInSecs(); index.getHomePath(); index.getHomePathExpanded(); index.getIndexThreads(); index.getLastInitTime(); index.getMaxBloomBackfillBucketAge(); index.getMaxConcurrentOptimizes(); index.getMaxDataSize(); index.getMaxHotBuckets(); index.getMaxHotIdleSecs(); index.getMaxHotSpanSecs(); index.getMaxMemMB(); index.getMaxMetaEntries(); index.getMaxRunningProcessGroups(); index.getMaxTime(); index.getMaxTotalDataSizeMB(); index.getMaxWarmDBCount(); index.getMemPoolMB(); index.getMinRawFileSyncSecs(); index.getMinTime(); index.getNumBloomfilters(); index.getNumHotBuckets(); index.getNumWarmBuckets(); index.getPartialServiceMetaPeriod(); index.getQuarantineFutureSecs(); index.getQuarantinePastSecs(); index.getRawChunkSizeBytes(); index.getRotatePeriodInSecs(); index.getServiceMetaPeriod(); index.getSuppressBannerList(); index.getSync(); index.getSyncMeta(); index.getThawedPath(); index.getThawedPathExpanded(); index.getThrottleCheckPeriod(); index.getTotalEventCount(); index.isDisabled(); index.isInternal(); // Fields only available from 5.0 on. if (service.versionIsAtLeast("5.0.0")) { index.getBucketRebuildMemoryHint(); index.getMaxTimeUnreplicatedNoAcks(); index.getMaxTimeUnreplicatedWithAcks(); } } @Test public void testSetters() { int newBlockSignSize = index.getBlockSignSize() + 1; index.setBlockSignSize(newBlockSignSize); int newFrozenTimePeriodInSecs = index.getFrozenTimePeriodInSecs()+1; index.setFrozenTimePeriodInSecs(newFrozenTimePeriodInSecs); int newMaxConcurrentOptimizes = index.getMaxConcurrentOptimizes()+1; index.setMaxConcurrentOptimizes(newMaxConcurrentOptimizes); String newMaxDataSize = "auto"; index.setMaxDataSize(newMaxDataSize); int newMaxHotBuckets = index.getMaxHotBuckets()+1; index.setMaxHotBuckets(newMaxHotBuckets); int newMaxHotIdleSecs = index.getMaxHotIdleSecs()+1; index.setMaxHotIdleSecs(newMaxHotIdleSecs); int newMaxMemMB = index.getMaxMemMB()+1; index.setMaxMemMB(newMaxMemMB); int newMaxMetaEntries = index.getMaxMetaEntries()+1; index.setMaxMetaEntries(newMaxMetaEntries); int newMaxTotalDataSizeMB = index.getMaxTotalDataSizeMB()+1; index.setMaxTotalDataSizeMB(newMaxTotalDataSizeMB); int newMaxWarmDBCount = index.getMaxWarmDBCount()+1; index.setMaxWarmDBCount(newMaxWarmDBCount); String newMinRawFileSyncSecs = "disable"; index.setMinRawFileSyncSecs(newMinRawFileSyncSecs); int newPartialServiceMetaPeriod = index.getPartialServiceMetaPeriod()+1; index.setPartialServiceMetaPeriod(newPartialServiceMetaPeriod); int newQuarantineFutureSecs = index.getQuarantineFutureSecs()+1; index.setQuarantineFutureSecs(newQuarantineFutureSecs); int newQuarantinePastSecs = index.getQuarantinePastSecs()+1; index.setQuarantinePastSecs(newQuarantinePastSecs); int newRawChunkSizeBytes = index.getRawChunkSizeBytes()+1; index.setRawChunkSizeBytes(newRawChunkSizeBytes); int newRotatePeriodInSecs = index.getRotatePeriodInSecs()+1; index.setRotatePeriodInSecs(newRotatePeriodInSecs); int newServiceMetaPeriod = index.getServiceMetaPeriod()+1; index.setServiceMetaPeriod(newServiceMetaPeriod); boolean newSyncMeta = !index.getSyncMeta(); index.setSyncMeta(newSyncMeta); int newThrottleCheckPeriod = index.getThrottleCheckPeriod()+1; index.setThrottleCheckPeriod(newThrottleCheckPeriod); String coldToFrozenDir = index.getColdToFrozenDir(); if (service.getInfo().getOsName().equals("Windows")) { index.setColdToFrozenDir("C:\\frozenDir\\" + index.getName()); } else { index.setColdToFrozenDir("/tmp/foobar" + index.getName()); } boolean newEnableOnlineBucketRepair = false; String newMaxBloomBackfillBucketAge = null; if (service.versionIsAtLeast("4.3")) { newEnableOnlineBucketRepair = !index.getEnableOnlineBucketRepair(); index.setEnableOnlineBucketRepair(newEnableOnlineBucketRepair); newMaxBloomBackfillBucketAge = "20d"; index.setMaxBloomBackfillBucketAge(newMaxBloomBackfillBucketAge); } String newBucketRebuildMemoryHint = null; int newMaxTimeUnreplicatedNoAcks = -1; int newMaxTimeUnreplicatedWithAcks = -1; if (service.versionIsAtLeast("5.0")) { newBucketRebuildMemoryHint = "auto"; index.setBucketRebuildMemoryHint(newBucketRebuildMemoryHint); newMaxTimeUnreplicatedNoAcks = 300; index.setMaxTimeUnreplicatedNoAcks(newMaxTimeUnreplicatedNoAcks); newMaxTimeUnreplicatedWithAcks = 60; index.setMaxTimeUnreplicatedWithAcks(newMaxTimeUnreplicatedWithAcks); } index.update(); index.refresh(); Assert.assertEquals(newBlockSignSize, index.getBlockSignSize()); Assert.assertEquals(newFrozenTimePeriodInSecs, index.getFrozenTimePeriodInSecs()); Assert.assertEquals(newMaxConcurrentOptimizes, index.getMaxConcurrentOptimizes()); Assert.assertEquals(newMaxDataSize, index.getMaxDataSize()); Assert.assertEquals(newMaxHotBuckets, index.getMaxHotBuckets()); Assert.assertEquals(newMaxHotIdleSecs, index.getMaxHotIdleSecs()); Assert.assertEquals(newMaxMemMB, index.getMaxMemMB()); Assert.assertEquals(newMaxMetaEntries, index.getMaxMetaEntries()); Assert.assertEquals(newMaxTotalDataSizeMB, index.getMaxTotalDataSizeMB()); Assert.assertEquals(newMaxWarmDBCount, index.getMaxWarmDBCount()); Assert.assertEquals(newMinRawFileSyncSecs, index.getMinRawFileSyncSecs()); Assert.assertEquals(newPartialServiceMetaPeriod, index.getPartialServiceMetaPeriod()); Assert.assertEquals(newQuarantineFutureSecs, index.getQuarantineFutureSecs()); Assert.assertEquals(newQuarantinePastSecs, index.getQuarantinePastSecs()); Assert.assertEquals(newRawChunkSizeBytes, index.getRawChunkSizeBytes()); Assert.assertEquals(newRotatePeriodInSecs, index.getRotatePeriodInSecs()); Assert.assertEquals(newServiceMetaPeriod, index.getServiceMetaPeriod()); Assert.assertEquals(newSyncMeta, index.getSyncMeta()); Assert.assertEquals(newThrottleCheckPeriod, index.getThrottleCheckPeriod()); if (service.getInfo().getOsName().equals("Windows")) { Assert.assertEquals("C:\\frozenDir\\" + index.getName(), index.getColdToFrozenDir()); } else { Assert.assertEquals("/tmp/foobar" + index.getName(), index.getColdToFrozenDir()); } if (service.versionIsAtLeast("4.3")) { Assert.assertEquals( newEnableOnlineBucketRepair, index.getEnableOnlineBucketRepair() ); Assert.assertEquals( newMaxBloomBackfillBucketAge, index.getMaxBloomBackfillBucketAge() ); } if (service.versionIsAtLeast("5.0")) { Assert.assertEquals( newBucketRebuildMemoryHint, index.getBucketRebuildMemoryHint() ); Assert.assertEquals( newMaxTimeUnreplicatedNoAcks, index.getMaxTimeUnreplicatedNoAcks() ); Assert.assertEquals( newMaxTimeUnreplicatedWithAcks, index.getMaxTimeUnreplicatedWithAcks() ); } index.setColdToFrozenDir(coldToFrozenDir == null ? "" : coldToFrozenDir); index.update(); String coldToFrozenScript = index.getColdToFrozenScript(); index.setColdToFrozenScript("/bin/sh"); index.update(); Assert.assertEquals("/bin/sh", index.getColdToFrozenScript()); index.setColdToFrozenScript(coldToFrozenScript == null ? "" : coldToFrozenScript); index.update(); //index.setColdToFrozenScript(coldToFrozenScript); if (restartRequired()) { splunkRestart(); } } @Test public void testEnable() { Assert.assertFalse(index.isDisabled()); // Force the index to be disabled index.disable(); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); return index.isDisabled(); } }); // Disabling an index before Splunk 6 puts Splunk into a weird state that actually // requires a restart to get out of. if (service.versionIsEarlierThan("6.0.0")) { splunkRestart(); } // And then enable it index.enable(); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); return !index.isDisabled(); } }); } @Test public void testSubmitOne() throws Exception { try { tryTestSubmitOne(); } catch (AssertionFailedError e) { if (e.getMessage().contains("Test timed out before true.") && restartRequired()) { System.out.println( "WARNING: Splunk indicated restart required while " + "running a test. Trying to recover..."); splunkRestart(); tryTestSubmitOne(); } else { throw e; } } } private void tryTestSubmitOne() { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); index.submit(createTimestamp() + " This is a test of the emergency broadcasting system."); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 1; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); return index.getTotalEventCount() == 1; } }); } @Test public void testSubmitOneArgs() throws Exception { try { tryTestSubmitOneArgs(); } catch (AssertionFailedError e) { if (e.getMessage().contains("Test timed out before true.") && restartRequired()) { System.out.println( "WARNING: Splunk indicated restart required while " + "running a test. Trying to recover..."); splunkRestart(); tryTestSubmitOne(); } else { throw e; } } } private void tryTestSubmitOneArgs() { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); Args args = Args.create("sourcetype", "mysourcetype"); index.submit(args, createTimestamp() + " This is a test of the emergency broadcasting system."); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 1; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); return index.getTotalEventCount() == 1; } }); } @Test public void testSubmitOneInEachCall() { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); index.submit(createTimestamp() + " Hello world!\u0150"); index.submit(createTimestamp() + " Goodbye world!\u0150"); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 2; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 2); } }); } @Test public void testSubmitMultipleInOneCall() { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); index.submit( createTimestamp() + " Hello world!\u0150" + "\r\n" + createTimestamp() + " Goodbye world!\u0150"); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 2; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 2); } }); } @Test public void testAttach() throws IOException { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); Socket socket = index.attach(); OutputStream ostream = socket.getOutputStream(); Writer out = new OutputStreamWriter(ostream, "UTF-8"); out.write(createTimestamp() + " Hello world!\u0150\r\n"); out.write(createTimestamp() + " Goodbye world!\u0150\r\n"); out.flush(); socket.close(); index.refresh(); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { index.refresh(); return getResultCountOfIndex() == 2; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 2); } }); } @Test public void testAttachArgs() throws IOException { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); Args args = Args.create("sourcetype", "mysourcetype"); Socket socket = index.attach(args); OutputStream ostream = socket.getOutputStream(); Writer out = new OutputStreamWriter(ostream, "UTF-8"); out.write(createTimestamp() + " Hello world!\u0150\r\n"); out.write(createTimestamp() + " Goodbye world!\u0150\r\n"); out.write(createTimestamp() + " Goodbye world again!\u0150\r\n"); out.flush(); socket.close(); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { return getResultCountOfIndex() == 3; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 3); } }); } @Test public void testUploadArgs() throws Exception { if (!hasTestData()) { System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test."); return; } installApplicationFromTestData("file_to_upload"); Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); String fileToUpload = joinServerPath(new String[] { service.getSettings().getSplunkHome(), "etc", "apps", "file_to_upload", "log.txt"}); Args args = new Args(); args.add("sourcetype", "log"); args.add("host", "IndexTest"); args.add("rename-source", "IndexTestSrc"); index.upload(fileToUpload, args); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { Service con = index.getService(); Job search = con.search("search index=" + index.getTitle() + " sourcetype=log host=IndexTest source=IndexTestSrc"); return getResultCountOfIndex() == 4 && search.getEventCount() == 4; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 4); } }); } @Test public void testUploadArgsFailure() throws Exception{ if (!hasTestData()) { System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test."); return; } installApplicationFromTestData("file_to_upload"); Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); String fileToUpload = joinServerPath(new String[] { service.getSettings().getSplunkHome(), "etc", "apps", "file_to_upload", "log.txt"}); Args args = new Args(); args.add("sourcetype", "log"); args.add("host", "IndexTest"); args.add("index", index.getTitle()); args.add("rename-source", "IndexTestSrc"); // The index argument cannot be passed into the upload function. try{ index.upload(fileToUpload, args); Assert.fail("Uploading to an index with an index argument? No need for redundency!"); } catch(Exception e){ Assert.assertEquals(e.getMessage(), "The 'index' parameter cannot be passed to an index's oneshot upload."); } } @Test public void testUpload() throws Exception { if (!hasTestData()) { System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test."); return; } installApplicationFromTestData("file_to_upload"); Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); String fileToUpload = joinServerPath(new String[] { service.getSettings().getSplunkHome(), "etc", "apps", "file_to_upload", "log.txt"}); index.upload(fileToUpload); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 4; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 4); } }); } @Test public void testSubmitAndClean() throws InterruptedException { try { tryTestSubmitAndClean(); } catch (SplunkException e) { if (e.getCode() == SplunkException.TIMEOUT) { // Due to flakiness of the underlying implementation, // this index clean method doesn't always work on a "dirty" // Splunk instance. Try again on a "clean" instance. System.out.println( "WARNING: Index clean timed out. Trying again on a " + "freshly restarted Splunk instance..."); uncheckedSplunkRestart(); tryTestSubmitAndClean(); } else { throw e; } } } private void tryTestSubmitAndClean() throws InterruptedException { Assert.assertTrue(getResultCountOfIndex() == 0); // Make sure the index is not empty. index.submit("Hello world"); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 50; } @Override public boolean predicate() { return getResultCountOfIndex() == 1; } }); // Clean the index and make sure it's empty. // NOTE: Average time for this is 65s (!!!). Have seen 110+. index.clean(150); Assert.assertTrue(getResultCountOfIndex() == 0); } @Test public void testUpdateNameShouldFail() { try { index.update(new Args("name", createTemporaryName())); Assert.fail("Expected IllegalStateException."); } catch (IllegalStateException e) { // Good } } // === Utility === private int getResultCountOfIndex() { InputStream results = service.oneshotSearch("search index=" + indexName); try { ResultsReaderXml resultsReader = new ResultsReaderXml(results); int numEvents = 0; while (resultsReader.getNextEvent() != null) { numEvents++; } return numEvents; } catch (IOException e) { throw new RuntimeException(e); } } }
tests/com/splunk/IndexTest.java
/* * Copyright 2012 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.splunk; import junit.framework.AssertionFailedError; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.*; import java.net.Socket; public class IndexTest extends SDKTestCase { private String indexName; private Index index; @Before @Override public void setUp() throws Exception { super.setUp(); indexName = createTemporaryName(); index = service.getIndexes().create(indexName); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return service.getIndexes().containsKey(indexName); } }); } @After @Override public void tearDown() throws Exception { if (service.versionIsAtLeast("5.0.0")) { if (service.getIndexes().containsKey(indexName)) { index.remove(); } } else { // Can't delete indexes via the REST API. Just let them build up. } super.tearDown(); } @Test public void testDeletion() { if (service.versionIsEarlierThan("5.0.0")) { // Can't delete indexes via the REST API. return; } Assert.assertTrue(service.getIndexes().containsKey(indexName)); index.remove(); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return !service.getIndexes().containsKey(indexName); } }); } @Test public void testDeletionFromCollection() { if (service.versionIsEarlierThan("5.0.0")) { // Can't delete indexes via the REST API. return; } Assert.assertTrue(service.getIndexes().containsKey(indexName)); service.getIndexes().remove(indexName); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return !service.getIndexes().containsKey(indexName); } }); } @Test public void testAttachWith() throws IOException { final int originalEventCount = index.getTotalEventCount(); index.attachWith(new ReceiverBehavior() { public void run(OutputStream stream) throws IOException { String s = createTimestamp() + " Boris the mad baboon!\r\n"; stream.write(s.getBytes("UTF-8")); } }); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { index.refresh(); return index.getTotalEventCount() == originalEventCount + 1; } }); } @Test @SuppressWarnings("deprecation") public void testIndexGettersThrowNoErrors() { index.getAssureUTF8(); index.getBlockSignatureDatabase(); index.getBlockSignSize(); index.getBloomfilterTotalSizeKB(); index.getColdPath(); index.getColdPathExpanded(); index.getColdToFrozenDir(); index.getColdToFrozenScript(); index.getCompressRawdata(); index.getCurrentDBSizeMB(); index.getDefaultDatabase(); index.getEnableRealtimeSearch(); index.getFrozenTimePeriodInSecs(); index.getHomePath(); index.getHomePathExpanded(); index.getIndexThreads(); index.getLastInitTime(); index.getMaxBloomBackfillBucketAge(); index.getMaxConcurrentOptimizes(); index.getMaxDataSize(); index.getMaxHotBuckets(); index.getMaxHotIdleSecs(); index.getMaxHotSpanSecs(); index.getMaxMemMB(); index.getMaxMetaEntries(); index.getMaxRunningProcessGroups(); index.getMaxTime(); index.getMaxTotalDataSizeMB(); index.getMaxWarmDBCount(); index.getMemPoolMB(); index.getMinRawFileSyncSecs(); index.getMinTime(); index.getNumBloomfilters(); index.getNumHotBuckets(); index.getNumWarmBuckets(); index.getPartialServiceMetaPeriod(); index.getQuarantineFutureSecs(); index.getQuarantinePastSecs(); index.getRawChunkSizeBytes(); index.getRotatePeriodInSecs(); index.getServiceMetaPeriod(); index.getSuppressBannerList(); index.getSync(); index.getSyncMeta(); index.getThawedPath(); index.getThawedPathExpanded(); index.getThrottleCheckPeriod(); index.getTotalEventCount(); index.isDisabled(); index.isInternal(); // Fields only available from 5.0 on. if (service.versionIsAtLeast("5.0.0")) { index.getBucketRebuildMemoryHint(); index.getMaxTimeUnreplicatedNoAcks(); index.getMaxTimeUnreplicatedWithAcks(); } } @Test public void testSetters() { int newBlockSignSize = index.getBlockSignSize() + 1; index.setBlockSignSize(newBlockSignSize); int newFrozenTimePeriodInSecs = index.getFrozenTimePeriodInSecs()+1; index.setFrozenTimePeriodInSecs(newFrozenTimePeriodInSecs); int newMaxConcurrentOptimizes = index.getMaxConcurrentOptimizes()+1; index.setMaxConcurrentOptimizes(newMaxConcurrentOptimizes); String newMaxDataSize = "auto"; index.setMaxDataSize(newMaxDataSize); int newMaxHotBuckets = index.getMaxHotBuckets()+1; index.setMaxHotBuckets(newMaxHotBuckets); int newMaxHotIdleSecs = index.getMaxHotIdleSecs()+1; index.setMaxHotIdleSecs(newMaxHotIdleSecs); int newMaxMemMB = index.getMaxMemMB()+1; index.setMaxMemMB(newMaxMemMB); int newMaxMetaEntries = index.getMaxMetaEntries()+1; index.setMaxMetaEntries(newMaxMetaEntries); int newMaxTotalDataSizeMB = index.getMaxTotalDataSizeMB()+1; index.setMaxTotalDataSizeMB(newMaxTotalDataSizeMB); int newMaxWarmDBCount = index.getMaxWarmDBCount()+1; index.setMaxWarmDBCount(newMaxWarmDBCount); String newMinRawFileSyncSecs = "disable"; index.setMinRawFileSyncSecs(newMinRawFileSyncSecs); int newPartialServiceMetaPeriod = index.getPartialServiceMetaPeriod()+1; index.setPartialServiceMetaPeriod(newPartialServiceMetaPeriod); int newQuarantineFutureSecs = index.getQuarantineFutureSecs()+1; index.setQuarantineFutureSecs(newQuarantineFutureSecs); int newQuarantinePastSecs = index.getQuarantinePastSecs()+1; index.setQuarantinePastSecs(newQuarantinePastSecs); int newRawChunkSizeBytes = index.getRawChunkSizeBytes()+1; index.setRawChunkSizeBytes(newRawChunkSizeBytes); int newRotatePeriodInSecs = index.getRotatePeriodInSecs()+1; index.setRotatePeriodInSecs(newRotatePeriodInSecs); int newServiceMetaPeriod = index.getServiceMetaPeriod()+1; index.setServiceMetaPeriod(newServiceMetaPeriod); boolean newSyncMeta = !index.getSyncMeta(); index.setSyncMeta(newSyncMeta); int newThrottleCheckPeriod = index.getThrottleCheckPeriod()+1; index.setThrottleCheckPeriod(newThrottleCheckPeriod); String coldToFrozenDir = index.getColdToFrozenDir(); if (service.getInfo().getOsName().equals("Windows")) { index.setColdToFrozenDir("C:\\frozenDir\\" + index.getName()); } else { index.setColdToFrozenDir("/tmp/foobar" + index.getName()); } boolean newEnableOnlineBucketRepair = false; String newMaxBloomBackfillBucketAge = null; if (service.versionIsAtLeast("4.3")) { newEnableOnlineBucketRepair = !index.getEnableOnlineBucketRepair(); index.setEnableOnlineBucketRepair(newEnableOnlineBucketRepair); newMaxBloomBackfillBucketAge = "20d"; index.setMaxBloomBackfillBucketAge(newMaxBloomBackfillBucketAge); } String newBucketRebuildMemoryHint = null; int newMaxTimeUnreplicatedNoAcks = -1; int newMaxTimeUnreplicatedWithAcks = -1; if (service.versionIsAtLeast("5.0")) { newBucketRebuildMemoryHint = "auto"; index.setBucketRebuildMemoryHint(newBucketRebuildMemoryHint); newMaxTimeUnreplicatedNoAcks = 300; index.setMaxTimeUnreplicatedNoAcks(newMaxTimeUnreplicatedNoAcks); newMaxTimeUnreplicatedWithAcks = 60; index.setMaxTimeUnreplicatedWithAcks(newMaxTimeUnreplicatedWithAcks); } index.update(); index.refresh(); Assert.assertEquals(newBlockSignSize, index.getBlockSignSize()); Assert.assertEquals(newFrozenTimePeriodInSecs, index.getFrozenTimePeriodInSecs()); Assert.assertEquals(newMaxConcurrentOptimizes, index.getMaxConcurrentOptimizes()); Assert.assertEquals(newMaxDataSize, index.getMaxDataSize()); Assert.assertEquals(newMaxHotBuckets, index.getMaxHotBuckets()); Assert.assertEquals(newMaxHotIdleSecs, index.getMaxHotIdleSecs()); Assert.assertEquals(newMaxMemMB, index.getMaxMemMB()); Assert.assertEquals(newMaxMetaEntries, index.getMaxMetaEntries()); Assert.assertEquals(newMaxTotalDataSizeMB, index.getMaxTotalDataSizeMB()); Assert.assertEquals(newMaxWarmDBCount, index.getMaxWarmDBCount()); Assert.assertEquals(newMinRawFileSyncSecs, index.getMinRawFileSyncSecs()); Assert.assertEquals(newPartialServiceMetaPeriod, index.getPartialServiceMetaPeriod()); Assert.assertEquals(newQuarantineFutureSecs, index.getQuarantineFutureSecs()); Assert.assertEquals(newQuarantinePastSecs, index.getQuarantinePastSecs()); Assert.assertEquals(newRawChunkSizeBytes, index.getRawChunkSizeBytes()); Assert.assertEquals(newRotatePeriodInSecs, index.getRotatePeriodInSecs()); Assert.assertEquals(newServiceMetaPeriod, index.getServiceMetaPeriod()); Assert.assertEquals(newSyncMeta, index.getSyncMeta()); Assert.assertEquals(newThrottleCheckPeriod, index.getThrottleCheckPeriod()); if (service.getInfo().getOsName().equals("Windows")) { Assert.assertEquals("C:\\frozenDir\\" + index.getName(), index.getColdToFrozenDir()); } else { Assert.assertEquals("/tmp/foobar" + index.getName(), index.getColdToFrozenDir()); } if (service.versionIsAtLeast("4.3")) { Assert.assertEquals( newEnableOnlineBucketRepair, index.getEnableOnlineBucketRepair() ); Assert.assertEquals( newMaxBloomBackfillBucketAge, index.getMaxBloomBackfillBucketAge() ); } if (service.versionIsAtLeast("5.0")) { Assert.assertEquals( newBucketRebuildMemoryHint, index.getBucketRebuildMemoryHint() ); Assert.assertEquals( newMaxTimeUnreplicatedNoAcks, index.getMaxTimeUnreplicatedNoAcks() ); Assert.assertEquals( newMaxTimeUnreplicatedWithAcks, index.getMaxTimeUnreplicatedWithAcks() ); } index.setColdToFrozenDir(coldToFrozenDir == null ? "" : coldToFrozenDir); index.update(); String coldToFrozenScript = index.getColdToFrozenScript(); index.setColdToFrozenScript("/bin/sh"); index.update(); Assert.assertEquals("/bin/sh", index.getColdToFrozenScript()); index.setColdToFrozenScript(coldToFrozenScript == null ? "" : coldToFrozenScript); index.update(); //index.setColdToFrozenScript(coldToFrozenScript); if (restartRequired()) { splunkRestart(); } } @Test public void testEnable() { Assert.assertFalse(index.isDisabled()); // Force the index to be disabled index.disable(); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); return index.isDisabled(); } }); // Disabling an index before Splunk 6 puts Splunk into a weird state that actually // requires a restart to get out of. if (service.versionIsEarlierThan("6.0.0")) { splunkRestart(); } // And then enable it index.enable(); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); return !index.isDisabled(); } }); } @Test public void testSubmitOne() throws Exception { try { tryTestSubmitOne(); } catch (AssertionFailedError e) { if (e.getMessage().contains("Test timed out before true.") && restartRequired()) { System.out.println( "WARNING: Splunk indicated restart required while " + "running a test. Trying to recover..."); splunkRestart(); tryTestSubmitOne(); } else { throw e; } } } private void tryTestSubmitOne() { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); index.submit(createTimestamp() + " This is a test of the emergency broadcasting system."); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 1; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); return index.getTotalEventCount() == 1; } }); } @Test public void testSubmitOneArgs() throws Exception { try { tryTestSubmitOneArgs(); } catch (AssertionFailedError e) { if (e.getMessage().contains("Test timed out before true.") && restartRequired()) { System.out.println( "WARNING: Splunk indicated restart required while " + "running a test. Trying to recover..."); splunkRestart(); tryTestSubmitOne(); } else { throw e; } } } private void tryTestSubmitOneArgs() { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); Args args = Args.create("sourcetype", "mysourcetype"); index.submit(args, createTimestamp() + " This is a test of the emergency broadcasting system."); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 1; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); return index.getTotalEventCount() == 1; } }); } @Test public void testSubmitOneInEachCall() { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); index.submit(createTimestamp() + " Hello world!\u0150"); index.submit(createTimestamp() + " Goodbye world!\u0150"); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 2; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 2); } }); } @Test public void testSubmitMultipleInOneCall() { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); index.submit( createTimestamp() + " Hello world!\u0150" + "\r\n" + createTimestamp() + " Goodbye world!\u0150"); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 2; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 2); } }); } @Test public void testAttach() throws IOException { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); Socket socket = index.attach(); OutputStream ostream = socket.getOutputStream(); Writer out = new OutputStreamWriter(ostream, "UTF-8"); out.write(createTimestamp() + " Hello world!\u0150\r\n"); out.write(createTimestamp() + " Goodbye world!\u0150\r\n"); out.flush(); socket.close(); index.refresh(); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { index.refresh(); return getResultCountOfIndex() == 2; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 2); } }); } @Test public void testAttachArgs() throws IOException { Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); Args args = Args.create("sourcetype", "mysourcetype"); Socket socket = index.attach(args); OutputStream ostream = socket.getOutputStream(); Writer out = new OutputStreamWriter(ostream, "UTF-8"); out.write(createTimestamp() + " Hello world!\u0150\r\n"); out.write(createTimestamp() + " Goodbye world!\u0150\r\n"); out.write(createTimestamp() + " Goodbye world again!\u0150\r\n"); out.flush(); socket.close(); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { return getResultCountOfIndex() == 3; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 60; } @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 3); } }); } @Test public void testUploadArgs() throws Exception { if (!hasTestData()) { System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test."); return; } installApplicationFromTestData("file_to_upload"); Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); String fileToUpload = joinServerPath(new String[] { service.getSettings().getSplunkHome(), "etc", "apps", "file_to_upload", "log.txt"}); Args args = new Args(); args.add("sourcetype", "log"); args.add("host", "IndexTest"); args.add("rename-source", "IndexTestSrc"); index.upload(fileToUpload, args); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { Service con = index.getService(); Job search = con.search("search index=" + index.getTitle() + " sourcetype=log host=IndexTest source=IndexTestSrc"); return getResultCountOfIndex() == 4 && search.getEventCount() == 4; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 4); } }); } @Test public void testUploadArgsFailure() throws Exception{ if (!hasTestData()) { System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test."); return; } installApplicationFromTestData("file_to_upload"); Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); String fileToUpload = joinServerPath(new String[] { service.getSettings().getSplunkHome(), "etc", "apps", "file_to_upload", "log.txt"}); Args args = new Args(); args.add("sourcetype", "log"); args.add("host", "IndexTest"); args.add("index", index.getTitle()); args.add("rename-source", "IndexTestSrc"); // The index argument cannot be passed into the upload function. try{ index.upload(fileToUpload, args); Assert.fail("Uploading to an index with an index argument? No need for redundency!"); } catch(Exception e){ Assert.assertEquals(e.getMessage(), "The 'index' parameter cannot be passed to an index's oneshot upload."); } } @Test public void testUpload() throws Exception { if (!hasTestData()) { System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test."); return; } installApplicationFromTestData("file_to_upload"); Assert.assertTrue(getResultCountOfIndex() == 0); Assert.assertTrue(index.getTotalEventCount() == 0); String fileToUpload = joinServerPath(new String[] { service.getSettings().getSplunkHome(), "etc", "apps", "file_to_upload", "log.txt"}); index.upload(fileToUpload); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { return getResultCountOfIndex() == 4; } }); assertEventuallyTrue(new EventuallyTrueBehavior() { @Override public boolean predicate() { index.refresh(); // Some versions of Splunk only increase event count by 1. // Event count should never go up by more than the result count. int tec = index.getTotalEventCount(); return (1 <= tec) && (tec <= 4); } }); } @Test public void testSubmitAndClean() throws InterruptedException { try { tryTestSubmitAndClean(); } catch (SplunkException e) { if (e.getCode() == SplunkException.TIMEOUT) { // Due to flakiness of the underlying implementation, // this index clean method doesn't always work on a "dirty" // Splunk instance. Try again on a "clean" instance. System.out.println( "WARNING: Index clean timed out. Trying again on a " + "freshly restarted Splunk instance..."); uncheckedSplunkRestart(); tryTestSubmitAndClean(); } else { throw e; } } } private void tryTestSubmitAndClean() throws InterruptedException { Assert.assertTrue(getResultCountOfIndex() == 0); // Make sure the index is not empty. index.submit("Hello world"); assertEventuallyTrue(new EventuallyTrueBehavior() { { tries = 50; } @Override public boolean predicate() { return getResultCountOfIndex() == 1; } }); // Clean the index and make sure it's empty. // NOTE: Average time for this is 65s (!!!). Have seen 110+. index.clean(150); Assert.assertTrue(getResultCountOfIndex() == 0); } @Test public void testUpdateNameShouldFail() { try { index.update(new Args("name", createTemporaryName())); Assert.fail("Expected IllegalStateException."); } catch (IllegalStateException e) { // Good } } // === Utility === private int getResultCountOfIndex() { InputStream results = service.oneshotSearch("search index=" + indexName); try { ResultsReaderXml resultsReader = new ResultsReaderXml(results); int numEvents = 0; while (resultsReader.getNextEvent() != null) { numEvents++; } return numEvents; } catch (IOException e) { throw new RuntimeException(e); } } }
Adding an index test for cookies
tests/com/splunk/IndexTest.java
Adding an index test for cookies
<ide><path>ests/com/splunk/IndexTest.java <ide> @Override <ide> public void setUp() throws Exception { <ide> super.setUp(); <del> <add> <ide> indexName = createTemporaryName(); <ide> index = service.getIndexes().create(indexName); <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> } else { <ide> // Can't delete indexes via the REST API. Just let them build up. <ide> } <del> <add> <ide> super.tearDown(); <add> } <add> <add> @Test <add> public void testAttachWithCookieHeader() throws IOException { <add> if (service.versionIsEarlierThan("6.2")) { <add> // Cookies not implemented before version 6.2 <add> return; <add> } <add> <add> Assert.assertTrue(getResultCountOfIndex() == 0); <add> Assert.assertTrue(index.getTotalEventCount() == 0); <add> <add> Assert.assertTrue(service.hasCookies()); <add> <add> String validCookie = service.stringifyCookies(); <add> <add> Args args = new Args(); <add> args.put("cookie", (String) validCookie); <add> <add> Service s = new Service(args); <add> <add> <add> Index localIndex = s.getIndexes().get(indexName); <add> Socket socket = localIndex.attach(); <add> <add> OutputStream ostream = socket.getOutputStream(); <add> Writer out = new OutputStreamWriter(ostream, "UTF-8"); <add> out.write(createTimestamp() + " Hello world!\u0150\r\n"); <add> out.write(createTimestamp() + " Goodbye world!\u0150\r\n"); <add> <add> out.flush(); <add> socket.close(); <add> <add> localIndex.refresh(); <add> <add> assertEventuallyTrue(new EventuallyTrueBehavior() { <add> { tries = 60; } <add> <add> @Override <add> public boolean predicate() { <add> index.refresh(); <add> return getResultCountOfIndex() == 2; <add> } <add> }); <add> <add> assertEventuallyTrue(new EventuallyTrueBehavior() { <add> @Override <add> public boolean predicate() { <add> index.refresh(); <add> <add> // Some versions of Splunk only increase event count by 1. <add> // Event count should never go up by more than the result count. <add> int tec = index.getTotalEventCount(); <add> return (1 <= tec) && (tec <= 2); <add> } <add> }); <add> <add> <ide> } <ide> <ide> @Test <ide> // Can't delete indexes via the REST API. <ide> return; <ide> } <del> <add> <ide> Assert.assertTrue(service.getIndexes().containsKey(indexName)); <del> <add> <ide> index.remove(); <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> @Override <ide> // Can't delete indexes via the REST API. <ide> return; <ide> } <del> <add> <ide> Assert.assertTrue(service.getIndexes().containsKey(indexName)); <ide> service.getIndexes().remove(indexName); <del> <add> <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> @Override <ide> public boolean predicate() { <ide> @Test <ide> public void testAttachWith() throws IOException { <ide> final int originalEventCount = index.getTotalEventCount(); <del> <add> <ide> index.attachWith(new ReceiverBehavior() { <ide> public void run(OutputStream stream) throws IOException { <ide> String s = createTimestamp() + " Boris the mad baboon!\r\n"; <ide> stream.write(s.getBytes("UTF-8")); <ide> } <ide> }); <del> <add> <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> { tries = 60; } <ide> <ide> index.getTotalEventCount(); <ide> index.isDisabled(); <ide> index.isInternal(); <del> <add> <ide> // Fields only available from 5.0 on. <ide> if (service.versionIsAtLeast("5.0.0")) { <ide> index.getBucketRebuildMemoryHint(); <ide> newMaxBloomBackfillBucketAge = "20d"; <ide> index.setMaxBloomBackfillBucketAge(newMaxBloomBackfillBucketAge); <ide> } <del> <add> <ide> String newBucketRebuildMemoryHint = null; <ide> int newMaxTimeUnreplicatedNoAcks = -1; <ide> int newMaxTimeUnreplicatedWithAcks = -1; <ide> index.getMaxTimeUnreplicatedWithAcks() <ide> ); <ide> } <del> <add> <ide> index.setColdToFrozenDir(coldToFrozenDir == null ? "" : coldToFrozenDir); <ide> index.update(); <del> <add> <ide> String coldToFrozenScript = index.getColdToFrozenScript(); <ide> index.setColdToFrozenScript("/bin/sh"); <ide> index.update(); <ide> index.setColdToFrozenScript(coldToFrozenScript == null ? "" : coldToFrozenScript); <ide> index.update(); <ide> //index.setColdToFrozenScript(coldToFrozenScript); <del> <add> <ide> if (restartRequired()) { <ide> splunkRestart(); <ide> } <ide> @Test <ide> public void testEnable() { <ide> Assert.assertFalse(index.isDisabled()); <del> <add> <ide> // Force the index to be disabled <ide> index.disable(); <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> try { <ide> tryTestSubmitOne(); <ide> } catch (AssertionFailedError e) { <del> if (e.getMessage().contains("Test timed out before true.") && <add> if (e.getMessage().contains("Test timed out before true.") && <ide> restartRequired()) { <ide> System.out.println( <ide> "WARNING: Splunk indicated restart required while " + <ide> "running a test. Trying to recover..."); <ide> splunkRestart(); <del> <add> <ide> tryTestSubmitOne(); <ide> } else { <ide> throw e; <ide> } <ide> } <ide> } <del> <add> <ide> private void tryTestSubmitOne() { <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> Assert.assertTrue(index.getTotalEventCount() == 0); <del> <add> <ide> index.submit(createTimestamp() + " This is a test of the emergency broadcasting system."); <del> <add> <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> @Override <ide> public boolean predicate() { <ide> try { <ide> tryTestSubmitOneArgs(); <ide> } catch (AssertionFailedError e) { <del> if (e.getMessage().contains("Test timed out before true.") && <add> if (e.getMessage().contains("Test timed out before true.") && <ide> restartRequired()) { <ide> System.out.println( <ide> "WARNING: Splunk indicated restart required while " + <ide> "running a test. Trying to recover..."); <ide> splunkRestart(); <del> <add> <ide> tryTestSubmitOne(); <ide> } else { <ide> throw e; <ide> } <ide> } <ide> } <del> <add> <ide> private void tryTestSubmitOneArgs() { <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> Assert.assertTrue(index.getTotalEventCount() == 0); <del> <add> <ide> Args args = Args.create("sourcetype", "mysourcetype"); <ide> index.submit(args, createTimestamp() + " This is a test of the emergency broadcasting system."); <del> <add> <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> @Override <ide> public boolean predicate() { <ide> } <ide> }); <ide> } <del> <add> <ide> @Test <ide> public void testSubmitOneInEachCall() { <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> Assert.assertTrue(index.getTotalEventCount() == 0); <del> <add> <ide> index.submit(createTimestamp() + " Hello world!\u0150"); <ide> index.submit(createTimestamp() + " Goodbye world!\u0150"); <del> <add> <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> @Override <ide> public boolean predicate() { <ide> @Override <ide> public boolean predicate() { <ide> index.refresh(); <del> <add> <ide> // Some versions of Splunk only increase event count by 1. <ide> // Event count should never go up by more than the result count. <ide> int tec = index.getTotalEventCount(); <ide> } <ide> }); <ide> } <del> <add> <ide> @Test <ide> public void testSubmitMultipleInOneCall() { <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> Assert.assertTrue(index.getTotalEventCount() == 0); <del> <add> <ide> index.submit( <ide> createTimestamp() + " Hello world!\u0150" + "\r\n" + <ide> createTimestamp() + " Goodbye world!\u0150"); <del> <add> <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> @Override <ide> public boolean predicate() { <ide> @Override <ide> public boolean predicate() { <ide> index.refresh(); <del> <add> <ide> // Some versions of Splunk only increase event count by 1. <ide> // Event count should never go up by more than the result count. <ide> int tec = index.getTotalEventCount(); <ide> @Override <ide> public boolean predicate() { <ide> index.refresh(); <del> <add> <ide> // Some versions of Splunk only increase event count by 1. <ide> // Event count should never go up by more than the result count. <ide> int tec = index.getTotalEventCount(); <ide> public void testAttachArgs() throws IOException { <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> Assert.assertTrue(index.getTotalEventCount() == 0); <del> <add> <ide> Args args = Args.create("sourcetype", "mysourcetype"); <ide> Socket socket = index.attach(args); <ide> OutputStream ostream = socket.getOutputStream(); <ide> <ide> out.flush(); <ide> socket.close(); <del> <add> <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> { tries = 60; } <ide> @Override <ide> @Override <ide> public boolean predicate() { <ide> index.refresh(); <del> <add> <ide> // Some versions of Splunk only increase event count by 1. <ide> // Event count should never go up by more than the result count. <ide> int tec = index.getTotalEventCount(); <ide> System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test."); <ide> return; <ide> } <del> <add> <ide> installApplicationFromTestData("file_to_upload"); <ide> <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> String fileToUpload = joinServerPath(new String[] { <ide> service.getSettings().getSplunkHome(), <ide> "etc", "apps", "file_to_upload", "log.txt"}); <del> <add> <ide> Args args = new Args(); <ide> args.add("sourcetype", "log"); <ide> args.add("host", "IndexTest"); <ide> args.add("rename-source", "IndexTestSrc"); <del> <add> <ide> index.upload(fileToUpload, args); <ide> <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> } <ide> }); <ide> } <del> <add> <ide> @Test <ide> public void testUploadArgsFailure() throws Exception{ <ide> if (!hasTestData()) { <ide> return; <ide> } <ide> installApplicationFromTestData("file_to_upload"); <del> <add> <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> Assert.assertTrue(index.getTotalEventCount() == 0); <ide> <ide> String fileToUpload = joinServerPath(new String[] { <ide> service.getSettings().getSplunkHome(), <ide> "etc", "apps", "file_to_upload", "log.txt"}); <del> <add> <ide> Args args = new Args(); <ide> args.add("sourcetype", "log"); <ide> args.add("host", "IndexTest"); <ide> args.add("index", index.getTitle()); <ide> args.add("rename-source", "IndexTestSrc"); <del> // The index argument cannot be passed into the upload function. <add> // The index argument cannot be passed into the upload function. <ide> try{ <ide> index.upload(fileToUpload, args); <ide> Assert.fail("Uploading to an index with an index argument? No need for redundency!"); <ide> catch(Exception e){ <ide> Assert.assertEquals(e.getMessage(), "The 'index' parameter cannot be passed to an index's oneshot upload."); <ide> } <del> <del> } <del> <del> <del> <del> <del> <add> <add> } <add> <add> <add> <add> <add> <ide> @Test <ide> public void testUpload() throws Exception { <ide> if (!hasTestData()) { <ide> System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test."); <ide> return; <ide> } <del> <add> <ide> installApplicationFromTestData("file_to_upload"); <del> <add> <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> Assert.assertTrue(index.getTotalEventCount() == 0); <ide> <ide> @Override <ide> public boolean predicate() { <ide> index.refresh(); <del> <add> <ide> // Some versions of Splunk only increase event count by 1. <ide> // Event count should never go up by more than the result count. <ide> int tec = index.getTotalEventCount(); <ide> "WARNING: Index clean timed out. Trying again on a " + <ide> "freshly restarted Splunk instance..."); <ide> uncheckedSplunkRestart(); <del> <add> <ide> tryTestSubmitAndClean(); <ide> } else { <ide> throw e; <ide> } <ide> } <ide> } <del> <add> <ide> private void tryTestSubmitAndClean() throws InterruptedException { <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <del> <add> <ide> // Make sure the index is not empty. <ide> index.submit("Hello world"); <ide> assertEventuallyTrue(new EventuallyTrueBehavior() { <ide> return getResultCountOfIndex() == 1; <ide> } <ide> }); <del> <add> <ide> // Clean the index and make sure it's empty. <ide> // NOTE: Average time for this is 65s (!!!). Have seen 110+. <ide> index.clean(150); <ide> Assert.assertTrue(getResultCountOfIndex() == 0); <ide> } <del> <add> <ide> @Test <ide> public void testUpdateNameShouldFail() { <ide> try { <ide> // Good <ide> } <ide> } <del> <add> <ide> // === Utility === <ide> <ide> private int getResultCountOfIndex() { <ide> InputStream results = service.oneshotSearch("search index=" + indexName); <ide> try { <ide> ResultsReaderXml resultsReader = new ResultsReaderXml(results); <del> <add> <ide> int numEvents = 0; <ide> while (resultsReader.getNextEvent() != null) { <ide> numEvents++;
Java
lgpl-2.1
f8b16c6fa707a2556de8fad6a830c2f1cc6e7631
0
johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,johnscancella/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.cloud.db; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugRanker; import edu.umd.cs.findbugs.DetectorFactoryCollection; import edu.umd.cs.findbugs.FindBugs; import edu.umd.cs.findbugs.ProjectPackagePrefixes; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.StartTime; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.Version; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.cloud.AbstractCloud; import edu.umd.cs.findbugs.cloud.OnlineCloud; import edu.umd.cs.findbugs.cloud.BugFilingCommentHelper; import edu.umd.cs.findbugs.cloud.CloudFactory; import edu.umd.cs.findbugs.cloud.CloudPlugin; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.Util; /** * @author pwilliam */ public class DBCloud extends AbstractCloud implements OnlineCloud { public static final String FINDBUGS_USER_PROPERTY = "findbugsUser"; static final long FIRST_LIGHT = FindBugs.MINIMUM_TIMESTAMP; static final long ONE_DAY = 24L * 60 * 60 * 1000; static final String USER_NAME = "user.name"; private SigninState signinState = SigninState.SIGNING_IN; class BugData { final String instanceHash; public BugData(String instanceHash) { this.instanceHash = instanceHash; } int id; boolean inDatabase; long firstSeen = bugCollection.getTimestamp(); String bugLink = NONE; String filedBy; String bugStatus; String bugAssignedTo; String bugComponentName; long bugFiled = Long.MAX_VALUE; SortedSet<BugDesignation> designations = new TreeSet<BugDesignation>(); Collection<BugInstance> bugs = new LinkedHashSet<BugInstance>(); long lastSeen; @CheckForNull BugDesignation getPrimaryDesignation() { for (BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return bd; return null; } @CheckForNull BugDesignation getUserDesignation() { for (BugDesignation d : designations) if (findbugsUser.equals(d.getUser())) return new BugDesignation(d); return null; } Collection<BugDesignation> getUniqueDesignations() { if (designations.isEmpty()) return Collections.emptyList(); HashSet<String> reviewers = new HashSet<String>(); ArrayList<BugDesignation> result = new ArrayList<BugDesignation>(designations.size()); for (BugDesignation d : designations) if (reviewers.add(d.getUser())) result.add(d); return result; } Set<String> getReviewers() { HashSet<String> reviewers = new HashSet<String>(); for (BugDesignation bd : designations) reviewers.add(bd.getUser()); reviewers.remove(""); reviewers.remove(null); return reviewers; } boolean isClaimed() { for (BugDesignation bd : getUniqueDesignations()) { if (bd.getDesignationKey().equals(UserDesignation.I_WILL_FIX.name())) return true; } return false; } BugDesignation getNonnullUserDesignation() { BugDesignation d = getUserDesignation(); if (d != null) return d; d = new BugDesignation(UserDesignation.UNCLASSIFIED.name(), System.currentTimeMillis(), "", findbugsUser); return d; } public boolean canSeeCommentsByOthers() { switch (getMode()) { case SECRET: return false; case COMMUNAL: return true; case VOTING: return hasVoted(); } throw new IllegalStateException(); } public boolean hasVoted() { for (BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return true; return false; } } int updatesSentToDatabase; Date lastUpdate = new Date(); Date resync; Date attemptedResync; IPAddressLookup ipAddressLookup; int resyncCount; final Map<String, BugData> instanceMap = new HashMap<String, BugData>(); final Map<Integer, BugData> idMap = new HashMap<Integer, BugData>(); final IdentityHashMap<BugDesignation, Integer> bugDesignationId = new IdentityHashMap<BugDesignation, Integer>(); BugData getBugData(String instanceHash) { BugData bd = instanceMap.get(instanceHash); if (bd == null) { bd = new BugData(instanceHash); instanceMap.put(instanceHash, bd); } return bd; } BugData getBugData(BugInstance bug) { try { initialSyncDone.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } BugData bugData = getBugData(bug.getInstanceHash()); bugData.bugs.add(bug); return bugData; } @SuppressWarnings("boxing") void loadDatabaseInfo(String hash, int id, long firstSeen, long lastSeen) { BugData bd = instanceMap.get(hash); firstSeen = sanityCheckFirstSeen(firstSeen); lastSeen = sanityCheckLastSeen(lastSeen); if (bd == null) return; if (idMap.containsKey(id)) { assert bd == idMap.get(id); assert bd.id == id; assert bd.firstSeen == firstSeen; } else { bd.id = id; bd.firstSeen = firstSeen; bd.lastSeen = lastSeen; bd.inDatabase = true; idMap.put(id, bd); } if (bd.firstSeen < FIRST_LIGHT) throw new IllegalStateException("Bug has first seen of " + new Date(bd.firstSeen)); } private BugFilingCommentHelper bugFilingCommentHelper = new BugFilingCommentHelper(this); final long now; public DBCloud(CloudPlugin plugin, BugCollection bugs, Properties properties) { super(plugin, bugs, properties); sqlDriver = getJDBCProperty("dbDriver"); url = getJDBCProperty("dbUrl"); dbName = getJDBCProperty("dbName"); dbUser = getJDBCProperty("dbUser"); dbPassword = getJDBCProperty("dbPassword"); findbugsUser = getCloudProperty(FINDBUGS_USER_PROPERTY); if (PROMPT_FOR_USER_NAME) ipAddressLookup = new IPAddressLookup(); this.now = System.currentTimeMillis(); } long sanityCheckFirstSeen(long time) { if (time < FIRST_LIGHT) return now; return time; } long sanityCheckLastSeen(long time) { if (time > now + ONE_DAY) return now; return time; } public boolean availableForInitialization() { String msg = String.format("%s %s %s %s", sqlDriver, dbUser, url, dbPassword); if (CloudFactory.DEBUG) { System.out.println("DB properties: " + msg); } if (sqlDriver == null || dbUser == null || url == null || dbPassword == null) { if (CloudFactory.DEBUG) { bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } signinState = SigninState.SIGNIN_FAILED; if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to load database properties"); return false; } return true; } final Pattern FORBIDDEN_PACKAGE_PREFIXES = Pattern.compile(properties.getProperty("findbugs.forbiddenPackagePrefixes", " none ").replace(',', '|')); final boolean PROMPT_FOR_USER_NAME = properties.getBoolean("findbugs.cloud.promptForUserName", false); int sessionId = -1; final CountDownLatch initialSyncDone = new CountDownLatch(1); final CountDownLatch bugsPopulated = new CountDownLatch(1); AtomicBoolean communicationInitiated = new AtomicBoolean(false); public void bugsPopulated() { bugsPopulated.countDown(); } public void initiateCommunication() { bugsPopulated(); if (communicationInitiated.compareAndSet(false, true)) queue.add(new PopulateBugs(true)); } /** * Returns true if communication has already been initiated (and perhaps completed). * */ @Override public boolean communicationInitiated() { return bugsPopulated.getCount() == 0 && communicationInitiated.get(); } private static final long LAST_SEEN_UPDATE_WINDOW = TimeUnit.MILLISECONDS.convert(7 * 24 * 3600, TimeUnit.SECONDS); long boundDuration(long milliseconds) { if (milliseconds < 0) return 0; if (milliseconds > 1000 * 1000) return 1000 * 1000; return milliseconds; } static boolean invocationRecorded; static final boolean LOG_BUG_UPLOADS = SystemProperties.getBoolean("cloud.buguploads.log"); class PopulateBugs implements Update { /** * True if this is the initial load from the database, false if we are * getting updates for an already loaded database. */ final boolean performFullLoad; PopulateBugs(boolean performFullLoad) { this.performFullLoad = performFullLoad; } @SuppressWarnings("boxing") public void execute(DatabaseSyncTask t) throws SQLException { if (startShutdown) return; String commonPrefix = null; int updates = 0; if (performFullLoad) { for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { commonPrefix = Util.commonPrefix(commonPrefix, b.getPrimaryClass().getClassName()); getBugData(b.getInstanceHash()).bugs.add(b); } if (commonPrefix == null) commonPrefix = "<no bugs>"; else if (commonPrefix.length() > 128) commonPrefix = commonPrefix.substring(0, 128); } try { long startTime = System.currentTimeMillis(); Connection c = getConnection(); PreparedStatement ps; ResultSet rs; if (performFullLoad) { ps = c.prepareStatement("SELECT id, hash, firstSeen, lastSeen FROM findbugs_issue"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String hash = rs.getString(col++); Timestamp firstSeen = rs.getTimestamp(col++); Timestamp lastSeen = rs.getTimestamp(col++); loadDatabaseInfo(hash, id, firstSeen.getTime(), lastSeen.getTime()); } rs.close(); ps.close(); } if (startShutdown) return; ps = c.prepareStatement("SELECT id, issueId, who, designation, comment, time FROM findbugs_evaluation"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); int issueId = rs.getInt(col++); String who = rs.getString(col++); String designation = rs.getString(col++); String comment = rs.getString(col++); Timestamp when = rs.getTimestamp(col++); BugData data = idMap.get(issueId); if (data != null) { BugDesignation bd = new BugDesignation(designation, when.getTime(), comment, who); if (data.designations.add(bd)) { bugDesignationId.put(bd, id); updates++; for (BugInstance bug : data.bugs) { updatedIssue(bug); } } } } rs.close(); ps.close(); if (startShutdown) return; ps = c.prepareStatement("SELECT hash, bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; String hash = rs.getString(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String status = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); BugData data = instanceMap.get(hash); if (data != null) { if (Util.nullSafeEquals(data.bugLink, bugReportId) && Util.nullSafeEquals(data.filedBy, whoFiled) && data.bugFiled == whenFiled.getTime() && Util.nullSafeEquals(data.bugAssignedTo, assignedTo) && Util.nullSafeEquals(data.bugStatus, status) && Util.nullSafeEquals(data.bugComponentName, componentName)) continue; data.bugLink = bugReportId; data.filedBy = whoFiled; data.bugFiled = whenFiled.getTime(); data.bugAssignedTo = assignedTo; data.bugStatus = status; data.bugComponentName = componentName; updates++; for (BugInstance bug : data.bugs) { updatedIssue(bug); } } } rs.close(); ps.close(); if (startShutdown) return; if (!invocationRecorded) { long jvmStartTime = StartTime.START_TIME - StartTime.VM_START_TIME; SortedBugCollection sbc = (SortedBugCollection) bugCollection; long findbugsStartTime = sbc.getTimeStartedLoading() - StartTime.START_TIME; URL findbugsURL = DetectorFactoryCollection.getCoreResource("findbugs.xml"); String loadURL = findbugsURL == null ? "" : findbugsURL.toString(); long initialLoadTime = sbc.getTimeFinishedLoading() - sbc.getTimeStartedLoading(); // long lostTime = startTime - sbc.getTimeStartedLoading(); long initialSyncTime = System.currentTimeMillis() - sbc.getTimeFinishedLoading(); String os = SystemProperties.getProperty("os.name", ""); String osVersion = SystemProperties.getProperty("os.version"); String jvmVersion = SystemProperties.getProperty("java.runtime.version"); if (osVersion != null) os = os + " " + osVersion; PreparedStatement insertSession = c .prepareStatement( "INSERT INTO findbugs_invocation (who, ipAddress, entryPoint, dataSource, fbVersion, os, jvmVersion, jvmLoadTime, findbugsLoadTime, analysisLoadTime, initialSyncTime, numIssues, startTime, commonPrefix)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); @SuppressWarnings("hiding") Timestamp now = new Timestamp(startTime); int col = 1; insertSession.setString(col++, findbugsUser); String ipAddress = PROMPT_FOR_USER_NAME ? ipAddressLookup.get() : "self-authenticated"; insertSession.setString(col++, ipAddress); insertSession.setString(col++, limitToMaxLength(loadURL, 128)); insertSession.setString(col++, limitToMaxLength(sbc.getDataSource(), 128)); insertSession.setString(col++, Version.RELEASE); insertSession.setString(col++, limitToMaxLength(os, 128)); insertSession.setString(col++, limitToMaxLength(jvmVersion, 64)); insertSession.setLong(col++, boundDuration(jvmStartTime)); insertSession.setLong(col++, boundDuration(findbugsStartTime)); insertSession.setLong(col++, boundDuration(initialLoadTime)); insertSession.setLong(col++, boundDuration(initialSyncTime)); insertSession.setInt(col++, bugCollection.getCollection().size()); insertSession.setTimestamp(col++, now); insertSession.setString(col++, commonPrefix); insertSession.executeUpdate(); rs = insertSession.getGeneratedKeys(); if (rs.next()) { sessionId = rs.getInt(1); } insertSession.close(); rs.close(); invocationRecorded = true; } c.close(); } catch (Exception e) { e.printStackTrace(); displayMessage("problem bulk loading database", e); } if (startShutdown) return; if (!performFullLoad) { attemptedResync = new Date(); if (updates > 0) { resync = attemptedResync; resyncCount = updates; } } else { long stillPresentAt = bugCollection.getTimestamp(); for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { BugData bd = getBugData(b.getInstanceHash()); if (!bd.inDatabase) { storeNewBug(b, stillPresentAt); if (LOG_BUG_UPLOADS) System.out.printf("NEW %tD: %s%n", new Date(getLocalFirstSeen(b)), b.getMessage()); } else { long firstSeenLocally = getLocalFirstSeen(b); if (FindBugs.validTimestamp(firstSeenLocally) && (firstSeenLocally < bd.firstSeen || !FindBugs.validTimestamp(bd.firstSeen))) { if (LOG_BUG_UPLOADS) System.out.printf("BACKDATED %tD -> %tD: %s%n", new Date(bd.firstSeen), new Date(firstSeenLocally), b.getMessage()); bd.firstSeen = firstSeenLocally; storeFirstSeen(bd); } else if (FindBugs.validTimestamp(stillPresentAt) && stillPresentAt > bd.lastSeen + LAST_SEEN_UPDATE_WINDOW) { storeLastSeen(bd, stillPresentAt); } BugDesignation designation = bd.getPrimaryDesignation(); if (designation != null) b.setUserDesignation(new BugDesignation(designation)); } } initialSyncDone.countDown(); assert !scheduled; if (startShutdown) return; long delay = 10 * 60 * 1000; // 10 minutes if (!scheduled) { try { resyncTimer.schedule(new TimerTask() { @Override public void run() { if (attemptedResync == null || lastUpdate.after(attemptedResync) || numSkipped++ > 6) { numSkipped = 0; queue.add(new PopulateBugs(false)); } } }, delay, delay); } catch (Exception e) { AnalysisContext.logError("Error scheduling resync", e); } } scheduled = true; } updatedStatus(); } } boolean scheduled = false; int numSkipped = 0; private static String limitToMaxLength(String s, int maxLength) { if (s.length() <= maxLength) return s; return s.substring(0, maxLength); } private String getJDBCProperty(String propertyName) { String override = System.getProperty("findbugs.override-jdbc." + propertyName); if (override != null) { System.out.println("Using override value for " + propertyName + ":" + override); return override; } return properties.getProperty("findbugs.jdbc." + propertyName); } final int MAX_DB_RANK = properties.getInt("findbugs.db.maxrank", 14); final String url, dbUser, dbPassword, dbName; String findbugsUser; ProjectPackagePrefixes projectMapping = new ProjectPackagePrefixes(); Map<String, String> prefixBugComponentMapping = new HashMap<String, String>(); private final String sqlDriver; Connection getConnection() throws SQLException { return DriverManager.getConnection(url, dbUser, dbPassword); } @Override public boolean initialize() throws IOException { if (CloudFactory.DEBUG) System.out.println("Starting DBCloud initialization"); if (initializationIsDoomed()) { signinState = SigninState.SIGNIN_FAILED; return false; } signinState = SigninState.SIGNED_IN; if (CloudFactory.DEBUG) System.out.println("DBCloud initialization preflight checks completed"); loadBugComponents(); Connection c = null; try { Class<?> driverClass; try { driverClass = this.getClass().getClassLoader().loadClass(sqlDriver); } catch (ClassNotFoundException e) { try { driverClass = plugin.getClassLoader().loadClass(sqlDriver); } catch (ClassNotFoundException e2) { driverClass = Class.forName(sqlDriver); } } if (CloudFactory.DEBUG) { System.out.println("Loaded " + driverClass.getName()); } DriverManager.registerDriver(new DriverShim((java.sql.Driver) driverClass.newInstance())); c = getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) from findbugs_issue"); boolean result = false; if (rs.next()) { result = true; } rs.close(); stmt.close(); c.close(); if (result) { runnerThread.setDaemon(true); runnerThread.start(); return true; } else if (THROW_EXCEPTION_IF_CANT_CONNECT) { throw new RuntimeException("Unable to get database results"); } else { if (CloudFactory.DEBUG) System.out.println("Unable to connect to database"); signinState = SigninState.SIGNIN_FAILED; return false; } } catch (RuntimeException e) { displayMessage("Unable to connect to " + dbName, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw e; return false; } catch (Exception e) { displayMessage("Unable to connect to " + dbName, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to connect to database", e); return false; } finally { Util.closeSilently(c); } } public void waitUntilIssueDataDownloaded() { initiateCommunication(); try { initialSyncDone.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private boolean initializationIsDoomed() throws IOException { if (!super.initialize()) return true; if (!availableForInitialization()) return true; findbugsUser = getUsernameLookup().getUsername(); if (findbugsUser == null) return true; return false; } private String getBugComponent(@SlashedClassName String className) { int longestMatch = -1; String result = null; for (Map.Entry<String, String> e : prefixBugComponentMapping.entrySet()) { String key = e.getKey(); if (className.startsWith(key) && longestMatch < key.length()) { longestMatch = key.length(); result = e.getValue(); } } return result; } private void loadBugComponents() { try { URL u = DetectorFactoryCollection.getCoreResource("bugComponents.properties"); if (u != null) { BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream())); while (true) { String s = in.readLine(); if (s == null) break; if (s.trim().length() == 0) continue; int x = s.indexOf(' '); if (x == -1) { if (!prefixBugComponentMapping.containsKey("")) prefixBugComponentMapping.put("", s); } else { String prefix = s.substring(x + 1); if (!prefixBugComponentMapping.containsKey(prefix)) prefixBugComponentMapping.put(prefix, s.substring(0, x)); } } in.close(); } } catch (IOException e) { AnalysisContext.logError("Unable to load bug component properties", e); } } final LinkedBlockingQueue<Update> queue = new LinkedBlockingQueue<Update>(); volatile boolean shutdown = false; volatile boolean startShutdown = false; final DatabaseSyncTask runner = new DatabaseSyncTask(); final Thread runnerThread = new Thread(runner, "Database synchronization thread"); final Timer resyncTimer = new Timer("Resync scheduler", true); @Override public void shutdown() { try { startShutdown = true; resyncTimer.cancel(); queue.add(new ShutdownTask()); Connection c = null; try { c = getConnection(); PreparedStatement setEndTime = c.prepareStatement("UPDATE findbugs_invocation SET endTime = ? WHERE id = ?"); Timestamp date = new Timestamp(System.currentTimeMillis()); int col = 1; setEndTime.setTimestamp(col++, date); setEndTime.setInt(col++, sessionId); setEndTime.execute(); setEndTime.close(); } catch (Throwable e) { // we're in shutdown mode, not going to complain assert true; } finally { Util.closeSilently(c); } if (!queue.isEmpty() && runnerThread.isAlive()) { setErrorMsg("waiting for synchronization to complete before shutdown"); for (int i = 0; i < 100; i++) { if (queue.isEmpty() || !runnerThread.isAlive()) break; try { Thread.sleep(30); } catch (InterruptedException e) { break; } } } } finally { shutdown = true; runnerThread.interrupt(); } } private RuntimeException shutdownException = new RuntimeException("DBCloud shutdown"); private void checkForShutdown() { if (!shutdown) return; IllegalStateException e = new IllegalStateException("DBCloud has already been shutdown"); e.initCause(shutdownException); throw e; } public void storeNewBug(BugInstance bug, long analysisTime) { checkForShutdown(); queue.add(new StoreNewBug(bug, analysisTime)); } public void storeFirstSeen(final BugData bd) { checkForShutdown(); queue.add(new Update() { public void execute(DatabaseSyncTask t) throws SQLException { t.storeFirstSeen(bd); } }); } public void storeLastSeen(final BugData bd, final long timestamp) { checkForShutdown(); queue.add(new Update() { public void execute(DatabaseSyncTask t) throws SQLException { t.storeLastSeen(bd, timestamp); } }); } public BugDesignation getPrimaryDesignation(BugInstance b) { return getBugData(b).getPrimaryDesignation(); } public void storeUserAnnotation(BugData data, BugDesignation bd) { checkForShutdown(); queue.add(new StoreUserAnnotation(data, bd)); updatedStatus(); if (firstTimeDoing(HAS_CLASSIFIED_ISSUES)) { String msg = "Classification and comments have been sent to database.\n" + "You'll only see this message the first time your classifcations/comments are sent\n" + "to the database."; if (getMode() == Mode.VOTING) msg += "\nOnce you've classified an issue, you can see how others have classified it."; msg += "\nYour classification and comments are independent from filing a bug using an external\n" + "bug reporting system."; bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } } private static final String HAS_SKIPPED_BUG = "has_skipped_bugs"; private boolean skipBug(BugInstance bug) { boolean result = bug.getBugPattern().getCategory().equals("NOISE") || bug.isDead() || BugRanker.findRank(bug) > MAX_DB_RANK; if (result && firstTimeDoing(HAS_SKIPPED_BUG)) { bugCollection .getProject() .getGuiCallback() .showMessageDialog( "To limit database load, some issues are not persisted to database.\n" + "For example, issues with rank greater than " + MAX_DB_RANK + " are not stored in the db.\n" + "One of more of the issues you are reviewing will not be persisted,\n" + "and you will not be able to record an evalution of those issues.\n" + "As we scale up the database, we hope to relax these restrictions"); } return result; } public static final String PENDING = "-- pending --"; public static final String NONE = "none"; class DatabaseSyncTask implements Runnable { int handled; Connection c; public void establishConnection() throws SQLException { if (c != null) return; c = getConnection(); } public void closeConnection() throws SQLException { if (c == null) return; c.close(); c = null; } public void run() { try { while (!shutdown) { Update u = queue.poll(10, TimeUnit.SECONDS); if (u == null) { closeConnection(); continue; } establishConnection(); u.execute(this); if ((handled++) % 100 == 0 || queue.isEmpty()) { updatedStatus(); } } } catch (DatabaseSyncShutdownException e) { assert true; } catch (RuntimeException e) { displayMessage("Runtime exception; database connection shutdown", e); } catch (SQLException e) { displayMessage("SQL exception; database connection shutdown", e); } catch (InterruptedException e) { assert true; } try { closeConnection(); } catch (SQLException e) { } } @SuppressWarnings("boxing") public void newEvaluation(BugData data, BugDesignation bd) { if (!data.inDatabase) return; try { data.designations.add(bd); if (bd.getUser() == null) bd.setUser(findbugsUser); if (bd.getAnnotationText() == null) bd.setAnnotationText(""); PreparedStatement insertEvaluation = c .prepareStatement( "INSERT INTO findbugs_evaluation (issueId, who, invocationId, designation, comment, time) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(bd.getTimestamp()); int col = 1; insertEvaluation.setInt(col++, data.id); insertEvaluation.setString(col++, bd.getUser()); insertEvaluation.setInt(col++, sessionId); insertEvaluation.setString(col++, bd.getDesignationKey()); insertEvaluation.setString(col++, bd.getAnnotationText()); insertEvaluation.setTimestamp(col++, date); insertEvaluation.executeUpdate(); ResultSet rs = insertEvaluation.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); bugDesignationId.put(bd, id); } rs.close(); insertEvaluation.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } lastUpdate = new Date(); updatesSentToDatabase++; } public void newBug(BugInstance b) { try { BugData bug = getBugData(b.getInstanceHash()); if (bug.inDatabase) return; PreparedStatement insertBugData = c .prepareStatement( "INSERT INTO findbugs_issue (firstSeen, lastSeen, hash, bugPattern, priority, primaryClass) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); int col = 1; insertBugData.setTimestamp(col++, new Timestamp(bug.firstSeen)); insertBugData.setTimestamp(col++, new Timestamp(bug.lastSeen)); insertBugData.setString(col++, bug.instanceHash); insertBugData.setString(col++, b.getBugPattern().getType()); insertBugData.setInt(col++, b.getPriority()); insertBugData.setString(col++, b.getPrimaryClass().getClassName()); insertBugData.executeUpdate(); ResultSet rs = insertBugData.getGeneratedKeys(); if (rs.next()) { bug.id = rs.getInt(1); bug.inDatabase = true; } rs.close(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeFirstSeen(BugData bug) { if (bug.firstSeen <= FIRST_LIGHT) return; try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET firstSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(bug.firstSeen); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeLastSeen(BugData bug, long timestamp) { if (bug.lastSeen >= now + ONE_DAY) return; try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET lastSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(timestamp); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } /** * @param bd */ public void fileBug(BugData bug) { try { insertPendingRecord(c, bug, bug.bugFiled, bug.filedBy); } catch (Exception e) { displayMessage("Problem filing bug", e); } lastUpdate = new Date(); updatesSentToDatabase++; } } /** * @param bug * @return * @throws SQLException */ private void insertPendingRecord(Connection c, BugData bug, long when, String who) throws SQLException { int pendingId = -1; PreparedStatement query = null; ResultSet rs = null; boolean needsUpdate = false; try { query = c.prepareStatement("SELECT id, bugReportId, whoFiled, whenFiled FROM findbugs_bugreport where hash=?"); query.setString(1, bug.instanceHash); rs = query.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); if (!bugReportId.equals(PENDING) || !who.equals(whoFiled) && !pendingStatusHasExpired(whenFiled.getTime())) { rs.close(); query.close(); throw new IllegalArgumentException(whoFiled + " already filed bug report " + bugReportId + " for " + bug.instanceHash); } pendingId = id; needsUpdate = !who.equals(whoFiled); } } catch (SQLException e) { String msg = "Problem inserting pending record for " + bug.instanceHash; AnalysisContext.logError(msg, e); return; } finally { Util.closeSilently(rs); Util.closeSilently(query); } if (pendingId == -1) { PreparedStatement insert = c .prepareStatement("INSERT INTO findbugs_bugreport (hash, bugReportId, whoFiled, whenFiled)" + " VALUES (?, ?, ?, ?)"); Timestamp date = new Timestamp(when); int col = 1; insert.setString(col++, bug.instanceHash); insert.setString(col++, PENDING); insert.setString(col++, who); insert.setTimestamp(col++, date); insert.executeUpdate(); insert.close(); } else if (needsUpdate) { PreparedStatement updateBug = c .prepareStatement("UPDATE findbugs_bugreport SET whoFiled = ?, whenFiled = ? WHERE id = ?"); try { int col = 1; updateBug.setString(col++, bug.filedBy); updateBug.setTimestamp(col++, new Timestamp(bug.bugFiled)); updateBug.setInt(col++, pendingId); updateBug.executeUpdate(); } catch (SQLException e) { String msg = "Problem inserting pending record for id " + pendingId + ", bug hash " + bug.instanceHash; AnalysisContext.logError(msg, e); } finally { updateBug.close(); } } } static interface Update { void execute(DatabaseSyncTask t) throws SQLException; } static class ShutdownTask implements Update { public void execute(DatabaseSyncTask t) { throw new DatabaseSyncShutdownException(); } } static class DatabaseSyncShutdownException extends RuntimeException { } boolean bugAlreadyFiled(BugInstance b) { BugData bd = getBugData(b.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); return bd.bugLink != null && !bd.bugLink.equals(NONE) && !bd.bugLink.equals(PENDING); } class FileBug implements Update { public FileBug(BugInstance bug) { this.bd = getBugData(bug.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); bd.bugFiled = System.currentTimeMillis(); bd.bugLink = PENDING; bd.filedBy = findbugsUser; } final BugData bd; public void execute(DatabaseSyncTask t) throws SQLException { t.fileBug(bd); } } class StoreNewBug implements Update { public StoreNewBug(BugInstance bug, long analysisTime) { this.bug = bug; this.analysisTime = analysisTime; } final BugInstance bug; final long analysisTime; public void execute(DatabaseSyncTask t) throws SQLException { BugData data = getBugData(bug.getInstanceHash()); if (data.lastSeen < analysisTime && FindBugs.validTimestamp(analysisTime)) data.lastSeen = analysisTime; long timestamp = getLocalFirstSeen(bug); if (timestamp < FIRST_LIGHT) timestamp = analysisTime; timestamp = sanityCheckFirstSeen(sanityCheckLastSeen(timestamp)); data.firstSeen = timestamp; if (data.inDatabase) return; t.newBug(bug); data.inDatabase = true; } } static class StoreUserAnnotation implements Update { public StoreUserAnnotation(BugData data, BugDesignation designation) { super(); this.data = data; this.designation = designation; } public void execute(DatabaseSyncTask t) throws SQLException { t.newEvaluation(data, new BugDesignation(designation)); } final BugData data; final BugDesignation designation; } private void displayMessage(String msg, Exception e) { AnalysisContext.logError(msg, e); if (bugCollection != null && bugCollection.getProject().isGuiAvaliable()) { StringWriter stackTraceWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stackTraceWriter); e.printStackTrace(printWriter); bugCollection.getProject().getGuiCallback() .showMessageDialog(String.format("%s - %s%n%s", msg, e.getMessage(), stackTraceWriter.toString())); } else { System.err.println(msg); e.printStackTrace(System.err); } } public SigninState getSigninState() { return signinState; } public void setSaveSignInInformation(boolean save) { // not saved anyway } public boolean isSavingSignInInformationEnabled() { return false; } public void signIn() { if (getSigninState() != SigninState.SIGNED_IN) throw new UnsupportedOperationException("Unable to sign in"); } public void signOut() { throw new UnsupportedOperationException(); } public String getUser() { return findbugsUser; } @Override public long getFirstSeen(BugInstance b) { return getBugData(b).firstSeen; } @Override public void addDateSeen(BugInstance b, long when) { if (when <= 0) return; when = sanityCheckFirstSeen(when); BugData bd = getBugData(b); if (bd.firstSeen < when) return; bd.firstSeen = when; storeFirstSeen(bd); } static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { assert false; return "No utf-8 encoding"; } } @Override public double getClassificationScore(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); double total = 0; int count = 0; for (BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (designation.nonVoting()) continue; total += designation.score(); count++; } return total / count; } @Override public double getPortionObsoleteClassifications(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; int count = 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); for (BugDesignation d : uniqueDesignations) if (UserDesignation.valueOf(d.getDesignationKey()) == UserDesignation.OBSOLETE_CODE) count++; return ((double) count) / uniqueDesignations.size(); } @Override public double getClassificationVariance(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); double total = 0; double totalSquares = 0; int count = 0; for (BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (designation.nonVoting()) continue; int score = designation.score(); total += score; totalSquares += score * score; count++; } double average = total / count; return totalSquares / count - average * average; } @Override public double getClassificationDisagreement(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); int shouldFix = 0; int dontFix = 0; for (BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (designation.nonVoting()) continue; int score = designation.score(); if (score > 0) shouldFix++; else dontFix++; } return Math.min(shouldFix, dontFix) / (double) (shouldFix + dontFix); } public Set<String> getReviewers(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return Collections.emptySet(); return bd.getReviewers(); } public boolean isClaimed(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; return bd.isClaimed(); } static final int MAX_URL_LENGTH = 1999; private static final String HAS_FILED_BUGS = "has_filed_bugs"; private static final String HAS_CLASSIFIED_ISSUES = "has_classified_issues"; private static boolean firstTimeDoing(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); if (!prefs.getBoolean(activity, false)) { prefs.putBoolean(activity, true); return true; } return false; } private static void alreadyDone(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); prefs.putBoolean(activity, true); } private boolean firstBugRequest = true; final String BUG_LINK_FORMAT = properties.getProperty("findbugs.filebug.link"); final String BUG_LOGIN_LINK = properties.getProperty("findbugs.filebug.login"); final String BUG_LOGIN_MSG = properties.getProperty("findbugs.filebug.loginMsg"); final String COMPONENT_FOR_BAD_ANALYSIS = properties.getProperty("findbugs.filebug.badAnalysisComponent"); @Override @CheckForNull public URL getBugLink(BugInstance b) { BugData bd = getBugData(b); String bugNumber = bd.bugLink; BugFilingStatus status = getBugLinkStatus(b); if (status == BugFilingStatus.VIEW_BUG) return getBugViewLink(bugNumber); Connection c = null; try { c = getConnection(); PreparedStatement ps = c .prepareStatement("SELECT bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport WHERE hash=?"); ps.setString(1, b.getInstanceHash()); ResultSet rs = ps.executeQuery(); Timestamp pendingFiledAt = null; while (rs.next()) { int col = 1; String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String statusString = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); if (bugReportId.equals(PENDING)) { if (!findbugsUser.equals(whoFiled) && !pendingStatusHasExpired(whenFiled.getTime())) pendingFiledAt = whenFiled; continue; } if (bugReportId.equals(NONE)) continue; rs.close(); ps.close(); bd.bugLink = bugReportId; bd.filedBy = whoFiled; bd.bugFiled = whenFiled.getTime(); bd.bugAssignedTo = assignedTo; bd.bugStatus = statusString; bd.bugComponentName = componentName; int answer = getBugCollection() .getProject() .getGuiCallback() .showConfirmDialog( "Sorry, but since the time we last received updates from the database,\n" + "someone else already filed a bug report. Would you like to view the bug report?", "Someone else already filed a bug report", "Yes", "No"); if (answer == 0) return null; return getBugViewLink(bugReportId); } rs.close(); ps.close(); if (pendingFiledAt != null) { bd.bugLink = PENDING; bd.bugFiled = pendingFiledAt.getTime(); getBugCollection() .getProject() .getGuiCallback() .showMessageDialog( "Sorry, but since the time we last received updates from the database,\n" + "someone else already has started a bug report for this issue. "); return null; } // OK, not in database if (status == BugFilingStatus.FILE_BUG) { URL u = getBugFilingLink(b); if (u != null && firstTimeDoing(HAS_FILED_BUGS)) { String bugFilingNote = String.format(properties.getProperty("findbugs.filebug.note", "")); int response = bugCollection .getProject() .getGuiCallback() .showConfirmDialog( "This looks like the first time you've filed a bug from this machine. Please:\n" + " * Please check the component the issue is assigned to; we sometimes get it wrong.\n" + " * Try to figure out the right person to assign it to.\n" + " * Provide the information needed to understand the issue.\n" + bugFilingNote + "Note that classifying an issue is distinct from (and lighter weight than) filing a bug.", "Do you want to file a bug report", "Yes", "No"); if (response != 0) return null; } if (u != null) insertPendingRecord(c, bd, System.currentTimeMillis(), findbugsUser); return u; } else { assert status == BugFilingStatus.FILE_AGAIN; alreadyDone(HAS_FILED_BUGS); URL u = getBugFilingLink(b); if (u != null) insertPendingRecord(c, bd, System.currentTimeMillis(), findbugsUser); return u; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { Util.closeSilently(c); } return null; } /** * @param bugNumber * @return * @throws MalformedURLException */ private @CheckForNull URL getBugViewLink(String bugNumber) { String viewLinkPattern = properties.getProperty("findbugs.viewbug.link"); if (viewLinkPattern == null) return null; firstBugRequest = false; String u = String.format(viewLinkPattern, bugNumber); try { return new URL(u); } catch (MalformedURLException e) { return null; } } private void displaySupplementalBugReport(String supplemental) { supplemental = "[Can't squeeze this information into the URL used to prepopulate the bug entry\n" + " please cut and paste into the bug report as appropriate]\n\n" + supplemental; bugCollection.getProject().getGuiCallback() .displayNonmodelMessage("Cut and paste as needed into bug entry", supplemental); } private URL getBugFilingLink(BugInstance b) throws MalformedURLException { if (BUG_LINK_FORMAT == null) return null; int maxURLLength = MAX_URL_LENGTH; if (firstBugRequest) { if (BUG_LOGIN_LINK != null && BUG_LOGIN_MSG != null) { URL u = new URL(String.format(BUG_LOGIN_LINK)); if (!bugCollection.getProject().getGuiCallback().showDocument(u)) return null; int r = bugCollection.getProject().getGuiCallback() .showConfirmDialog(BUG_LOGIN_MSG, "Logging into bug tracker...", "OK", "Cancel"); if (r != 0) return null; } else maxURLLength = maxURLLength * 2 / 3; } firstBugRequest = false; String component; if (getUserDesignation(b) == UserDesignation.BAD_ANALYSIS && COMPONENT_FOR_BAD_ANALYSIS != null) component = COMPONENT_FOR_BAD_ANALYSIS; else component = getBugComponent(b.getPrimaryClass().getClassName().replace('.', '/')); String summary = bugFilingCommentHelper.getBugReportSummary(b); String report = bugFilingCommentHelper.getBugReportText(b); String u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > maxURLLength) { String head = bugFilingCommentHelper.getBugReportHead(b); String sourceCode = bugFilingCommentHelper.getBugReportSourceCode(b); String tail = bugFilingCommentHelper.getBugReportTail(b); report = head + sourceCode + tail; String lineTerminatedUserEvaluation = bugFilingCommentHelper.getLineTerminatedUserEvaluation(b); String explanation = bugFilingCommentHelper.getBugPatternExplanation(b); String supplemental = lineTerminatedUserEvaluation + explanation; u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > maxURLLength) { report = head + tail; supplemental = sourceCode + lineTerminatedUserEvaluation + explanation; u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > maxURLLength) { // Last resort: Just make the link work with a minimal // report and by shortening the summary supplemental = head + sourceCode + lineTerminatedUserEvaluation + explanation; report = tail; // (assuming BUG_URL_FORMAT + component + report tail is // always < maxUrlLength) String urlEncodedSummary = urlEncode(summary); String urlEncodedReport = urlEncode(report); String urlEncodedComponent = urlEncode(component); int maxSummaryLength = maxURLLength - BUG_LINK_FORMAT.length() + 6 /* * 3 * % * s * placeholders */ - urlEncodedReport.length() - urlEncodedComponent.length(); if (urlEncodedSummary.length() > maxSummaryLength) { urlEncodedSummary = urlEncodedSummary.substring(0, maxSummaryLength - 1); // Chop of any incomplete trailing percent encoded part if ("%".equals(urlEncodedSummary.substring(urlEncodedSummary.length() - 1))) { urlEncodedSummary = urlEncodedSummary.substring(0, urlEncodedSummary.length() - 2); } else if ("%".equals(urlEncodedSummary.substring(urlEncodedSummary.length() - 2, urlEncodedSummary.length() - 1))) { urlEncodedSummary = urlEncodedSummary.substring(0, urlEncodedSummary.length() - 3); } } u = String.format(BUG_LINK_FORMAT, urlEncodedComponent, urlEncodedSummary, urlEncodedReport); } } displaySupplementalBugReport(supplemental); } return new URL(u); } @Override public boolean supportsCloudReports() { return true; } @Override public boolean supportsBugLinks() { return BUG_LINK_FORMAT != null; } public void storeUserAnnotation(BugInstance bugInstance) { storeUserAnnotation(getBugData(bugInstance), bugInstance.getNonnullUserDesignation()); updatedIssue(bugInstance); } @Override public BugFilingStatus getBugLinkStatus(BugInstance b) { BugData bd = getBugData(b); String link = bd.bugLink; if (link == null || link.length() == 0 || link.equals(NONE)) return BugFilingStatus.FILE_BUG; if (link.equals(PENDING)) { if (findbugsUser.equals(bd.filedBy)) return BugFilingStatus.FILE_AGAIN; else { long whenFiled = bd.bugFiled; if (pendingStatusHasExpired(whenFiled)) return BugFilingStatus.FILE_BUG; else return BugFilingStatus.BUG_PENDING; } } try { Integer.parseInt(link); return BugFilingStatus.VIEW_BUG; } catch (RuntimeException e) { assert true; } return BugFilingStatus.NA; } @Override public String getBugStatus(BugInstance b) { String status = getBugData(b).bugStatus; if (status != null) return status; return "Unknown"; } private boolean pendingStatusHasExpired(long whenFiled) { return System.currentTimeMillis() - whenFiled > 60 * 60 * 1000L; } public void bugFiled(BugInstance b, Object bugLink) { checkForShutdown(); if (bugAlreadyFiled(b)) { return; } queue.add(new FileBug(b)); updatedStatus(); } String errorMsg; long errorTime = 0; void setErrorMsg(String msg) { errorMsg = msg; errorTime = System.currentTimeMillis(); updatedStatus(); } void clearErrorMsg() { errorMsg = null; updatedStatus(); } @Override public String getStatusMsg() { if (errorMsg != null) { if (errorTime + 2 * 60 * 1000 > System.currentTimeMillis()) { errorMsg = null; } else return errorMsg + "; " + getStatusMsg0(); } return getStatusMsg0(); } @SuppressWarnings("boxing") public String getStatusMsg0() { SimpleDateFormat format = new SimpleDateFormat("h:mm a"); int numToSync = queue.size(); if (numToSync > 0) return String.format("%d remain to be synchronized", numToSync); else if (resync != null && resync.after(lastUpdate)) return String.format("%d updates received from db at %s", resyncCount, format.format(resync)); else if (updatesSentToDatabase == 0) { int skipped = bugCollection.getCollection().size() - idMap.size(); if (skipped == 0) return String.format("%d issues synchronized with database", idMap.size()); else return String.format("%d issues synchronized with database, %d low rank issues not synchronized", idMap.size(), skipped); } else return String.format("%d classifications/bug filings sent to db, last updated at %s", updatesSentToDatabase, format.format(lastUpdate)); } @Override public boolean getIWillFix(BugInstance b) { if (super.getIWillFix(b)) return true; BugData bd = getBugData(b); return bd != null && findbugsUser.equals(bd.bugAssignedTo); } @Override public boolean getBugIsUnassigned(BugInstance b) { BugData bd = getBugData(b); return bd != null && bd.inDatabase && getBugLinkStatus(b) == BugFilingStatus.VIEW_BUG && ("NEW".equals(bd.bugStatus) || bd.bugAssignedTo == null || bd.bugAssignedTo.length() == 0); } @Override public boolean getWillNotBeFixed(BugInstance b) { BugData bd = getBugData(b); return bd != null && bd.inDatabase && getBugLinkStatus(b) == BugFilingStatus.VIEW_BUG && ("WILL_NOT_FIX".equals(bd.bugStatus) || "OBSOLETE".equals(bd.bugStatus) || "WORKS_AS_INTENDED".equals(bd.bugStatus) || "NOT_FEASIBLE".equals(bd.bugStatus)); } @Override public boolean supportsCloudSummaries() { return true; } @Override public boolean canStoreUserAnnotation(BugInstance bugInstance) { return !skipBug(bugInstance); } @Override public @CheckForNull String claimedBy(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return null; for (BugDesignation designation : bd.getUniqueDesignations()) { if ("I_WILL_FIX".equals(designation.getDesignationKey())) return designation.getUser(); } return null; } @Override protected Iterable<BugDesignation> getLatestDesignationFromEachUser(BugInstance bd) { BugData bugData = instanceMap.get(bd.getInstanceHash()); if (bugData == null) return Collections.emptyList(); return bugData.getUniqueDesignations(); } @Override public BugInstance getBugByHash(String hash) { Collection<BugInstance> bugs = instanceMap.get(hash).bugs; return bugs.isEmpty() ? null : bugs.iterator().next(); } public Collection<String> getProjects(String className) { return projectMapping.getProjects(className); } public boolean isInCloud(BugInstance b) { if (b == null) throw new NullPointerException("null bug"); String instanceHash = b.getInstanceHash(); BugData bugData = instanceMap.get(instanceHash); return bugData != null && bugData.inDatabase; } @Override public String notInCloudeMsg(BugInstance b) { if (isInCloud(b)) { assert false; return "Is in cloud"; } int rank = BugRanker.findRank(b); if (rank > MAX_DB_RANK) return String.format("This issue is rank %d, only issues up to rank %d are recorded in the cloud", rank, MAX_DB_RANK); return "Issue is not recorded in cloud"; } public boolean isOnlineCloud() { return true; } @Override public URL fileBug(BugInstance bug) { return null; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.cloud.Cloud#waitUntilNewIssuesUploaded() */ public void waitUntilNewIssuesUploaded() { try { initiateCommunication(); initialSyncDone.await(); } catch (InterruptedException e) { } } }
plugins/jdbcCloudClient/src/java/edu/umd/cs/findbugs/cloud/db/DBCloud.java
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.cloud.db; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugRanker; import edu.umd.cs.findbugs.DetectorFactoryCollection; import edu.umd.cs.findbugs.FindBugs; import edu.umd.cs.findbugs.ProjectPackagePrefixes; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.StartTime; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.Version; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.cloud.AbstractCloud; import edu.umd.cs.findbugs.cloud.OnlineCloud; import edu.umd.cs.findbugs.cloud.BugFilingCommentHelper; import edu.umd.cs.findbugs.cloud.CloudFactory; import edu.umd.cs.findbugs.cloud.CloudPlugin; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.Util; /** * @author pwilliam */ public class DBCloud extends AbstractCloud implements OnlineCloud { public static final String FINDBUGS_USER_PROPERTY = "findbugsUser"; static final long FIRST_LIGHT = FindBugs.MINIMUM_TIMESTAMP; static final long ONE_DAY = 24L * 60 * 60 * 1000; static final String USER_NAME = "user.name"; private SigninState signinState = SigninState.SIGNING_IN; class BugData { final String instanceHash; public BugData(String instanceHash) { this.instanceHash = instanceHash; } int id; boolean inDatabase; long firstSeen = bugCollection.getTimestamp(); String bugLink = NONE; String filedBy; String bugStatus; String bugAssignedTo; String bugComponentName; long bugFiled = Long.MAX_VALUE; SortedSet<BugDesignation> designations = new TreeSet<BugDesignation>(); Collection<BugInstance> bugs = new LinkedHashSet<BugInstance>(); long lastSeen; @CheckForNull BugDesignation getPrimaryDesignation() { for (BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return bd; return null; } @CheckForNull BugDesignation getUserDesignation() { for (BugDesignation d : designations) if (findbugsUser.equals(d.getUser())) return new BugDesignation(d); return null; } Collection<BugDesignation> getUniqueDesignations() { if (designations.isEmpty()) return Collections.emptyList(); HashSet<String> reviewers = new HashSet<String>(); ArrayList<BugDesignation> result = new ArrayList<BugDesignation>(designations.size()); for (BugDesignation d : designations) if (reviewers.add(d.getUser())) result.add(d); return result; } Set<String> getReviewers() { HashSet<String> reviewers = new HashSet<String>(); for (BugDesignation bd : designations) reviewers.add(bd.getUser()); reviewers.remove(""); reviewers.remove(null); return reviewers; } boolean isClaimed() { for (BugDesignation bd : getUniqueDesignations()) { if (bd.getDesignationKey().equals(UserDesignation.I_WILL_FIX.name())) return true; } return false; } BugDesignation getNonnullUserDesignation() { BugDesignation d = getUserDesignation(); if (d != null) return d; d = new BugDesignation(UserDesignation.UNCLASSIFIED.name(), System.currentTimeMillis(), "", findbugsUser); return d; } public boolean canSeeCommentsByOthers() { switch (getMode()) { case SECRET: return false; case COMMUNAL: return true; case VOTING: return hasVoted(); } throw new IllegalStateException(); } public boolean hasVoted() { for (BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return true; return false; } } int updatesSentToDatabase; Date lastUpdate = new Date(); Date resync; Date attemptedResync; IPAddressLookup ipAddressLookup; int resyncCount; final Map<String, BugData> instanceMap = new HashMap<String, BugData>(); final Map<Integer, BugData> idMap = new HashMap<Integer, BugData>(); final IdentityHashMap<BugDesignation, Integer> bugDesignationId = new IdentityHashMap<BugDesignation, Integer>(); BugData getBugData(String instanceHash) { BugData bd = instanceMap.get(instanceHash); if (bd == null) { bd = new BugData(instanceHash); instanceMap.put(instanceHash, bd); } return bd; } BugData getBugData(BugInstance bug) { try { initialSyncDone.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } BugData bugData = getBugData(bug.getInstanceHash()); bugData.bugs.add(bug); return bugData; } @SuppressWarnings("boxing") void loadDatabaseInfo(String hash, int id, long firstSeen, long lastSeen) { BugData bd = instanceMap.get(hash); firstSeen = sanityCheckFirstSeen(firstSeen); lastSeen = sanityCheckLastSeen(lastSeen); if (bd == null) return; if (idMap.containsKey(id)) { assert bd == idMap.get(id); assert bd.id == id; assert bd.firstSeen == firstSeen; } else { bd.id = id; bd.firstSeen = firstSeen; bd.lastSeen = lastSeen; bd.inDatabase = true; idMap.put(id, bd); } if (bd.firstSeen < FIRST_LIGHT) throw new IllegalStateException("Bug has first seen of " + new Date(bd.firstSeen)); } private BugFilingCommentHelper bugFilingCommentHelper = new BugFilingCommentHelper(this); final long now; public DBCloud(CloudPlugin plugin, BugCollection bugs, Properties properties) { super(plugin, bugs, properties); sqlDriver = getJDBCProperty("dbDriver"); url = getJDBCProperty("dbUrl"); dbName = getJDBCProperty("dbName"); dbUser = getJDBCProperty("dbUser"); dbPassword = getJDBCProperty("dbPassword"); findbugsUser = getCloudProperty(FINDBUGS_USER_PROPERTY); if (PROMPT_FOR_USER_NAME) ipAddressLookup = new IPAddressLookup(); this.now = System.currentTimeMillis(); } long sanityCheckFirstSeen(long time) { if (time < FIRST_LIGHT) return now; return time; } long sanityCheckLastSeen(long time) { if (time > now + ONE_DAY) return now; return time; } public boolean availableForInitialization() { String msg = String.format("%s %s %s %s", sqlDriver, dbUser, url, dbPassword); if (CloudFactory.DEBUG) { System.out.println("DB properties: " + msg); } if (sqlDriver == null || dbUser == null || url == null || dbPassword == null) { if (CloudFactory.DEBUG) { bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } signinState = SigninState.SIGNIN_FAILED; if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to load database properties"); return false; } return true; } final Pattern FORBIDDEN_PACKAGE_PREFIXES = Pattern.compile(properties.getProperty("findbugs.forbiddenPackagePrefixes", " none ").replace(',', '|')); final boolean PROMPT_FOR_USER_NAME = properties.getBoolean("findbugs.cloud.promptForUserName", false); int sessionId = -1; final CountDownLatch initialSyncDone = new CountDownLatch(1); final CountDownLatch bugsPopulated = new CountDownLatch(1); AtomicBoolean communicationInitiated = new AtomicBoolean(false); public void bugsPopulated() { bugsPopulated.countDown(); } public void initiateCommunication() { bugsPopulated(); if (communicationInitiated.compareAndSet(false, true)) queue.add(new PopulateBugs(true)); } /** * Returns true if communication has already been initiated (and perhaps completed). * */ @Override public boolean communicationInitiated() { return bugsPopulated.getCount() == 0 && communicationInitiated.get(); } private static final long LAST_SEEN_UPDATE_WINDOW = TimeUnit.MILLISECONDS.convert(7 * 24 * 3600, TimeUnit.SECONDS); long boundDuration(long milliseconds) { if (milliseconds < 0) return 0; if (milliseconds > 1000 * 1000) return 1000 * 1000; return milliseconds; } static boolean invocationRecorded; static final boolean LOG_BUG_UPLOADS = SystemProperties.getBoolean("cloud.buguploads.log"); class PopulateBugs implements Update { /** * True if this is the initial load from the database, false if we are * getting updates for an already loaded database. */ final boolean performFullLoad; PopulateBugs(boolean performFullLoad) { this.performFullLoad = performFullLoad; } @SuppressWarnings("boxing") public void execute(DatabaseSyncTask t) throws SQLException { if (startShutdown) return; String commonPrefix = null; int updates = 0; if (performFullLoad) { for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { commonPrefix = Util.commonPrefix(commonPrefix, b.getPrimaryClass().getClassName()); getBugData(b.getInstanceHash()).bugs.add(b); } if (commonPrefix == null) commonPrefix = "<no bugs>"; else if (commonPrefix.length() > 128) commonPrefix = commonPrefix.substring(0, 128); } try { long startTime = System.currentTimeMillis(); Connection c = getConnection(); PreparedStatement ps; ResultSet rs; if (performFullLoad) { ps = c.prepareStatement("SELECT id, hash, firstSeen, lastSeen FROM findbugs_issue"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String hash = rs.getString(col++); Timestamp firstSeen = rs.getTimestamp(col++); Timestamp lastSeen = rs.getTimestamp(col++); loadDatabaseInfo(hash, id, firstSeen.getTime(), lastSeen.getTime()); } rs.close(); ps.close(); } if (startShutdown) return; ps = c.prepareStatement("SELECT id, issueId, who, designation, comment, time FROM findbugs_evaluation"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); int issueId = rs.getInt(col++); String who = rs.getString(col++); String designation = rs.getString(col++); String comment = rs.getString(col++); Timestamp when = rs.getTimestamp(col++); BugData data = idMap.get(issueId); if (data != null) { BugDesignation bd = new BugDesignation(designation, when.getTime(), comment, who); if (data.designations.add(bd)) { bugDesignationId.put(bd, id); updates++; for (BugInstance bug : data.bugs) { updatedIssue(bug); } } } } rs.close(); ps.close(); if (startShutdown) return; ps = c.prepareStatement("SELECT hash, bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; String hash = rs.getString(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String status = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); BugData data = instanceMap.get(hash); if (data != null) { if (Util.nullSafeEquals(data.bugLink, bugReportId) && Util.nullSafeEquals(data.filedBy, whoFiled) && data.bugFiled == whenFiled.getTime() && Util.nullSafeEquals(data.bugAssignedTo, assignedTo) && Util.nullSafeEquals(data.bugStatus, status) && Util.nullSafeEquals(data.bugComponentName, componentName)) continue; data.bugLink = bugReportId; data.filedBy = whoFiled; data.bugFiled = whenFiled.getTime(); data.bugAssignedTo = assignedTo; data.bugStatus = status; data.bugComponentName = componentName; updates++; for (BugInstance bug : data.bugs) { updatedIssue(bug); } } } rs.close(); ps.close(); if (startShutdown) return; if (!invocationRecorded) { long jvmStartTime = StartTime.START_TIME - StartTime.VM_START_TIME; SortedBugCollection sbc = (SortedBugCollection) bugCollection; long findbugsStartTime = sbc.getTimeStartedLoading() - StartTime.START_TIME; URL findbugsURL = DetectorFactoryCollection.getCoreResource("findbugs.xml"); String loadURL = findbugsURL == null ? "" : findbugsURL.toString(); long initialLoadTime = sbc.getTimeFinishedLoading() - sbc.getTimeStartedLoading(); // long lostTime = startTime - sbc.getTimeStartedLoading(); long initialSyncTime = System.currentTimeMillis() - sbc.getTimeFinishedLoading(); String os = SystemProperties.getProperty("os.name", ""); String osVersion = SystemProperties.getProperty("os.version"); String jvmVersion = SystemProperties.getProperty("java.runtime.version"); if (osVersion != null) os = os + " " + osVersion; PreparedStatement insertSession = c .prepareStatement( "INSERT INTO findbugs_invocation (who, ipAddress, entryPoint, dataSource, fbVersion, os, jvmVersion, jvmLoadTime, findbugsLoadTime, analysisLoadTime, initialSyncTime, numIssues, startTime, commonPrefix)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); @SuppressWarnings("hiding") Timestamp now = new Timestamp(startTime); int col = 1; insertSession.setString(col++, findbugsUser); String ipAddress = PROMPT_FOR_USER_NAME ? ipAddressLookup.get() : "self-authenticated"; insertSession.setString(col++, ipAddress); insertSession.setString(col++, limitToMaxLength(loadURL, 128)); insertSession.setString(col++, limitToMaxLength(sbc.getDataSource(), 128)); insertSession.setString(col++, Version.RELEASE); insertSession.setString(col++, limitToMaxLength(os, 128)); insertSession.setString(col++, limitToMaxLength(jvmVersion, 64)); insertSession.setLong(col++, boundDuration(jvmStartTime)); insertSession.setLong(col++, boundDuration(findbugsStartTime)); insertSession.setLong(col++, boundDuration(initialLoadTime)); insertSession.setLong(col++, boundDuration(initialSyncTime)); insertSession.setInt(col++, bugCollection.getCollection().size()); insertSession.setTimestamp(col++, now); insertSession.setString(col++, commonPrefix); insertSession.executeUpdate(); rs = insertSession.getGeneratedKeys(); if (rs.next()) { sessionId = rs.getInt(1); } insertSession.close(); rs.close(); invocationRecorded = true; } c.close(); } catch (Exception e) { e.printStackTrace(); displayMessage("problem bulk loading database", e); } if (startShutdown) return; if (!performFullLoad) { attemptedResync = new Date(); if (updates > 0) { resync = attemptedResync; resyncCount = updates; } } else { long stillPresentAt = bugCollection.getTimestamp(); for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { BugData bd = getBugData(b.getInstanceHash()); if (!bd.inDatabase) { storeNewBug(b, stillPresentAt); if (LOG_BUG_UPLOADS) System.out.printf("NEW %tD: %s%n", new Date(getLocalFirstSeen(b)), b.getMessage()); } else { long firstSeenLocally = getLocalFirstSeen(b); if (FindBugs.validTimestamp(firstSeenLocally) && (firstSeenLocally < bd.firstSeen || !FindBugs.validTimestamp(bd.firstSeen))) { if (LOG_BUG_UPLOADS) System.out.printf("BACKDATED %tD -> %tD: %s%n", new Date(bd.firstSeen), new Date(firstSeenLocally), b.getMessage()); bd.firstSeen = firstSeenLocally; storeFirstSeen(bd); } else if (FindBugs.validTimestamp(stillPresentAt) && stillPresentAt > bd.lastSeen + LAST_SEEN_UPDATE_WINDOW) { storeLastSeen(bd, stillPresentAt); } BugDesignation designation = bd.getPrimaryDesignation(); if (designation != null) b.setUserDesignation(new BugDesignation(designation)); } } initialSyncDone.countDown(); assert !scheduled; if (startShutdown) return; long delay = 10 * 60 * 1000; // 10 minutes if (!scheduled) { try { resyncTimer.schedule(new TimerTask() { @Override public void run() { if (attemptedResync == null || lastUpdate.after(attemptedResync) || numSkipped++ > 6) { numSkipped = 0; queue.add(new PopulateBugs(false)); } } }, delay, delay); } catch (Exception e) { AnalysisContext.logError("Error scheduling resync", e); } } scheduled = true; } updatedStatus(); } } boolean scheduled = false; int numSkipped = 0; private static String limitToMaxLength(String s, int maxLength) { if (s.length() <= maxLength) return s; return s.substring(0, maxLength); } private String getJDBCProperty(String propertyName) { String override = System.getProperty("findbugs.override-jdbc." + propertyName); if (override != null) { System.out.println("Using override value for " + propertyName + ":" + override); return override; } return properties.getProperty("findbugs.jdbc." + propertyName); } final int MAX_DB_RANK = properties.getInt("findbugs.db.maxrank", 14); final String url, dbUser, dbPassword, dbName; String findbugsUser; ProjectPackagePrefixes projectMapping = new ProjectPackagePrefixes(); Map<String, String> prefixBugComponentMapping = new HashMap<String, String>(); private final String sqlDriver; Connection getConnection() throws SQLException { return DriverManager.getConnection(url, dbUser, dbPassword); } @Override public boolean initialize() throws IOException { if (CloudFactory.DEBUG) System.out.println("Starting DBCloud initialization"); if (initializationIsDoomed()) { signinState = SigninState.SIGNIN_FAILED; return false; } signinState = SigninState.SIGNED_IN; if (CloudFactory.DEBUG) System.out.println("DBCloud initialization preflight checks completed"); loadBugComponents(); Connection c = null; try { Class<?> driverClass; try { driverClass = this.getClass().getClassLoader().loadClass(sqlDriver); } catch (ClassNotFoundException e) { try { driverClass = plugin.getClassLoader().loadClass(sqlDriver); } catch (ClassNotFoundException e2) { driverClass = Class.forName(sqlDriver); } } if (CloudFactory.DEBUG) { System.out.println("Loaded " + driverClass.getName()); } DriverManager.registerDriver(new DriverShim((java.sql.Driver) driverClass.newInstance())); c = getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) from findbugs_issue"); boolean result = false; if (rs.next()) { result = true; } rs.close(); stmt.close(); c.close(); if (result) { runnerThread.setDaemon(true); runnerThread.start(); return true; } else if (THROW_EXCEPTION_IF_CANT_CONNECT) { throw new RuntimeException("Unable to get database results"); } else { if (CloudFactory.DEBUG) System.out.println("Unable to connect to database"); signinState = SigninState.SIGNIN_FAILED; return false; } } catch (RuntimeException e) { displayMessage("Unable to connect to " + dbName, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw e; return false; } catch (Exception e) { displayMessage("Unable to connect to " + dbName, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to connect to database", e); return false; } finally { Util.closeSilently(c); } } public void waitUntilIssueDataDownloaded() { initiateCommunication(); try { initialSyncDone.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private boolean initializationIsDoomed() throws IOException { if (!super.initialize()) return true; if (!availableForInitialization()) return true; findbugsUser = getUsernameLookup().getUsername(); if (findbugsUser == null) return true; return false; } private String getBugComponent(@SlashedClassName String className) { int longestMatch = -1; String result = null; for (Map.Entry<String, String> e : prefixBugComponentMapping.entrySet()) { String key = e.getKey(); if (className.startsWith(key) && longestMatch < key.length()) { longestMatch = key.length(); result = e.getValue(); } } return result; } private void loadBugComponents() { try { URL u = DetectorFactoryCollection.getCoreResource("bugComponents.properties"); if (u != null) { BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream())); while (true) { String s = in.readLine(); if (s == null) break; if (s.trim().length() == 0) continue; int x = s.indexOf(' '); if (x == -1) { if (!prefixBugComponentMapping.containsKey("")) prefixBugComponentMapping.put("", s); } else { String prefix = s.substring(x + 1); if (!prefixBugComponentMapping.containsKey(prefix)) prefixBugComponentMapping.put(prefix, s.substring(0, x)); } } in.close(); } } catch (IOException e) { AnalysisContext.logError("Unable to load bug component properties", e); } } final LinkedBlockingQueue<Update> queue = new LinkedBlockingQueue<Update>(); volatile boolean shutdown = false; volatile boolean startShutdown = false; final DatabaseSyncTask runner = new DatabaseSyncTask(); final Thread runnerThread = new Thread(runner, "Database synchronization thread"); final Timer resyncTimer = new Timer("Resync scheduler", true); @Override public void shutdown() { try { startShutdown = true; resyncTimer.cancel(); queue.add(new ShutdownTask()); Connection c = null; try { c = getConnection(); PreparedStatement setEndTime = c.prepareStatement("UPDATE findbugs_invocation SET endTime = ? WHERE id = ?"); Timestamp date = new Timestamp(System.currentTimeMillis()); int col = 1; setEndTime.setTimestamp(col++, date); setEndTime.setInt(col++, sessionId); setEndTime.execute(); setEndTime.close(); } catch (Throwable e) { // we're in shutdown mode, not going to complain assert true; } finally { Util.closeSilently(c); } if (!queue.isEmpty() && runnerThread.isAlive()) { setErrorMsg("waiting for synchronization to complete before shutdown"); for (int i = 0; i < 100; i++) { if (queue.isEmpty() || !runnerThread.isAlive()) break; try { Thread.sleep(30); } catch (InterruptedException e) { break; } } } } finally { shutdown = true; runnerThread.interrupt(); } } private RuntimeException shutdownException = new RuntimeException("DBCloud shutdown"); private void checkForShutdown() { if (!shutdown) return; IllegalStateException e = new IllegalStateException("DBCloud has already been shutdown"); e.initCause(shutdownException); throw e; } public void storeNewBug(BugInstance bug, long analysisTime) { checkForShutdown(); queue.add(new StoreNewBug(bug, analysisTime)); } public void storeFirstSeen(final BugData bd) { checkForShutdown(); queue.add(new Update() { public void execute(DatabaseSyncTask t) throws SQLException { t.storeFirstSeen(bd); } }); } public void storeLastSeen(final BugData bd, final long timestamp) { checkForShutdown(); queue.add(new Update() { public void execute(DatabaseSyncTask t) throws SQLException { t.storeLastSeen(bd, timestamp); } }); } public BugDesignation getPrimaryDesignation(BugInstance b) { return getBugData(b).getPrimaryDesignation(); } public void storeUserAnnotation(BugData data, BugDesignation bd) { checkForShutdown(); queue.add(new StoreUserAnnotation(data, bd)); updatedStatus(); if (firstTimeDoing(HAS_CLASSIFIED_ISSUES)) { String msg = "Classification and comments have been sent to database.\n" + "You'll only see this message the first time your classifcations/comments are sent\n" + "to the database."; if (getMode() == Mode.VOTING) msg += "\nOnce you've classified an issue, you can see how others have classified it."; msg += "\nYour classification and comments are independent from filing a bug using an external\n" + "bug reporting system."; bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } } private static final String HAS_SKIPPED_BUG = "has_skipped_bugs"; private boolean skipBug(BugInstance bug) { boolean result = bug.getBugPattern().getCategory().equals("NOISE") || bug.isDead() || BugRanker.findRank(bug) > MAX_DB_RANK; if (result && firstTimeDoing(HAS_SKIPPED_BUG)) { bugCollection .getProject() .getGuiCallback() .showMessageDialog( "To limit database load, some issues are not persisted to database.\n" + "For example, issues with rank greater than " + MAX_DB_RANK + " are not stored in the db.\n" + "One of more of the issues you are reviewing will not be persisted,\n" + "and you will not be able to record an evalution of those issues.\n" + "As we scale up the database, we hope to relax these restrictions"); } return result; } public static final String PENDING = "-- pending --"; public static final String NONE = "none"; class DatabaseSyncTask implements Runnable { int handled; Connection c; public void establishConnection() throws SQLException { if (c != null) return; c = getConnection(); } public void closeConnection() throws SQLException { if (c == null) return; c.close(); c = null; } public void run() { try { while (!shutdown) { Update u = queue.poll(10, TimeUnit.SECONDS); if (u == null) { closeConnection(); continue; } establishConnection(); u.execute(this); if ((handled++) % 100 == 0 || queue.isEmpty()) { updatedStatus(); } } } catch (DatabaseSyncShutdownException e) { assert true; } catch (RuntimeException e) { displayMessage("Runtime exception; database connection shutdown", e); } catch (SQLException e) { displayMessage("SQL exception; database connection shutdown", e); } catch (InterruptedException e) { assert true; } try { closeConnection(); } catch (SQLException e) { } } @SuppressWarnings("boxing") public void newEvaluation(BugData data, BugDesignation bd) { if (!data.inDatabase) return; try { data.designations.add(bd); if (bd.getUser() == null) bd.setUser(findbugsUser); if (bd.getAnnotationText() == null) bd.setAnnotationText(""); PreparedStatement insertEvaluation = c .prepareStatement( "INSERT INTO findbugs_evaluation (issueId, who, invocationId, designation, comment, time) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(bd.getTimestamp()); int col = 1; insertEvaluation.setInt(col++, data.id); insertEvaluation.setString(col++, bd.getUser()); insertEvaluation.setInt(col++, sessionId); insertEvaluation.setString(col++, bd.getDesignationKey()); insertEvaluation.setString(col++, bd.getAnnotationText()); insertEvaluation.setTimestamp(col++, date); insertEvaluation.executeUpdate(); ResultSet rs = insertEvaluation.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); bugDesignationId.put(bd, id); } rs.close(); insertEvaluation.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } lastUpdate = new Date(); updatesSentToDatabase++; } public void newBug(BugInstance b) { try { BugData bug = getBugData(b.getInstanceHash()); if (bug.inDatabase) return; PreparedStatement insertBugData = c .prepareStatement( "INSERT INTO findbugs_issue (firstSeen, lastSeen, hash, bugPattern, priority, primaryClass) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); int col = 1; insertBugData.setTimestamp(col++, new Timestamp(bug.firstSeen)); insertBugData.setTimestamp(col++, new Timestamp(bug.lastSeen)); insertBugData.setString(col++, bug.instanceHash); insertBugData.setString(col++, b.getBugPattern().getType()); insertBugData.setInt(col++, b.getPriority()); insertBugData.setString(col++, b.getPrimaryClass().getClassName()); insertBugData.executeUpdate(); ResultSet rs = insertBugData.getGeneratedKeys(); if (rs.next()) { bug.id = rs.getInt(1); bug.inDatabase = true; } rs.close(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeFirstSeen(BugData bug) { if (bug.firstSeen <= FIRST_LIGHT) return; try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET firstSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(bug.firstSeen); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeLastSeen(BugData bug, long timestamp) { if (bug.lastSeen >= now + ONE_DAY) return; try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET lastSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(timestamp); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } /** * @param bd */ public void fileBug(BugData bug) { try { insertPendingRecord(c, bug, bug.bugFiled, bug.filedBy); } catch (Exception e) { displayMessage("Problem filing bug", e); } lastUpdate = new Date(); updatesSentToDatabase++; } } /** * @param bug * @return * @throws SQLException */ private void insertPendingRecord(Connection c, BugData bug, long when, String who) throws SQLException { int pendingId = -1; PreparedStatement query = null; ResultSet rs = null; boolean needsUpdate = false; try { query = c.prepareStatement("SELECT id, bugReportId, whoFiled, whenFiled FROM findbugs_bugreport where hash=?"); query.setString(1, bug.instanceHash); rs = query.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); if (!bugReportId.equals(PENDING) || !who.equals(whoFiled) && !pendingStatusHasExpired(whenFiled.getTime())) { rs.close(); query.close(); throw new IllegalArgumentException(whoFiled + " already filed bug report " + bugReportId + " for " + bug.instanceHash); } pendingId = id; needsUpdate = !who.equals(whoFiled); } } catch (SQLException e) { String msg = "Problem inserting pending record for " + bug.instanceHash; AnalysisContext.logError(msg, e); return; } finally { Util.closeSilently(rs); Util.closeSilently(query); } if (pendingId == -1) { PreparedStatement insert = c .prepareStatement("INSERT INTO findbugs_bugreport (hash, bugReportId, whoFiled, whenFiled)" + " VALUES (?, ?, ?, ?)"); Timestamp date = new Timestamp(when); int col = 1; insert.setString(col++, bug.instanceHash); insert.setString(col++, PENDING); insert.setString(col++, who); insert.setTimestamp(col++, date); insert.executeUpdate(); insert.close(); } else if (needsUpdate) { PreparedStatement updateBug = c .prepareStatement("UPDATE findbugs_bugreport SET whoFiled = ?, whenFiled = ? WHERE id = ?"); try { int col = 1; updateBug.setString(col++, bug.filedBy); updateBug.setTimestamp(col++, new Timestamp(bug.bugFiled)); updateBug.setInt(col++, pendingId); updateBug.executeUpdate(); } catch (SQLException e) { String msg = "Problem inserting pending record for id " + pendingId + ", bug hash " + bug.instanceHash; AnalysisContext.logError(msg, e); } finally { updateBug.close(); } } } static interface Update { void execute(DatabaseSyncTask t) throws SQLException; } static class ShutdownTask implements Update { public void execute(DatabaseSyncTask t) { throw new DatabaseSyncShutdownException(); } } static class DatabaseSyncShutdownException extends RuntimeException { } boolean bugAlreadyFiled(BugInstance b) { BugData bd = getBugData(b.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); return bd.bugLink != null && !bd.bugLink.equals(NONE) && !bd.bugLink.equals(PENDING); } class FileBug implements Update { public FileBug(BugInstance bug) { this.bd = getBugData(bug.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); bd.bugFiled = System.currentTimeMillis(); bd.bugLink = PENDING; bd.filedBy = findbugsUser; } final BugData bd; public void execute(DatabaseSyncTask t) throws SQLException { t.fileBug(bd); } } class StoreNewBug implements Update { public StoreNewBug(BugInstance bug, long analysisTime) { this.bug = bug; this.analysisTime = analysisTime; } final BugInstance bug; final long analysisTime; public void execute(DatabaseSyncTask t) throws SQLException { BugData data = getBugData(bug.getInstanceHash()); if (data.lastSeen < analysisTime && FindBugs.validTimestamp(analysisTime)) data.lastSeen = analysisTime; long timestamp = getLocalFirstSeen(bug); if (timestamp < FIRST_LIGHT) timestamp = analysisTime; timestamp = sanityCheckFirstSeen(sanityCheckLastSeen(timestamp)); data.firstSeen = timestamp; if (data.inDatabase) return; t.newBug(bug); data.inDatabase = true; } } static class StoreUserAnnotation implements Update { public StoreUserAnnotation(BugData data, BugDesignation designation) { super(); this.data = data; this.designation = designation; } public void execute(DatabaseSyncTask t) throws SQLException { t.newEvaluation(data, new BugDesignation(designation)); } final BugData data; final BugDesignation designation; } private void displayMessage(String msg, Exception e) { AnalysisContext.logError(msg, e); if (bugCollection != null && bugCollection.getProject().isGuiAvaliable()) { StringWriter stackTraceWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stackTraceWriter); e.printStackTrace(printWriter); bugCollection.getProject().getGuiCallback() .showMessageDialog(String.format("%s - %s%n%s", msg, e.getMessage(), stackTraceWriter.toString())); } else { System.err.println(msg); e.printStackTrace(System.err); } } public SigninState getSigninState() { return signinState; } public void setSaveSignInInformation(boolean save) { // not saved anyway } public boolean isSavingSignInInformationEnabled() { return false; } public void signIn() { if (getSigninState() != SigninState.SIGNED_IN) throw new UnsupportedOperationException("Unable to sign in"); } public void signOut() { throw new UnsupportedOperationException(); } public String getUser() { return findbugsUser; } @Override public long getFirstSeen(BugInstance b) { return getBugData(b).firstSeen; } @Override public void addDateSeen(BugInstance b, long when) { if (when <= 0) return; when = sanityCheckFirstSeen(when); BugData bd = getBugData(b); if (bd.firstSeen < when) return; bd.firstSeen = when; storeFirstSeen(bd); } static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { assert false; return "No utf-8 encoding"; } } @Override public double getClassificationScore(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); double total = 0; int count = 0; for (BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (designation.nonVoting()) continue; total += designation.score(); count++; } return total / count; } @Override public double getPortionObsoleteClassifications(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; int count = 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); for (BugDesignation d : uniqueDesignations) if (UserDesignation.valueOf(d.getDesignationKey()) == UserDesignation.OBSOLETE_CODE) count++; return ((double) count) / uniqueDesignations.size(); } @Override public double getClassificationVariance(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); double total = 0; double totalSquares = 0; int count = 0; for (BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (designation.nonVoting()) continue; int score = designation.score(); total += score; totalSquares += score * score; count++; } double average = total / count; return totalSquares / count - average * average; } @Override public double getClassificationDisagreement(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); int shouldFix = 0; int dontFix = 0; for (BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (designation.nonVoting()) continue; int score = designation.score(); if (score > 0) shouldFix++; else dontFix++; } return Math.min(shouldFix, dontFix) / (double) (shouldFix + dontFix); } public Set<String> getReviewers(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return Collections.emptySet(); return bd.getReviewers(); } public boolean isClaimed(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; return bd.isClaimed(); } static final int MAX_URL_LENGTH = 1999; private static final String HAS_FILED_BUGS = "has_filed_bugs"; private static final String HAS_CLASSIFIED_ISSUES = "has_classified_issues"; private static boolean firstTimeDoing(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); if (!prefs.getBoolean(activity, false)) { prefs.putBoolean(activity, true); return true; } return false; } private static void alreadyDone(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); prefs.putBoolean(activity, true); } private boolean firstBugRequest = true; final String BUG_LINK_FORMAT = properties.getProperty("findbugs.filebug.link"); final String BUG_LOGIN_LINK = properties.getProperty("findbugs.filebug.login"); final String BUG_LOGIN_MSG = properties.getProperty("findbugs.filebug.loginMsg"); final String COMPONENT_FOR_BAD_ANALYSIS = properties.getProperty("findbugs.filebug.badAnalysisComponent"); @Override @CheckForNull public URL getBugLink(BugInstance b) { BugData bd = getBugData(b); String bugNumber = bd.bugLink; BugFilingStatus status = getBugLinkStatus(b); if (status == BugFilingStatus.VIEW_BUG) return getBugViewLink(bugNumber); Connection c = null; try { c = getConnection(); PreparedStatement ps = c .prepareStatement("SELECT bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport WHERE hash=?"); ps.setString(1, b.getInstanceHash()); ResultSet rs = ps.executeQuery(); Timestamp pendingFiledAt = null; while (rs.next()) { int col = 1; String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String statusString = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); if (bugReportId.equals(PENDING)) { if (!findbugsUser.equals(whoFiled) && !pendingStatusHasExpired(whenFiled.getTime())) pendingFiledAt = whenFiled; continue; } if (bugReportId.equals(NONE)) continue; rs.close(); ps.close(); bd.bugLink = bugReportId; bd.filedBy = whoFiled; bd.bugFiled = whenFiled.getTime(); bd.bugAssignedTo = assignedTo; bd.bugStatus = statusString; bd.bugComponentName = componentName; int answer = getBugCollection() .getProject() .getGuiCallback() .showConfirmDialog( "Sorry, but since the time we last received updates from the database,\n" + "someone else already filed a bug report. Would you like to view the bug report?", "Someone else already filed a bug report", "Yes", "No"); if (answer == 0) return null; return getBugViewLink(bugReportId); } rs.close(); ps.close(); if (pendingFiledAt != null) { bd.bugLink = PENDING; bd.bugFiled = pendingFiledAt.getTime(); getBugCollection() .getProject() .getGuiCallback() .showMessageDialog( "Sorry, but since the time we last received updates from the database,\n" + "someone else already has started a bug report for this issue. "); return null; } // OK, not in database if (status == BugFilingStatus.FILE_BUG) { URL u = getBugFilingLink(b); if (u != null && firstTimeDoing(HAS_FILED_BUGS)) { String bugFilingNote = String.format(properties.getProperty("findbugs.filebug.note", "")); int response = bugCollection .getProject() .getGuiCallback() .showConfirmDialog( "This looks like the first time you've filed a bug from this machine. Please:\n" + " * Please check the component the issue is assigned to; we sometimes get it wrong.\n" + " * Try to figure out the right person to assign it to.\n" + " * Provide the information needed to understand the issue.\n" + bugFilingNote + "Note that classifying an issue is distinct from (and lighter weight than) filing a bug.", "Do you want to file a bug report", "Yes", "No"); if (response != 0) return null; } if (u != null) insertPendingRecord(c, bd, System.currentTimeMillis(), findbugsUser); return u; } else { assert status == BugFilingStatus.FILE_AGAIN; alreadyDone(HAS_FILED_BUGS); URL u = getBugFilingLink(b); if (u != null) insertPendingRecord(c, bd, System.currentTimeMillis(), findbugsUser); return u; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { Util.closeSilently(c); } return null; } /** * @param bugNumber * @return * @throws MalformedURLException */ private @CheckForNull URL getBugViewLink(String bugNumber) { String viewLinkPattern = properties.getProperty("findbugs.viewbug.link"); if (viewLinkPattern == null) return null; firstBugRequest = false; String u = String.format(viewLinkPattern, bugNumber); try { return new URL(u); } catch (MalformedURLException e) { return null; } } private void displaySupplementalBugReport(String supplemental) { supplemental = "[Can't squeeze this information into the URL used to prepopulate the bug entry\n" + " please cut and paste into the bug report as appropriate]\n\n" + supplemental; bugCollection.getProject().getGuiCallback() .displayNonmodelMessage("Cut and paste as needed into bug entry", supplemental); } private URL getBugFilingLink(BugInstance b) throws MalformedURLException { if (BUG_LINK_FORMAT == null) return null; int maxURLLength = MAX_URL_LENGTH; if (firstBugRequest) { if (BUG_LOGIN_LINK != null && BUG_LOGIN_MSG != null) { URL u = new URL(String.format(BUG_LOGIN_LINK)); if (!bugCollection.getProject().getGuiCallback().showDocument(u)) return null; int r = bugCollection.getProject().getGuiCallback() .showConfirmDialog(BUG_LOGIN_MSG, "Logging into bug tracker...", "OK", "Cancel"); if (r != 0) return null; } else maxURLLength = maxURLLength * 2 / 3; } firstBugRequest = false; String component; if (getUserDesignation(b) == UserDesignation.BAD_ANALYSIS && COMPONENT_FOR_BAD_ANALYSIS != null) component = COMPONENT_FOR_BAD_ANALYSIS; else component = getBugComponent(b.getPrimaryClass().getClassName().replace('.', '/')); String summary = bugFilingCommentHelper.getBugReportSummary(b); String report = bugFilingCommentHelper.getBugReportText(b); String u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > maxURLLength) { String head = bugFilingCommentHelper.getBugReportHead(b); String sourceCode = bugFilingCommentHelper.getBugReportSourceCode(b); String tail = bugFilingCommentHelper.getBugReportTail(b); report = head + sourceCode + tail; String lineTerminatedUserEvaluation = bugFilingCommentHelper.getLineTerminatedUserEvaluation(b); String explanation = bugFilingCommentHelper.getBugPatternExplanation(b); String supplemental = lineTerminatedUserEvaluation + explanation; u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > maxURLLength) { report = head + tail; supplemental = sourceCode + lineTerminatedUserEvaluation + explanation; u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > maxURLLength) { // Last resort: Just make the link work with a minimal // report and by shortening the summary supplemental = head + sourceCode + lineTerminatedUserEvaluation + explanation; report = tail; // (assuming BUG_URL_FORMAT + component + report tail is // always < maxUrlLength) String urlEncodedSummary = urlEncode(summary); String urlEncodedReport = urlEncode(report); String urlEncodedComponent = urlEncode(component); int maxSummaryLength = maxURLLength - BUG_LINK_FORMAT.length() + 6 /* * 3 * % * s * placeholders */ - urlEncodedReport.length() - urlEncodedComponent.length(); if (urlEncodedSummary.length() > maxSummaryLength) { urlEncodedSummary = urlEncodedSummary.substring(0, maxSummaryLength - 1); // Chop of any incomplete trailing percent encoded part if ("%".equals(urlEncodedSummary.substring(urlEncodedSummary.length() - 1))) { urlEncodedSummary = urlEncodedSummary.substring(0, urlEncodedSummary.length() - 2); } else if ("%".equals(urlEncodedSummary.substring(urlEncodedSummary.length() - 2, urlEncodedSummary.length() - 1))) { urlEncodedSummary = urlEncodedSummary.substring(0, urlEncodedSummary.length() - 3); } } u = String.format(BUG_LINK_FORMAT, urlEncodedComponent, urlEncodedSummary, urlEncodedReport); } } displaySupplementalBugReport(supplemental); } return new URL(u); } @Override public boolean supportsCloudReports() { return true; } @Override public boolean supportsBugLinks() { return BUG_LINK_FORMAT != null; } public void storeUserAnnotation(BugInstance bugInstance) { storeUserAnnotation(getBugData(bugInstance), bugInstance.getNonnullUserDesignation()); updatedIssue(bugInstance); } @Override public BugFilingStatus getBugLinkStatus(BugInstance b) { BugData bd = getBugData(b); String link = bd.bugLink; if (link == null || link.length() == 0 || link.equals(NONE)) return BugFilingStatus.FILE_BUG; if (link.equals(PENDING)) { if (findbugsUser.equals(bd.filedBy)) return BugFilingStatus.FILE_AGAIN; else { long whenFiled = bd.bugFiled; if (pendingStatusHasExpired(whenFiled)) return BugFilingStatus.FILE_BUG; else return BugFilingStatus.BUG_PENDING; } } try { Integer.parseInt(link); return BugFilingStatus.VIEW_BUG; } catch (RuntimeException e) { assert true; } return BugFilingStatus.NA; } @Override public String getBugStatus(BugInstance b) { String status = getBugData(b).bugStatus; if (status != null) return status; return "Unknown"; } private boolean pendingStatusHasExpired(long whenFiled) { return System.currentTimeMillis() - whenFiled > 60 * 60 * 1000L; } public void bugFiled(BugInstance b, Object bugLink) { checkForShutdown(); if (bugAlreadyFiled(b)) { return; } queue.add(new FileBug(b)); updatedStatus(); } String errorMsg; long errorTime = 0; void setErrorMsg(String msg) { errorMsg = msg; errorTime = System.currentTimeMillis(); updatedStatus(); } void clearErrorMsg() { errorMsg = null; updatedStatus(); } @Override public String getStatusMsg() { if (errorMsg != null) { if (errorTime + 2 * 60 * 1000 > System.currentTimeMillis()) { errorMsg = null; } else return errorMsg + "; " + getStatusMsg0(); } return getStatusMsg0(); } @SuppressWarnings("boxing") public String getStatusMsg0() { SimpleDateFormat format = new SimpleDateFormat("h:mm a"); int numToSync = queue.size(); if (numToSync > 0) return String.format("%d remain to be synchronized", numToSync); else if (resync != null && resync.after(lastUpdate)) return String.format("%d updates received from db at %s", resyncCount, format.format(resync)); else if (updatesSentToDatabase == 0) { int skipped = bugCollection.getCollection().size() - idMap.size(); if (skipped == 0) return String.format("%d issues synchronized with database", idMap.size()); else return String.format("%d issues synchronized with database, %d low rank issues not synchronized", idMap.size(), skipped); } else return String.format("%d classifications/bug filings sent to db, last updated at %s", updatesSentToDatabase, format.format(lastUpdate)); } @Override public boolean getIWillFix(BugInstance b) { if (super.getIWillFix(b)) return true; BugData bd = getBugData(b); return bd != null && findbugsUser.equals(bd.bugAssignedTo); } @Override public boolean getBugIsUnassigned(BugInstance b) { BugData bd = getBugData(b); return bd != null && bd.inDatabase && getBugLinkStatus(b) == BugFilingStatus.VIEW_BUG && ("NEW".equals(bd.bugStatus) || bd.bugAssignedTo == null || bd.bugAssignedTo.length() == 0); } @Override public boolean getWillNotBeFixed(BugInstance b) { BugData bd = getBugData(b); return bd != null && bd.inDatabase && getBugLinkStatus(b) == BugFilingStatus.VIEW_BUG && ("WILL_NOT_FIX".equals(bd.bugStatus) || "OBSOLETE".equals(bd.bugStatus) || "WORKS_AS_INTENDED".equals(bd.bugStatus) || "NOT_FEASIBLE".equals(bd.bugStatus)); } @Override public boolean supportsCloudSummaries() { return true; } @Override public boolean canStoreUserAnnotation(BugInstance bugInstance) { return !skipBug(bugInstance); } @Override public @CheckForNull String claimedBy(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return null; for (BugDesignation designation : bd.getUniqueDesignations()) { if ("I_WILL_FIX".equals(designation.getDesignationKey())) return designation.getUser(); } return null; } @Override protected Iterable<BugDesignation> getLatestDesignationFromEachUser(BugInstance bd) { BugData bugData = instanceMap.get(bd.getInstanceHash()); if (bugData == null) return Collections.emptyList(); return bugData.getUniqueDesignations(); } @Override public BugInstance getBugByHash(String hash) { Collection<BugInstance> bugs = instanceMap.get(hash).bugs; return bugs.isEmpty() ? null : bugs.iterator().next(); } public Collection<String> getProjects(String className) { return projectMapping.getProjects(className); } public boolean isInCloud(BugInstance b) { if (b == null) throw new NullPointerException("null bug"); String instanceHash = b.getInstanceHash(); BugData bugData = instanceMap.get(instanceHash); return bugData != null && bugData.inDatabase; } @Override public String notInCloudeMsg(BugInstance b) { if (isInCloud(b)) { assert false; return "Is in cloud"; } int rank = BugRanker.findRank(b); if (rank > MAX_DB_RANK) return String.format("This issue is rank %d, only issues up to rank %d are recorded in the cloud", rank, MAX_DB_RANK); return "Issue is not recorded in cloud"; } public boolean isOnlineCloud() { return true; } @Override public URL fileBug(BugInstance bug) { return null; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.cloud.Cloud#waitUntilNewIssuesUploaded() */ public void waitUntilNewIssuesUploaded() { try { initiateCommunication(); initialSyncDone.await(); } catch (InterruptedException e) { } } }
fix tab git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@13670 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
plugins/jdbcCloudClient/src/java/edu/umd/cs/findbugs/cloud/db/DBCloud.java
fix tab
<ide><path>lugins/jdbcCloudClient/src/java/edu/umd/cs/findbugs/cloud/db/DBCloud.java <ide> else if (updatesSentToDatabase == 0) { <ide> int skipped = bugCollection.getCollection().size() - idMap.size(); <ide> if (skipped == 0) <del> return String.format("%d issues synchronized with database", idMap.size()); <add> return String.format("%d issues synchronized with database", idMap.size()); <ide> else <ide> return String.format("%d issues synchronized with database, %d low rank issues not synchronized", <ide> idMap.size(), skipped); <ide> } <ide> <ide> public boolean isInCloud(BugInstance b) { <del> if (b == null) <del> throw new NullPointerException("null bug"); <add> if (b == null) <add> throw new NullPointerException("null bug"); <ide> String instanceHash = b.getInstanceHash(); <del> BugData bugData = instanceMap.get(instanceHash); <del> return bugData != null && bugData.inDatabase; <add> BugData bugData = instanceMap.get(instanceHash); <add> return bugData != null && bugData.inDatabase; <ide> } <ide> <ide> @Override <ide> public String notInCloudeMsg(BugInstance b) { <del> if (isInCloud(b)) { <del> assert false; <del> return "Is in cloud"; <add> if (isInCloud(b)) { <add> assert false; <add> return "Is in cloud"; <ide> } <del> int rank = BugRanker.findRank(b); <del> if (rank > MAX_DB_RANK) <del> return <add> int rank = BugRanker.findRank(b); <add> if (rank > MAX_DB_RANK) <add> return <ide> String.format("This issue is rank %d, only issues up to rank %d are recorded in the cloud", <del> rank, MAX_DB_RANK); <del> return "Issue is not recorded in cloud"; <add> rank, MAX_DB_RANK); <add> return "Issue is not recorded in cloud"; <ide> } <ide> <ide> public boolean isOnlineCloud() {
Java
mpl-2.0
de445c32e4f6bad21418b138c09a6170201a2af4
0
sensiasoft/sensorhub,TheRestOfMe/sensorhub,TheRestOfMe/sensorhub,sensiasoft/sensorhub-core,sensiasoft/sensorhub,sensiasoft/sensorhub-core,TheRestOfMe/sensorhub,sensiasoft/sensorhub,sensiasoft/sensorhub-core
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.sensorhub.ui; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import net.opengis.swe.v20.DataBlock; import net.opengis.swe.v20.DataComponent; import net.opengis.swe.v20.DataRecord; import net.opengis.swe.v20.ScalarComponent; import net.opengis.swe.v20.Vector; import org.sensorhub.api.module.ModuleConfig; import org.sensorhub.api.persistence.DataFilter; import org.sensorhub.api.persistence.IRecordStoreInfo; import org.sensorhub.api.persistence.IRecordStorageModule; import org.sensorhub.ui.api.IModuleAdminPanel; import org.sensorhub.ui.data.MyBeanItem; import org.tltv.gantt.Gantt; import org.tltv.gantt.client.shared.Resolution; import org.tltv.gantt.client.shared.Step; import org.tltv.gantt.client.shared.SubStep; import org.vast.swe.SWEConstants; import org.vast.swe.ScalarIndexer; import org.vast.util.DateTimeFormat; import com.vaadin.data.util.converter.Converter; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Component; import com.vaadin.ui.GridLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.Table; /** * <p> * Admin panel for sensor modules.<br/> * This adds a section to view structure of inputs and outputs, * and allows the user to send commands and view output data values. * </p> * * @author Alex Robin <[email protected]> * @since 1.0 */ public class StorageAdminPanel extends DefaultModulePanel<IRecordStorageModule<?>> implements IModuleAdminPanel<IRecordStorageModule<?>> { private static final long serialVersionUID = 9206002459600214988L; Panel oldPanel; @Override public void build(final MyBeanItem<ModuleConfig> beanItem, final IRecordStorageModule<?> storage) { super.build(beanItem, storage); if (storage != null) { // section layout final GridLayout form = new GridLayout(); form.setWidth(100.0f, Unit.PERCENTAGE); form.setMargin(false); form.setSpacing(true); // section title form.addComponent(new Label("")); HorizontalLayout titleBar = new HorizontalLayout(); titleBar.setSpacing(true); Label sectionLabel = new Label("Data Store Content"); sectionLabel.addStyleName(STYLE_H3); sectionLabel.addStyleName(STYLE_COLORED); titleBar.addComponent(sectionLabel); titleBar.setComponentAlignment(sectionLabel, Alignment.MIDDLE_LEFT); // refresh button to show latest record Button refreshButton = new Button("Refresh"); refreshButton.setDescription("Reload data from storage"); refreshButton.setIcon(REFRESH_ICON); refreshButton.addStyleName(STYLE_QUIET); titleBar.addComponent(refreshButton); titleBar.setComponentAlignment(refreshButton, Alignment.MIDDLE_LEFT); refreshButton.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { buildDataPanel(form, storage); } }); form.addComponent(titleBar); // add I/O panel buildDataPanel(form, storage); addComponent(form); } } protected void buildDataPanel(GridLayout form, IRecordStorageModule<?> storage) { // measurement outputs int i = 1; for (IRecordStoreInfo dsInfo: storage.getRecordStores().values()) { Panel panel = newPanel("Stream #" + i++); GridLayout panelLayout = ((GridLayout)panel.getContent()); panelLayout.setSpacing(true); // stored time period double[] timeRange = storage.getRecordsTimeRange(dsInfo.getName()); Label l = new Label("<b>Time Range:</b> " + new DateTimeFormat().formatIso(timeRange[0], 0) + " / " + new DateTimeFormat().formatIso(timeRange[1], 0)); l.setContentMode(ContentMode.HTML); panelLayout.addComponent(l, 0, 0, 1, 0); // time line panelLayout.addComponent(buildGantt(storage, dsInfo), 0, 1, 1, 1); // data structure DataComponent dataStruct = dsInfo.getRecordDescription(); Component sweForm = new SWECommonForm(dataStruct); panelLayout.addComponent(sweForm); // data table panelLayout.addComponent(buildTable(storage, dsInfo)); if (oldPanel != null) form.replaceComponent(oldPanel, panel); else form.addComponent(panel); oldPanel = panel; } } protected Gantt buildGantt(IRecordStorageModule<?> storage, IRecordStoreInfo recordInfo) { double[] timeRange = storage.getRecordsTimeRange(recordInfo.getName()); timeRange[0] -= 3600; timeRange[1] += 3600; Gantt gantt = new Gantt(); gantt.setWidth(100, Unit.PERCENTAGE); gantt.setHeight(130, Unit.PIXELS); gantt.setResizableSteps(false); gantt.setMovableSteps(false); gantt.setStartDate(new Date((long)(timeRange[0]*1000))); gantt.setEndDate(new Date((long)(timeRange[1]*1000))); gantt.setYearsVisible(false); gantt.setTimelineMonthFormat("MMMM yyyy"); gantt.setResolution(Resolution.Hour); Step dataTimeRange = new Step(getPrettyName(recordInfo.getRecordDescription())); dataTimeRange.setBackgroundColor("FFFFFF"); dataTimeRange.setStartDate((long)(timeRange[0]*1000)); dataTimeRange.setEndDate((long)(timeRange[1]*1000)); // add periods when data is actually available Iterator<double[]> clusterTimes = storage.getRecordsTimeClusters(recordInfo.getName()); while (clusterTimes.hasNext()) { timeRange = clusterTimes.next(); SubStep clusterPeriod = new SubStep(); clusterPeriod.setStartDate((long)(timeRange[0]*1000)); clusterPeriod.setEndDate((long)(timeRange[1]*1000)); dataTimeRange.addSubStep(clusterPeriod); clusterPeriod.setDescription( new DateTimeFormat().formatIso(timeRange[0], 0) + " / " + new DateTimeFormat().formatIso(timeRange[1], 0) ); } gantt.addStep(dataTimeRange); gantt.addClickListener(new Gantt.ClickListener() { private static final long serialVersionUID = 1L; public void onGanttClick(org.tltv.gantt.Gantt.ClickEvent event) { System.out.println("click"); } }); return gantt; } protected Table buildTable(IRecordStorageModule<?> storage, IRecordStoreInfo recordInfo) { Table table = new Table(); table.setWidth(100, Unit.PERCENTAGE); table.setPageLength(10); // add column names List<ScalarIndexer> indexers = new ArrayList<ScalarIndexer>(); DataComponent recordDef = recordInfo.getRecordDescription(); addColumns(recordDef, recordDef, table, indexers); // add data Iterator<DataBlock> it = storage.getDataBlockIterator(new DataFilter(recordInfo.getName())); int count = 0; int pageSize = 10; while (it.hasNext() && count < pageSize) { DataBlock dataBlk = it.next(); Object[] values = new Object[indexers.size()]; for (int i=0; i<values.length; i++) values[i] = indexers.get(i).getStringValue(dataBlk); table.addItem(values, count); count++; } return table; } protected void addColumns(DataComponent recordDef, DataComponent component, Table table, List<ScalarIndexer> indexers) { if (component instanceof ScalarComponent) { // add column names String propId = component.getName(); String label = getPrettyName(component); table.addContainerProperty(propId, String.class, null, label, null, null); // correct time formatting String def = component.getDefinition(); if (def != null && def.equals(SWEConstants.DEF_SAMPLING_TIME)) { table.setConverter(propId, new Converter<String, String>() { private static final long serialVersionUID = 1L; DateTimeFormat dateFormat = new DateTimeFormat(); public String convertToPresentation(String value, Class<? extends String> targetType, Locale locale) throws ConversionException { return dateFormat.formatIso(Double.parseDouble(value), 0); } @Override public String convertToModel(String value, Class<? extends String> targetType, Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException { return null; } @Override public Class<String> getModelType() { return String.class; } @Override public Class<String> getPresentationType() { return String.class; } }); } // prepare indexer for reading from datablocks indexers.add(new ScalarIndexer(recordDef, (ScalarComponent)component)); } // call recursively for records else if (component instanceof DataRecord || component instanceof Vector) { for (int i = 0; i < component.getComponentCount(); i++) { DataComponent child = component.getComponent(i); addColumns(recordDef, child, table, indexers); } } } protected String getPrettyName(DataComponent dataComponent) { String label = dataComponent.getLabel(); if (label == null) label = DisplayUtils.getPrettyName(dataComponent.getName()); return label; } protected Panel newPanel(String title) { Panel panel = new Panel(title); GridLayout layout = new GridLayout(2, 2); layout.setWidth(100.0f, Unit.PERCENTAGE); layout.setMargin(true); layout.setSpacing(true); layout.setColumnExpandRatio(0, 0.2f); layout.setColumnExpandRatio(1, 0.8f); layout.setDefaultComponentAlignment(Alignment.TOP_LEFT); panel.setContent(layout); return panel; } }
sensorhub-webui-core/src/main/java/org/sensorhub/ui/StorageAdminPanel.java
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.sensorhub.ui; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import net.opengis.swe.v20.DataBlock; import net.opengis.swe.v20.DataComponent; import net.opengis.swe.v20.ScalarComponent; import org.sensorhub.api.module.ModuleConfig; import org.sensorhub.api.persistence.DataFilter; import org.sensorhub.api.persistence.IRecordStoreInfo; import org.sensorhub.api.persistence.IRecordStorageModule; import org.sensorhub.ui.api.IModuleAdminPanel; import org.sensorhub.ui.data.MyBeanItem; import org.tltv.gantt.Gantt; import org.tltv.gantt.client.shared.Resolution; import org.tltv.gantt.client.shared.Step; import org.tltv.gantt.client.shared.SubStep; import org.vast.swe.SWEConstants; import org.vast.swe.ScalarIndexer; import org.vast.util.DateTimeFormat; import com.vaadin.data.util.converter.StringToDoubleConverter; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Component; import com.vaadin.ui.GridLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.Table; /** * <p> * Admin panel for sensor modules.<br/> * This adds a section to view structure of inputs and outputs, * and allows the user to send commands and view output data values. * </p> * * @author Alex Robin <[email protected]> * @since 1.0 */ public class StorageAdminPanel extends DefaultModulePanel<IRecordStorageModule<?>> implements IModuleAdminPanel<IRecordStorageModule<?>> { private static final long serialVersionUID = 9206002459600214988L; Panel oldPanel; @Override public void build(final MyBeanItem<ModuleConfig> beanItem, final IRecordStorageModule<?> storage) { super.build(beanItem, storage); if (storage != null) { // section layout final GridLayout form = new GridLayout(); form.setWidth(100.0f, Unit.PERCENTAGE); form.setMargin(false); form.setSpacing(true); // section title form.addComponent(new Label("")); HorizontalLayout titleBar = new HorizontalLayout(); titleBar.setSpacing(true); Label sectionLabel = new Label("Data Store Content"); sectionLabel.addStyleName(STYLE_H3); sectionLabel.addStyleName(STYLE_COLORED); titleBar.addComponent(sectionLabel); titleBar.setComponentAlignment(sectionLabel, Alignment.MIDDLE_LEFT); // refresh button to show latest record Button refreshButton = new Button("Refresh"); refreshButton.setDescription("Reload data from storage"); refreshButton.setIcon(REFRESH_ICON); refreshButton.addStyleName(STYLE_QUIET); titleBar.addComponent(refreshButton); titleBar.setComponentAlignment(refreshButton, Alignment.MIDDLE_LEFT); refreshButton.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { buildDataPanel(form, storage); } }); form.addComponent(titleBar); // add I/O panel buildDataPanel(form, storage); addComponent(form); } } protected void buildDataPanel(GridLayout form, IRecordStorageModule<?> storage) { // measurement outputs int i = 1; for (IRecordStoreInfo dsInfo: storage.getRecordStores().values()) { Panel panel = newPanel("Stream #" + i++); GridLayout panelLayout = ((GridLayout)panel.getContent()); panelLayout.setSpacing(true); // stored time period double[] timeRange = storage.getRecordsTimeRange(dsInfo.getName()); Label l = new Label("<b>Time Range:</b> " + new DateTimeFormat().formatIso(timeRange[0], 0) + " / " + new DateTimeFormat().formatIso(timeRange[1], 0)); l.setContentMode(ContentMode.HTML); panelLayout.addComponent(l, 0, 0, 1, 0); // time line panelLayout.addComponent(buildGantt(storage, dsInfo), 0, 1, 1, 1); // data structure DataComponent dataStruct = dsInfo.getRecordDescription(); Component sweForm = new SWECommonForm(dataStruct); panelLayout.addComponent(sweForm); // data table panelLayout.addComponent(buildTable(storage, dsInfo)); if (oldPanel != null) form.replaceComponent(oldPanel, panel); else form.addComponent(panel); oldPanel = panel; } } protected Gantt buildGantt(IRecordStorageModule<?> storage, IRecordStoreInfo recordInfo) { double[] timeRange = storage.getRecordsTimeRange(recordInfo.getName()); timeRange[0] -= 3600; timeRange[1] += 3600; Gantt gantt = new Gantt(); gantt.setWidth(100, Unit.PERCENTAGE); gantt.setHeight(130, Unit.PIXELS); gantt.setResizableSteps(false); gantt.setMovableSteps(false); gantt.setStartDate(new Date((long)(timeRange[0]*1000))); gantt.setEndDate(new Date((long)(timeRange[1]*1000))); gantt.setYearsVisible(false); gantt.setTimelineMonthFormat("MMMM yyyy"); gantt.setResolution(Resolution.Hour); Step dataTimeRange = new Step(getPrettyName(recordInfo.getRecordDescription())); dataTimeRange.setBackgroundColor("FFFFFF"); dataTimeRange.setStartDate((long)(timeRange[0]*1000)); dataTimeRange.setEndDate((long)(timeRange[1]*1000)); // add periods when data is actually available Iterator<double[]> clusterTimes = storage.getRecordsTimeClusters(recordInfo.getName()); while (clusterTimes.hasNext()) { timeRange = clusterTimes.next(); SubStep clusterPeriod = new SubStep(); clusterPeriod.setStartDate((long)(timeRange[0]*1000)); clusterPeriod.setEndDate((long)(timeRange[1]*1000)); dataTimeRange.addSubStep(clusterPeriod); clusterPeriod.setDescription( new DateTimeFormat().formatIso(timeRange[0], 0) + " / " + new DateTimeFormat().formatIso(timeRange[1], 0) ); } gantt.addStep(dataTimeRange); gantt.addClickListener(new Gantt.ClickListener() { private static final long serialVersionUID = 1L; public void onGanttClick(org.tltv.gantt.Gantt.ClickEvent event) { System.out.println("click"); } }); return gantt; } protected Table buildTable(IRecordStorageModule<?> storage, IRecordStoreInfo recordInfo) { Table table = new Table(); table.setWidth(100, Unit.PERCENTAGE); table.setPageLength(10); // add column names List<ScalarIndexer> indexers = new ArrayList<ScalarIndexer>(); DataComponent recordDef = recordInfo.getRecordDescription(); for (int i = 0; i < recordDef.getComponentCount(); i++) { DataComponent child = recordDef.getComponent(i); if (child instanceof ScalarComponent) { // add column names String propId = child.getName(); String label = getPrettyName(child); table.addContainerProperty(propId, Double.class, null, label, null, null); // correct time formatting if (child.getDefinition().equals(SWEConstants.DEF_SAMPLING_TIME)) { table.setConverter(propId, new StringToDoubleConverter() { private static final long serialVersionUID = 1L; DateTimeFormat dateFormat = new DateTimeFormat(); public String convertToPresentation(Double value, Class<? extends String> targetType, Locale locale) throws ConversionException { return dateFormat.formatIso(value, 0); } }); } // prepare indexer for reading from datablocks indexers.add(new ScalarIndexer(recordDef, (ScalarComponent)child)); } } // add data Iterator<DataBlock> it = storage.getDataBlockIterator(new DataFilter(recordInfo.getName())); int count = 0; int pageSize = 10; while (it.hasNext() && count < pageSize) { DataBlock dataBlk = it.next(); Object[] values = new Object[indexers.size()]; for (int i=0; i<values.length; i++) values[i] = indexers.get(i).getDoubleValue(dataBlk); table.addItem(values, count); count++; } return table; } protected String getPrettyName(DataComponent dataComponent) { String label = dataComponent.getLabel(); if (label == null) label = DisplayUtils.getPrettyName(dataComponent.getName()); return label; } protected Panel newPanel(String title) { Panel panel = new Panel(title); GridLayout layout = new GridLayout(2, 2); layout.setWidth(100.0f, Unit.PERCENTAGE); layout.setMargin(true); layout.setSpacing(true); layout.setColumnExpandRatio(0, 0.2f); layout.setColumnExpandRatio(1, 0.8f); layout.setDefaultComponentAlignment(Alignment.TOP_LEFT); panel.setContent(layout); return panel; } }
Bug fix to display other field types than quantities/decimals
sensorhub-webui-core/src/main/java/org/sensorhub/ui/StorageAdminPanel.java
Bug fix to display other field types than quantities/decimals
<ide><path>ensorhub-webui-core/src/main/java/org/sensorhub/ui/StorageAdminPanel.java <ide> import java.util.Locale; <ide> import net.opengis.swe.v20.DataBlock; <ide> import net.opengis.swe.v20.DataComponent; <add>import net.opengis.swe.v20.DataRecord; <ide> import net.opengis.swe.v20.ScalarComponent; <add>import net.opengis.swe.v20.Vector; <ide> import org.sensorhub.api.module.ModuleConfig; <ide> import org.sensorhub.api.persistence.DataFilter; <ide> import org.sensorhub.api.persistence.IRecordStoreInfo; <ide> import org.vast.swe.SWEConstants; <ide> import org.vast.swe.ScalarIndexer; <ide> import org.vast.util.DateTimeFormat; <del>import com.vaadin.data.util.converter.StringToDoubleConverter; <add>import com.vaadin.data.util.converter.Converter; <ide> import com.vaadin.shared.ui.label.ContentMode; <ide> import com.vaadin.ui.Alignment; <ide> import com.vaadin.ui.Button; <ide> // add column names <ide> List<ScalarIndexer> indexers = new ArrayList<ScalarIndexer>(); <ide> DataComponent recordDef = recordInfo.getRecordDescription(); <del> for (int i = 0; i < recordDef.getComponentCount(); i++) <del> { <del> DataComponent child = recordDef.getComponent(i); <del> if (child instanceof ScalarComponent) <del> { <del> // add column names <del> String propId = child.getName(); <del> String label = getPrettyName(child); <del> table.addContainerProperty(propId, Double.class, null, label, null, null); <del> <del> // correct time formatting <del> if (child.getDefinition().equals(SWEConstants.DEF_SAMPLING_TIME)) <del> { <del> table.setConverter(propId, new StringToDoubleConverter() { <del> private static final long serialVersionUID = 1L; <del> DateTimeFormat dateFormat = new DateTimeFormat(); <del> public String convertToPresentation(Double value, Class<? extends String> targetType, Locale locale) throws ConversionException <del> { <del> return dateFormat.formatIso(value, 0); <del> } <del> <del> }); <del> } <del> <del> // prepare indexer for reading from datablocks <del> indexers.add(new ScalarIndexer(recordDef, (ScalarComponent)child)); <del> } <del> } <add> addColumns(recordDef, recordDef, table, indexers); <ide> <ide> // add data <ide> Iterator<DataBlock> it = storage.getDataBlockIterator(new DataFilter(recordInfo.getName())); <ide> <ide> Object[] values = new Object[indexers.size()]; <ide> for (int i=0; i<values.length; i++) <del> values[i] = indexers.get(i).getDoubleValue(dataBlk); <add> values[i] = indexers.get(i).getStringValue(dataBlk); <ide> <ide> table.addItem(values, count); <ide> count++; <ide> } <ide> <ide> return table; <add> } <add> <add> <add> protected void addColumns(DataComponent recordDef, DataComponent component, Table table, List<ScalarIndexer> indexers) <add> { <add> if (component instanceof ScalarComponent) <add> { <add> // add column names <add> String propId = component.getName(); <add> String label = getPrettyName(component); <add> table.addContainerProperty(propId, String.class, null, label, null, null); <add> <add> // correct time formatting <add> String def = component.getDefinition(); <add> if (def != null && def.equals(SWEConstants.DEF_SAMPLING_TIME)) <add> { <add> table.setConverter(propId, new Converter<String, String>() { <add> private static final long serialVersionUID = 1L; <add> DateTimeFormat dateFormat = new DateTimeFormat(); <add> public String convertToPresentation(String value, Class<? extends String> targetType, Locale locale) throws ConversionException <add> { <add> return dateFormat.formatIso(Double.parseDouble(value), 0); <add> } <add> @Override <add> public String convertToModel(String value, Class<? extends String> targetType, Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException <add> { <add> return null; <add> } <add> @Override <add> public Class<String> getModelType() <add> { <add> return String.class; <add> } <add> @Override <add> public Class<String> getPresentationType() <add> { <add> return String.class; <add> } <add> }); <add> } <add> <add> // prepare indexer for reading from datablocks <add> indexers.add(new ScalarIndexer(recordDef, (ScalarComponent)component)); <add> } <add> <add> // call recursively for records <add> else if (component instanceof DataRecord || component instanceof Vector) <add> { <add> for (int i = 0; i < component.getComponentCount(); i++) <add> { <add> DataComponent child = component.getComponent(i); <add> addColumns(recordDef, child, table, indexers); <add> } <add> } <ide> } <ide> <ide>
Java
apache-2.0
f5464363c217ed2a84a3e6f72d626f2fc92beaeb
0
mtamme/promises
/* * Copyright © Martin Tamme * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.util.concurrent; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a default deferred. * * @param <T> The value type. */ final class DefaultDeferred<T> implements Deferred<T> { /** * The private logger. */ private static final Logger logger = LoggerFactory.getLogger(DefaultDeferred.class); /** * The state of the deferred. */ private final AtomicReference<State<T>> _state; /** * Initializes a new instance of the {@link DefaultDeferred} class. */ public DefaultDeferred() { final State<T> initialState = new PendingState(); _state = new AtomicReference<State<T>>(initialState); } /** * Initializes a new instance of the {@link DefaultDeferred} class. * * @param value The value. */ public DefaultDeferred(final T value) { final State<T> initialState = new SuccessState<T>(value); _state = new AtomicReference<State<T>>(initialState); } /** * Initializes a new instance of the {@link DefaultDeferred} class. * * @param cause The cause. */ public DefaultDeferred(final Throwable cause) { if (cause == null) { throw new IllegalArgumentException("Cause must not be null"); } final State<T> initialState = new FailureState<T>(cause); _state = new AtomicReference<State<T>>(initialState); } @Override public void setSuccess(final T value) { if (!trySuccess(value)) { throw new IllegalStateException("Deferred is already complete"); } } @Override public void setFailure(final Throwable cause) { if (!tryFailure(cause)) { throw new IllegalStateException("Deferred is already complete"); } } @Override public final boolean trySuccess(final T value) { return _state.get().trySuccess(value); } @Override public final boolean tryFailure(final Throwable cause) { if (cause == null) { throw new IllegalArgumentException("Cause must not be null"); } return _state.get().tryFailure(cause); } @Override public final boolean isComplete() { return _state.get().isComplete(); } @Override public void then(final Completable<T> completable) { if (completable == null) { throw new IllegalArgumentException("Completable must not be null"); } _state.get().then(completable); } @Override public final <R> Promise<R> then(final Continuation<T, R> continuation) { if (continuation == null) { throw new IllegalArgumentException("Continuation must not be null"); } final Deferred<R> deferred = new DefaultDeferred<R>(); _state.get().then(new Completable<T>() { @Override public void setSuccess(final T value) { try { continuation.setSuccess(value, deferred); } catch (final Throwable t) { deferred.tryFailure(t); } } @Override public void setFailure(final Throwable cause) { try { continuation.setFailure(cause, deferred); } catch (final Throwable t) { t.addSuppressed(cause); deferred.tryFailure(t); } } }); return deferred; } /** * Defines a state. * * @param <T> The value type. */ private static interface State<T> { /** * Returns a value indicating whether the deferred is complete. * * @return a value indicating whether the deferred is complete. */ boolean isComplete(); /** * Tries to complete the deferred with the specified value. * * @param value The value. * @return A value indicating whether the deferred has been completed. */ boolean trySuccess(T value); /** * Tries to complete the deferred with the specified cause. * * @param cause The cause. * @return A value indicating whether the deferred has been completed. */ boolean tryFailure(Throwable throwable); /** * Adds the specified completable. * * @param completable The completable. */ void then(Completable<T> completable); } /** * Represents a pending state. * * @param <V> The value type. */ private final class PendingState implements State<T> { /** * The stage queue. */ private final ConcurrentLinkedQueue<Stage<T>> _stages; /** * Initializes a new instance of the {@link PendingState} class. */ public PendingState() { _stages = new ConcurrentLinkedQueue<Stage<T>>(); } /** * Tries to change the state to the specified state. * * @param state The state. * @return A value indicating whether the state has been changed. */ private boolean tryChangeState(final State<T> state) { if (!_state.compareAndSet(this, state)) { return false; } completeStages(state); return true; } /** * Adds the specified stage. * * @param stage The stage. */ private void addStage(final Stage<T> stage) { // As the queue is unbounded, this method will never return false. _stages.offer(stage); // Trigger completion when the promise has been completed in the meantime. final State<T> state = _state.get(); if (state != this) { completeStages(state); } } /** * Completes the stages with the specified state. * * @param state The state. */ private void completeStages(final State<T> state) { Stage<T> stage; while ((stage = _stages.poll()) != null) { try { stage.complete(state); } catch (final Throwable t) { logger.warn("Failed to complete stage", t); } } } @Override public boolean isComplete() { return false; } @Override public boolean trySuccess(final T value) { final State<T> state = new SuccessState<T>(value); return tryChangeState(state); } @Override public boolean tryFailure(final Throwable cause) { final State<T> state = new FailureState<T>(cause); return tryChangeState(state); } @Override public void then(final Completable<T> completable) { final Stage<T> stage = new Stage<T>(completable); addStage(stage); } } /** * Represents a complete state. * * @param <T> The value type. */ private static abstract class CompleteState<T> implements State<T> { @Override public boolean isComplete() { return true; } @Override public final boolean trySuccess(final T value) { return false; } @Override public final boolean tryFailure(final Throwable cause) { return false; } } /** * Represents a success state. * * @param <T> The value type. */ private static final class SuccessState<T> extends CompleteState<T> { /** * The value. */ private final T _value; /** * Initializes a new instance of the {@link SuccessState} class. * * @param value The value. */ public SuccessState(final T value) { _value = value; } @Override public void then(final Completable<T> completable) { completable.setSuccess(_value); } } /** * Represents a failure state. * * @param <T> The value type. */ private static final class FailureState<T> extends CompleteState<T> { /** * The cause. */ private final Throwable _cause; /** * Initializes a new instance of the {@link FailureState} class. * * @param cause The cause. */ public FailureState(final Throwable cause) { _cause = cause; } @Override public void then(final Completable<T> completable) { completable.setFailure(_cause); } } /** * Represents a stage. * * @param <T> The value type. */ private static final class Stage<T> { /** * The completable. */ private final Completable<T> _completable; /** * A value indicating whether the stage completed. */ private final AtomicBoolean _completed; /** * Initializes a new instance of the {@link Stage} class. * * @param completable The completable. */ public Stage(final Completable<T> completable) { _completable = completable; _completed = new AtomicBoolean(false); } /** * Completes the stage with the specified state. * * @param state The state. */ public void complete(final State<T> state) { if (_completed.compareAndSet(false, true)) { state.then(_completable); } } } }
src/main/java/org/util/concurrent/DefaultDeferred.java
/* * Copyright © Martin Tamme * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.util.concurrent; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a default deferred. * * @param <T> The value type. */ final class DefaultDeferred<T> implements Deferred<T> { /** * The private logger. */ private static final Logger logger = LoggerFactory.getLogger(DefaultDeferred.class); /** * The state of the deferred. */ private final AtomicReference<State<T>> _state; /** * Initializes a new instance of the {@link DefaultDeferred} class. */ public DefaultDeferred() { final State<T> initialState = new PendingState(); _state = new AtomicReference<State<T>>(initialState); } /** * Initializes a new instance of the {@link DefaultDeferred} class. * * @param value The value. */ public DefaultDeferred(final T value) { final State<T> initialState = new SuccessState<T>(value); _state = new AtomicReference<State<T>>(initialState); } /** * Initializes a new instance of the {@link DefaultDeferred} class. * * @param cause The cause. */ public DefaultDeferred(final Throwable cause) { if (cause == null) { throw new IllegalArgumentException("Cause must not be null"); } final State<T> initialState = new FailureState<T>(cause); _state = new AtomicReference<State<T>>(initialState); } @Override public void setSuccess(final T value) { if (!trySuccess(value)) { throw new IllegalStateException("Deferred is already completed"); } } @Override public void setFailure(final Throwable cause) { if (!tryFailure(cause)) { throw new IllegalStateException("Deferred is already completed"); } } @Override public final boolean trySuccess(final T value) { return _state.get().setSuccess(value); } @Override public final boolean tryFailure(final Throwable cause) { if (cause == null) { throw new IllegalArgumentException("Cause must not be null"); } return _state.get().setFailure(cause); } @Override public final boolean isComplete() { return _state.get().isComplete(); } @Override public void then(final Completable<T> completable) { if (completable == null) { throw new IllegalArgumentException("Completable must not be null"); } _state.get().then(completable); } @Override public final <R> Promise<R> then(final Continuation<T, R> continuation) { if (continuation == null) { throw new IllegalArgumentException("Continuation must not be null"); } final Deferred<R> deferred = new DefaultDeferred<R>(); _state.get().then(new Completable<T>() { @Override public void setSuccess(final T value) { try { continuation.setSuccess(value, deferred); } catch (final Throwable t) { deferred.tryFailure(t); } } @Override public void setFailure(final Throwable cause) { try { continuation.setFailure(cause, deferred); } catch (final Throwable t) { t.addSuppressed(cause); deferred.tryFailure(t); } } }); return deferred; } /** * Defines a state. * * @param <T> The value type. */ private static interface State<T> { /** * Returns a value indicating whether the deferred is complete. * * @return a value indicating whether the deferred is complete. */ boolean isComplete(); /** * Completes the deferred with the specified value. * * @param value The value. * @return A value indicating whether the deferred has been completed. */ boolean setSuccess(T value); /** * Completes the deferred with the specified cause. * * @param cause The cause. * @return A value indicating whether the deferred has been completed. */ boolean setFailure(Throwable throwable); /** * Adds the specified completable. * * @param completable The completable. */ void then(Completable<T> completable); } /** * Represents a pending state. * * @param <V> The value type. */ private final class PendingState implements State<T> { /** * The stage queue. */ private final ConcurrentLinkedQueue<Stage<T>> _stages; /** * Initializes a new instance of the {@link PendingState} class. */ public PendingState() { _stages = new ConcurrentLinkedQueue<Stage<T>>(); } /** * Changes the state to the specified state. * * @param state The state. * @return A value indicating whether the state has been changed. */ private boolean changeState(final State<T> state) { if (!_state.compareAndSet(this, state)) { return false; } completeStages(state); return true; } /** * Adds the specified stage. * * @param stage The stage. */ private void addStage(final Stage<T> stage) { // As the queue is unbounded, this method will never return false. _stages.offer(stage); // Trigger completion when the promise has been completed in the meantime. final State<T> state = _state.get(); if (state != this) { completeStages(state); } } /** * Completes the stages with the specified state. * * @param state The state. */ private void completeStages(final State<T> state) { Stage<T> stage; while ((stage = _stages.poll()) != null) { try { stage.complete(state); } catch (final Throwable t) { logger.warn("Failed to complete stage", t); } } } @Override public boolean isComplete() { return false; } @Override public boolean setSuccess(final T value) { final State<T> state = new SuccessState<T>(value); return changeState(state); } @Override public boolean setFailure(final Throwable cause) { final State<T> state = new FailureState<T>(cause); return changeState(state); } @Override public void then(final Completable<T> completable) { final Stage<T> stage = new Stage<T>(completable); addStage(stage); } } /** * Represents a complete state. * * @param <T> The value type. */ private static abstract class CompleteState<T> implements State<T> { @Override public boolean isComplete() { return true; } @Override public final boolean setSuccess(final T value) { return false; } @Override public final boolean setFailure(final Throwable cause) { return false; } } /** * Represents a success state. * * @param <T> The value type. */ private static final class SuccessState<T> extends CompleteState<T> { /** * The value. */ private final T _value; /** * Initializes a new instance of the {@link SuccessState} class. * * @param value The value. */ public SuccessState(final T value) { _value = value; } @Override public void then(final Completable<T> completable) { completable.setSuccess(_value); } } /** * Represents a failure state. * * @param <T> The value type. */ private static final class FailureState<T> extends CompleteState<T> { /** * The cause. */ private final Throwable _cause; /** * Initializes a new instance of the {@link FailureState} class. * * @param cause The cause. */ public FailureState(final Throwable cause) { _cause = cause; } @Override public void then(final Completable<T> completable) { completable.setFailure(_cause); } } /** * Represents a stage. * * @param <T> The value type. */ private static final class Stage<T> { /** * The completable. */ private final Completable<T> _completable; /** * A value indicating whether the stage completed. */ private final AtomicBoolean _completed; /** * Initializes a new instance of the {@link Stage} class. * * @param completable The completable. */ public Stage(final Completable<T> completable) { _completable = completable; _completed = new AtomicBoolean(false); } /** * Completes the stage with the specified state. * * @param state The state. */ public void complete(final State<T> state) { if (_completed.compareAndSet(false, true)) { state.then(_completable); } } } }
Minor changes.
src/main/java/org/util/concurrent/DefaultDeferred.java
Minor changes.
<ide><path>rc/main/java/org/util/concurrent/DefaultDeferred.java <ide> @Override <ide> public void setSuccess(final T value) { <ide> if (!trySuccess(value)) { <del> throw new IllegalStateException("Deferred is already completed"); <add> throw new IllegalStateException("Deferred is already complete"); <ide> } <ide> } <ide> <ide> @Override <ide> public void setFailure(final Throwable cause) { <ide> if (!tryFailure(cause)) { <del> throw new IllegalStateException("Deferred is already completed"); <add> throw new IllegalStateException("Deferred is already complete"); <ide> } <ide> } <ide> <ide> @Override <ide> public final boolean trySuccess(final T value) { <del> return _state.get().setSuccess(value); <add> return _state.get().trySuccess(value); <ide> } <ide> <ide> @Override <ide> throw new IllegalArgumentException("Cause must not be null"); <ide> } <ide> <del> return _state.get().setFailure(cause); <add> return _state.get().tryFailure(cause); <ide> } <ide> <ide> @Override <ide> boolean isComplete(); <ide> <ide> /** <del> * Completes the deferred with the specified value. <add> * Tries to complete the deferred with the specified value. <ide> * <ide> * @param value The value. <ide> * @return A value indicating whether the deferred has been completed. <ide> */ <del> boolean setSuccess(T value); <del> <del> /** <del> * Completes the deferred with the specified cause. <add> boolean trySuccess(T value); <add> <add> /** <add> * Tries to complete the deferred with the specified cause. <ide> * <ide> * @param cause The cause. <ide> * @return A value indicating whether the deferred has been completed. <ide> */ <del> boolean setFailure(Throwable throwable); <add> boolean tryFailure(Throwable throwable); <ide> <ide> /** <ide> * Adds the specified completable. <ide> } <ide> <ide> /** <del> * Changes the state to the specified state. <add> * Tries to change the state to the specified state. <ide> * <ide> * @param state The state. <ide> * @return A value indicating whether the state has been changed. <ide> */ <del> private boolean changeState(final State<T> state) { <add> private boolean tryChangeState(final State<T> state) { <ide> if (!_state.compareAndSet(this, state)) { <ide> return false; <ide> } <ide> } <ide> <ide> @Override <del> public boolean setSuccess(final T value) { <add> public boolean trySuccess(final T value) { <ide> final State<T> state = new SuccessState<T>(value); <ide> <del> return changeState(state); <del> } <del> <del> @Override <del> public boolean setFailure(final Throwable cause) { <add> return tryChangeState(state); <add> } <add> <add> @Override <add> public boolean tryFailure(final Throwable cause) { <ide> final State<T> state = new FailureState<T>(cause); <ide> <del> return changeState(state); <add> return tryChangeState(state); <ide> } <ide> <ide> @Override <ide> } <ide> <ide> @Override <del> public final boolean setSuccess(final T value) { <add> public final boolean trySuccess(final T value) { <ide> return false; <ide> } <ide> <ide> @Override <del> public final boolean setFailure(final Throwable cause) { <add> public final boolean tryFailure(final Throwable cause) { <ide> return false; <ide> } <ide> }
Java
apache-2.0
06a4648e2432d0e17cca48dbac47a38e49fac3b6
0
apache/commons-text,apache/commons-text
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.commons.text.lookup; import java.util.Map; import org.apache.commons.text.StringSubstitutor; /** * Provides access to lookups defined in this package. * <p> * The default lookups are: * </p> * <table> * <caption>Default String Lookups</caption> * <tr> * <th>Key</th> * <th>Implementation</th> * <th>Factory Method</th> * <th>Since</th> * </tr> * <tr> * <td>{@value #KEY_BASE64_DECODER}</td> * <td>{@link Base64DecoderStringLookup}</td> * <td>{@link #base64DecoderStringLookup()}</td> * <td>1.6</td> * </tr> * <tr> * <td>{@value #KEY_BASE64_ENCODER}</td> * <td>{@link Base64EncoderStringLookup}</td> * <td>{@link #base64EncoderStringLookup()}</td> * <td>1.6</td> * </tr> * <tr> * <td>{@value #KEY_CONST}</td> * <td>{@link ConstantStringLookup}</td> * <td>{@link #constantStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_DATE}</td> * <td>{@link DateStringLookup}</td> * <td>{@link #dateStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_DNS}</td> * <td>{@link DnsStringLookup}</td> * <td>{@link #dnsStringLookup()}</td> * <td>1.8</td> * </tr> * <tr> * <td>{@value #KEY_ENV}</td> * <td>{@link EnvironmentVariableStringLookup}</td> * <td>{@link #environmentVariableStringLookup()}</td> * <td>1.3</td> * </tr> * <tr> * <td>{@value #KEY_FILE}</td> * <td>{@link FileStringLookup}</td> * <td>{@link #fileStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_JAVA}</td> * <td>{@link JavaPlatformStringLookup}</td> * <td>{@link #javaPlatformStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_LOCALHOST}</td> * <td>{@link LocalHostStringLookup}</td> * <td>{@link #localHostStringLookup()}</td> * <td>1.3</td> * </tr> * <tr> * <td>{@value #KEY_PROPERTIES}</td> * <td>{@link PropertiesStringLookup}</td> * <td>{@link #propertiesStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_RESOURCE_BUNDLE}</td> * <td>{@link ResourceBundleStringLookup}</td> * <td>{@link #resourceBundleStringLookup()}</td> * <td>1.6</td> * </tr> * <tr> * <td>{@value #KEY_SCRIPT}</td> * <td>{@link ScriptStringLookup}</td> * <td>{@link #scriptStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_SYS}</td> * <td>{@link SystemPropertyStringLookup}</td> * <td>{@link #systemPropertyStringLookup()}</td> * <td>1.3</td> * </tr> * <tr> * <td>{@value #KEY_URL}</td> * <td>{@link UrlStringLookup}</td> * <td>{@link #urlStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_URL_DECODER}</td> * <td>{@link UrlDecoderStringLookup}</td> * <td>{@link #urlDecoderStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_URL_ENCODER}</td> * <td>{@link UrlEncoderStringLookup}</td> * <td>{@link #urlEncoderStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_XML}</td> * <td>{@link XmlStringLookup}</td> * <td>{@link #xmlStringLookup()}</td> * <td>1.5</td> * </tr> * </table> * * @since 1.3 */ public final class StringLookupFactory { /** * Defines the singleton for this class. */ public static final StringLookupFactory INSTANCE = new StringLookupFactory(); /** * Default lookup key for interpolation {@value #KEY_BASE64_DECODER}. * * @since 1.6 */ public static final String KEY_BASE64_DECODER = "base64Decoder"; /** * Default lookup key for interpolation {@value #KEY_BASE64_ENCODER}. * * @since 1.6 */ public static final String KEY_BASE64_ENCODER = "base64Encoder"; /** * Default lookup key for interpolation {@value #KEY_CONST}. * * @since 1.6 */ public static final String KEY_CONST = "const"; /** * Default lookup key for interpolation {@value #KEY_DATE}. * * @since 1.6 */ public static final String KEY_DATE = "date"; /** * Default lookup key for interpolation {@value #KEY_DNS}. * * @since 1.8 */ public static final String KEY_DNS = "dns"; /** * Default lookup key for interpolation {@value #KEY_ENV}. * * @since 1.6 */ public static final String KEY_ENV = "env"; /** * Default lookup key for interpolation {@value #KEY_FILE}. * * @since 1.6 */ public static final String KEY_FILE = "file"; /** * Default lookup key for interpolation {@value #KEY_JAVA}. * * @since 1.6 */ public static final String KEY_JAVA = "java"; /** * Default lookup key for interpolation {@value #KEY_LOCALHOST}. * * @since 1.6 */ public static final String KEY_LOCALHOST = "localhost"; /** * Default lookup key for interpolation {@value #KEY_PROPERTIES}. * * @since 1.6 */ public static final String KEY_PROPERTIES = "properties"; /** * Default lookup key for interpolation {@value #KEY_RESOURCE_BUNDLE}. * * @since 1.6 */ public static final String KEY_RESOURCE_BUNDLE = "resourceBundle"; /** * Default lookup key for interpolation {@value #KEY_SCRIPT}. * * @since 1.6 */ public static final String KEY_SCRIPT = "script"; /** * Default lookup key for interpolation {@value #KEY_SYS}. * * @since 1.6 */ public static final String KEY_SYS = "sys"; /** * Default lookup key for interpolation {@value #KEY_URL}. * * @since 1.6 */ public static final String KEY_URL = "url"; /** * Default lookup key for interpolation {@value #KEY_URL_DECODER}. * * @since 1.6 */ public static final String KEY_URL_DECODER = "urlDecoder"; /** * Default lookup key for interpolation {@value #KEY_URL_ENCODER}. * * @since 1.6 */ public static final String KEY_URL_ENCODER = "urlEncoder"; /** * Default lookup key for interpolation {@value #KEY_XML}. * * @since 1.6 */ public static final String KEY_XML = "xml"; /** * Clears any static resources. * * @since 1.5 */ public static void clear() { ConstantStringLookup.clear(); } /** * No need to build instances for now. */ private StringLookupFactory() { // empty } /** * Adds the {@link StringLookupFactory default lookups}. * * @param stringLookupMap the map of string lookups. * @since 1.5 */ public void addDefaultStringLookups(final Map<String, StringLookup> stringLookupMap) { if (stringLookupMap != null) { // "base64" is deprecated in favor of KEY_BASE64_DECODER. stringLookupMap.put("base64", Base64DecoderStringLookup.INSTANCE); for (final DefaultStringLookup stringLookup : DefaultStringLookup.values()) { stringLookupMap.put(InterpolatorStringLookup.toKey(stringLookup.getKey()), stringLookup.getStringLookup()); } } } /** * Returns the Base64DecoderStringLookup singleton instance to decode Base64 strings. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.base64DecoderStringLookup().lookup("SGVsbG9Xb3JsZCE="); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${base64Decoder:SGVsbG9Xb3JsZCE=} ...")); * </pre> * <p> * The above examples convert {@code "SGVsbG9Xb3JsZCE="} to {@code "HelloWorld!"}. * </p> * * @return The DateStringLookup singleton instance. * @since 1.5 */ public StringLookup base64DecoderStringLookup() { return Base64DecoderStringLookup.INSTANCE; } /** * Returns the Base64EncoderStringLookup singleton instance to encode strings to Base64. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.base64EncoderStringLookup().lookup("HelloWorld!"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${base64Encoder:HelloWorld!} ...")); * </pre> * <p> * The above examples convert {@code } to {@code "SGVsbG9Xb3JsZCE="}. * </p> * * @return The DateStringLookup singleton instance. * @since 1.6 */ public StringLookup base64EncoderStringLookup() { return Base64EncoderStringLookup.INSTANCE; } /** * Returns the Base64DecoderStringLookup singleton instance to decode Base64 strings. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.base64DecoderStringLookup().lookup("SGVsbG9Xb3JsZCE="); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${base64Decoder:SGVsbG9Xb3JsZCE=} ...")); * </pre> * <p> * The above examples convert {@code "SGVsbG9Xb3JsZCE="} to {@code "HelloWorld!"}. * </p> * * @return The DateStringLookup singleton instance. * @since 1.5 * @deprecated Use {@link #base64DecoderStringLookup()}. */ @Deprecated public StringLookup base64StringLookup() { return Base64DecoderStringLookup.INSTANCE; } /** * Returns the ConstantStringLookup singleton instance to look up the value of a fully-qualified static final value. * <p> * Sometimes it is necessary in a configuration file to refer to a constant defined in a class. This can be done * with this lookup implementation. Variable names must be in the format {@code apackage.AClass.AFIELD}. The * {@code lookup(String)} method will split the passed in string at the last dot, separating the fully qualified * class name and the name of the constant (i.e. <b>static final</b>) member field. Then the class is loaded and the * field's value is obtained using reflection. * </p> * <p> * Once retrieved values are cached for fast access. This class is thread-safe. It can be used as a standard (i.e. * global) lookup object and serve multiple clients concurrently. * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.constantStringLookup().lookup("java.awt.event.KeyEvent.VK_ESCAPE"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${const:java.awt.event.KeyEvent.VK_ESCAPE} ...")); * </pre> * <p> * The above examples convert {@code java.awt.event.KeyEvent.VK_ESCAPE} to {@code "27"}. * </p> * * @return The DateStringLookup singleton instance. * @since 1.5 */ public StringLookup constantStringLookup() { return ConstantStringLookup.INSTANCE; } /** * Returns the DateStringLookup singleton instance to format the current date with the format given in the key in a * format compatible with {@link java.text.SimpleDateFormat}. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.dateStringLookup().lookup("yyyy-MM-dd"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${date:yyyy-MM-dd} ...")); * </pre> * <p> * The above examples convert {@code "yyyy-MM-dd"} to todays's date, for example, {@code "2019-08-04"}. * </p> * * @return The DateStringLookup singleton instance. */ public StringLookup dateStringLookup() { return DateStringLookup.INSTANCE; } /** * Returns the DnsStringLookup singleton instance where the lookup key is one of: * <ul> * <li><b>name</b>: for the local host name, for example {@code EXAMPLE} but also {@code EXAMPLE.apache.org}.</li> * <li><b>canonical-name</b>: for the local canonical host name, for example {@code EXAMPLE.apache.org}.</li> * <li><b>address</b>: for the local host address, for example {@code 192.168.56.1}.</li> * </ul> * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.dnsStringLookup().lookup("address|apache.org"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${dns:address|apache.org} ...")); * </pre> * <p> * The above examples convert {@code "address|apache.org"} to {@code "95.216.24.32} (or {@code "40.79.78.1"}). * </p> * * @return the DateStringLookup singleton instance. * @since 1.8 */ public StringLookup dnsStringLookup() { return DnsStringLookup.INSTANCE; } /** * Returns the EnvironmentVariableStringLookup singleton instance where the lookup key is an environment variable * name. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.dateStringLookup().lookup("USER"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${env:USER} ...")); * </pre> * <p> * The above examples convert (on Linux) {@code "USER"} to the current user name. On Windows 10, you would use * {@code "USERNAME"} to the same effect. * </p> * * @return The EnvironmentVariableStringLookup singleton instance. */ public StringLookup environmentVariableStringLookup() { return EnvironmentVariableStringLookup.INSTANCE; } /** * Returns the FileStringLookup singleton instance. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.fileStringLookup().lookup("UTF-8:com/domain/document.properties"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${file:UTF-8:com/domain/document.properties} ...")); * </pre> * <p> * The above examples convert {@code "UTF-8:com/domain/document.properties"} to the contents of the file. * </p> * * @return The FileStringLookup singleton instance. * @since 1.5 */ public StringLookup fileStringLookup() { return FileStringLookup.INSTANCE; } /** * Returns a new InterpolatorStringLookup using the {@link StringLookupFactory default lookups}. * <p> * The lookups available to an interpolator are defined in * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.interpolatorStringLookup().lookup("${sys:os.name}, ${env:USER}"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${sys:os.name}, ${env:USER} ...")); * </pre> * <p> * The above examples convert {@code "${sys:os.name}, ${env:USER}"} to the OS name and Linux user name. * </p> * * @return a new InterpolatorStringLookup. */ public StringLookup interpolatorStringLookup() { return InterpolatorStringLookup.INSTANCE; } /** * Returns a new InterpolatorStringLookup using the {@link StringLookupFactory default lookups}. * <p> * If {@code addDefaultLookups} is true, the following lookups are used in addition to the ones provided in * {@code stringLookupMap}: * </p> * * @param stringLookupMap the map of string lookups. * @param defaultStringLookup the default string lookup. * @param addDefaultLookups whether to use lookups as described above. * @return a new InterpolatorStringLookup. * @since 1.4 */ public StringLookup interpolatorStringLookup(final Map<String, StringLookup> stringLookupMap, final StringLookup defaultStringLookup, final boolean addDefaultLookups) { return new InterpolatorStringLookup(stringLookupMap, defaultStringLookup, addDefaultLookups); } /** * Returns a new InterpolatorStringLookup using the {@link StringLookupFactory default lookups}. * * @param <V> the value type the default string lookup's map. * @param map the default map for string lookups. * @return a new InterpolatorStringLookup. */ public <V> StringLookup interpolatorStringLookup(final Map<String, V> map) { return new InterpolatorStringLookup(map); } /** * Returns a new InterpolatorStringLookup using the {@link StringLookupFactory default lookups}. * * @param defaultStringLookup the default string lookup. * @return a new InterpolatorStringLookup. */ public StringLookup interpolatorStringLookup(final StringLookup defaultStringLookup) { return new InterpolatorStringLookup(defaultStringLookup); } /** * Returns the JavaPlatformStringLookup singleton instance. Looks up keys related to Java: Java version, JRE * version, VM version, and so on. * <p> * The lookup keys with examples are: * </p> * <ul> * <li><b>version</b>: "Java version 1.8.0_181"</li> * <li><b>runtime</b>: "Java(TM) SE Runtime Environment (build 1.8.0_181-b13) from Oracle Corporation"</li> * <li><b>vm</b>: "Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)"</li> * <li><b>os</b>: "Windows 10 10.0, architecture: amd64-64"</li> * <li><b>hardware</b>: "processors: 4, architecture: amd64-64, instruction sets: amd64"</li> * <li><b>locale</b>: "default locale: en_US, platform encoding: iso-8859-1"</li> * </ul> * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.javaPlatformStringLookup().lookup("version"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${java:version} ...")); * </pre> * <p> * The above examples convert {@code "version"} to the current VM version, for example, * {@code "Java version 1.8.0_181"}. * </p> * * @return The JavaPlatformStringLookup singleton instance. */ public StringLookup javaPlatformStringLookup() { return JavaPlatformStringLookup.INSTANCE; } /** * Returns the LocalHostStringLookup singleton instance where the lookup key is one of: * <ul> * <li><b>name</b>: for the local host name, for example {@code EXAMPLE}.</li> * <li><b>canonical-name</b>: for the local canonical host name, for example {@code EXAMPLE.apache.org}.</li> * <li><b>address</b>: for the local host address, for example {@code 192.168.56.1}.</li> * </ul> * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.localHostStringLookup().lookup("canonical-name"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${localhost:canonical-name} ...")); * </pre> * <p> * The above examples convert {@code "canonical-name"} to the current host name, for example, * {@code "EXAMPLE.apache.org"}. * </p> * * @return The DateStringLookup singleton instance. */ public StringLookup localHostStringLookup() { return LocalHostStringLookup.INSTANCE; } /** * Returns a new map-based lookup where the request for a lookup is answered with the value for that key. * * @param <V> the map value type. * @param map the map. * @return a new MapStringLookup. */ public <V> StringLookup mapStringLookup(final Map<String, V> map) { return MapStringLookup.on(map); } /** * Returns the NullStringLookup singleton instance which always returns null. * * @return The NullStringLookup singleton instance. */ public StringLookup nullStringLookup() { return NullStringLookup.INSTANCE; } /** * Returns the PropertiesStringLookup singleton instance. * <p> * Looks up the value for the key in the format "DocumentPath::MyKey". * </p> * <p> * Note the use of "::" instead of ":" to allow for "C:" drive letters in paths. * </p> * <p> * For example: "com/domain/document.properties::MyKey". * </p> * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.propertiesStringLookup().lookup("com/domain/document.properties::MyKey"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${properties:com/domain/document.properties::MyKey} ...")); * </pre> * <p> * The above examples convert {@code "com/domain/document.properties::MyKey"} to the key value in the properties * file at the path "com/domain/document.properties". * </p> * * @return The PropertiesStringLookup singleton instance. * @since 1.5 */ public StringLookup propertiesStringLookup() { return PropertiesStringLookup.INSTANCE; } /** * Returns the ResourceBundleStringLookup singleton instance. * <p> * Looks up the value for a given key in the format "BundleName:BundleKey". * </p> * <p> * For example: "com.domain.messages:MyKey". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.resourceBundleStringLookup().lookup("com.domain.messages:MyKey"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${resourceBundle:com.domain.messages:MyKey} ...")); * </pre> * <p> * The above examples convert {@code "com.domain.messages:MyKey"} to the key value in the resource bundle at * {@code "com.domain.messages"}. * </p> * * @return The ResourceBundleStringLookup singleton instance. */ public StringLookup resourceBundleStringLookup() { return ResourceBundleStringLookup.INSTANCE; } /** * Returns a ResourceBundleStringLookup instance for the given bundle name. * <p> * Looks up the value for a given key in the format "MyKey". * </p> * <p> * For example: "MyKey". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.resourceBundleStringLookup("com.domain.messages").lookup("MyKey"); * </pre> * <p> * The above example converts {@code "MyKey"} to the key value in the resource bundle at * {@code "com.domain.messages"}. * </p> * * @param bundleName Only lookup in this bundle. * @return a ResourceBundleStringLookup instance for the given bundle name. * @since 1.5 */ public StringLookup resourceBundleStringLookup(final String bundleName) { return new ResourceBundleStringLookup(bundleName); } /** * Returns the ScriptStringLookup singleton instance. * <p> * Looks up the value for the key in the format "ScriptEngineName:Script". * </p> * <p> * For example: "javascript:3 + 4". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.scriptStringLookup().lookup("javascript:3 + 4"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${javascript:3 + 4} ...")); * </pre> * <p> * The above examples convert {@code "javascript:3 + 4"} to {@code "7"}. * </p> * * @return The ScriptStringLookup singleton instance. * @since 1.5 */ public StringLookup scriptStringLookup() { return ScriptStringLookup.INSTANCE; } /** * Returns the SystemPropertyStringLookup singleton instance where the lookup key is a system property name. * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.systemPropertyStringLookup().lookup("os.name"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${sys:os.name} ...")); * </pre> * <p> * The above examples convert {@code "os.name"} to the operating system name. * </p> * * @return The SystemPropertyStringLookup singleton instance. */ public StringLookup systemPropertyStringLookup() { return SystemPropertyStringLookup.INSTANCE; } /** * Returns the UrlDecoderStringLookup singleton instance. * <p> * Decodes URL Strings using the UTF-8 encoding. * </p> * <p> * For example: "Hello%20World%21" becomes "Hello World!". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.urlDecoderStringLookup().lookup("Hello%20World%21"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${urlDecoder:Hello%20World%21} ...")); * </pre> * <p> * The above examples convert {@code "Hello%20World%21"} to {@code "Hello World!"}. * </p> * * @return The UrlStringLookup singleton instance. * @since 1.6 */ public StringLookup urlDecoderStringLookup() { return UrlDecoderStringLookup.INSTANCE; } /** * Returns the UrlDecoderStringLookup singleton instance. * <p> * Decodes URL Strings using the UTF-8 encoding. * </p> * <p> * For example: "Hello World!" becomes "Hello+World%21". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.urlEncoderStringLookup().lookup("Hello World!"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${urlEncoder:Hello World!} ...")); * </pre> * <p> * The above examples convert {@code "Hello World!"} to {@code "Hello%20World%21"}. * </p> * * @return The UrlStringLookup singleton instance. * @since 1.6 */ public StringLookup urlEncoderStringLookup() { return UrlEncoderStringLookup.INSTANCE; } /** * Returns the UrlStringLookup singleton instance. * <p> * Looks up the value for the key in the format "CharsetName:URL". * </p> * <p> * For example, using the HTTP scheme: "UTF-8:http://www.google.com" * </p> * <p> * For example, using the file scheme: * "UTF-8:file:///C:/somehome/commons/commons-text/src/test/resources/document.properties" * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.urlStringLookup().lookup("UTF-8:https://www.apache.org"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${url:UTF-8:https://www.apache.org} ...")); * </pre> * <p> * The above examples convert {@code "UTF-8:https://www.apache.org"} to the contents of that page. * </p> * * @return The UrlStringLookup singleton instance. * @since 1.5 */ public StringLookup urlStringLookup() { return UrlStringLookup.INSTANCE; } /** * Returns the XmlStringLookup singleton instance. * <p> * Looks up the value for the key in the format "DocumentPath:XPath". * </p> * <p> * For example: "com/domain/document.xml:/path/to/node". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.xmlStringLookup().lookup("com/domain/document.xml:/path/to/node"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${xml:com/domain/document.xml:/path/to/node} ...")); * </pre> * <p> * The above examples convert {@code "com/domain/document.xml:/path/to/node"} to the value of the XPath in the XML * document. * </p> * * @return The XmlStringLookup singleton instance. * @since 1.5 */ public StringLookup xmlStringLookup() { return XmlStringLookup.INSTANCE; } }
src/main/java/org/apache/commons/text/lookup/StringLookupFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.commons.text.lookup; import java.util.Map; import org.apache.commons.text.StringSubstitutor; /** * Provides access to lookups defined in this package. * <p> * The default lookups are: * </p> * <table> * <caption>Default String Lookups</caption> * <tr> * <th>Key</th> * <th>Implementation</th> * <th>Factory Method</th> * <th>Since</th> * </tr> * <tr> * <td>{@value #KEY_BASE64_DECODER}</td> * <td>{@link Base64DecoderStringLookup}</td> * <td>{@link #base64DecoderStringLookup()}</td> * <td>1.6</td> * </tr> * <tr> * <td>{@value #KEY_BASE64_ENCODER}</td> * <td>{@link Base64EncoderStringLookup}</td> * <td>{@link #base64EncoderStringLookup()}</td> * <td>1.6</td> * </tr> * <tr> * <td>{@value #KEY_CONST}</td> * <td>{@link ConstantStringLookup}</td> * <td>{@link #constantStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_DATE}</td> * <td>{@link DateStringLookup}</td> * <td>{@link #dateStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_DNS}</td> * <td>{@link DnsStringLookup}</td> * <td>{@link #dnsStringLookup()}</td> * <td>1.8</td> * </tr> * <tr> * <td>{@value #KEY_ENV}</td> * <td>{@link EnvironmentVariableStringLookup}</td> * <td>{@link #environmentVariableStringLookup()}</td> * <td>1.3</td> * </tr> * <tr> * <td>{@value #KEY_FILE}</td> * <td>{@link FileStringLookup}</td> * <td>{@link #fileStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_JAVA}</td> * <td>{@link JavaPlatformStringLookup}</td> * <td>{@link #javaPlatformStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_LOCALHOST}</td> * <td>{@link LocalHostStringLookup}</td> * <td>{@link #localHostStringLookup()}</td> * <td>1.3</td> * </tr> * <tr> * <td>{@value #KEY_PROPERTIES}</td> * <td>{@link PropertiesStringLookup}</td> * <td>{@link #propertiesStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_RESOURCE_BUNDLE}</td> * <td>{@link ResourceBundleStringLookup}</td> * <td>{@link #resourceBundleStringLookup()}</td> * <td>1.6</td> * </tr> * <tr> * <td>{@value #KEY_SCRIPT}</td> * <td>{@link ScriptStringLookup}</td> * <td>{@link #scriptStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_SYS}</td> * <td>{@link SystemPropertyStringLookup}</td> * <td>{@link #systemPropertyStringLookup()}</td> * <td>1.3</td> * </tr> * <tr> * <td>{@value #KEY_URL}</td> * <td>{@link UrlStringLookup}</td> * <td>{@link #urlStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_URL_DECODER}</td> * <td>{@link UrlDecoderStringLookup}</td> * <td>{@link #urlDecoderStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_URL_ENCODER}</td> * <td>{@link UrlEncoderStringLookup}</td> * <td>{@link #urlEncoderStringLookup()}</td> * <td>1.5</td> * </tr> * <tr> * <td>{@value #KEY_XML}</td> * <td>{@link XmlStringLookup}</td> * <td>{@link #xmlStringLookup()}</td> * <td>1.5</td> * </tr> * </table> * * @since 1.3 */ public final class StringLookupFactory { /** * Defines the singleton for this class. */ public static final StringLookupFactory INSTANCE = new StringLookupFactory(); /** * Default lookup key for interpolation {@value #KEY_BASE64_DECODER}. * * @since 1.6 */ public static final String KEY_BASE64_DECODER = "base64Decoder"; /** * Default lookup key for interpolation {@value #KEY_BASE64_ENCODER}. * * @since 1.6 */ public static final String KEY_BASE64_ENCODER = "base64Encoder"; /** * Default lookup key for interpolation {@value #KEY_CONST}. * * @since 1.6 */ public static final String KEY_CONST = "const"; /** * Default lookup key for interpolation {@value #KEY_DATE}. * * @since 1.6 */ public static final String KEY_DATE = "date"; /** * Default lookup key for interpolation {@value #KEY_DNS}. * * @since 1.8 */ public static final String KEY_DNS = "dns"; /** * Default lookup key for interpolation {@value #KEY_ENV}. * * @since 1.6 */ public static final String KEY_ENV = "env"; /** * Default lookup key for interpolation {@value #KEY_FILE}. * * @since 1.6 */ public static final String KEY_FILE = "file"; /** * Default lookup key for interpolation {@value #KEY_JAVA}. * * @since 1.6 */ public static final String KEY_JAVA = "java"; /** * Default lookup key for interpolation {@value #KEY_LOCALHOST}. * * @since 1.6 */ public static final String KEY_LOCALHOST = "localhost"; /** * Default lookup key for interpolation {@value #KEY_PROPERTIES}. * * @since 1.6 */ public static final String KEY_PROPERTIES = "properties"; /** * Default lookup key for interpolation {@value #KEY_RESOURCE_BUNDLE}. * * @since 1.6 */ public static final String KEY_RESOURCE_BUNDLE = "resourceBundle"; /** * Default lookup key for interpolation {@value #KEY_SCRIPT}. * * @since 1.6 */ public static final String KEY_SCRIPT = "script"; /** * Default lookup key for interpolation {@value #KEY_SYS}. * * @since 1.6 */ public static final String KEY_SYS = "sys"; /** * Default lookup key for interpolation {@value #KEY_URL}. * * @since 1.6 */ public static final String KEY_URL = "url"; /** * Default lookup key for interpolation {@value #KEY_URL_DECODER}. * * @since 1.6 */ public static final String KEY_URL_DECODER = "urlDecoder"; /** * Default lookup key for interpolation {@value #KEY_URL_ENCODER}. * * @since 1.6 */ public static final String KEY_URL_ENCODER = "urlEncoder"; /** * Default lookup key for interpolation {@value #KEY_XML}. * * @since 1.6 */ public static final String KEY_XML = "xml"; /** * Clears any static resources. * * @since 1.5 */ public static void clear() { ConstantStringLookup.clear(); } /** * No need to build instances for now. */ private StringLookupFactory() { // empty } /** * Adds the {@link StringLookupFactory default lookups}. * * @param stringLookupMap the map of string lookups. * @since 1.5 */ public void addDefaultStringLookups(final Map<String, StringLookup> stringLookupMap) { if (stringLookupMap != null) { // "base64" is deprecated in favor of KEY_BASE64_DECODER. stringLookupMap.put("base64", Base64DecoderStringLookup.INSTANCE); for (final DefaultStringLookup stringLookup : DefaultStringLookup.values()) { stringLookupMap.put(InterpolatorStringLookup.toKey(stringLookup.getKey()), stringLookup.getStringLookup()); } } } /** * Returns the Base64DecoderStringLookup singleton instance to decode Base64 strings. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.base64DecoderStringLookup().lookup("SGVsbG9Xb3JsZCE="); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${base64Decoder:SGVsbG9Xb3JsZCE=} ...")); * </pre> * <p> * The above examples convert {@code "SGVsbG9Xb3JsZCE="} to {@code "HelloWorld!"}. * </p> * * @return The DateStringLookup singleton instance. * @since 1.5 */ public StringLookup base64DecoderStringLookup() { return Base64DecoderStringLookup.INSTANCE; } /** * Returns the Base64EncoderStringLookup singleton instance to encode strings to Base64. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.base64EncoderStringLookup().lookup("HelloWorld!"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${base64Encoder:HelloWorld!} ...")); * </pre> * <p> * The above examples convert {@code } to {@code "SGVsbG9Xb3JsZCE="}. * </p> * * @return The DateStringLookup singleton instance. * @since 1.6 */ public StringLookup base64EncoderStringLookup() { return Base64EncoderStringLookup.INSTANCE; } /** * Returns the Base64DecoderStringLookup singleton instance to decode Base64 strings. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.base64DecoderStringLookup().lookup("SGVsbG9Xb3JsZCE="); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${base64Decoder:SGVsbG9Xb3JsZCE=} ...")); * </pre> * <p> * The above examples convert {@code "SGVsbG9Xb3JsZCE="} to {@code "HelloWorld!"}. * </p> * * @return The DateStringLookup singleton instance. * @since 1.5 * @deprecated Use {@link #base64DecoderStringLookup()}. */ @Deprecated public StringLookup base64StringLookup() { return Base64DecoderStringLookup.INSTANCE; } /** * Returns the ConstantStringLookup singleton instance to look up the value of a fully-qualified static final value. * <p> * Sometimes it is necessary in a configuration file to refer to a constant defined in a class. This can be done * with this lookup implementation. Variable names must be in the format {@code apackage.AClass.AFIELD}. The * {@code lookup(String)} method will split the passed in string at the last dot, separating the fully qualified * class name and the name of the constant (i.e. <b>static final</b>) member field. Then the class is loaded and the * field's value is obtained using reflection. * </p> * <p> * Once retrieved values are cached for fast access. This class is thread-safe. It can be used as a standard (i.e. * global) lookup object and serve multiple clients concurrently. * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.constantStringLookup().lookup("java.awt.event.KeyEvent.VK_ESCAPE"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${const:java.awt.event.KeyEvent.VK_ESCAPE} ...")); * </pre> * <p> * The above examples convert {@code java.awt.event.KeyEvent.VK_ESCAPE} to {@code "27"}. * </p> * * @return The DateStringLookup singleton instance. * @since 1.5 */ public StringLookup constantStringLookup() { return ConstantStringLookup.INSTANCE; } /** * Returns the DateStringLookup singleton instance to format the current date with the format given in the key in a * format compatible with {@link java.text.SimpleDateFormat}. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.dateStringLookup().lookup("yyyy-MM-dd"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${date:yyyy-MM-dd} ...")); * </pre> * <p> * The above examples convert {@code "yyyy-MM-dd"} to todays's date, for example, {@code "2019-08-04"}. * </p> * * @return The DateStringLookup singleton instance. */ public StringLookup dateStringLookup() { return DateStringLookup.INSTANCE; } /** * Returns the EnvironmentVariableStringLookup singleton instance where the lookup key is an environment variable * name. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.dateStringLookup().lookup("USER"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${env:USER} ...")); * </pre> * <p> * The above examples convert (on Linux) {@code "USER"} to the current user name. On Windows 10, you would use * {@code "USERNAME"} to the same effect. * </p> * * @return The EnvironmentVariableStringLookup singleton instance. */ public StringLookup environmentVariableStringLookup() { return EnvironmentVariableStringLookup.INSTANCE; } /** * Returns the FileStringLookup singleton instance. * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.fileStringLookup().lookup("UTF-8:com/domain/document.properties"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${file:UTF-8:com/domain/document.properties} ...")); * </pre> * <p> * The above examples convert {@code "UTF-8:com/domain/document.properties"} to the contents of the file. * </p> * * @return The FileStringLookup singleton instance. * @since 1.5 */ public StringLookup fileStringLookup() { return FileStringLookup.INSTANCE; } /** * Returns a new InterpolatorStringLookup using the {@link StringLookupFactory default lookups}. * <p> * The lookups available to an interpolator are defined in * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.interpolatorStringLookup().lookup("${sys:os.name}, ${env:USER}"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${sys:os.name}, ${env:USER} ...")); * </pre> * <p> * The above examples convert {@code "${sys:os.name}, ${env:USER}"} to the OS name and Linux user name. * </p> * * @return a new InterpolatorStringLookup. */ public StringLookup interpolatorStringLookup() { return InterpolatorStringLookup.INSTANCE; } /** * Returns a new InterpolatorStringLookup using the {@link StringLookupFactory default lookups}. * <p> * If {@code addDefaultLookups} is true, the following lookups are used in addition to the ones provided in * {@code stringLookupMap}: * </p> * * @param stringLookupMap the map of string lookups. * @param defaultStringLookup the default string lookup. * @param addDefaultLookups whether to use lookups as described above. * @return a new InterpolatorStringLookup. * @since 1.4 */ public StringLookup interpolatorStringLookup(final Map<String, StringLookup> stringLookupMap, final StringLookup defaultStringLookup, final boolean addDefaultLookups) { return new InterpolatorStringLookup(stringLookupMap, defaultStringLookup, addDefaultLookups); } /** * Returns a new InterpolatorStringLookup using the {@link StringLookupFactory default lookups}. * * @param <V> the value type the default string lookup's map. * @param map the default map for string lookups. * @return a new InterpolatorStringLookup. */ public <V> StringLookup interpolatorStringLookup(final Map<String, V> map) { return new InterpolatorStringLookup(map); } /** * Returns a new InterpolatorStringLookup using the {@link StringLookupFactory default lookups}. * * @param defaultStringLookup the default string lookup. * @return a new InterpolatorStringLookup. */ public StringLookup interpolatorStringLookup(final StringLookup defaultStringLookup) { return new InterpolatorStringLookup(defaultStringLookup); } /** * Returns the JavaPlatformStringLookup singleton instance. Looks up keys related to Java: Java version, JRE * version, VM version, and so on. * <p> * The lookup keys with examples are: * </p> * <ul> * <li><b>version</b>: "Java version 1.8.0_181"</li> * <li><b>runtime</b>: "Java(TM) SE Runtime Environment (build 1.8.0_181-b13) from Oracle Corporation"</li> * <li><b>vm</b>: "Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)"</li> * <li><b>os</b>: "Windows 10 10.0, architecture: amd64-64"</li> * <li><b>hardware</b>: "processors: 4, architecture: amd64-64, instruction sets: amd64"</li> * <li><b>locale</b>: "default locale: en_US, platform encoding: iso-8859-1"</li> * </ul> * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.javaPlatformStringLookup().lookup("version"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${java:version} ...")); * </pre> * <p> * The above examples convert {@code "version"} to the current VM version, for example, * {@code "Java version 1.8.0_181"}. * </p> * * @return The JavaPlatformStringLookup singleton instance. */ public StringLookup javaPlatformStringLookup() { return JavaPlatformStringLookup.INSTANCE; } /** * Returns the LocalHostStringLookup singleton instance where the lookup key is one of: * <ul> * <li><b>name</b>: for the local host name, for example {@code EXAMPLE}.</li> * <li><b>canonical-name</b>: for the local canonical host name, for example {@code EXAMPLE.apache.org}.</li> * <li><b>address</b>: for the local host address, for example {@code 192.168.56.1}.</li> * </ul> * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.localHostStringLookup().lookup("canonical-name"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${localhost:canonical-name} ...")); * </pre> * <p> * The above examples convert {@code "canonical-name"} to the current host name, for example, * {@code "EXAMPLE.apache.org"}. * </p> * * @return The DateStringLookup singleton instance. */ public StringLookup localHostStringLookup() { return LocalHostStringLookup.INSTANCE; } /** * Returns the DnsStringLookup singleton instance where the lookup key is one of: * <ul> * <li><b>name</b>: for the local host name, for example {@code EXAMPLE} but also {@code EXAMPLE.apache.org}.</li> * <li><b>canonical-name</b>: for the local canonical host name, for example {@code EXAMPLE.apache.org}.</li> * <li><b>address</b>: for the local host address, for example {@code 192.168.56.1}.</li> * </ul> * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.dnsStringLookup().lookup("address|apache.org"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${dns:address|apache.org} ...")); * </pre> * <p> * The above examples convert {@code "address|apache.org"} to {@code "95.216.24.32} (or {@code "40.79.78.1"}). * </p> * * @return the DateStringLookup singleton instance. * @since 1.8 */ public StringLookup dnsStringLookup() { return DnsStringLookup.INSTANCE; } /** * Returns a new map-based lookup where the request for a lookup is answered with the value for that key. * * @param <V> the map value type. * @param map the map. * @return a new MapStringLookup. */ public <V> StringLookup mapStringLookup(final Map<String, V> map) { return MapStringLookup.on(map); } /** * Returns the NullStringLookup singleton instance which always returns null. * * @return The NullStringLookup singleton instance. */ public StringLookup nullStringLookup() { return NullStringLookup.INSTANCE; } /** * Returns the PropertiesStringLookup singleton instance. * <p> * Looks up the value for the key in the format "DocumentPath::MyKey". * </p> * <p> * Note the use of "::" instead of ":" to allow for "C:" drive letters in paths. * </p> * <p> * For example: "com/domain/document.properties::MyKey". * </p> * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.propertiesStringLookup().lookup("com/domain/document.properties::MyKey"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${properties:com/domain/document.properties::MyKey} ...")); * </pre> * <p> * The above examples convert {@code "com/domain/document.properties::MyKey"} to the key value in the properties * file at the path "com/domain/document.properties". * </p> * * @return The PropertiesStringLookup singleton instance. * @since 1.5 */ public StringLookup propertiesStringLookup() { return PropertiesStringLookup.INSTANCE; } /** * Returns the ResourceBundleStringLookup singleton instance. * <p> * Looks up the value for a given key in the format "BundleName:BundleKey". * </p> * <p> * For example: "com.domain.messages:MyKey". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.resourceBundleStringLookup().lookup("com.domain.messages:MyKey"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${resourceBundle:com.domain.messages:MyKey} ...")); * </pre> * <p> * The above examples convert {@code "com.domain.messages:MyKey"} to the key value in the resource bundle at * {@code "com.domain.messages"}. * </p> * * @return The ResourceBundleStringLookup singleton instance. */ public StringLookup resourceBundleStringLookup() { return ResourceBundleStringLookup.INSTANCE; } /** * Returns a ResourceBundleStringLookup instance for the given bundle name. * <p> * Looks up the value for a given key in the format "MyKey". * </p> * <p> * For example: "MyKey". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.resourceBundleStringLookup("com.domain.messages").lookup("MyKey"); * </pre> * <p> * The above example converts {@code "MyKey"} to the key value in the resource bundle at * {@code "com.domain.messages"}. * </p> * * @param bundleName Only lookup in this bundle. * @return a ResourceBundleStringLookup instance for the given bundle name. * @since 1.5 */ public StringLookup resourceBundleStringLookup(final String bundleName) { return new ResourceBundleStringLookup(bundleName); } /** * Returns the ScriptStringLookup singleton instance. * <p> * Looks up the value for the key in the format "ScriptEngineName:Script". * </p> * <p> * For example: "javascript:3 + 4". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.scriptStringLookup().lookup("javascript:3 + 4"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${javascript:3 + 4} ...")); * </pre> * <p> * The above examples convert {@code "javascript:3 + 4"} to {@code "7"}. * </p> * * @return The ScriptStringLookup singleton instance. * @since 1.5 */ public StringLookup scriptStringLookup() { return ScriptStringLookup.INSTANCE; } /** * Returns the SystemPropertyStringLookup singleton instance where the lookup key is a system property name. * * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.systemPropertyStringLookup().lookup("os.name"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${sys:os.name} ...")); * </pre> * <p> * The above examples convert {@code "os.name"} to the operating system name. * </p> * * @return The SystemPropertyStringLookup singleton instance. */ public StringLookup systemPropertyStringLookup() { return SystemPropertyStringLookup.INSTANCE; } /** * Returns the UrlDecoderStringLookup singleton instance. * <p> * Decodes URL Strings using the UTF-8 encoding. * </p> * <p> * For example: "Hello%20World%21" becomes "Hello World!". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.urlDecoderStringLookup().lookup("Hello%20World%21"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${urlDecoder:Hello%20World%21} ...")); * </pre> * <p> * The above examples convert {@code "Hello%20World%21"} to {@code "Hello World!"}. * </p> * * @return The UrlStringLookup singleton instance. * @since 1.6 */ public StringLookup urlDecoderStringLookup() { return UrlDecoderStringLookup.INSTANCE; } /** * Returns the UrlDecoderStringLookup singleton instance. * <p> * Decodes URL Strings using the UTF-8 encoding. * </p> * <p> * For example: "Hello World!" becomes "Hello+World%21". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.urlEncoderStringLookup().lookup("Hello World!"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${urlEncoder:Hello World!} ...")); * </pre> * <p> * The above examples convert {@code "Hello World!"} to {@code "Hello%20World%21"}. * </p> * * @return The UrlStringLookup singleton instance. * @since 1.6 */ public StringLookup urlEncoderStringLookup() { return UrlEncoderStringLookup.INSTANCE; } /** * Returns the UrlStringLookup singleton instance. * <p> * Looks up the value for the key in the format "CharsetName:URL". * </p> * <p> * For example, using the HTTP scheme: "UTF-8:http://www.google.com" * </p> * <p> * For example, using the file scheme: * "UTF-8:file:///C:/somehome/commons/commons-text/src/test/resources/document.properties" * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.urlStringLookup().lookup("UTF-8:https://www.apache.org"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${url:UTF-8:https://www.apache.org} ...")); * </pre> * <p> * The above examples convert {@code "UTF-8:https://www.apache.org"} to the contents of that page. * </p> * * @return The UrlStringLookup singleton instance. * @since 1.5 */ public StringLookup urlStringLookup() { return UrlStringLookup.INSTANCE; } /** * Returns the XmlStringLookup singleton instance. * <p> * Looks up the value for the key in the format "DocumentPath:XPath". * </p> * <p> * For example: "com/domain/document.xml:/path/to/node". * </p> * <p> * Using a {@link StringLookup} from the {@link StringLookupFactory}: * </p> * * <pre> * StringLookupFactory.INSTANCE.xmlStringLookup().lookup("com/domain/document.xml:/path/to/node"); * </pre> * <p> * Using a {@link StringSubstitutor}: * </p> * * <pre> * StringSubstitutor.createInterpolator().replace("... ${xml:com/domain/document.xml:/path/to/node} ...")); * </pre> * <p> * The above examples convert {@code "com/domain/document.xml:/path/to/node"} to the value of the XPath in the XML * document. * </p> * * @return The XmlStringLookup singleton instance. * @since 1.5 */ public StringLookup xmlStringLookup() { return XmlStringLookup.INSTANCE; } }
Sort members.
src/main/java/org/apache/commons/text/lookup/StringLookupFactory.java
Sort members.
<ide><path>rc/main/java/org/apache/commons/text/lookup/StringLookupFactory.java <ide> } <ide> <ide> /** <add> * Returns the DnsStringLookup singleton instance where the lookup key is one of: <add> * <ul> <add> * <li><b>name</b>: for the local host name, for example {@code EXAMPLE} but also {@code EXAMPLE.apache.org}.</li> <add> * <li><b>canonical-name</b>: for the local canonical host name, for example {@code EXAMPLE.apache.org}.</li> <add> * <li><b>address</b>: for the local host address, for example {@code 192.168.56.1}.</li> <add> * </ul> <add> * <add> * <p> <add> * Using a {@link StringLookup} from the {@link StringLookupFactory}: <add> * </p> <add> * <add> * <pre> <add> * StringLookupFactory.INSTANCE.dnsStringLookup().lookup("address|apache.org"); <add> * </pre> <add> * <p> <add> * Using a {@link StringSubstitutor}: <add> * </p> <add> * <add> * <pre> <add> * StringSubstitutor.createInterpolator().replace("... ${dns:address|apache.org} ...")); <add> * </pre> <add> * <p> <add> * The above examples convert {@code "address|apache.org"} to {@code "95.216.24.32} (or {@code "40.79.78.1"}). <add> * </p> <add> * <add> * @return the DateStringLookup singleton instance. <add> * @since 1.8 <add> */ <add> public StringLookup dnsStringLookup() { <add> return DnsStringLookup.INSTANCE; <add> } <add> <add> /** <ide> * Returns the EnvironmentVariableStringLookup singleton instance where the lookup key is an environment variable <ide> * name. <ide> * <p> <ide> } <ide> <ide> /** <del> * Returns the DnsStringLookup singleton instance where the lookup key is one of: <del> * <ul> <del> * <li><b>name</b>: for the local host name, for example {@code EXAMPLE} but also {@code EXAMPLE.apache.org}.</li> <del> * <li><b>canonical-name</b>: for the local canonical host name, for example {@code EXAMPLE.apache.org}.</li> <del> * <li><b>address</b>: for the local host address, for example {@code 192.168.56.1}.</li> <del> * </ul> <del> * <del> * <p> <del> * Using a {@link StringLookup} from the {@link StringLookupFactory}: <del> * </p> <del> * <del> * <pre> <del> * StringLookupFactory.INSTANCE.dnsStringLookup().lookup("address|apache.org"); <del> * </pre> <del> * <p> <del> * Using a {@link StringSubstitutor}: <del> * </p> <del> * <del> * <pre> <del> * StringSubstitutor.createInterpolator().replace("... ${dns:address|apache.org} ...")); <del> * </pre> <del> * <p> <del> * The above examples convert {@code "address|apache.org"} to {@code "95.216.24.32} (or {@code "40.79.78.1"}). <del> * </p> <del> * <del> * @return the DateStringLookup singleton instance. <del> * @since 1.8 <del> */ <del> public StringLookup dnsStringLookup() { <del> return DnsStringLookup.INSTANCE; <del> } <del> <del> /** <ide> * Returns a new map-based lookup where the request for a lookup is answered with the value for that key. <ide> * <ide> * @param <V> the map value type.
Java
mit
fdfe4eb8b498ea2fd44976847a83df53a9bba757
0
trujunzhang/IEATTA-ANDROID,trujunzhang/IEATTA-ANDROID
package org.ieatta.tasks; import org.ieatta.activity.Page; import org.ieatta.activity.PageProperties; import org.ieatta.activity.PageTitle; import org.ieatta.database.models.DBEvent; import org.ieatta.database.models.DBPhoto; import org.ieatta.database.models.DBRestaurant; import org.ieatta.database.models.DBReview; import org.ieatta.database.provide.ReviewType; import org.ieatta.database.query.LocalDatabaseQuery; import org.ieatta.database.realm.DBBuilder; import org.ieatta.database.realm.RealmModelReader; import org.ieatta.parse.DBConstant; import org.ieatta.server.cache.ThumbnailImageUtil; import java.io.File; import java.util.List; import java.util.Properties; import bolts.Continuation; import bolts.Task; import io.realm.RealmResults; public class RestaurantDetailTask { public DBRestaurant restaurant; public RealmResults<DBEvent> events; public RealmResults<DBReview> reviews; public List<File> galleryCollection; /** * Execute Task for Restaurant detail. * * @param restaurantUUID restaurant's UUID * @return */ public Task<Void> executeTask(final String restaurantUUID) { return new RealmModelReader<DBRestaurant>(DBRestaurant.class).getFirstObject(LocalDatabaseQuery.get(restaurantUUID), false).onSuccessTask(new Continuation<DBRestaurant, Task<List<File>>>() { @Override public Task<List<File>> then(Task<DBRestaurant> task) throws Exception { RestaurantDetailTask.this.restaurant = task.getResult(); return ThumbnailImageUtil.sharedInstance.getImagesList(restaurantUUID); } }).onSuccessTask(new Continuation<List<File>, Task<RealmResults<DBEvent>>>() { @Override public Task<RealmResults<DBEvent>> then(Task<List<File>> task) throws Exception { RestaurantDetailTask.this.galleryCollection = task.getResult(); return new RealmModelReader<DBEvent>(DBEvent.class).fetchResults( new DBBuilder() .whereEqualTo(DBConstant.kPAPFieldLocalRestaurantKey, restaurantUUID), false); } }).onSuccessTask(new Continuation<RealmResults<DBEvent>, Task<RealmResults<DBReview>>>() { @Override public Task<RealmResults<DBReview>> then(Task<RealmResults<DBEvent>> task) throws Exception { RestaurantDetailTask.this.events = task.getResult(); return new RealmModelReader<DBReview>(DBReview.class).fetchResults( new DBBuilder() .whereEqualTo(DBConstant.kPAPFieldReviewRefKey, restaurantUUID) .whereEqualTo(DBConstant.kPAPFieldReviewTypeKey, ReviewType.Review_Restaurant.getType()), false); } }).onSuccess(new Continuation<RealmResults<DBReview>, Void>() { @Override public Void then(Task<RealmResults<DBReview>> task) throws Exception { RestaurantDetailTask.this.reviews = task.getResult(); return null; } }); } public Page getPage(){ PageTitle title = new PageTitle(restaurant.getDisplayName(),""); // String imagePath = PageProperties properties = new PageProperties(); Page page = new Page(title, properties); return page; } }
app/src/main/java/org/ieatta/tasks/RestaurantDetailTask.java
package org.ieatta.tasks; import org.ieatta.activity.Page; import org.ieatta.activity.PageProperties; import org.ieatta.activity.PageTitle; import org.ieatta.database.models.DBEvent; import org.ieatta.database.models.DBPhoto; import org.ieatta.database.models.DBRestaurant; import org.ieatta.database.models.DBReview; import org.ieatta.database.provide.ReviewType; import org.ieatta.database.query.LocalDatabaseQuery; import org.ieatta.database.realm.DBBuilder; import org.ieatta.database.realm.RealmModelReader; import org.ieatta.parse.DBConstant; import java.util.Properties; import bolts.Continuation; import bolts.Task; import io.realm.RealmResults; public class RestaurantDetailTask { public DBRestaurant restaurant; public RealmResults<DBEvent> events; public RealmResults<DBReview> reviews; public RealmResults<DBPhoto> galleryCollection; /** * Execute Task for Restaurant detail. * * @param restaurantUUID restaurant's UUID * @return */ public Task<Void> executeTask(final String restaurantUUID) { return new RealmModelReader<DBRestaurant>(DBRestaurant.class).getFirstObject(LocalDatabaseQuery.get(restaurantUUID), false).onSuccessTask(new Continuation<DBRestaurant, Task<RealmResults<DBPhoto>>>() { @Override public Task<RealmResults<DBPhoto>> then(Task<DBRestaurant> task) throws Exception { RestaurantDetailTask.this.restaurant = task.getResult(); return LocalDatabaseQuery.queryPhotosForRestaurant(restaurantUUID); } }).onSuccessTask(new Continuation<RealmResults<DBPhoto>, Task<RealmResults<DBEvent>>>() { @Override public Task<RealmResults<DBEvent>> then(Task<RealmResults<DBPhoto>> task) throws Exception { RestaurantDetailTask.this.galleryCollection = task.getResult(); return new RealmModelReader<DBEvent>(DBEvent.class).fetchResults( new DBBuilder() .whereEqualTo(DBConstant.kPAPFieldLocalRestaurantKey, restaurantUUID), false); } }).onSuccessTask(new Continuation<RealmResults<DBEvent>, Task<RealmResults<DBReview>>>() { @Override public Task<RealmResults<DBReview>> then(Task<RealmResults<DBEvent>> task) throws Exception { RestaurantDetailTask.this.events = task.getResult(); return new RealmModelReader<DBReview>(DBReview.class).fetchResults( new DBBuilder() .whereEqualTo(DBConstant.kPAPFieldReviewRefKey, restaurantUUID) .whereEqualTo(DBConstant.kPAPFieldReviewTypeKey, ReviewType.Review_Restaurant.getType()), false); } }).onSuccess(new Continuation<RealmResults<DBReview>, Void>() { @Override public Void then(Task<RealmResults<DBReview>> task) throws Exception { RestaurantDetailTask.this.reviews = task.getResult(); return null; } }); } public Page getPage(){ PageTitle title = new PageTitle(restaurant.getDisplayName(),""); // String imagePath = PageProperties properties = new PageProperties(); Page page = new Page(title, properties); return page; } }
IEATTA
app/src/main/java/org/ieatta/tasks/RestaurantDetailTask.java
IEATTA
<ide><path>pp/src/main/java/org/ieatta/tasks/RestaurantDetailTask.java <ide> import org.ieatta.database.realm.DBBuilder; <ide> import org.ieatta.database.realm.RealmModelReader; <ide> import org.ieatta.parse.DBConstant; <add>import org.ieatta.server.cache.ThumbnailImageUtil; <ide> <add>import java.io.File; <add>import java.util.List; <ide> import java.util.Properties; <ide> <ide> import bolts.Continuation; <ide> public DBRestaurant restaurant; <ide> public RealmResults<DBEvent> events; <ide> public RealmResults<DBReview> reviews; <del> public RealmResults<DBPhoto> galleryCollection; <add> public List<File> galleryCollection; <ide> <ide> /** <ide> * Execute Task for Restaurant detail. <ide> * @return <ide> */ <ide> public Task<Void> executeTask(final String restaurantUUID) { <del> return new RealmModelReader<DBRestaurant>(DBRestaurant.class).getFirstObject(LocalDatabaseQuery.get(restaurantUUID), false).onSuccessTask(new Continuation<DBRestaurant, Task<RealmResults<DBPhoto>>>() { <add> return new RealmModelReader<DBRestaurant>(DBRestaurant.class).getFirstObject(LocalDatabaseQuery.get(restaurantUUID), false).onSuccessTask(new Continuation<DBRestaurant, Task<List<File>>>() { <ide> @Override <del> public Task<RealmResults<DBPhoto>> then(Task<DBRestaurant> task) throws Exception { <add> public Task<List<File>> then(Task<DBRestaurant> task) throws Exception { <ide> RestaurantDetailTask.this.restaurant = task.getResult(); <del> return LocalDatabaseQuery.queryPhotosForRestaurant(restaurantUUID); <add> return ThumbnailImageUtil.sharedInstance.getImagesList(restaurantUUID); <ide> } <del> }).onSuccessTask(new Continuation<RealmResults<DBPhoto>, Task<RealmResults<DBEvent>>>() { <add> }).onSuccessTask(new Continuation<List<File>, Task<RealmResults<DBEvent>>>() { <ide> @Override <del> public Task<RealmResults<DBEvent>> then(Task<RealmResults<DBPhoto>> task) throws Exception { <add> public Task<RealmResults<DBEvent>> then(Task<List<File>> task) throws Exception { <ide> RestaurantDetailTask.this.galleryCollection = task.getResult(); <ide> return new RealmModelReader<DBEvent>(DBEvent.class).fetchResults( <ide> new DBBuilder()
Java
bsd-3-clause
6fd7bc949cefec9d7e5084ee0419f57219ef9b90
0
CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers
package gov.nih.nci.cabig.caaers.web.study; import gov.nih.nci.cabig.caaers.domain.Agent; import gov.nih.nci.cabig.caaers.domain.INDType; import gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyAgent; import gov.nih.nci.cabig.caaers.domain.StudyAgentINDAssociation; import gov.nih.nci.cabig.caaers.web.fields.DefaultInputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputField; import gov.nih.nci.cabig.caaers.web.fields.InputFieldAttributes; import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.BeanWrapper; import org.springframework.validation.Errors; /** * @author Rhett Sutphin */ public class AgentsTab extends StudyTab { @Deprecated public static int IND_TYPE_NOT_USED = 0; @Deprecated public static int IND_TYPE_CTEP = 1; @Deprecated public static int IND_TYPE_OTHER = 2; @Deprecated public static int IND_TYPE_NA_COMMERCIAL_AGENT = 3; @Deprecated public static int IND_TYPE_EXEMPT = 4; @Deprecated public static int IND_TYPE_DCP_IND = 5; @Deprecated public static int CTEP_IND = -111; private LinkedHashMap<Object, Object> indTypeMap = new LinkedHashMap<Object, Object>(); public AgentsTab() { super("Agents", "Agents", "study/study_agents"); // setAutoPopulateHelpKey(true); for (INDType indType : INDType.values()) { indTypeMap.put(indType.name(), indType.getDisplayName()); } } @Override public void postProcess(final HttpServletRequest request, final StudyCommand command, final Errors errors) { handleStudyAgentAction(command, request.getParameter("_action"), request.getParameter("_selected"), request.getParameter("_selectedInd")); } @Override protected void validate(final StudyCommand command, final BeanWrapper commandBean, final Map<String, InputFieldGroup> fieldGroups, final Errors errors) { boolean isAgentEmpty = false; StudyAgent studyAgent = null; List<StudyAgent> studyAgents = command.getStudy().getStudyAgents(); for (int i = 0; i < command.getStudy().getStudyAgents().size(); i++) { studyAgent = studyAgents.get(i); if(!studyAgent.isRetired()){ if (studyAgent.getAgent() == null && studyAgent.getOtherAgent() == null) { isAgentEmpty = true; errors.rejectValue("study.studyAgents[" + i + "].otherAgent", "STU_007","Select either Agent or Other "); continue; } if (studyAgent.getAgent() != null) { studyAgent.setOtherAgent(null); } } } if (isAgentEmpty) { errors.rejectValue("study.studyAgents", "STU_008", "One or more Agents are missing or not in list"); } } @Override public Map<String, InputFieldGroup> createFieldGroups(final StudyCommand command) { InputFieldGroupMap map = new InputFieldGroupMap(); String baseName = "study.studyAgents"; int i = -1; for (StudyAgent sa : command.getStudy().getStudyAgents()) { i++; InputFieldGroup fieldGrp = new DefaultInputFieldGroup("main" + i); InputFieldGroup indFieldGroup = new DefaultInputFieldGroup("ind" + i); List<InputField> fields = fieldGrp.getFields(); InputField agentField = InputFieldFactory.createAutocompleterField(baseName + "[" + i + "].agent", "Agent", false); InputFieldAttributes.setSize(agentField, 70); agentField.getAttributes().put(InputField.ENABLE_CLEAR, false); fields.add(agentField); InputField otherAgentField = InputFieldFactory.createTextField(baseName + "[" + i + "].otherAgent", "Other", false); InputFieldAttributes.setSize(otherAgentField, 70); fields.add(otherAgentField); InputField indTypeField = InputFieldFactory.createSelectField(baseName + "[" + i + "].indType", "Enter IND information", indTypeMap); fields.add(indTypeField); if (sa.getStudyAgentINDAssociations() != null) { int j = -1; for (StudyAgentINDAssociation saInd : sa.getStudyAgentINDAssociations()) { // dont show IND field for CTEP unspecified IND InvestigationalNewDrug ind = saInd.getInvestigationalNewDrug(); if (ind != null && ind.getIndNumber() != null && ind.getIndNumber() == CTEP_IND) { continue; } j++; InputField indField = InputFieldFactory.createAutocompleterField(baseName + "[" + i + "].studyAgentINDAssociations[" + j + "].investigationalNewDrug", "IND #", false); indField.getAttributes().put(InputField.ENABLE_CLEAR, true); InputFieldAttributes.setSize(indField, 41); indFieldGroup.getFields().add(indField); } }// ~if InputField partOfLeadIND = InputFieldFactory.createBooleanSelectField(baseName + "[" + i + "].partOfLeadIND", "Lead IND ?"); fields.add(partOfLeadIND); map.addInputFieldGroup(fieldGrp); map.addInputFieldGroup(indFieldGroup); } return map; } private void handleStudyAgentAction(final StudyCommand command, final String action, final String selected, final String selectedInd) { Study study = command.getStudy(); if ("addStudyAgent".equals(action)) { StudyAgent studyAgent = new StudyAgent(); studyAgent.setAgent(new Agent()); study.addStudyAgent(studyAgent); } else if ("removeInd".equals(action)) { StudyAgent sa = study.getStudyAgents().get(Integer.parseInt(selected)); List<StudyAgentINDAssociation> sas = sa.getStudyAgentINDAssociations(); if (sas.size() > 0) { sas.remove(Integer.parseInt(selectedInd)); } } } }
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/study/AgentsTab.java
package gov.nih.nci.cabig.caaers.web.study; import gov.nih.nci.cabig.caaers.domain.Agent; import gov.nih.nci.cabig.caaers.domain.INDType; import gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyAgent; import gov.nih.nci.cabig.caaers.domain.StudyAgentINDAssociation; import gov.nih.nci.cabig.caaers.web.fields.DefaultInputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputField; import gov.nih.nci.cabig.caaers.web.fields.InputFieldAttributes; import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.BeanWrapper; import org.springframework.validation.Errors; /** * @author Rhett Sutphin */ public class AgentsTab extends StudyTab { @Deprecated public static int IND_TYPE_NOT_USED = 0; @Deprecated public static int IND_TYPE_CTEP = 1; @Deprecated public static int IND_TYPE_OTHER = 2; @Deprecated public static int IND_TYPE_NA_COMMERCIAL_AGENT = 3; @Deprecated public static int IND_TYPE_EXEMPT = 4; @Deprecated public static int IND_TYPE_DCP_IND = 5; @Deprecated public static int CTEP_IND = -111; private LinkedHashMap<Object, Object> indTypeMap = new LinkedHashMap<Object, Object>(); public AgentsTab() { super("Agents", "Agents", "study/study_agents"); // setAutoPopulateHelpKey(true); for (INDType indType : INDType.values()) { indTypeMap.put(indType.name(), indType.getDisplayName()); } } @Override public void postProcess(final HttpServletRequest request, final StudyCommand command, final Errors errors) { handleStudyAgentAction(command, request.getParameter("_action"), request.getParameter("_selected"), request.getParameter("_selectedInd")); } @Override protected void validate(final StudyCommand command, final BeanWrapper commandBean, final Map<String, InputFieldGroup> fieldGroups, final Errors errors) { boolean isAgentEmpty = false; StudyAgent studyAgent = null; List<StudyAgent> studyAgents = command.getStudy().getStudyAgents(); for (int i = 0; i < command.getStudy().getStudyAgents().size(); i++) { studyAgent = studyAgents.get(i); if(!studyAgent.isRetired()){ if (studyAgent.getAgent() == null && studyAgent.getOtherAgent() == null) { isAgentEmpty = true; errors.rejectValue("study.studyAgents[" + i + "].otherAgent", "STU_007","Select either Agent or Other "); continue; } if (studyAgent.getAgent() != null) { studyAgent.setOtherAgent(null); } } } if (isAgentEmpty) { errors.rejectValue("study.studyAgents", "STU_008", "One or more Agents are missing or not in list"); } } @Override public Map<String, InputFieldGroup> createFieldGroups(final StudyCommand command) { InputFieldGroupMap map = new InputFieldGroupMap(); String baseName = "study.studyAgents"; int i = -1; for (StudyAgent sa : command.getStudy().getStudyAgents()) { i++; InputFieldGroup fieldGrp = new DefaultInputFieldGroup("main" + i); InputFieldGroup indFieldGroup = new DefaultInputFieldGroup("ind" + i); List<InputField> fields = fieldGrp.getFields(); InputField agentField = InputFieldFactory.createAutocompleterField(baseName + "[" + i + "].agent", "Agent", false); InputFieldAttributes.setSize(agentField, 70); agentField.getAttributes().put(InputField.ENABLE_CLEAR, false); fields.add(agentField); InputField otherAgentField = InputFieldFactory.createTextField(baseName + "[" + i + "].otherAgent", "Other", false); InputFieldAttributes.setSize(otherAgentField, 70); fields.add(otherAgentField); InputField indTypeField = InputFieldFactory.createSelectField(baseName + "[" + i + "].indType", "Enter IND information", indTypeMap); fields.add(indTypeField); if (sa.getStudyAgentINDAssociations() != null) { int j = -1; for (StudyAgentINDAssociation saInd : sa.getStudyAgentINDAssociations()) { // dont show IND field for CTEP unspecified IND InvestigationalNewDrug ind = saInd.getInvestigationalNewDrug(); if (ind != null && ind.getIndNumber() != null && ind.getIndNumber() == CTEP_IND) { continue; } j++; InputField indField = InputFieldFactory.createAutocompleterField(baseName + "[" + i + "].studyAgentINDAssociations[" + j + "].investigationalNewDrug", "IND #", true); indField.getAttributes().put(InputField.ENABLE_CLEAR, true); InputFieldAttributes.setSize(indField, 41); indFieldGroup.getFields().add(indField); } }// ~if InputField partOfLeadIND = InputFieldFactory.createBooleanSelectField(baseName + "[" + i + "].partOfLeadIND", "Lead IND ?"); fields.add(partOfLeadIND); map.addInputFieldGroup(fieldGrp); map.addInputFieldGroup(indFieldGroup); } return map; } private void handleStudyAgentAction(final StudyCommand command, final String action, final String selected, final String selectedInd) { Study study = command.getStudy(); if ("addStudyAgent".equals(action)) { StudyAgent studyAgent = new StudyAgent(); studyAgent.setAgent(new Agent()); study.addStudyAgent(studyAgent); } else if ("removeInd".equals(action)) { StudyAgent sa = study.getStudyAgents().get(Integer.parseInt(selected)); List<StudyAgentINDAssociation> sas = sa.getStudyAgentINDAssociations(); if (sas.size() > 0) { sas.remove(Integer.parseInt(selectedInd)); } } } }
CAAERS-2739 SVN-Revision: 10531
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/study/AgentsTab.java
CAAERS-2739
<ide><path>aAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/study/AgentsTab.java <ide> } <ide> j++; <ide> <del> InputField indField = InputFieldFactory.createAutocompleterField(baseName + "[" + i + "].studyAgentINDAssociations[" + j + "].investigationalNewDrug", "IND #", true); <add> InputField indField = InputFieldFactory.createAutocompleterField(baseName + "[" + i + "].studyAgentINDAssociations[" + j + "].investigationalNewDrug", "IND #", false); <ide> indField.getAttributes().put(InputField.ENABLE_CLEAR, true); <ide> InputFieldAttributes.setSize(indField, 41); <ide> indFieldGroup.getFields().add(indField);
Java
apache-2.0
056400026f0560e8ccd93ebbc60450e5734dacca
0
FHannes/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ahb0327/intellij-community,caot/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,signed/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,da1z/intellij-community,adedayo/intellij-community,ryano144/intellij-community,apixandru/intellij-community,allotria/intellij-community,vladmm/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,signed/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,kool79/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,da1z/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,supersven/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,dslomov/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,caot/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,kool79/intellij-community,apixandru/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,izonder/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,amith01994/intellij-community,adedayo/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,holmes/intellij-community,holmes/intellij-community,jagguli/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,fnouama/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,slisson/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,robovm/robovm-studio,ibinti/intellij-community,da1z/intellij-community,fitermay/intellij-community,allotria/intellij-community,signed/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,FHannes/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,slisson/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ibinti/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,caot/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,consulo/consulo,youdonghai/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,da1z/intellij-community,joewalnes/idea-community,supersven/intellij-community,slisson/intellij-community,amith01994/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,signed/intellij-community,kdwink/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,signed/intellij-community,joewalnes/idea-community,jagguli/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,orekyuu/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,retomerz/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,da1z/intellij-community,robovm/robovm-studio,samthor/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,semonte/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,caot/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,signed/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,ernestp/consulo,kdwink/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,ernestp/consulo,amith01994/intellij-community,signed/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,signed/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,kdwink/intellij-community,caot/intellij-community,izonder/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,ernestp/consulo,izonder/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,caot/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,allotria/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,adedayo/intellij-community,slisson/intellij-community,izonder/intellij-community,youdonghai/intellij-community,semonte/intellij-community,consulo/consulo,Distrotech/intellij-community,dslomov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,caot/intellij-community,Distrotech/intellij-community,semonte/intellij-community,amith01994/intellij-community,da1z/intellij-community,retomerz/intellij-community,signed/intellij-community,suncycheng/intellij-community,semonte/intellij-community,diorcety/intellij-community,vladmm/intellij-community,izonder/intellij-community,holmes/intellij-community,ibinti/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,vladmm/intellij-community,vladmm/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,fitermay/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,izonder/intellij-community,vladmm/intellij-community,signed/intellij-community,consulo/consulo,clumsy/intellij-community,semonte/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,caot/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,da1z/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,ryano144/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,holmes/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ibinti/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,ibinti/intellij-community,jagguli/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,blademainer/intellij-community,kool79/intellij-community,supersven/intellij-community,caot/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,apixandru/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,allotria/intellij-community,robovm/robovm-studio,clumsy/intellij-community,izonder/intellij-community,asedunov/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,kool79/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,adedayo/intellij-community,ernestp/consulo,adedayo/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,supersven/intellij-community,holmes/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,slisson/intellij-community,supersven/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,vladmm/intellij-community,adedayo/intellij-community,jagguli/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,blademainer/intellij-community,apixandru/intellij-community,da1z/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,consulo/consulo,robovm/robovm-studio,vvv1559/intellij-community,dslomov/intellij-community,kool79/intellij-community,ryano144/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,supersven/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,kool79/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,asedunov/intellij-community,retomerz/intellij-community,samthor/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,retomerz/intellij-community,apixandru/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,jagguli/intellij-community,signed/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,asedunov/intellij-community,izonder/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,apixandru/intellij-community,robovm/robovm-studio,ibinti/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,slisson/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,signed/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,supersven/intellij-community,ibinti/intellij-community,ibinti/intellij-community,caot/intellij-community,blademainer/intellij-community,caot/intellij-community,ryano144/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,holmes/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,holmes/intellij-community,samthor/intellij-community,suncycheng/intellij-community,slisson/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,signed/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,samthor/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,samthor/intellij-community,kdwink/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,samthor/intellij-community,consulo/consulo,FHannes/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,kdwink/intellij-community,Distrotech/intellij-community
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.wm.impl; import com.intellij.ide.IdeEventQueue; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationAdapter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.EdtRunnable; import com.intellij.openapi.util.Expirable; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy; import com.intellij.ui.FocusTrackback; import com.intellij.util.Alarm; import com.intellij.util.containers.WeakHashMap; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Set; public class FocusManagerImpl extends IdeFocusManager implements Disposable { private Application myApp; private FocusCommand myRequestFocusCmd; private final ArrayList<FocusCommand> myFocusRequests = new ArrayList<FocusCommand>(); private final ArrayList<KeyEvent> myToDispatchOnDone = new ArrayList<KeyEvent>(); private int myFlushingIdleRequestsEntryCount = 0; private WeakReference<FocusCommand> myLastForcedRequest = new WeakReference<FocusCommand>(null); private FocusCommand myFocusCommandOnAppActivation; private ActionCallback myCallbackOnActivation; private final IdeEventQueue myQueue; private final KeyProcessorConext myKeyProcessorContext = new KeyProcessorConext(); private long myCmdTimestamp; private long myForcedCmdTimestamp; final EdtAlarm myFocusedComponentAlaram; private final EdtAlarm myForcedFocusRequestsAlarm; private final EdtAlarm myIdleAlarm; private final Set<Runnable> myIdleRequests = new com.intellij.util.containers.HashSet<Runnable>(); private final EdtRunnable myIdleRunnable = new EdtRunnable() { public void runEdt() { if (isFocusTransferReady() && !isIdleQueueEmpty()) { flushIdleRequests(); } else { restartIdleAlarm(); } } }; private WindowManager myWindowManager; private Map<IdeFrame, Component> myLastFocused = new WeakHashMap<IdeFrame, Component>(); private Map<IdeFrame, Component> myLastFocusedAtDeactivation = new WeakHashMap<IdeFrame, Component>(); public FocusManagerImpl(WindowManager wm) { myApp = ApplicationManager.getApplication(); myQueue = IdeEventQueue.getInstance(); myWindowManager = wm; myFocusedComponentAlaram = new EdtAlarm(this); myForcedFocusRequestsAlarm = new EdtAlarm(this); myIdleAlarm = new EdtAlarm(this); final AppListener myAppListener = new AppListener(); myApp.addApplicationListener(myAppListener); IdeEventQueue.getInstance().addDispatcher(new IdeEventQueue.EventDispatcher() { public boolean dispatch(AWTEvent e) { if (e instanceof FocusEvent) { final FocusEvent fe = (FocusEvent)e; final Component c = fe.getComponent(); if (c instanceof Window || c == null) return false; Component parent = UIUtil.findUltimateParent(c); if (parent instanceof IdeFrame) { myLastFocused.put((IdeFrame)parent, c); } } return false; } }, this); } public ActionCallback requestFocus(final Component c, final boolean forced) { return requestFocus(new FocusCommand.ByComponent(c), forced); } public ActionCallback requestFocus(final FocusCommand command, final boolean forced) { final ActionCallback result = new ActionCallback(); if (!forced) { if (!myFocusRequests.contains(command)) { myFocusRequests.add(command); } SwingUtilities.invokeLater(new Runnable() { public void run() { resetUnforcedCommand(command); _requestFocus(command, forced, result); } }); } else { _requestFocus(command, forced, result); } result.doWhenProcessed(new Runnable() { public void run() { restartIdleAlarm(); } }); return result; } private void _requestFocus(final FocusCommand command, final boolean forced, final ActionCallback result) { if (checkForRejectOrByPass(command, forced, result)) return; setCommand(command); command.setCallback(result); if (forced) { myForcedFocusRequestsAlarm.cancelAllRequests(); setLastEffectiveForcedRequest(command); } SwingUtilities.invokeLater(new Runnable() { public void run() { if (checkForRejectOrByPass(command, forced, result)) return; if (myRequestFocusCmd == command) { final ActionCallback.TimedOut focusTimeout = new ActionCallback.TimedOut(Registry.intValue("actionSystem.commandProcessingTimeout"), "Focus command timed out, cmd=" + command, command.getAllocation(), true) { @Override protected void onTimeout() { forceFinishFocusSettledown(command, result); } }; myCmdTimestamp++; if (forced) { myForcedCmdTimestamp++; } command.run().doWhenDone(new Runnable() { public void run() { SwingUtilities.invokeLater(new Runnable() { public void run() { result.setDone(); } }); } }).doWhenRejected(new Runnable() { public void run() { result.setRejected(); } }).doWhenProcessed(new Runnable() { public void run() { resetCommand(command, false); if (forced) { myForcedFocusRequestsAlarm.addRequest(new EdtRunnable() { public void runEdt() { setLastEffectiveForcedRequest(null); } }, 250); } } }).notify(focusTimeout); } else { rejectCommand(command, result); } } }); } private boolean checkForRejectOrByPass(final FocusCommand cmd, final boolean forced, final ActionCallback result) { if (cmd.isExpired()) { rejectCommand(cmd, result); return true; } final FocusCommand lastRequest = getLastEffectiveForcedRequest(); if (!forced && !isUnforcedRequestAllowed()) { if (cmd.equals(lastRequest)) { resetCommand(cmd, false); result.setDone(); } else { rejectCommand(cmd, result); } return true; } if (lastRequest != null && lastRequest.dominatesOver(cmd)) { rejectCommand(cmd, result); return true; } boolean doNotExecuteBecauseAppIsInactive = !myApp.isActive() && (!canExecuteOnInactiveApplication(cmd) && Registry.is("actionSystem.suspendFocusTransferIfApplicationInactive")); if (doNotExecuteBecauseAppIsInactive) { if (myCallbackOnActivation != null) { myCallbackOnActivation.setRejected(); if (myFocusCommandOnAppActivation != null) { resetCommand(myFocusCommandOnAppActivation, true); } } myFocusCommandOnAppActivation = cmd; myCallbackOnActivation = result; return true; } return false; } private void setCommand(FocusCommand command) { myRequestFocusCmd = command; if (!myFocusRequests.contains(command)) { myFocusRequests.add(command); } } private void resetCommand(FocusCommand cmd, boolean reject) { if (cmd == myRequestFocusCmd) { myRequestFocusCmd = null; } final KeyEventProcessor processor = cmd.getProcessor(); if (processor != null) { processor.finish(myKeyProcessorContext); } myFocusRequests.remove(cmd); if (reject) { ActionCallback cb = cmd.getCallback(); if (cb != null && !cb.isProcessed()) { cmd.getCallback().setRejected(); } } } private void resetUnforcedCommand(FocusCommand cmd) { myFocusRequests.remove(cmd); } private static boolean canExecuteOnInactiveApplication(FocusCommand cmd) { return cmd.canExecuteOnInactiveApp(); } private void setLastEffectiveForcedRequest(FocusCommand command) { myLastForcedRequest = new WeakReference<FocusCommand>(command); } @Nullable private FocusCommand getLastEffectiveForcedRequest() { if (myLastForcedRequest == null) return null; final FocusCommand request = myLastForcedRequest.get(); return request != null && !request.isExpired() ? request : null; } boolean isUnforcedRequestAllowed() { return getLastEffectiveForcedRequest() == null; } public static FocusManagerImpl getInstance() { return (FocusManagerImpl)ApplicationManager.getApplication().getComponent(IdeFocusManager.class); } public void dispose() { } private class KeyProcessorConext implements KeyEventProcessor.Context { public java.util.List<KeyEvent> getQueue() { return myToDispatchOnDone; } public void dispatch(final java.util.List<KeyEvent> events) { doWhenFocusSettlesDown(new Runnable() { public void run() { myToDispatchOnDone.addAll(events); restartIdleAlarm(); } }); } } public void doWhenFocusSettlesDown(@NotNull final Runnable runnable) { final boolean needsRestart = isIdleQueueEmpty(); myIdleRequests.add(runnable); if (needsRestart) { restartIdleAlarm(); } } private void restartIdleAlarm() { myIdleAlarm.cancelAllRequests(); myIdleAlarm.addRequest(myIdleRunnable, Registry.intValue("actionSystem.focusIdleTimeout")); } private void flushIdleRequests() { try { myFlushingIdleRequestsEntryCount++; final KeyEvent[] events = myToDispatchOnDone.toArray(new KeyEvent[myToDispatchOnDone.size()]); IdeEventQueue.getInstance().getKeyEventDispatcher().resetState(); boolean keyWasPressed = false; for (KeyEvent each : events) { if (!isFocusTransferReady()) break; if (!keyWasPressed) { if (each.getID() == KeyEvent.KEY_PRESSED) { keyWasPressed = true; } else { myToDispatchOnDone.remove(each); continue; } } final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner != null && SwingUtilities.getWindowAncestor(owner) != null) { myToDispatchOnDone.remove(each); IdeEventQueue.getInstance().dispatchEvent( new KeyEvent(owner, each.getID(), each.getWhen(), each.getModifiersEx(), each.getKeyCode(), each.getKeyChar(), each.getKeyLocation())); } else { break; } } if (isPendingKeyEventsRedispatched()) { final Runnable[] all = myIdleRequests.toArray(new Runnable[myIdleRequests.size()]); myIdleRequests.clear(); for (Runnable each : all) { each.run(); } } } finally { myFlushingIdleRequestsEntryCount--; if (!isIdleQueueEmpty()) { restartIdleAlarm(); } } } public boolean isFocusTransferReady() { invalidateFocusRequestsQueue(); if (!myFocusRequests.isEmpty()) return false; if (myQueue == null) return true; return !myQueue.isSuspendMode() && !myQueue.hasFocusEventsPending(); } private void invalidateFocusRequestsQueue() { if (myFocusRequests.size() == 0) return; FocusCommand[] requests = myFocusRequests.toArray(new FocusCommand[myFocusRequests.size()]); boolean wasChanged = false; for (FocusCommand each : requests) { if (each.isExpired()) { resetCommand(each, true); wasChanged = true; } } if (wasChanged && myFocusRequests.size() == 0) { restartIdleAlarm(); } } private boolean isIdleQueueEmpty() { return isPendingKeyEventsRedispatched() && myIdleRequests.isEmpty(); } private boolean isPendingKeyEventsRedispatched() { return myToDispatchOnDone.isEmpty(); } public boolean dispatch(KeyEvent e) { if (!Registry.is("actionSystem.fixLostTyping")) return false; if (myFlushingIdleRequestsEntryCount > 0) return false; if (!isFocusTransferReady() || !isPendingKeyEventsRedispatched()) { for (FocusCommand each : myFocusRequests) { final KeyEventProcessor processor = each.getProcessor(); if (processor != null) { final Boolean result = processor.dispatch(e, myKeyProcessorContext); if (result != null) { return result.booleanValue(); } } } myToDispatchOnDone.add(e); restartIdleAlarm(); return true; } else { return false; } } public void suspendKeyProcessingUntil(final ActionCallback done) { requestFocus(new FocusCommand(done) { public ActionCallback run() { return done; } }.saveAllocation(), true); } public Expirable getTimestamp(final boolean trackOnlyForcedCommands) { return new Expirable() { long myOwnStamp = trackOnlyForcedCommands ? myForcedCmdTimestamp : myCmdTimestamp; public boolean isExpired() { return myOwnStamp < (trackOnlyForcedCommands ? myForcedCmdTimestamp : myCmdTimestamp); } }; } static class EdtAlarm { private final Alarm myAlarm; private EdtAlarm(Disposable parent) { myAlarm = new Alarm(Alarm.ThreadToUse.OWN_THREAD, parent); } public void cancelAllRequests() { myAlarm.cancelAllRequests(); } public void addRequest(EdtRunnable runnable, int delay) { myAlarm.addRequest(runnable, delay); } } private void forceFinishFocusSettledown(FocusCommand cmd, ActionCallback cmdCallback) { rejectCommand(cmd, cmdCallback); } private void rejectCommand(FocusCommand cmd, ActionCallback callback) { resetCommand(cmd, true); resetUnforcedCommand(cmd); callback.setRejected(); } private class AppListener extends ApplicationAdapter { @Override public void applicationDeactivated(IdeFrame ideFrame) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); Component parent = UIUtil.findUltimateParent(owner); if (parent == ideFrame) { myLastFocusedAtDeactivation.put(ideFrame, owner); } } @Override public void applicationActivated(final IdeFrame ideFrame) { final FocusCommand cmd = myFocusCommandOnAppActivation; ActionCallback callback = myCallbackOnActivation; myFocusCommandOnAppActivation = null; myCallbackOnActivation = null; if (cmd != null) { requestFocus(cmd, true).notify(callback).doWhenRejected(new Runnable() { public void run() { focusLastFocusedComponent(ideFrame); } }); } else { focusLastFocusedComponent(ideFrame); } } private void focusLastFocusedComponent(IdeFrame ideFrame) { final KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager(); if (mgr.getFocusOwner() == null) { Component c = myLastFocusedAtDeactivation.get(ideFrame); if (c == null || !c.isShowing()) { c = myLastFocused.get(ideFrame); } if (c != null && c.isShowing()) { requestFocus(c, false); } } myLastFocusedAtDeactivation.remove(ideFrame); } } @Override public JComponent getFocusTargetFor(@NotNull JComponent comp) { return IdeFocusTraversalPolicy.getPreferredFocusedComponent(comp); } @Override public Component getFocusedDescendantFor(Component comp) { final Component focused = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (focused == null) return null; if (focused == comp || SwingUtilities.isDescendingFrom(focused, comp)) return focused; java.util.List<JBPopup> popups = FocusTrackback.getChildPopups(comp); for (JBPopup each : popups) { if (each.isFocused()) return focused; } return null; } @Override public boolean isFocusBeingTransferred() { return !isFocusTransferReady(); } @Override public ActionCallback requestDefaultFocus(boolean forced) { return new ActionCallback.Done(); } }
platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.wm.impl; import com.intellij.ide.IdeEventQueue; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationAdapter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.EdtRunnable; import com.intellij.openapi.util.Expirable; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy; import com.intellij.ui.FocusTrackback; import com.intellij.util.Alarm; import com.intellij.util.containers.WeakHashMap; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Set; public class FocusManagerImpl extends IdeFocusManager implements Disposable { private Application myApp; private FocusCommand myRequestFocusCmd; private final ArrayList<FocusCommand> myFocusRequests = new ArrayList<FocusCommand>(); private final ArrayList<KeyEvent> myToDispatchOnDone = new ArrayList<KeyEvent>(); private int myFlushingIdleRequestsEntryCount = 0; private WeakReference<FocusCommand> myLastForcedRequest = new WeakReference<FocusCommand>(null); private FocusCommand myFocusCommandOnAppActivation; private ActionCallback myCallbackOnActivation; private final IdeEventQueue myQueue; private final KeyProcessorConext myKeyProcessorContext = new KeyProcessorConext(); private long myCmdTimestamp; private long myForcedCmdTimestamp; final EdtAlarm myFocusedComponentAlaram; private final EdtAlarm myForcedFocusRequestsAlarm; private final EdtAlarm myIdleAlarm; private final Set<Runnable> myIdleRequests = new com.intellij.util.containers.HashSet<Runnable>(); private final EdtRunnable myIdleRunnable = new EdtRunnable() { public void runEdt() { if (isFocusTransferReady() && !isIdleQueueEmpty()) { flushIdleRequests(); } else { restartIdleAlarm(); } } }; private WindowManager myWindowManager; private Map<IdeFrame, Component> myLastFocused = new WeakHashMap<IdeFrame, Component>(); private Map<IdeFrame, Component> myLastFocusedAtDeactivation = new WeakHashMap<IdeFrame, Component>(); public FocusManagerImpl(WindowManager wm) { myApp = ApplicationManager.getApplication(); myQueue = IdeEventQueue.getInstance(); myWindowManager = wm; myFocusedComponentAlaram = new EdtAlarm(this); myForcedFocusRequestsAlarm = new EdtAlarm(this); myIdleAlarm = new EdtAlarm(this); final AppListener myAppListener = new AppListener(); myApp.addApplicationListener(myAppListener); IdeEventQueue.getInstance().addDispatcher(new IdeEventQueue.EventDispatcher() { public boolean dispatch(AWTEvent e) { if (e instanceof FocusEvent) { final FocusEvent fe = (FocusEvent)e; final Component c = fe.getComponent(); if (c instanceof Window || c == null) return false; Component parent = UIUtil.findUltimateParent(c); if (parent instanceof IdeFrame) { myLastFocused.put((IdeFrame)parent, c); } } return false; } }, this); } public ActionCallback requestFocus(final Component c, final boolean forced) { return requestFocus(new FocusCommand.ByComponent(c), forced); } public ActionCallback requestFocus(final FocusCommand command, final boolean forced) { final ActionCallback result = new ActionCallback(); if (!forced) { myFocusRequests.add(command); SwingUtilities.invokeLater(new Runnable() { public void run() { resetUnforcedCommand(command); _requestFocus(command, forced, result); } }); } else { _requestFocus(command, forced, result); } result.doWhenProcessed(new Runnable() { public void run() { restartIdleAlarm(); } }); return result; } private void _requestFocus(final FocusCommand command, final boolean forced, final ActionCallback result) { if (checkForRejectOrByPass(command, forced, result)) return; setCommand(command); command.setCallback(result); if (forced) { myForcedFocusRequestsAlarm.cancelAllRequests(); setLastEffectiveForcedRequest(command); } SwingUtilities.invokeLater(new Runnable() { public void run() { if (checkForRejectOrByPass(command, forced, result)) return; if (myRequestFocusCmd == command) { final ActionCallback.TimedOut focusTimeout = new ActionCallback.TimedOut(Registry.intValue("actionSystem.commandProcessingTimeout"), "Focus command timed out, cmd=" + command, command.getAllocation(), true) { @Override protected void onTimeout() { forceFinishFocusSettledown(command, result); } }; myCmdTimestamp++; if (forced) { myForcedCmdTimestamp++; } command.run().doWhenDone(new Runnable() { public void run() { SwingUtilities.invokeLater(new Runnable() { public void run() { result.setDone(); } }); } }).doWhenRejected(new Runnable() { public void run() { result.setRejected(); } }).doWhenProcessed(new Runnable() { public void run() { resetCommand(command, true); if (forced) { myForcedFocusRequestsAlarm.addRequest(new EdtRunnable() { public void runEdt() { setLastEffectiveForcedRequest(null); } }, 250); } } }).notify(focusTimeout); } else { rejectCommand(command, result); } } }); } private boolean checkForRejectOrByPass(final FocusCommand cmd, final boolean forced, final ActionCallback result) { if (cmd.isExpired()) { rejectCommand(cmd, result); return true; } final FocusCommand lastRequest = getLastEffectiveForcedRequest(); if (!forced && !isUnforcedRequestAllowed()) { if (cmd.equals(lastRequest)) { result.setDone(); } else { rejectCommand(cmd, result); } return true; } if (lastRequest != null && lastRequest.dominatesOver(cmd)) { rejectCommand(cmd, result); return true; } boolean doNotExecuteBecauseAppIsInactive = !myApp.isActive() && (!canExecuteOnInactiveApplication(cmd) && Registry.is("actionSystem.suspendFocusTransferIfApplicationInactive")); if (doNotExecuteBecauseAppIsInactive) { if (myCallbackOnActivation != null) { myCallbackOnActivation.setRejected(); } myFocusCommandOnAppActivation = cmd; myCallbackOnActivation = result; return true; } return false; } private void setCommand(FocusCommand command) { myRequestFocusCmd = command; if (!myFocusRequests.contains(command)) { myFocusRequests.add(command); } } private void resetCommand(FocusCommand cmd, boolean reject) { if (cmd == myRequestFocusCmd) { myRequestFocusCmd = null; } final KeyEventProcessor processor = cmd.getProcessor(); if (processor != null) { processor.finish(myKeyProcessorContext); } myFocusRequests.remove(cmd); if (reject) { ActionCallback cb = cmd.getCallback(); if (cb != null && !cb.isProcessed()) { cmd.getCallback().setRejected(); } } } private void resetUnforcedCommand(FocusCommand cmd) { myFocusRequests.remove(cmd); } private static boolean canExecuteOnInactiveApplication(FocusCommand cmd) { return cmd.canExecuteOnInactiveApp(); } private void setLastEffectiveForcedRequest(FocusCommand command) { myLastForcedRequest = new WeakReference<FocusCommand>(command); } @Nullable private FocusCommand getLastEffectiveForcedRequest() { if (myLastForcedRequest == null) return null; final FocusCommand request = myLastForcedRequest.get(); return request != null && !request.isExpired() ? request : null; } boolean isUnforcedRequestAllowed() { return getLastEffectiveForcedRequest() == null; } public static FocusManagerImpl getInstance() { return (FocusManagerImpl)ApplicationManager.getApplication().getComponent(IdeFocusManager.class); } public void dispose() { } private class KeyProcessorConext implements KeyEventProcessor.Context { public java.util.List<KeyEvent> getQueue() { return myToDispatchOnDone; } public void dispatch(final java.util.List<KeyEvent> events) { doWhenFocusSettlesDown(new Runnable() { public void run() { myToDispatchOnDone.addAll(events); restartIdleAlarm(); } }); } } public void doWhenFocusSettlesDown(@NotNull final Runnable runnable) { final boolean needsRestart = isIdleQueueEmpty(); myIdleRequests.add(runnable); if (needsRestart) { restartIdleAlarm(); } } private void restartIdleAlarm() { myIdleAlarm.cancelAllRequests(); myIdleAlarm.addRequest(myIdleRunnable, Registry.intValue("actionSystem.focusIdleTimeout")); } private void flushIdleRequests() { try { myFlushingIdleRequestsEntryCount++; final KeyEvent[] events = myToDispatchOnDone.toArray(new KeyEvent[myToDispatchOnDone.size()]); IdeEventQueue.getInstance().getKeyEventDispatcher().resetState(); boolean keyWasPressed = false; for (KeyEvent each : events) { if (!isFocusTransferReady()) break; if (!keyWasPressed) { if (each.getID() == KeyEvent.KEY_PRESSED) { keyWasPressed = true; } else { myToDispatchOnDone.remove(each); continue; } } final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner != null && SwingUtilities.getWindowAncestor(owner) != null) { myToDispatchOnDone.remove(each); IdeEventQueue.getInstance().dispatchEvent( new KeyEvent(owner, each.getID(), each.getWhen(), each.getModifiersEx(), each.getKeyCode(), each.getKeyChar(), each.getKeyLocation())); } else { break; } } if (isPendingKeyEventsRedispatched()) { final Runnable[] all = myIdleRequests.toArray(new Runnable[myIdleRequests.size()]); myIdleRequests.clear(); for (Runnable each : all) { each.run(); } } } finally { myFlushingIdleRequestsEntryCount--; if (!isIdleQueueEmpty()) { restartIdleAlarm(); } } } public boolean isFocusTransferReady() { invalidateFocusRequestsQueue(); if (!myFocusRequests.isEmpty()) return false; if (myQueue == null) return true; return !myQueue.isSuspendMode() && !myQueue.hasFocusEventsPending(); } private void invalidateFocusRequestsQueue() { if (myFocusRequests.size() == 0) return; FocusCommand[] requests = myFocusRequests.toArray(new FocusCommand[myFocusRequests.size()]); boolean wasChanged = false; for (FocusCommand each : requests) { if (each.isExpired()) { resetCommand(each, true); wasChanged = true; } } if (wasChanged && myFocusRequests.size() == 0) { restartIdleAlarm(); } } private boolean isIdleQueueEmpty() { return isPendingKeyEventsRedispatched() && myIdleRequests.isEmpty(); } private boolean isPendingKeyEventsRedispatched() { return myToDispatchOnDone.isEmpty(); } public boolean dispatch(KeyEvent e) { if (!Registry.is("actionSystem.fixLostTyping")) return false; if (myFlushingIdleRequestsEntryCount > 0) return false; if (!isFocusTransferReady() || !isPendingKeyEventsRedispatched()) { for (FocusCommand each : myFocusRequests) { final KeyEventProcessor processor = each.getProcessor(); if (processor != null) { final Boolean result = processor.dispatch(e, myKeyProcessorContext); if (result != null) { return result.booleanValue(); } } } myToDispatchOnDone.add(e); restartIdleAlarm(); return true; } else { return false; } } public void suspendKeyProcessingUntil(final ActionCallback done) { requestFocus(new FocusCommand(done) { public ActionCallback run() { return done; } }.saveAllocation(), true); } public Expirable getTimestamp(final boolean trackOnlyForcedCommands) { return new Expirable() { long myOwnStamp = trackOnlyForcedCommands ? myForcedCmdTimestamp : myCmdTimestamp; public boolean isExpired() { return myOwnStamp < (trackOnlyForcedCommands ? myForcedCmdTimestamp : myCmdTimestamp); } }; } static class EdtAlarm { private final Alarm myAlarm; private EdtAlarm(Disposable parent) { myAlarm = new Alarm(Alarm.ThreadToUse.OWN_THREAD, parent); } public void cancelAllRequests() { myAlarm.cancelAllRequests(); } public void addRequest(EdtRunnable runnable, int delay) { myAlarm.addRequest(runnable, delay); } } private void forceFinishFocusSettledown(FocusCommand cmd, ActionCallback cmdCallback) { rejectCommand(cmd, cmdCallback); } private void rejectCommand(FocusCommand cmd, ActionCallback callback) { resetCommand(cmd, true); resetUnforcedCommand(cmd); callback.setRejected(); } private class AppListener extends ApplicationAdapter { @Override public void applicationDeactivated(IdeFrame ideFrame) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); Component parent = UIUtil.findUltimateParent(owner); if (parent == ideFrame) { myLastFocusedAtDeactivation.put(ideFrame, owner); } } @Override public void applicationActivated(final IdeFrame ideFrame) { final FocusCommand cmd = myFocusCommandOnAppActivation; ActionCallback callback = myCallbackOnActivation; myFocusCommandOnAppActivation = null; myCallbackOnActivation = null; if (cmd != null) { requestFocus(cmd, true).notify(callback).doWhenRejected(new Runnable() { public void run() { focusLastFocusedComponent(ideFrame); } }); } else { focusLastFocusedComponent(ideFrame); } } private void focusLastFocusedComponent(IdeFrame ideFrame) { final KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager(); if (mgr.getFocusOwner() == null) { Component c = myLastFocusedAtDeactivation.get(ideFrame); if (c == null || !c.isShowing()) { c = myLastFocused.get(ideFrame); } if (c != null && c.isShowing()) { requestFocus(c, false); } } myLastFocusedAtDeactivation.remove(ideFrame); } } @Override public JComponent getFocusTargetFor(@NotNull JComponent comp) { return IdeFocusTraversalPolicy.getPreferredFocusedComponent(comp); } @Override public Component getFocusedDescendantFor(Component comp) { final Component focused = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (focused == null) return null; if (focused == comp || SwingUtilities.isDescendingFrom(focused, comp)) return focused; java.util.List<JBPopup> popups = FocusTrackback.getChildPopups(comp); for (JBPopup each : popups) { if (each.isFocused()) return focused; } return null; } @Override public boolean isFocusBeingTransferred() { return !isFocusTransferReady(); } @Override public ActionCallback requestDefaultFocus(boolean forced) { return new ActionCallback.Done(); } }
focus manager -- lost typing between app activation/deactivation, was caused by non-released focus requests which were actually rejected by forced focus command
platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java
focus manager -- lost typing between app activation/deactivation, was caused by non-released focus requests which were actually rejected by forced focus command
<ide><path>latform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java <ide> final ActionCallback result = new ActionCallback(); <ide> <ide> if (!forced) { <del> myFocusRequests.add(command); <add> if (!myFocusRequests.contains(command)) { <add> myFocusRequests.add(command); <add> } <ide> <ide> SwingUtilities.invokeLater(new Runnable() { <ide> public void run() { <ide> } <ide> }).doWhenProcessed(new Runnable() { <ide> public void run() { <del> resetCommand(command, true); <add> resetCommand(command, false); <ide> <ide> if (forced) { <ide> myForcedFocusRequestsAlarm.addRequest(new EdtRunnable() { <ide> <ide> if (!forced && !isUnforcedRequestAllowed()) { <ide> if (cmd.equals(lastRequest)) { <add> resetCommand(cmd, false); <ide> result.setDone(); <ide> } <ide> else { <ide> if (doNotExecuteBecauseAppIsInactive) { <ide> if (myCallbackOnActivation != null) { <ide> myCallbackOnActivation.setRejected(); <add> if (myFocusCommandOnAppActivation != null) { <add> resetCommand(myFocusCommandOnAppActivation, true); <add> } <ide> } <ide> <ide> myFocusCommandOnAppActivation = cmd;
Java
apache-2.0
bd874a061d76c705e7c17e52c096005e4ca200cf
0
real-logic/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,real-logic/Aeron,galderz/Aeron,mikeb01/Aeron,oleksiyp/Aeron,real-logic/Aeron,mikeb01/Aeron,galderz/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,oleksiyp/Aeron,oleksiyp/Aeron,galderz/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,mikeb01/Aeron
package io.aeron.archiver; import io.aeron.Image; import io.aeron.Publication; import org.agrona.concurrent.EpochClock; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.*; public class ControlSessionTest { private ControlSession session; private Image mockImage = mock(Image.class); private ArchiveConductor mockConductor = mock(ArchiveConductor.class); private EpochClock mockEpochClock = mock(EpochClock.class); private Publication mockControlPublication = mock(Publication.class); @Before public void setUp() throws Exception { session = new ControlSession(mockImage, mockConductor, mockEpochClock); when(mockControlPublication.isClosed()).thenReturn(false); when(mockControlPublication.isConnected()).thenReturn(true); when(mockConductor.newControlPublication("mock", 42)).thenReturn(mockControlPublication); session.onConnect("mock", 42); session.doWork(); } @Test public void shouldSequenceListRecordingsProcessing() throws Exception { final ListRecordingsSession mockListRecordingSession1 = mock(ListRecordingsSession.class); when(mockConductor.newListRecordingsSession(1, mockControlPublication, 2, 3, session)) .thenReturn(mockListRecordingSession1); // first list recording is created and added to conductor session.onListRecordings(1, 2, 3); verify(mockConductor).newListRecordingsSession(1, mockControlPublication, 2, 3, session); verify(mockConductor).addSession(mockListRecordingSession1); final ListRecordingsSession mockListRecordingSession2 = mock(ListRecordingsSession.class); when(mockConductor.newListRecordingsSession(2, mockControlPublication, 3, 4, session)) .thenReturn(mockListRecordingSession2); // second list recording is created but cannot start until the first is done session.onListRecordings(2, 3, 4); verify(mockConductor).newListRecordingsSession(2, mockControlPublication, 3, 4, session); verify(mockConductor, never()).addSession(mockListRecordingSession2); // second session added to conductor after the first is done session.onListRecordingSessionClosed(mockListRecordingSession1); verify(mockConductor).addSession(mockListRecordingSession2); } }
aeron-archiver/src/test/java/io/aeron/archiver/ControlSessionTest.java
package io.aeron.archiver; import io.aeron.Image; import io.aeron.Publication; import org.agrona.concurrent.EpochClock; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.*; public class ControlSessionTest { private ControlSession session; private Image mockImage = mock(Image.class); private ArchiveConductor mockConductor = mock(ArchiveConductor.class); private EpochClock mockEpochClock = mock(EpochClock.class); private Publication mockControlPublication = mock(Publication.class); @Before public void setUp() throws Exception { session = new ControlSession(mockImage, mockConductor, mockEpochClock); when(mockControlPublication.isClosed()).thenReturn(false); when(mockControlPublication.isConnected()).thenReturn(true); when(mockConductor.newControlPublication("mock", 42)).thenReturn(mockControlPublication); session.onConnect("mock", 42); session.doWork(); } @Test public void shouldSequenceListRecordingsProcessing() throws Exception { final ListRecordingsSession mockListRecordingSession1 = mock(ListRecordingsSession.class); when(mockConductor.newListRecordingsSession(1, mockControlPublication, 2, 3, session)) .thenReturn(mockListRecordingSession1); // first list recording is created and added to conductor session.onListRecordings(1, 2, 3); verify(mockConductor).newListRecordingsSession(1, mockControlPublication, 2, 3, session); verify(mockConductor).addSession(mockListRecordingSession1); final ListRecordingsSession mockListRecordingSession2 = mock(ListRecordingsSession.class); when(mockConductor.newListRecordingsSession(2, mockControlPublication, 3, 4, session)) .thenReturn(mockListRecordingSession2); // second list recording is created but cannot start until the first is done session.onListRecordings(2, 3, 4); verify(mockConductor).newListRecordingsSession(2, mockControlPublication, 3, 4, session); verify(mockConductor, never()).addSession(mockListRecordingSession2); // second session added to conductor after the first is done session.onListRecordingSessionClosed(mockListRecordingSession1); verify(mockConductor).addSession(mockListRecordingSession2); } }
[Java] remove line
aeron-archiver/src/test/java/io/aeron/archiver/ControlSessionTest.java
[Java] remove line
<ide><path>eron-archiver/src/test/java/io/aeron/archiver/ControlSessionTest.java <ide> // second session added to conductor after the first is done <ide> session.onListRecordingSessionClosed(mockListRecordingSession1); <ide> verify(mockConductor).addSession(mockListRecordingSession2); <del> <ide> } <ide> }
Java
lgpl-2.1
bd81536576c6cecf2aee9b25dbecb693cec8c1a4
0
pdvrieze/chatterbox,pdvrieze/chatterbox
package net.devrieze.chatterbox.client; import java.util.Date; import net.devrieze.chatterbox.client.StatusEvent.StatusLevel; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.AnchorElement; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Node; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.SimpleEventBus; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat; import com.google.gwt.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.*; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class ChatterboxUI extends Composite implements UpdateMessageEvent.Handler, MoveMessagesEvent.Handler, StatusEvent.Handler { public static final String LOGGER = "chatterbox"; private EventBus eventBus = new SimpleEventBus(); interface ChatterboxBinder extends UiBinder<Widget, ChatterboxUI> { /* Needed by GWT */ } private static ChatterboxBinder uiBinder = GWT.create(ChatterboxBinder.class); interface MyStyle extends CssResource { String even(); } @UiField MyStyle style; @UiField Button sendButton; @UiField Button toggleChannel; @UiField Label errorLabel; @UiField TextBox textBox; @UiField DivElement outputdiv; @UiField AnchorElement logoutRef; private ChatterBoxQueue messageQueue; public ChatterboxUI() { initWidget(uiBinder.createAndBindUi(this)); textBox.setText(""); // We can add style names to widgets sendButton.addStyleName("sendButton"); sendButton.setEnabled(false); // Until there is a text eventBus.addHandler(UpdateMessageEvent.TYPE, this); eventBus.addHandler(StatusEvent.TYPE, this); messageQueue = new ChatterBoxQueue(eventBus, true); messageQueue.requestMessages(); } @UiHandler("textBox") void handleKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendMessage(); } else { sendButton.setEnabled(textBox.getText().length()>=4); } } @UiHandler("sendButton") void handleClick(@SuppressWarnings("unused") ClickEvent e) { errorLabel.setText(""); // Reset status updates before sending sendMessage(); } @UiHandler("toggleChannel") void handleChannelClick(@SuppressWarnings("unused") ClickEvent e) { messageQueue.setUseChannel(! messageQueue.isUseChannel()); if (messageQueue.isUseChannel()) { toggleChannel.setText("disable channel"); } else { toggleChannel.setText("enable channel"); } } private void sendMessage() { String textToServer = textBox.getText(); if (textToServer.length()<4) { errorLabel.setText("Please enter at least four characters"); return; } messageQueue.sendMessage(textToServer); textBox.setText(""); textBox.setFocus(true); } @Override public void onMoveMessages(MoveMessagesEvent event) { // TODO do this better; StringBuilder innerHtml = new StringBuilder(); int i = 0; for(Message m: messageQueue.getMessages()) { String mHtml = createMessageHtml(i, m); if (mHtml!=null && mHtml.length()>0) { i++; innerHtml.append(mHtml); } } outputdiv.setInnerHTML(innerHtml.toString()); } @Override public void onUpdateMessage(UpdateMessageEvent event) { // TODO do this much better // Special case message added if (event.getMessageIndex()==messageQueue.size()-1) { Message m = messageQueue.getMessages().get(event.getMessageIndex()); DivElement d = outputdiv.getOwnerDocument().createDivElement(); d.setInnerHTML(createMessageHtml(outputdiv.getChildCount(), m)); for(Node n = d.getFirstChild(); n!=null; n=n.getNextSibling()) { outputdiv.appendChild(n); } } else { // Pretend we can't be smart and just replace the whole list onMoveMessages(null); } scrollDown(); } private void scrollDown() { Document document = Document.get(); int height = document.getScrollHeight(); Window.scrollTo(0, height); } /** * Create the right HTML text to put a message in the output div * @param i position in the list * @param m message * @return the html text */ private String createMessageHtml(int i, Message m) { StringBuilder mHtml = new StringBuilder(); if (m!=null) { if (i%2==1) { mHtml.append("<div class=\"even\">"); } else { mHtml.append("<div class=\"odd\">"); } mHtml.append("<b class=\"sender\">").append(m.getSender()).append("</b> [<i>") .append(epochToString(m.getMsgTime())).append("</i>]: "); mHtml.append(m.getMessageBody()); mHtml.append("</div>"); } return mHtml.toString(); } private Object epochToString(long pMsgTime) { Date d = new Date(pMsgTime); DateTimeFormat format = DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_SHORT); return format.format(d); } @Override public void onStatusUpdate(StatusEvent e) { String messageText = e.getStatusLevel()+": "+e.getMessage(); if (e.getStatusLevel()==StatusLevel.WARNING) { errorLabel.setText(messageText); } GWT.log(messageText, e.getException()); } }
src/net/devrieze/chatterbox/client/ChatterboxUI.java
package net.devrieze.chatterbox.client; import net.devrieze.chatterbox.client.StatusEvent.StatusLevel; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.AnchorElement; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Node; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.SimpleEventBus; import com.google.gwt.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.*; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class ChatterboxUI extends Composite implements UpdateMessageEvent.Handler, MoveMessagesEvent.Handler, StatusEvent.Handler { public static final String LOGGER = "chatterbox"; private EventBus eventBus = new SimpleEventBus(); interface ChatterboxBinder extends UiBinder<Widget, ChatterboxUI> { /* Needed by GWT */ } private static ChatterboxBinder uiBinder = GWT.create(ChatterboxBinder.class); interface MyStyle extends CssResource { String even(); } @UiField MyStyle style; @UiField Button sendButton; @UiField Button toggleChannel; @UiField Label errorLabel; @UiField TextBox textBox; @UiField DivElement outputdiv; @UiField AnchorElement logoutRef; private ChatterBoxQueue messageQueue; public ChatterboxUI() { initWidget(uiBinder.createAndBindUi(this)); textBox.setText(""); // We can add style names to widgets sendButton.addStyleName("sendButton"); sendButton.setEnabled(false); // Until there is a text eventBus.addHandler(UpdateMessageEvent.TYPE, this); eventBus.addHandler(StatusEvent.TYPE, this); messageQueue = new ChatterBoxQueue(eventBus, true); messageQueue.requestMessages(); } @UiHandler("textBox") void handleKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendMessage(); } else { sendButton.setEnabled(textBox.getText().length()>=4); } } @UiHandler("sendButton") void handleClick(@SuppressWarnings("unused") ClickEvent e) { errorLabel.setText(""); // Reset status updates before sending sendMessage(); } @UiHandler("toggleChannel") void handleChannelClick(@SuppressWarnings("unused") ClickEvent e) { messageQueue.setUseChannel(! messageQueue.isUseChannel()); if (messageQueue.isUseChannel()) { toggleChannel.setText("disable channel"); } else { toggleChannel.setText("enable channel"); } } private void sendMessage() { String textToServer = textBox.getText(); if (textToServer.length()<4) { errorLabel.setText("Please enter at least four characters"); return; } messageQueue.sendMessage(textToServer); textBox.setText(""); textBox.setFocus(true); } @Override public void onMoveMessages(MoveMessagesEvent event) { // TODO do this better; StringBuilder innerHtml = new StringBuilder(); int i = 0; for(Message m: messageQueue.getMessages()) { String mHtml = createMessageHtml(i, m); if (mHtml!=null && mHtml.length()>0) { i++; innerHtml.append(mHtml); } } outputdiv.setInnerHTML(innerHtml.toString()); } @Override public void onUpdateMessage(UpdateMessageEvent event) { // TODO do this much better // Special case message added if (event.getMessageIndex()==messageQueue.size()-1) { Message m = messageQueue.getMessages().get(event.getMessageIndex()); DivElement d = outputdiv.getOwnerDocument().createDivElement(); d.setInnerHTML(createMessageHtml(outputdiv.getChildCount(), m)); for(Node n = d.getFirstChild(); n!=null; n=n.getNextSibling()) { outputdiv.appendChild(n); } } else { // Pretend we can't be smart and just replace the whole list onMoveMessages(null); } scrollDown(); } private void scrollDown() { Document document = Document.get(); int height = document.getScrollHeight(); Window.scrollTo(0, height); } /** * Create the right HTML text to put a message in the output div * @param i position in the list * @param m message * @return the html text */ private String createMessageHtml(int i, Message m) { StringBuilder mHtml = new StringBuilder(); if (m!=null) { if (i%2==1) { mHtml.append("<div class=\"even\">"); } else { mHtml.append("<div class=\"odd\">"); } mHtml.append("<b class=\"sender\">").append(m.getSender()).append(": </b>"); mHtml.append(m.getMessageBody()); mHtml.append("</div>"); } return mHtml.toString(); } @Override public void onStatusUpdate(StatusEvent e) { String messageText = e.getStatusLevel()+": "+e.getMessage(); if (e.getStatusLevel()==StatusLevel.WARNING) { errorLabel.setText(messageText); } GWT.log(messageText, e.getException()); } }
Make the web client display sender and time.
src/net/devrieze/chatterbox/client/ChatterboxUI.java
Make the web client display sender and time.
<ide><path>rc/net/devrieze/chatterbox/client/ChatterboxUI.java <ide> package net.devrieze.chatterbox.client; <add> <add>import java.util.Date; <ide> <ide> import net.devrieze.chatterbox.client.StatusEvent.StatusLevel; <ide> <ide> import com.google.gwt.event.dom.client.KeyUpEvent; <ide> import com.google.gwt.event.shared.EventBus; <ide> import com.google.gwt.event.shared.SimpleEventBus; <add>import com.google.gwt.i18n.client.DateTimeFormat; <add>import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat; <ide> import com.google.gwt.resources.client.CssResource; <ide> import com.google.gwt.uibinder.client.UiBinder; <ide> import com.google.gwt.uibinder.client.UiField; <ide> } else { <ide> mHtml.append("<div class=\"odd\">"); <ide> } <del> mHtml.append("<b class=\"sender\">").append(m.getSender()).append(": </b>"); <add> mHtml.append("<b class=\"sender\">").append(m.getSender()).append("</b> [<i>") <add> .append(epochToString(m.getMsgTime())).append("</i>]: "); <ide> mHtml.append(m.getMessageBody()); <ide> mHtml.append("</div>"); <ide> <ide> } <ide> return mHtml.toString(); <add> } <add> <add> private Object epochToString(long pMsgTime) { <add> Date d = new Date(pMsgTime); <add> DateTimeFormat format = DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_SHORT); <add> return format.format(d); <ide> } <ide> <ide> @Override
Java
agpl-3.0
ca93f24d1ad35256ba3f7070fbb8ab12baecd614
0
PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver
package nl.mpi.kinnate.svg; import java.awt.geom.AffineTransform; import java.net.URI; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.kinnate.kindata.DataTypes.RelationType; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.kindata.GraphLabel; import nl.mpi.kinnate.uniqueidentifiers.IdentifierException; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.w3c.dom.svg.SVGDocument; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.events.EventTarget; /** * Document : EntitySvg * Created on : Mar 9, 2011, 3:20:56 PM * Author : Peter Withers */ public class EntitySvg { protected HashMap<UniqueIdentifier, float[]> entityPositions = new HashMap<UniqueIdentifier, float[]>(); private HashMap<UniqueIdentifier, HashSet<UniqueIdentifier>> parentIdentifiers = new HashMap<UniqueIdentifier, HashSet<UniqueIdentifier>>(); private int symbolSize = 15; static protected int strokeWidth = 2; public void readEntityPositions(Node entityGroup) { // read the entity positions from the existing dom // this now replaces the position values in the entity data and the entity position is now stored in the svg entity visual not the entity data if (entityGroup != null) { for (Node entityNode = entityGroup.getFirstChild(); entityNode != null; entityNode = entityNode.getNextSibling()) { try { NamedNodeMap nodeMap = entityNode.getAttributes(); if (nodeMap != null) { Node idNode = nodeMap.getNamedItem("id"); Node transformNode = nodeMap.getNamedItem("transform"); if (idNode != null && transformNode != null) { UniqueIdentifier entityId = new UniqueIdentifier(idNode.getNodeValue()); //transform="translate(300.0, 192.5)" // because the svg dom has not been rendered we cannot get any of the screen data, so we must parse the transform tag String transformString = transformNode.getNodeValue(); transformString = transformString.replaceAll("\\s", ""); transformString = transformString.replace("translate(", ""); transformString = transformString.replace(")", ""); String[] stringPos = transformString.split(","); // System.out.println("entityId: " + entityId); // System.out.println("transformString: " + transformString); entityPositions.put(entityId, new float[]{Float.parseFloat(stringPos[0]), Float.parseFloat(stringPos[1])}); // SVGRect bbox = ((SVGLocatable) entityNode).getBBox(); // SVGMatrix sVGMatrix = ((SVGLocatable) entityNode).getCTM(); // System.out.println("getE: " + sVGMatrix.getE()); // System.out.println("getF: " + sVGMatrix.getF()); //// System.out.println("bbox X: " + bbox.getX()); //// System.out.println("bbox Y: " + bbox.getY()); //// System.out.println("bbox W: " + bbox.getWidth()); //// System.out.println("bbox H: " + bbox.getHeight()); // new float[]{sVGMatrix.getE() + bbox.getWidth() / 2, sVGMatrix.getF() + bbox.getHeight() / 2}; } } } catch (IdentifierException exception) { // GuiHelper.linorgBugCatcher.logError(exception); ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to read an entity position, layout might not be preserved", "Restore Layout"); } } } } public int insertSymbols(SVGDocument doc, String svgNameSpace) { Element svgRoot = doc.getDocumentElement(); Element defsNode = doc.createElementNS(svgNameSpace, "defs"); defsNode.setAttribute("id", "KinSymbols"); // add the circle symbol Element circleGroup = doc.createElementNS(svgNameSpace, "g"); circleGroup.setAttribute("id", "circle"); Element circleNode = doc.createElementNS(svgNameSpace, "circle"); circleNode.setAttribute("cx", Integer.toString(symbolSize / 2)); circleNode.setAttribute("cy", Integer.toString(symbolSize / 2)); circleNode.setAttribute("r", Integer.toString((symbolSize - strokeWidth) / 2)); // circleNode.setAttribute("height", Integer.toString(symbolSize - (strokeWidth * 3))); circleNode.setAttribute("stroke", "black"); circleNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); circleGroup.appendChild(circleNode); defsNode.appendChild(circleGroup); // add the square symbol Element squareGroup = doc.createElementNS(svgNameSpace, "g"); squareGroup.setAttribute("id", "square"); Element squareNode = doc.createElementNS(svgNameSpace, "rect"); squareNode.setAttribute("x", Integer.toString(strokeWidth)); squareNode.setAttribute("y", Integer.toString(strokeWidth)); squareNode.setAttribute("width", Integer.toString(symbolSize - strokeWidth * 2)); squareNode.setAttribute("height", Integer.toString(symbolSize - strokeWidth * 2)); squareNode.setAttribute("stroke", "black"); squareNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); squareGroup.appendChild(squareNode); defsNode.appendChild(squareGroup); svgRoot.appendChild(defsNode); // add the resource symbol Element resourceGroup = doc.createElementNS(svgNameSpace, "g"); resourceGroup.setAttribute("id", "square45"); Element resourceNode = doc.createElementNS(svgNameSpace, "rect"); resourceNode.setAttribute("x", "0"); resourceNode.setAttribute("y", "0"); resourceNode.setAttribute("transform", "rotate(-45 " + Integer.toString(symbolSize / 2) + " " + Integer.toString(symbolSize / 2) + ")"); resourceNode.setAttribute("width", Integer.toString(symbolSize)); resourceNode.setAttribute("height", Integer.toString(symbolSize)); resourceNode.setAttribute("stroke", "black"); resourceNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); resourceGroup.appendChild(resourceNode); defsNode.appendChild(resourceGroup); svgRoot.appendChild(defsNode); // add the rhombus symbol Element rhombusGroup = doc.createElementNS(svgNameSpace, "g"); rhombusGroup.setAttribute("id", "rhombus"); Element rhombusNode = doc.createElementNS(svgNameSpace, "rect"); rhombusNode.setAttribute("x", "0"); rhombusNode.setAttribute("y", "0"); rhombusNode.setAttribute("transform", "scale(1,2), rotate(-45 " + Integer.toString(symbolSize / 2) + " " + Integer.toString(symbolSize / 2) + ")"); rhombusNode.setAttribute("width", Integer.toString(symbolSize)); rhombusNode.setAttribute("height", Integer.toString(symbolSize)); rhombusNode.setAttribute("stroke", "black"); rhombusNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); rhombusGroup.appendChild(rhombusNode); defsNode.appendChild(rhombusGroup); svgRoot.appendChild(defsNode); // add the union symbol Element unionGroup = doc.createElementNS(svgNameSpace, "g"); unionGroup.setAttribute("id", "union"); Element upperNode = doc.createElementNS(svgNameSpace, "line"); Element lowerNode = doc.createElementNS(svgNameSpace, "line"); upperNode.setAttribute("x1", Integer.toString(0)); upperNode.setAttribute("y1", Integer.toString((symbolSize / 6))); upperNode.setAttribute("x2", Integer.toString(symbolSize)); upperNode.setAttribute("y2", Integer.toString((symbolSize / 6))); upperNode.setAttribute("stroke-width", Integer.toString(symbolSize / 3)); upperNode.setAttribute("stroke", "black"); lowerNode.setAttribute("x1", Integer.toString(0)); lowerNode.setAttribute("y1", Integer.toString(symbolSize - (symbolSize / 6))); lowerNode.setAttribute("x2", Integer.toString(symbolSize)); lowerNode.setAttribute("y2", Integer.toString(symbolSize - (symbolSize / 6))); lowerNode.setAttribute("stroke-width", Integer.toString(symbolSize / 3)); lowerNode.setAttribute("stroke", "black"); // add a background for selecting and draging Element backgroundNode = doc.createElementNS(svgNameSpace, "rect"); backgroundNode.setAttribute("x", "0"); backgroundNode.setAttribute("y", "0"); backgroundNode.setAttribute("width", Integer.toString(symbolSize)); backgroundNode.setAttribute("height", Integer.toString(symbolSize)); backgroundNode.setAttribute("stroke", "none"); backgroundNode.setAttribute("fill", "white"); unionGroup.appendChild(backgroundNode); unionGroup.appendChild(upperNode); unionGroup.appendChild(lowerNode); defsNode.appendChild(unionGroup); svgRoot.appendChild(defsNode); // add the triangle symbol Element triangleGroup = doc.createElementNS(svgNameSpace, "g"); triangleGroup.setAttribute("id", "triangle"); Element triangleNode = doc.createElementNS(svgNameSpace, "polygon"); int triangleSize = symbolSize - strokeWidth / 2; int triangleHeight = (int) (Math.sqrt(3) * triangleSize / 2); triangleNode.setAttribute("points", (symbolSize / 2) + "," + strokeWidth / 2 + " " + strokeWidth / 2 + "," + triangleHeight + " " + triangleSize + "," + triangleHeight); triangleNode.setAttribute("stroke", "black"); triangleNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); triangleGroup.appendChild(triangleNode); defsNode.appendChild(triangleGroup); svgRoot.appendChild(defsNode); // add the equals symbol Element equalsGroup = doc.createElementNS(svgNameSpace, "g"); equalsGroup.setAttribute("id", "equals"); Element equalsNode = doc.createElementNS(svgNameSpace, "polyline"); int offsetAmounta = symbolSize / 2; int posXa = 0; int posYa = +symbolSize / 2; equalsNode.setAttribute("points", (posXa + offsetAmounta * 3) + "," + (posYa + offsetAmounta) + " " + (posXa - offsetAmounta) + "," + (posYa + offsetAmounta) + " " + (posXa - offsetAmounta) + "," + (posYa - offsetAmounta) + " " + (posXa + offsetAmounta * 3) + "," + (posYa - offsetAmounta)); equalsNode.setAttribute("fill", "white"); equalsNode.setAttribute("stroke", "black"); equalsNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); equalsGroup.appendChild(equalsNode); defsNode.appendChild(equalsGroup); svgRoot.appendChild(defsNode); // add the cross symbol Element crossGroup = doc.createElementNS(svgNameSpace, "g"); crossGroup.setAttribute("id", "cross"); Element crossNode = doc.createElementNS(svgNameSpace, "polyline"); int posX = symbolSize / 2; int posY = symbolSize / 2; int offsetAmount = symbolSize / 2; crossNode.setAttribute("points", (posX - offsetAmount) + "," + (posY - offsetAmount) + " " + (posX + offsetAmount) + "," + (posY + offsetAmount) + " " + (posX) + "," + (posY) + " " + (posX - offsetAmount) + "," + (posY + offsetAmount) + " " + (posX + offsetAmount) + "," + (posY - offsetAmount)); crossNode.setAttribute("fill", "none"); crossNode.setAttribute("stroke", "black"); crossNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); crossGroup.appendChild(crossNode); defsNode.appendChild(crossGroup); svgRoot.appendChild(defsNode); // add the error symbol Element noneGroup = doc.createElementNS(svgNameSpace, "g"); noneGroup.setAttribute("id", "error"); Element noneNode = doc.createElementNS(svgNameSpace, "polyline"); int posXnone = symbolSize / 2; int posYnone = symbolSize / 2; int offsetNoneAmount = symbolSize / 2; noneNode.setAttribute("points", (posXnone - offsetNoneAmount) + "," + (posYnone - offsetNoneAmount) + " " + (posXnone + offsetNoneAmount) + "," + (posYnone + offsetNoneAmount) + " " + (posXnone) + "," + (posYnone) + " " + (posXnone - offsetNoneAmount) + "," + (posYnone + offsetNoneAmount) + " " + (posXnone + offsetNoneAmount) + "," + (posYnone - offsetNoneAmount)); noneNode.setAttribute("fill", "none"); noneNode.setAttribute("stroke", "red"); noneNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); noneGroup.appendChild(noneNode); defsNode.appendChild(noneGroup); svgRoot.appendChild(defsNode); return symbolSize; } public String[] listSymbolNames(SVGDocument doc, String svgNameSpace) { // get the symbol list from the dom ArrayList<String> symbolArray = new ArrayList<String>(); Element kinSymbols = doc.getElementById("KinSymbols"); if (kinSymbols == null) { insertSymbols(doc, svgNameSpace); kinSymbols = doc.getElementById("KinSymbols"); } for (Node kinSymbolNode = kinSymbols.getFirstChild(); kinSymbolNode != null; kinSymbolNode = kinSymbolNode.getNextSibling()) { NamedNodeMap attributesMap = kinSymbolNode.getAttributes(); if (attributesMap != null) { Node idNode = attributesMap.getNamedItem("id"); if (idNode != null) { symbolArray.add(idNode.getNodeValue()); } } } return symbolArray.toArray(new String[]{}); } public void clearEntityLocations(UniqueIdentifier[] selectedIdentifiers) { for (UniqueIdentifier currentIdentifier : selectedIdentifiers) { entityPositions.remove(currentIdentifier); } } public UniqueIdentifier getClosestEntity(float[] locationArray, int maximumDistance, ArrayList<UniqueIdentifier> excludeIdentifiers) { double closestDistance = -1; UniqueIdentifier closestIdentifier = null; for (Entry<UniqueIdentifier, float[]> currentEntry : entityPositions.entrySet()) { if (!excludeIdentifiers.contains(currentEntry.getKey())) { float hDistance = locationArray[0] - currentEntry.getValue()[0]; float vDistance = locationArray[1] - currentEntry.getValue()[1]; double entityDistance = Math.sqrt(hDistance * hDistance + vDistance * vDistance); if (closestIdentifier == null) { closestDistance = entityDistance; closestIdentifier = currentEntry.getKey(); } if (entityDistance < closestDistance) { closestDistance = entityDistance; closestIdentifier = currentEntry.getKey(); } } } // System.out.println("closestDistance: " + closestDistance); if (maximumDistance < closestDistance) { return null; } return closestIdentifier; } public float[] getEntityLocation(UniqueIdentifier entityId) { float[] returnLoc = entityPositions.get(entityId); float xPos = returnLoc[0] + (symbolSize / 2); float yPos = returnLoc[1] + (symbolSize / 2); return new float[]{xPos, yPos}; } public float[] getAverageParentLocation(UniqueIdentifier entityId) { // note that getAverageParentLocation(EntityData entityData) must be called at least once for each entity to poputlate parentIdentifiers Float maxY = null; float averageX = 0; int parentCount = 0; for (UniqueIdentifier parentIdentifier : parentIdentifiers.get(entityId)) { float[] parentLoc = getEntityLocation(parentIdentifier); if (maxY == null) { maxY = parentLoc[1]; } else { maxY = (maxY >= parentLoc[1]) ? maxY : parentLoc[1]; } averageX += parentLoc[0]; parentCount++; } averageX = averageX / parentCount; if (maxY == null) { return null; } else { return new float[]{averageX, maxY}; } } public float[] getAverageParentLocation(EntityData entityData) { HashSet<UniqueIdentifier> identifierSet = new HashSet<UniqueIdentifier>(); for (EntityRelation entityRelation : entityData.getVisiblyRelateNodes()) { if (entityRelation.relationType == RelationType.ancestor) { identifierSet.add(entityRelation.alterUniqueIdentifier); } } parentIdentifiers.put(entityData.getUniqueIdentifier(), identifierSet); return getAverageParentLocation(entityData.getUniqueIdentifier()); } // public float[] getEntityLocation(SVGDocument doc, String entityId) { // Element entitySymbol = doc.getElementById(entityId + "symbol"); //// Element entitySymbol = doc.getElementById(entityId); // the sybol group node // if (entitySymbol != null) { // SVGRect bbox = ((SVGLocatable) entitySymbol).getBBox(); // SVGMatrix sVGMatrix = ((SVGLocatable) entitySymbol).getCTM(); //// System.out.println("getA: " + sVGMatrix.getA()); //// System.out.println("getB: " + sVGMatrix.getB()); //// System.out.println("getC: " + sVGMatrix.getC()); //// System.out.println("getD: " + sVGMatrix.getD()); //// System.out.println("getE: " + sVGMatrix.getE()); //// System.out.println("getF: " + sVGMatrix.getF()); // //// System.out.println("bbox X: " + bbox.getX()); //// System.out.println("bbox Y: " + bbox.getY()); //// System.out.println("bbox W: " + bbox.getWidth()); //// System.out.println("bbox H: " + bbox.getHeight()); // return new float[]{sVGMatrix.getE() + bbox.getWidth() / 2, sVGMatrix.getF() + bbox.getHeight() / 2}; //// bbox.setX(sVGMatrix.getE()); //// bbox.setY(sVGMatrix.getF()); //// return bbox; // } else { // return null; // } // } public float[] moveEntity(GraphPanel graphPanel, UniqueIdentifier entityId, float shiftXfloat, float shiftYfloat, boolean snapToGrid, boolean allRealtionsSelected) { Element entitySymbol = graphPanel.doc.getElementById(entityId.getAttributeIdentifier()); Element highlightGroup = null; if (entityId.isGraphicsIdentifier()) { highlightGroup = graphPanel.doc.getElementById("highlight_" + entityId.getAttributeIdentifier()); } float remainderAfterSnapX = 0; float remainderAfterSnapY = 0; double scaleFactor = 1; double shiftXscaled; double shiftYscaled; if (entitySymbol != null) { boolean allowYshift = entitySymbol.getLocalName().equals("text"); if (allRealtionsSelected) { // if all the visible relations are selected then allow y shift allowYshift = true; } // todo: Ticket #1064 when the zig zag lines are done the y shift can be allowed allowYshift = true; AffineTransform affineTransform = graphPanel.svgCanvas.getRenderingTransform(); scaleFactor = affineTransform.getScaleX(); // the drawing should be proportional so only using X is adequate here shiftXscaled = shiftXfloat / scaleFactor; shiftYscaled = shiftYfloat / scaleFactor; //// sVGMatrix.setE(sVGMatrix.getE() + shiftX); //// sVGMatrix.setE(sVGMatrix.getF() + shiftY); //// System.out.println("shiftX: " + shiftX); // float updatedPositionX = sVGMatrix.getE() + shiftX; // float updatedPositionY = sVGMatrix.getF(); float[] entityPosition = entityPositions.get(entityId); float updatedPositionX = (float) (entityPosition[0] + shiftXscaled); float updatedPositionY = entityPosition[1]; if (allowYshift) { updatedPositionY = (float) (updatedPositionY + shiftYscaled); } // System.out.println("updatedPosition: " + updatedPositionX + " : " + updatedPositionY + " : " + shiftX + " : " + shiftY); if (snapToGrid) { double updatedSnapPositionX = Math.round(updatedPositionX / 50) * 50; // limit movement to the grid updatedPositionX = (float) updatedSnapPositionX; if (allowYshift) { float updatedSnapPositionY = Math.round(updatedPositionY / 50) * 50; // limit movement to the grid updatedPositionY = updatedSnapPositionY; } } else { updatedPositionX = (int) updatedPositionX; // prevent uncorrectable but visible variations in the position of entities to each other if (allowYshift) { updatedPositionY = (int) updatedPositionY; } } // AffineTransform at = new AffineTransform(); // at.translate(updatedPositionX, updatedPositionY); //// at.scale(scale, scale); // at.concatenate(graphPanel.svgCanvas.getRenderingTransform()); // svgCanvas.setRenderingTransform(at); // System.out.println("updatedPosition after snap: " + updatedPosition); // graphPanel.dataStoreSvg.graphData.setEntityLocation(entityId, updatedPositionX, updatedPositionY); // entityPositions.put(entityId, new float[]{(float) at.getTranslateX(), (float) at.getTranslateY()}); // ((Element) entitySymbol).setAttribute("transform", "translate(" + String.valueOf(at.getTranslateX()) + ", " + String.valueOf(at.getTranslateY()) + ")"); entityPositions.put(entityId, new float[]{updatedPositionX, updatedPositionY}); final String translateString = "translate(" + String.valueOf(updatedPositionX) + ", " + String.valueOf(updatedPositionY) + ")"; ((Element) entitySymbol).setAttribute("transform", translateString); if (highlightGroup != null) { highlightGroup.setAttribute("transform", translateString); } float distanceXmoved = ((float) ((updatedPositionX - entityPosition[0]) * scaleFactor)); float distanceYmoved = ((float) ((updatedPositionY - entityPosition[1]) * scaleFactor)); remainderAfterSnapX = shiftXfloat - distanceXmoved; remainderAfterSnapY = shiftYfloat - distanceYmoved; // ((Element) entitySymbol).setAttribute("transform", "translate(" + String.valueOf(sVGMatrix.getE() + shiftX) + ", " + (sVGMatrix.getF() + shiftY) + ")"); } // System.out.println("remainderAfterSnap: " + remainderAfterSnap); return new float[]{remainderAfterSnapX, remainderAfterSnapY}; } private int addTextLabel(GraphPanel graphPanel, Element groupNode, String currentTextLable, String textColour, int textSpanCounter) { int lineSpacing = 15; Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("x", Double.toString(symbolSize * 1.5)); labelText.setAttribute("y", Integer.toString(textSpanCounter)); labelText.setAttribute("fill", textColour); labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "14"); Text textNode = graphPanel.doc.createTextNode(currentTextLable); labelText.appendChild(textNode); textSpanCounter += lineSpacing; groupNode.appendChild(labelText); return textSpanCounter; } protected Element createEntitySymbol(GraphPanel graphPanel, EntityData currentNode) { Element groupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); groupNode.setAttribute("id", currentNode.getUniqueIdentifier().getAttributeIdentifier()); groupNode.setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:path", currentNode.getEntityPath()); // the kin type strings are stored here so that on selection in the graph the add kin term panel can be pre populatedwith the kin type strings of the selection groupNode.setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:kintype", currentNode.getKinTypeString()); // counterTest++; Element symbolNode; String symbolType = currentNode.getSymbolType(); if (symbolType == null || symbolType.length() == 0) { symbolType = "error"; } // todo: check that if an entity is already placed in which case do not recreate // todo: do not create a new dom each time but reuse it instead, or due to the need to keep things up to date maybe just store an array of entity locations instead symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "use"); symbolNode.setAttribute("id", currentNode.getUniqueIdentifier().getAttributeIdentifier() + ":symbol"); symbolNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + symbolType); // the xlink: of "xlink:href" is required for some svg viewers to render correctly float[] storedPosition = entityPositions.get(currentNode.getUniqueIdentifier()); if (storedPosition == null) { GuiHelper.linorgBugCatcher.logError(new Exception("No storedPosition found for: " + currentNode.getUniqueIdentifier().getAttributeIdentifier())); storedPosition = new float[]{0, 0}; // todo: it looks like the stored positon can be null // throw new Exception("Entity position should have been set in the graph sorter"); // // loop through the filled locations and move to the right or left if not empty required // // todo: check the related nodes and average their positions then check to see if it is free and insert the node there // boolean positionFree = false; // float preferedX = currentNode.getxPos(); // while (!positionFree) { // storedPosition = new Float[]{preferedX * hSpacing + hSpacing - symbolSize / 2.0f, // currentNode.getyPos() * vSpacing + vSpacing - symbolSize / 2.0f}; // if (entityPositions.isEmpty()) { // break; // } // for (Float[] currentPosition : entityPositions.values()) { // positionFree = !currentPosition[0].equals(storedPosition[0]) || !currentPosition[1].equals(storedPosition[1]); // if (!positionFree) { // break; // } // } // preferedX++; // } entityPositions.put(currentNode.getUniqueIdentifier(), storedPosition); } else { //// // prevent the y position being changed // storedPosition[1] = currentNode.getyPos() * vSpacing + vSpacing - symbolSize / 2.0f; } // todo: resolve the null pointer on first run with transient nodes (last test on this did not get a null pointer so maybe it is resolved) groupNode.setAttribute("transform", "translate(" + Float.toString(storedPosition[0]) + ", " + Float.toString(storedPosition[1]) + ")"); if (currentNode.isEgo) { symbolNode.setAttribute("fill", "black"); } else { symbolNode.setAttribute("fill", "white"); } symbolNode.setAttribute("stroke", "black"); symbolNode.setAttribute("stroke-width", "2"); groupNode.appendChild(symbolNode); ////////////////////////////// tspan method appears to fail in batik rendering process unless saved and reloaded //////////////////////////////////////////////// // Element labelText = doc.createElementNS(svgNS, "text"); //// labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2)); //// labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2)); // labelText.setAttribute("fill", "black"); // labelText.setAttribute("fill-opacity", "1"); // labelText.setAttribute("stroke-width", "0"); // labelText.setAttribute("font-size", "14px"); //// labelText.setAttribute("text-anchor", "end"); //// labelText.setAttribute("style", "font-size:14px;text-anchor:end;fill:black;fill-opacity:1"); // //labelText.setNodeValue(currentChild.toString()); // // //String textWithUni = "\u0041"; // int textSpanCounter = 0; // int lineSpacing = 10; // for (String currentTextLable : currentNode.getLabel()) { // Text textNode = doc.createTextNode(currentTextLable); // Element tspanElement = doc.createElement("tspan"); // tspanElement.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2)); // tspanElement.setAttribute("y", Integer.toString((currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + textSpanCounter)); //// tspanElement.setAttribute("y", Integer.toString(textSpanCounter * lineSpacing)); // tspanElement.appendChild(textNode); // labelText.appendChild(tspanElement); // textSpanCounter += lineSpacing; // } // groupNode.appendChild(labelText); ////////////////////////////// end tspan method appears to fail in batik rendering process //////////////////////////////////////////////// ////////////////////////////// alternate method //////////////////////////////////////////////// ArrayList<String> labelList = new ArrayList<String>(); if (graphPanel.dataStoreSvg.showLabels) { labelList.addAll(Arrays.asList(currentNode.getLabel())); } if (graphPanel.dataStoreSvg.showKinTypeLabels) { labelList.addAll(Arrays.asList(currentNode.getKinTypeStringArray())); } // if (graphPanel.dataStoreSvg.showKinTermLabels) { // labelList.addAll(Arrays.asList(currentNode.getKinTermStrings())); // } // todo: add the user specified id as a label // todo: this method has the draw back that the text is not selectable as a block int textSpanCounter = 0; if (currentNode.metadataRequiresSave) { textSpanCounter = addTextLabel(graphPanel, groupNode, "modified", "red", textSpanCounter); } for (String currentTextLable : labelList) { textSpanCounter = addTextLabel(graphPanel, groupNode, currentTextLable, "black", textSpanCounter); } for (GraphLabel currentTextLable : currentNode.getKinTermStrings()) { textSpanCounter = addTextLabel(graphPanel, groupNode, currentTextLable.getLabelString(), currentTextLable.getColourString(), textSpanCounter); } // add the date of birth/death string String dateString = ""; Date dob = currentNode.getDateOfBirth(); Date dod = currentNode.getDateOfDeath(); if (dob != null) { // todo: the date format should probably be user defined rather than assuming that the system prefs are correct dateString += DateFormat.getDateInstance().format(dob); } if (dod != null) { dateString += " - " + DateFormat.getDateInstance().format(dod); } if (dateString.length() > 0) { textSpanCounter = addTextLabel(graphPanel, groupNode, dateString, "black", textSpanCounter); } // end date of birth/death label int linkCounter = 0; if (graphPanel.dataStoreSvg.showArchiveLinks && currentNode.archiveLinkArray != null) { // loop through the archive links and optionaly add href tags for each linked archive data <a xlink:href="http://www.mpi.nl/imdi-archive-link" target="_blank"></a> Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("x", Double.toString(symbolSize * 1.5)); labelText.setAttribute("y", Integer.toString(textSpanCounter)); labelText.setAttribute("fill", "black"); labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "14"); Text textNode = graphPanel.doc.createTextNode("archive ref: "); labelText.appendChild(textNode); for (URI linkURI : currentNode.archiveLinkArray) { linkCounter++; Element labelTagA = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "a"); labelTagA.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", linkURI.toASCIIString()); labelTagA.setAttribute("target", "_blank"); if (linkCounter == 1) { labelTagA.appendChild(graphPanel.doc.createTextNode("" + linkCounter)); } else { labelTagA.appendChild(graphPanel.doc.createTextNode(", " + linkCounter)); } labelText.appendChild(labelTagA); } groupNode.appendChild(labelText); // textSpanCounter += lineSpacing; } ////////////////////////////// end alternate method //////////////////////////////////////////////// ((EventTarget) groupNode).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); // todo: use capture (currently false) could be useful for the mouse events return groupNode; } }
desktop/src/main/java/nl/mpi/kinnate/svg/EntitySvg.java
package nl.mpi.kinnate.svg; import java.awt.geom.AffineTransform; import java.net.URI; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.kinnate.kindata.DataTypes.RelationType; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.kindata.GraphLabel; import nl.mpi.kinnate.uniqueidentifiers.IdentifierException; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.w3c.dom.svg.SVGDocument; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.events.EventTarget; /** * Document : EntitySvg * Created on : Mar 9, 2011, 3:20:56 PM * Author : Peter Withers */ public class EntitySvg { protected HashMap<UniqueIdentifier, float[]> entityPositions = new HashMap<UniqueIdentifier, float[]>(); private HashMap<UniqueIdentifier, HashSet<UniqueIdentifier>> parentIdentifiers = new HashMap<UniqueIdentifier, HashSet<UniqueIdentifier>>(); private int symbolSize = 15; static protected int strokeWidth = 2; public void readEntityPositions(Node entityGroup) { // read the entity positions from the existing dom // this now replaces the position values in the entity data and the entity position is now stored in the svg entity visual not the entity data if (entityGroup != null) { for (Node entityNode = entityGroup.getFirstChild(); entityNode != null; entityNode = entityNode.getNextSibling()) { try { NamedNodeMap nodeMap = entityNode.getAttributes(); if (nodeMap != null) { Node idNode = nodeMap.getNamedItem("id"); Node transformNode = nodeMap.getNamedItem("transform"); if (idNode != null && transformNode != null) { UniqueIdentifier entityId = new UniqueIdentifier(idNode.getNodeValue()); //transform="translate(300.0, 192.5)" // because the svg dom has not been rendered we cannot get any of the screen data, so we must parse the transform tag String transformString = transformNode.getNodeValue(); transformString = transformString.replaceAll("\\s", ""); transformString = transformString.replace("translate(", ""); transformString = transformString.replace(")", ""); String[] stringPos = transformString.split(","); // System.out.println("entityId: " + entityId); // System.out.println("transformString: " + transformString); entityPositions.put(entityId, new float[]{Float.parseFloat(stringPos[0]), Float.parseFloat(stringPos[1])}); // SVGRect bbox = ((SVGLocatable) entityNode).getBBox(); // SVGMatrix sVGMatrix = ((SVGLocatable) entityNode).getCTM(); // System.out.println("getE: " + sVGMatrix.getE()); // System.out.println("getF: " + sVGMatrix.getF()); //// System.out.println("bbox X: " + bbox.getX()); //// System.out.println("bbox Y: " + bbox.getY()); //// System.out.println("bbox W: " + bbox.getWidth()); //// System.out.println("bbox H: " + bbox.getHeight()); // new float[]{sVGMatrix.getE() + bbox.getWidth() / 2, sVGMatrix.getF() + bbox.getHeight() / 2}; } } } catch (IdentifierException exception) { // GuiHelper.linorgBugCatcher.logError(exception); ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to read an entity position, layout might not be preserved", "Restore Layout"); } } } } public int insertSymbols(SVGDocument doc, String svgNameSpace) { Element svgRoot = doc.getDocumentElement(); Element defsNode = doc.createElementNS(svgNameSpace, "defs"); defsNode.setAttribute("id", "KinSymbols"); // add the circle symbol Element circleGroup = doc.createElementNS(svgNameSpace, "g"); circleGroup.setAttribute("id", "circle"); Element circleNode = doc.createElementNS(svgNameSpace, "circle"); circleNode.setAttribute("cx", Integer.toString(symbolSize / 2)); circleNode.setAttribute("cy", Integer.toString(symbolSize / 2)); circleNode.setAttribute("r", Integer.toString((symbolSize - strokeWidth) / 2)); // circleNode.setAttribute("height", Integer.toString(symbolSize - (strokeWidth * 3))); circleNode.setAttribute("stroke", "black"); circleNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); circleGroup.appendChild(circleNode); defsNode.appendChild(circleGroup); // add the square symbol Element squareGroup = doc.createElementNS(svgNameSpace, "g"); squareGroup.setAttribute("id", "square"); Element squareNode = doc.createElementNS(svgNameSpace, "rect"); squareNode.setAttribute("x", Integer.toString(strokeWidth)); squareNode.setAttribute("y", Integer.toString(strokeWidth)); squareNode.setAttribute("width", Integer.toString(symbolSize - strokeWidth * 2)); squareNode.setAttribute("height", Integer.toString(symbolSize - strokeWidth * 2)); squareNode.setAttribute("stroke", "black"); squareNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); squareGroup.appendChild(squareNode); defsNode.appendChild(squareGroup); svgRoot.appendChild(defsNode); // add the resource symbol Element resourceGroup = doc.createElementNS(svgNameSpace, "g"); resourceGroup.setAttribute("id", "square45"); Element resourceNode = doc.createElementNS(svgNameSpace, "rect"); resourceNode.setAttribute("x", "0"); resourceNode.setAttribute("y", "0"); resourceNode.setAttribute("transform", "rotate(-45 " + Integer.toString(symbolSize / 2) + " " + Integer.toString(symbolSize / 2) + ")"); resourceNode.setAttribute("width", Integer.toString(symbolSize)); resourceNode.setAttribute("height", Integer.toString(symbolSize)); resourceNode.setAttribute("stroke", "black"); resourceNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); resourceGroup.appendChild(resourceNode); defsNode.appendChild(resourceGroup); svgRoot.appendChild(defsNode); // add the rhombus symbol Element rhombusGroup = doc.createElementNS(svgNameSpace, "g"); rhombusGroup.setAttribute("id", "rhombus"); Element rhombusNode = doc.createElementNS(svgNameSpace, "rect"); rhombusNode.setAttribute("x", "0"); rhombusNode.setAttribute("y", "0"); rhombusNode.setAttribute("transform", "scale(1,2), rotate(-45 " + Integer.toString(symbolSize / 2) + " " + Integer.toString(symbolSize / 2) + ")"); rhombusNode.setAttribute("width", Integer.toString(symbolSize)); rhombusNode.setAttribute("height", Integer.toString(symbolSize)); rhombusNode.setAttribute("stroke", "black"); rhombusNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); rhombusGroup.appendChild(rhombusNode); defsNode.appendChild(rhombusGroup); svgRoot.appendChild(defsNode); // add the union symbol Element unionGroup = doc.createElementNS(svgNameSpace, "g"); unionGroup.setAttribute("id", "union"); Element upperNode = doc.createElementNS(svgNameSpace, "line"); Element lowerNode = doc.createElementNS(svgNameSpace, "line"); upperNode.setAttribute("x1", Integer.toString(0)); upperNode.setAttribute("y1", Integer.toString((symbolSize / 6))); upperNode.setAttribute("x2", Integer.toString(symbolSize)); upperNode.setAttribute("y2", Integer.toString((symbolSize / 6))); upperNode.setAttribute("stroke-width", Integer.toString(symbolSize / 3)); upperNode.setAttribute("stroke", "black"); lowerNode.setAttribute("x1", Integer.toString(0)); lowerNode.setAttribute("y1", Integer.toString(symbolSize - (symbolSize / 6))); lowerNode.setAttribute("x2", Integer.toString(symbolSize)); lowerNode.setAttribute("y2", Integer.toString(symbolSize - (symbolSize / 6))); lowerNode.setAttribute("stroke-width", Integer.toString(symbolSize / 3)); lowerNode.setAttribute("stroke", "black"); // add a background for selecting and draging Element backgroundNode = doc.createElementNS(svgNameSpace, "rect"); backgroundNode.setAttribute("x", "0"); backgroundNode.setAttribute("y", "0"); backgroundNode.setAttribute("width", Integer.toString(symbolSize)); backgroundNode.setAttribute("height", Integer.toString(symbolSize)); backgroundNode.setAttribute("stroke", "none"); backgroundNode.setAttribute("fill", "white"); unionGroup.appendChild(backgroundNode); unionGroup.appendChild(upperNode); unionGroup.appendChild(lowerNode); defsNode.appendChild(unionGroup); svgRoot.appendChild(defsNode); // add the triangle symbol Element triangleGroup = doc.createElementNS(svgNameSpace, "g"); triangleGroup.setAttribute("id", "triangle"); Element triangleNode = doc.createElementNS(svgNameSpace, "polygon"); int triangleSize = symbolSize - strokeWidth / 2; int triangleHeight = (int) (Math.sqrt(3) * triangleSize / 2); triangleNode.setAttribute("points", (symbolSize / 2) + "," + strokeWidth / 2 + " " + strokeWidth / 2 + "," + triangleHeight + " " + triangleSize + "," + triangleHeight); triangleNode.setAttribute("stroke", "black"); triangleNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); triangleGroup.appendChild(triangleNode); defsNode.appendChild(triangleGroup); svgRoot.appendChild(defsNode); // add the equals symbol Element equalsGroup = doc.createElementNS(svgNameSpace, "g"); equalsGroup.setAttribute("id", "equals"); Element equalsNode = doc.createElementNS(svgNameSpace, "polyline"); int offsetAmounta = symbolSize / 2; int posXa = 0; int posYa = +symbolSize / 2; equalsNode.setAttribute("points", (posXa + offsetAmounta * 3) + "," + (posYa + offsetAmounta) + " " + (posXa - offsetAmounta) + "," + (posYa + offsetAmounta) + " " + (posXa - offsetAmounta) + "," + (posYa - offsetAmounta) + " " + (posXa + offsetAmounta * 3) + "," + (posYa - offsetAmounta)); equalsNode.setAttribute("fill", "white"); equalsNode.setAttribute("stroke", "black"); equalsNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); equalsGroup.appendChild(equalsNode); defsNode.appendChild(equalsGroup); svgRoot.appendChild(defsNode); // add the cross symbol Element crossGroup = doc.createElementNS(svgNameSpace, "g"); crossGroup.setAttribute("id", "cross"); Element crossNode = doc.createElementNS(svgNameSpace, "polyline"); int posX = symbolSize / 2; int posY = symbolSize / 2; int offsetAmount = symbolSize / 2; crossNode.setAttribute("points", (posX - offsetAmount) + "," + (posY - offsetAmount) + " " + (posX + offsetAmount) + "," + (posY + offsetAmount) + " " + (posX) + "," + (posY) + " " + (posX - offsetAmount) + "," + (posY + offsetAmount) + " " + (posX + offsetAmount) + "," + (posY - offsetAmount)); crossNode.setAttribute("fill", "none"); crossNode.setAttribute("stroke", "black"); crossNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); crossGroup.appendChild(crossNode); defsNode.appendChild(crossGroup); svgRoot.appendChild(defsNode); // add the error symbol Element noneGroup = doc.createElementNS(svgNameSpace, "g"); noneGroup.setAttribute("id", "error"); Element noneNode = doc.createElementNS(svgNameSpace, "polyline"); int posXnone = symbolSize / 2; int posYnone = symbolSize / 2; int offsetNoneAmount = symbolSize / 2; noneNode.setAttribute("points", (posXnone - offsetNoneAmount) + "," + (posYnone - offsetNoneAmount) + " " + (posXnone + offsetNoneAmount) + "," + (posYnone + offsetNoneAmount) + " " + (posXnone) + "," + (posYnone) + " " + (posXnone - offsetNoneAmount) + "," + (posYnone + offsetNoneAmount) + " " + (posXnone + offsetNoneAmount) + "," + (posYnone - offsetNoneAmount)); noneNode.setAttribute("fill", "none"); noneNode.setAttribute("stroke", "red"); noneNode.setAttribute("stroke-width", Integer.toString(strokeWidth)); noneGroup.appendChild(noneNode); defsNode.appendChild(noneGroup); svgRoot.appendChild(defsNode); return symbolSize; } public String[] listSymbolNames(SVGDocument doc, String svgNameSpace) { // get the symbol list from the dom ArrayList<String> symbolArray = new ArrayList<String>(); Element kinSymbols = doc.getElementById("KinSymbols"); if (kinSymbols == null) { insertSymbols(doc, svgNameSpace); kinSymbols = doc.getElementById("KinSymbols"); } for (Node kinSymbolNode = kinSymbols.getFirstChild(); kinSymbolNode != null; kinSymbolNode = kinSymbolNode.getNextSibling()) { NamedNodeMap attributesMap = kinSymbolNode.getAttributes(); if (attributesMap != null) { Node idNode = attributesMap.getNamedItem("id"); if (idNode != null) { symbolArray.add(idNode.getNodeValue()); } } } return symbolArray.toArray(new String[]{}); } public void clearEntityLocations(UniqueIdentifier[] selectedIdentifiers) { for (UniqueIdentifier currentIdentifier : selectedIdentifiers) { entityPositions.remove(currentIdentifier); } } public UniqueIdentifier getClosestEntity(float[] locationArray, int maximumDistance, ArrayList<UniqueIdentifier> excludeIdentifiers) { double closestDistance = -1; UniqueIdentifier closestIdentifier = null; for (Entry<UniqueIdentifier, float[]> currentEntry : entityPositions.entrySet()) { if (!excludeIdentifiers.contains(currentEntry.getKey())) { float hDistance = locationArray[0] - currentEntry.getValue()[0]; float vDistance = locationArray[1] - currentEntry.getValue()[1]; double entityDistance = Math.sqrt(hDistance * hDistance + vDistance * vDistance); if (closestIdentifier == null) { closestDistance = entityDistance; closestIdentifier = currentEntry.getKey(); } if (entityDistance < closestDistance) { closestDistance = entityDistance; closestIdentifier = currentEntry.getKey(); } } } // System.out.println("closestDistance: " + closestDistance); if (maximumDistance < closestDistance) { return null; } return closestIdentifier; } public float[] getEntityLocation(UniqueIdentifier entityId) { float[] returnLoc = entityPositions.get(entityId); float xPos = returnLoc[0] + (symbolSize / 2); float yPos = returnLoc[1] + (symbolSize / 2); return new float[]{xPos, yPos}; } public float[] getAverageParentLocation(UniqueIdentifier entityId) { // note that getAverageParentLocation(EntityData entityData) must be called at least once for each entity to poputlate parentIdentifiers Float minY = null; float averageX = 0; int parentCount = 0; for (UniqueIdentifier parentIdentifier : parentIdentifiers.get(entityId)) { float[] parentLoc = getEntityLocation(parentIdentifier); if (minY == null) { minY = parentLoc[1]; } else { minY = (minY <= parentLoc[1]) ? minY : parentLoc[1]; } averageX += parentLoc[0]; parentCount++; } averageX = averageX / parentCount; if (minY == null) { return null; } else { return new float[]{averageX, minY}; } } public float[] getAverageParentLocation(EntityData entityData) { HashSet<UniqueIdentifier> identifierSet = new HashSet<UniqueIdentifier>(); for (EntityRelation entityRelation : entityData.getVisiblyRelateNodes()) { if (entityRelation.relationType == RelationType.ancestor) { identifierSet.add(entityRelation.alterUniqueIdentifier); } } parentIdentifiers.put(entityData.getUniqueIdentifier(), identifierSet); return getAverageParentLocation(entityData.getUniqueIdentifier()); } // public float[] getEntityLocation(SVGDocument doc, String entityId) { // Element entitySymbol = doc.getElementById(entityId + "symbol"); //// Element entitySymbol = doc.getElementById(entityId); // the sybol group node // if (entitySymbol != null) { // SVGRect bbox = ((SVGLocatable) entitySymbol).getBBox(); // SVGMatrix sVGMatrix = ((SVGLocatable) entitySymbol).getCTM(); //// System.out.println("getA: " + sVGMatrix.getA()); //// System.out.println("getB: " + sVGMatrix.getB()); //// System.out.println("getC: " + sVGMatrix.getC()); //// System.out.println("getD: " + sVGMatrix.getD()); //// System.out.println("getE: " + sVGMatrix.getE()); //// System.out.println("getF: " + sVGMatrix.getF()); // //// System.out.println("bbox X: " + bbox.getX()); //// System.out.println("bbox Y: " + bbox.getY()); //// System.out.println("bbox W: " + bbox.getWidth()); //// System.out.println("bbox H: " + bbox.getHeight()); // return new float[]{sVGMatrix.getE() + bbox.getWidth() / 2, sVGMatrix.getF() + bbox.getHeight() / 2}; //// bbox.setX(sVGMatrix.getE()); //// bbox.setY(sVGMatrix.getF()); //// return bbox; // } else { // return null; // } // } public float[] moveEntity(GraphPanel graphPanel, UniqueIdentifier entityId, float shiftXfloat, float shiftYfloat, boolean snapToGrid, boolean allRealtionsSelected) { Element entitySymbol = graphPanel.doc.getElementById(entityId.getAttributeIdentifier()); Element highlightGroup = null; if (entityId.isGraphicsIdentifier()) { highlightGroup = graphPanel.doc.getElementById("highlight_" + entityId.getAttributeIdentifier()); } float remainderAfterSnapX = 0; float remainderAfterSnapY = 0; double scaleFactor = 1; double shiftXscaled; double shiftYscaled; if (entitySymbol != null) { boolean allowYshift = entitySymbol.getLocalName().equals("text"); if (allRealtionsSelected) { // if all the visible relations are selected then allow y shift allowYshift = true; } // todo: Ticket #1064 when the zig zag lines are done the y shift can be allowed allowYshift = true; AffineTransform affineTransform = graphPanel.svgCanvas.getRenderingTransform(); scaleFactor = affineTransform.getScaleX(); // the drawing should be proportional so only using X is adequate here shiftXscaled = shiftXfloat / scaleFactor; shiftYscaled = shiftYfloat / scaleFactor; //// sVGMatrix.setE(sVGMatrix.getE() + shiftX); //// sVGMatrix.setE(sVGMatrix.getF() + shiftY); //// System.out.println("shiftX: " + shiftX); // float updatedPositionX = sVGMatrix.getE() + shiftX; // float updatedPositionY = sVGMatrix.getF(); float[] entityPosition = entityPositions.get(entityId); float updatedPositionX = (float) (entityPosition[0] + shiftXscaled); float updatedPositionY = entityPosition[1]; if (allowYshift) { updatedPositionY = (float) (updatedPositionY + shiftYscaled); } // System.out.println("updatedPosition: " + updatedPositionX + " : " + updatedPositionY + " : " + shiftX + " : " + shiftY); if (snapToGrid) { double updatedSnapPositionX = Math.round(updatedPositionX / 50) * 50; // limit movement to the grid updatedPositionX = (float) updatedSnapPositionX; if (allowYshift) { float updatedSnapPositionY = Math.round(updatedPositionY / 50) * 50; // limit movement to the grid updatedPositionY = updatedSnapPositionY; } } else { updatedPositionX = (int) updatedPositionX; // prevent uncorrectable but visible variations in the position of entities to each other if (allowYshift) { updatedPositionY = (int) updatedPositionY; } } // AffineTransform at = new AffineTransform(); // at.translate(updatedPositionX, updatedPositionY); //// at.scale(scale, scale); // at.concatenate(graphPanel.svgCanvas.getRenderingTransform()); // svgCanvas.setRenderingTransform(at); // System.out.println("updatedPosition after snap: " + updatedPosition); // graphPanel.dataStoreSvg.graphData.setEntityLocation(entityId, updatedPositionX, updatedPositionY); // entityPositions.put(entityId, new float[]{(float) at.getTranslateX(), (float) at.getTranslateY()}); // ((Element) entitySymbol).setAttribute("transform", "translate(" + String.valueOf(at.getTranslateX()) + ", " + String.valueOf(at.getTranslateY()) + ")"); entityPositions.put(entityId, new float[]{updatedPositionX, updatedPositionY}); final String translateString = "translate(" + String.valueOf(updatedPositionX) + ", " + String.valueOf(updatedPositionY) + ")"; ((Element) entitySymbol).setAttribute("transform", translateString); if (highlightGroup != null) { highlightGroup.setAttribute("transform", translateString); } float distanceXmoved = ((float) ((updatedPositionX - entityPosition[0]) * scaleFactor)); float distanceYmoved = ((float) ((updatedPositionY - entityPosition[1]) * scaleFactor)); remainderAfterSnapX = shiftXfloat - distanceXmoved; remainderAfterSnapY = shiftYfloat - distanceYmoved; // ((Element) entitySymbol).setAttribute("transform", "translate(" + String.valueOf(sVGMatrix.getE() + shiftX) + ", " + (sVGMatrix.getF() + shiftY) + ")"); } // System.out.println("remainderAfterSnap: " + remainderAfterSnap); return new float[]{remainderAfterSnapX, remainderAfterSnapY}; } private int addTextLabel(GraphPanel graphPanel, Element groupNode, String currentTextLable, String textColour, int textSpanCounter) { int lineSpacing = 15; Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("x", Double.toString(symbolSize * 1.5)); labelText.setAttribute("y", Integer.toString(textSpanCounter)); labelText.setAttribute("fill", textColour); labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "14"); Text textNode = graphPanel.doc.createTextNode(currentTextLable); labelText.appendChild(textNode); textSpanCounter += lineSpacing; groupNode.appendChild(labelText); return textSpanCounter; } protected Element createEntitySymbol(GraphPanel graphPanel, EntityData currentNode) { Element groupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); groupNode.setAttribute("id", currentNode.getUniqueIdentifier().getAttributeIdentifier()); groupNode.setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:path", currentNode.getEntityPath()); // the kin type strings are stored here so that on selection in the graph the add kin term panel can be pre populatedwith the kin type strings of the selection groupNode.setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:kintype", currentNode.getKinTypeString()); // counterTest++; Element symbolNode; String symbolType = currentNode.getSymbolType(); if (symbolType == null || symbolType.length() == 0) { symbolType = "error"; } // todo: check that if an entity is already placed in which case do not recreate // todo: do not create a new dom each time but reuse it instead, or due to the need to keep things up to date maybe just store an array of entity locations instead symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "use"); symbolNode.setAttribute("id", currentNode.getUniqueIdentifier().getAttributeIdentifier() + ":symbol"); symbolNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + symbolType); // the xlink: of "xlink:href" is required for some svg viewers to render correctly float[] storedPosition = entityPositions.get(currentNode.getUniqueIdentifier()); if (storedPosition == null) { GuiHelper.linorgBugCatcher.logError(new Exception("No storedPosition found for: " + currentNode.getUniqueIdentifier().getAttributeIdentifier())); storedPosition = new float[]{0, 0}; // todo: it looks like the stored positon can be null // throw new Exception("Entity position should have been set in the graph sorter"); // // loop through the filled locations and move to the right or left if not empty required // // todo: check the related nodes and average their positions then check to see if it is free and insert the node there // boolean positionFree = false; // float preferedX = currentNode.getxPos(); // while (!positionFree) { // storedPosition = new Float[]{preferedX * hSpacing + hSpacing - symbolSize / 2.0f, // currentNode.getyPos() * vSpacing + vSpacing - symbolSize / 2.0f}; // if (entityPositions.isEmpty()) { // break; // } // for (Float[] currentPosition : entityPositions.values()) { // positionFree = !currentPosition[0].equals(storedPosition[0]) || !currentPosition[1].equals(storedPosition[1]); // if (!positionFree) { // break; // } // } // preferedX++; // } entityPositions.put(currentNode.getUniqueIdentifier(), storedPosition); } else { //// // prevent the y position being changed // storedPosition[1] = currentNode.getyPos() * vSpacing + vSpacing - symbolSize / 2.0f; } // todo: resolve the null pointer on first run with transient nodes (last test on this did not get a null pointer so maybe it is resolved) groupNode.setAttribute("transform", "translate(" + Float.toString(storedPosition[0]) + ", " + Float.toString(storedPosition[1]) + ")"); if (currentNode.isEgo) { symbolNode.setAttribute("fill", "black"); } else { symbolNode.setAttribute("fill", "white"); } symbolNode.setAttribute("stroke", "black"); symbolNode.setAttribute("stroke-width", "2"); groupNode.appendChild(symbolNode); ////////////////////////////// tspan method appears to fail in batik rendering process unless saved and reloaded //////////////////////////////////////////////// // Element labelText = doc.createElementNS(svgNS, "text"); //// labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2)); //// labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2)); // labelText.setAttribute("fill", "black"); // labelText.setAttribute("fill-opacity", "1"); // labelText.setAttribute("stroke-width", "0"); // labelText.setAttribute("font-size", "14px"); //// labelText.setAttribute("text-anchor", "end"); //// labelText.setAttribute("style", "font-size:14px;text-anchor:end;fill:black;fill-opacity:1"); // //labelText.setNodeValue(currentChild.toString()); // // //String textWithUni = "\u0041"; // int textSpanCounter = 0; // int lineSpacing = 10; // for (String currentTextLable : currentNode.getLabel()) { // Text textNode = doc.createTextNode(currentTextLable); // Element tspanElement = doc.createElement("tspan"); // tspanElement.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2)); // tspanElement.setAttribute("y", Integer.toString((currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + textSpanCounter)); //// tspanElement.setAttribute("y", Integer.toString(textSpanCounter * lineSpacing)); // tspanElement.appendChild(textNode); // labelText.appendChild(tspanElement); // textSpanCounter += lineSpacing; // } // groupNode.appendChild(labelText); ////////////////////////////// end tspan method appears to fail in batik rendering process //////////////////////////////////////////////// ////////////////////////////// alternate method //////////////////////////////////////////////// ArrayList<String> labelList = new ArrayList<String>(); if (graphPanel.dataStoreSvg.showLabels) { labelList.addAll(Arrays.asList(currentNode.getLabel())); } if (graphPanel.dataStoreSvg.showKinTypeLabels) { labelList.addAll(Arrays.asList(currentNode.getKinTypeStringArray())); } // if (graphPanel.dataStoreSvg.showKinTermLabels) { // labelList.addAll(Arrays.asList(currentNode.getKinTermStrings())); // } // todo: add the user specified id as a label // todo: this method has the draw back that the text is not selectable as a block int textSpanCounter = 0; if (currentNode.metadataRequiresSave) { textSpanCounter = addTextLabel(graphPanel, groupNode, "modified", "red", textSpanCounter); } for (String currentTextLable : labelList) { textSpanCounter = addTextLabel(graphPanel, groupNode, currentTextLable, "black", textSpanCounter); } for (GraphLabel currentTextLable : currentNode.getKinTermStrings()) { textSpanCounter = addTextLabel(graphPanel, groupNode, currentTextLable.getLabelString(), currentTextLable.getColourString(), textSpanCounter); } // add the date of birth/death string String dateString = ""; Date dob = currentNode.getDateOfBirth(); Date dod = currentNode.getDateOfDeath(); if (dob != null) { // todo: the date format should probably be user defined rather than assuming that the system prefs are correct dateString += DateFormat.getDateInstance().format(dob); } if (dod != null) { dateString += " - " + DateFormat.getDateInstance().format(dod); } if (dateString.length() > 0) { textSpanCounter = addTextLabel(graphPanel, groupNode, dateString, "black", textSpanCounter); } // end date of birth/death label int linkCounter = 0; if (graphPanel.dataStoreSvg.showArchiveLinks && currentNode.archiveLinkArray != null) { // loop through the archive links and optionaly add href tags for each linked archive data <a xlink:href="http://www.mpi.nl/imdi-archive-link" target="_blank"></a> Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("x", Double.toString(symbolSize * 1.5)); labelText.setAttribute("y", Integer.toString(textSpanCounter)); labelText.setAttribute("fill", "black"); labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "14"); Text textNode = graphPanel.doc.createTextNode("archive ref: "); labelText.appendChild(textNode); for (URI linkURI : currentNode.archiveLinkArray) { linkCounter++; Element labelTagA = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "a"); labelTagA.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", linkURI.toASCIIString()); labelTagA.setAttribute("target", "_blank"); if (linkCounter == 1) { labelTagA.appendChild(graphPanel.doc.createTextNode("" + linkCounter)); } else { labelTagA.appendChild(graphPanel.doc.createTextNode(", " + linkCounter)); } labelText.appendChild(labelTagA); } groupNode.appendChild(labelText); // textSpanCounter += lineSpacing; } ////////////////////////////// end alternate method //////////////////////////////////////////////// ((EventTarget) groupNode).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); // todo: use capture (currently false) could be useful for the mouse events return groupNode; } }
Incorporated the use of clarin profile xml files and the requisite transform into kinship xml.
desktop/src/main/java/nl/mpi/kinnate/svg/EntitySvg.java
Incorporated the use of clarin profile xml files and the requisite transform into kinship xml.
<ide><path>esktop/src/main/java/nl/mpi/kinnate/svg/EntitySvg.java <ide> <ide> public float[] getAverageParentLocation(UniqueIdentifier entityId) { <ide> // note that getAverageParentLocation(EntityData entityData) must be called at least once for each entity to poputlate parentIdentifiers <del> Float minY = null; <add> Float maxY = null; <ide> float averageX = 0; <ide> int parentCount = 0; <ide> for (UniqueIdentifier parentIdentifier : parentIdentifiers.get(entityId)) { <ide> float[] parentLoc = getEntityLocation(parentIdentifier); <del> if (minY == null) { <del> minY = parentLoc[1]; <add> if (maxY == null) { <add> maxY = parentLoc[1]; <ide> } else { <del> minY = (minY <= parentLoc[1]) ? minY : parentLoc[1]; <add> maxY = (maxY >= parentLoc[1]) ? maxY : parentLoc[1]; <ide> } <ide> averageX += parentLoc[0]; <ide> parentCount++; <ide> } <ide> averageX = averageX / parentCount; <del> if (minY == null) { <add> if (maxY == null) { <ide> return null; <ide> } else { <del> return new float[]{averageX, minY}; <add> return new float[]{averageX, maxY}; <ide> } <ide> } <ide>
JavaScript
mit
ae5596d647a79e7bd3acb2c5e1fb24ea65366f0d
0
nqdy666/grunt-contrib-cssmin,fracmak/grunt-contrib-cssmin,MoLow/grunt-contrib-cssmin,bhamodi/grunt-contrib-cssmin,gruntjs/grunt-contrib-cssmin
'use strict'; var path = require('path'); var CleanCSS = require('clean-css'); var chalk = require('chalk'); var maxmin = require('maxmin'); module.exports = function (grunt) { var getAvailableFiles = function (filesArray) { return filesArray.filter(function (filepath) { if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file ' + chalk.cyan(filepath) + ' not found'); return false; } return true; }); }; grunt.registerMultiTask('cssmin', 'Minify CSS', function () { var created = { maps: 0, files: 0 }; var size = { before: 0, after: 0 }; this.files.forEach(function (file) { var options = this.options({ rebase: false, report: 'min', sourceMap: false }); var availableFiles = getAvailableFiles(file.src); var compiled = ''; options.target = file.dest; options.relativeTo = path.dirname(availableFiles[0]); try { compiled = new CleanCSS(options).minify(availableFiles); if (compiled.errors && compiled.errors.length) { throw compiled.errors.join('\n'); } } catch (err) { grunt.log.error(err); grunt.warn('CSS minification failed at ' + availableFiles + '.'); } var compiledCssString = compiled.styles; var unCompiledCssString = availableFiles.map(function (file) { return grunt.file.read(file); }).join(''); size.before += unCompiledCssString.length; if (options.sourceMap) { compiledCssString += '\n' + '/*# sourceMappingURL=' + path.basename(file.dest) + '.map */'; grunt.file.write(file.dest + '.map', compiled.sourceMap.toString()); created.maps++; grunt.verbose.writeln('File ' + chalk.cyan(file.dest + '.map') + ' created'); } grunt.file.write(file.dest, compiledCssString); created.files++; size.after += compiledCssString.length; grunt.verbose.writeln('File ' + chalk.cyan(file.dest) + ' created ' + chalk.dim(maxmin(unCompiledCssString, compiledCssString, options.report === 'gzip'))); }, this); if (created.maps > 0) { grunt.log.ok(created.maps + ' source' + grunt.util.pluralize(this.files.length, 'map/maps') + ' created.'); } if (created.files > 0) { grunt.log.ok(created.files + ' ' + grunt.util.pluralize(this.files.length, 'file/files') + ' created. ' + chalk.dim(maxmin(size.before, size.after))); } else { grunt.log.warn('No files created.'); } }); };
tasks/cssmin.js
'use strict'; var path = require('path'); var CleanCSS = require('clean-css'); var chalk = require('chalk'); var maxmin = require('maxmin'); module.exports = function (grunt) { var getAvailableFiles = function (filesArray) { return filesArray.filter(function (filepath) { if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file ' + chalk.cyan(filepath) + ' not found'); return false; } return true; }); }; grunt.registerMultiTask('cssmin', 'Minify CSS', function () { var created = { maps: 0, files: 0 }; var size = { before: 0, after: 0 }; this.files.forEach(function (file) { var options = this.options({ rebase: false, report: 'min', sourceMap: false }); var availableFiles = getAvailableFiles(file.src); var compiled = ''; options.target = file.dest; options.relativeTo = path.dirname(availableFiles[0]); try { compiled = new CleanCSS(options).minify(availableFiles); } catch (err) { grunt.log.error(err); grunt.warn('CSS minification failed at ' + availableFiles + '.'); } var compiledCssString = compiled.styles; var unCompiledCssString = availableFiles.map(function (file) { return grunt.file.read(file); }).join(''); size.before += unCompiledCssString.length; if (options.sourceMap) { compiledCssString += '\n' + '/*# sourceMappingURL=' + path.basename(file.dest) + '.map */'; grunt.file.write(file.dest + '.map', compiled.sourceMap.toString()); created.maps++; grunt.verbose.writeln('File ' + chalk.cyan(file.dest + '.map') + ' created'); } grunt.file.write(file.dest, compiledCssString); created.files++; size.after += compiledCssString.length; grunt.verbose.writeln('File ' + chalk.cyan(file.dest) + ' created ' + chalk.dim(maxmin(unCompiledCssString, compiledCssString, options.report === 'gzip'))); }, this); if (created.maps > 0) { grunt.log.ok(created.maps + ' source' + grunt.util.pluralize(this.files.length, 'map/maps') + ' created.'); } if (created.files > 0) { grunt.log.ok(created.files + ' ' + grunt.util.pluralize(this.files.length, 'file/files') + ' created. ' + chalk.dim(maxmin(size.before, size.after))); } else { grunt.log.warn('No files created.'); } }); };
Do not swallow Clean CSS errors. The errors produced by Clean CSS were slightly swallowed, so throw them when they appear. Signed-off-by: Balogh Levente <[email protected]>
tasks/cssmin.js
Do not swallow Clean CSS errors.
<ide><path>asks/cssmin.js <ide> <ide> try { <ide> compiled = new CleanCSS(options).minify(availableFiles); <add> if (compiled.errors && compiled.errors.length) { <add> throw compiled.errors.join('\n'); <add> } <ide> } catch (err) { <ide> grunt.log.error(err); <ide> grunt.warn('CSS minification failed at ' + availableFiles + '.');
JavaScript
mit
6d45eee3e038302b5754c6869ffa0990ba82f55a
0
Claudia108/puzzlenary,Claudia108/puzzlenary
import chai from 'chai'; import Game from '../lib/game'; import $ from "jquery"; const expect = chai.expect; describe('game', function () { after(function() { $('.game-table').remove(); }); context('start', function () { it('starts the game', function () { const game = new Game(2, 2); game.start(); expect($('.game-table').length).to.equal(1); expect(game.clicks).to.equal(0); expect(game.interval > 0).to.equal(true); }); it('starts click event handlers', function () { const game = new Game(2, 2); game.start(); $('.game-table td').first().trigger('click'); expect(game.clicks).to.equal(1); }); }); describe('handleOutcome', function () { context('when outcome is won', function () { it('adds a new game level', function () { const game = new Game(2, 2); const outcome = "win"; game.start(); expect(game.currentLevel).to.equal(1); expect($('#winGameModal').is(":visible")).to.equal(false); game.handleOutcome(outcome); expect(game.currentLevel).to.equal(2); // expect($('#winGameModal').is(":visible")).to.equal(true); }); }); context('when outcome is lost', function () { it('resets the current game level', function (done) { this.timeout(0); // check on duration of this function const game = new Game(2, 2); const outcome = "lost"; game.start(); expect(game.currentLevel).to.equal(1); expect($('#winGameModal').is(":visible")).to.equal(false); game.handleOutcome(outcome); expect(game.currentLevel).to.equal(1); done(); // expect($('#winGameModal').is(":visible")).to.equal(true); }); }); }); context('playAgain', function () { it('resets lives to 3 lives', function () { const game = new Game(2, 2); game.start(); expect(game.lives.length).to.equal(3); game.lives.length = 1; game.playAgain(); expect(game.lives.length).to.equal(3); }); context('from current level or level 1', function () { xit('when user decides for current level', function () { const game = new Game(2, 2); game.start(); game.currentLevel = 2; game.lives.length = 0; game.playAgain(); // $('button#close1').trigger('click'); expect(game.currentLevel).to.equal(2); }); xit('when user decides for current level', function () { const game = new Game(2, 2); game.start(); game.currentLevel = 3; game.lives.length = 0; game.playAgain(); // $('button#close1').trigger('click'); expect(game.currentLevel).to.equal(1); }); }); }); context('end', function () { it("resets the game's state", function () { const game = new Game(2, 2); game.start(); $('.game-table td').first().trigger('click', 'td'); game.end(); expect($('.game-table').length).to.equal(0); expect(game.clicks).to.equal(0); }); it('clears click event handlers', function () { const game = new Game(2, 2); expect(game.clicks).to.equal(0); game.start(); $('.game-table td').first().trigger('click'); expect(game.clicks).to.equal(1); game.end(); $('.game-table td').first().trigger('click'); expect(game.clicks).to.equal(0); }); }); });
test/game-test.js
import chai from 'chai'; import Game from '../lib/game'; import $ from "jquery"; const expect = chai.expect; describe('game', function () { after(function() { $('.game-table').remove(); }); context('start', function () { it('starts the game', function () { const game = new Game(2, 2); game.start(); expect($('.game-table').length).to.equal(1); expect(game.clicks).to.equal(0); expect(game.interval > 0).to.equal(true); }); it('starts click event handlers', function () { const game = new Game(2, 2); game.start(); $('.game-table td').first().trigger('click'); expect(game.clicks).to.equal(1); }); }); describe('handleOutcome', function () { context('when outcome is won', function () { it('adds a new game level', function () { const game = new Game(2, 2); const outcome = "win"; game.start(); expect(game.currentLevel).to.equal(1); expect($('#winGameModal').is(":visible")).to.equal(false); game.handleOutcome(outcome); expect(game.currentLevel).to.equal(2); // expect($('#winGameModal').is(":visible")).to.equal(true); }); }); context('when outcome is lost', function () { it('resets the current game level', function (done) { this.timeout(0); // check on duration of this function const game = new Game(2, 2); const outcome = "lost"; game.start(); expect(game.currentLevel).to.equal(1); expect($('#winGameModal').is(":visible")).to.equal(false); game.handleOutcome(outcome); expect(game.currentLevel).to.equal(1); done(); // expect($('#winGameModal').is(":visible")).to.equal(true); }); }); }); context('playAgain', function () { it('resets lives to 3 lives', function () { const game = new Game(2, 2); game.start(); expect(game.lives.length).to.equal(3); game.lives.length = 1; game.playAgain(); expect(game.lives.length).to.equal(3); }); context('from current level or level 1', function () { it('when user decides for current level', function () { const game = new Game(2, 2); game.start(); game.currentLevel = 2; game.lives.length = 0; game.playAgain(); $('button#close1').trigger('click'); expect(game.currentLevel).to.equal(2); }); }); }); context('end', function () { it("resets the game's state", function () { const game = new Game(2, 2); game.start(); $('.game-table td').first().trigger('click', 'td'); game.end(); expect($('.game-table').length).to.equal(0); expect(game.clicks).to.equal(0); }); it('clears click event handlers', function () { const game = new Game(2, 2); expect(game.clicks).to.equal(0); game.start(); $('.game-table td').first().trigger('click'); expect(game.clicks).to.equal(1); game.end(); $('.game-table td').first().trigger('click'); expect(game.clicks).to.equal(0); }); }); });
Add playAgain second option test
test/game-test.js
Add playAgain second option test
<ide><path>est/game-test.js <ide> }); <ide> <ide> context('from current level or level 1', function () { <del> it('when user decides for current level', function () { <add> xit('when user decides for current level', function () { <ide> const game = new Game(2, 2); <ide> <ide> game.start(); <ide> game.lives.length = 0; <ide> <ide> game.playAgain(); <del> $('button#close1').trigger('click'); <add> // $('button#close1').trigger('click'); <ide> <ide> expect(game.currentLevel).to.equal(2); <add> }); <add> <add> xit('when user decides for current level', function () { <add> const game = new Game(2, 2); <add> <add> game.start(); <add> <add> game.currentLevel = 3; <add> game.lives.length = 0; <add> <add> game.playAgain(); <add> // $('button#close1').trigger('click'); <add> <add> expect(game.currentLevel).to.equal(1); <ide> }); <ide> }); <ide> });
Java
apache-2.0
8fe7808866e4c857071086e8d5da0f0888bfae2d
0
mygreen/xlsmapper,mygreen/xlsmapper,mygreen/xlsmapper,mygreen/xlsmapper,mygreen/xlsmapper
package com.gh.mygreen.xlsmapper.validation; import java.awt.Point; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Stack; import com.gh.mygreen.xlsmapper.Utils; /** * シートのエラー情報を処理するためのクラス。 * * @version 0.5 * @author T.TSUCHIE * */ public class SheetBindingErrors { /** パスの区切り文字 */ public static final String PATH_SEPARATOR = "."; /** シート名 */ private String sheetName; /** オブジェクト名 */ private final String objectName; /** 現在のパス。キャッシュ用。 */ private String currentPath; /** 検証対象のオブジェクトの現在のパス */ private Stack<String> nestedPathStack = new Stack<String>(); /** エラーオブジェクト */ private final List<ObjectError> errors = new ArrayList<ObjectError>(); /** エラーコードの候補を生成するクラス */ private MessageCodeGenerator messageCodeGenerator = new MessageCodeGenerator(); public String getObjectName() { return objectName; } /** * オブジェクト名を指定しするコンストラクタ。 * <p>エラーメッセージを組み立てる際に、パスのルートとなる。 * @param objectName オブジェクト名 */ public SheetBindingErrors(final String objectName) { this.objectName = objectName; } /** * クラス名をオブジェクト名とするコンストラクタ。 * @param clazz クラス名 */ public SheetBindingErrors(final Class<?> clazz) { this(clazz.getCanonicalName()); } /** * 指定したパスで現在のパスを初期化します。 * <p>nullまたは空文字を与えると、トップに移動します。 * @param nestedPath */ public void setNestedPath(final String nestedPath) { final String canonicalPath = getCanonicalPath(nestedPath); this.nestedPathStack.clear(); if(canonicalPath.isEmpty()) { this.currentPath = buildPath(); } else { pushNestedPath(canonicalPath); } } /** * パスのルートに移動します。 */ public void setRootPath() { setNestedPath(null); } /** * パスを標準化する。 * <ol> * <li>トリムする。 * <li>値がnullの場合は、空文字を返す。 * <li>最後に'.'がついている場合、除去する。 * @param subPath * @return */ private String getCanonicalPath(final String subPath) { if(subPath == null) { return ""; } String value = subPath.trim(); if(value.isEmpty()) { return value; } if(value.startsWith(PATH_SEPARATOR)) { value = value.substring(1); } if(value.endsWith(PATH_SEPARATOR)) { value = value.substring(0, value.length()-1); } return value; } /** * パスを1つ下位に移動します。 * @param subPath * @return * @throws IllegalArgumentException subPath is empty. */ public void pushNestedPath(final String subPath) { final String canonicalPath = getCanonicalPath(subPath); if(canonicalPath.isEmpty()) { throw new IllegalArgumentException(String.format("subPath is invalid path : '%s'", subPath)); } this.nestedPathStack.push(canonicalPath); this.currentPath = buildPath(); } /** * インデックス付きのパスを1つ下位に移動します。 * @param subPath * @param index * @return * @throws IllegalArgumentException subPath is empty. */ public void pushNestedPath(final String subPath, final int index) { pushNestedPath(String.format("%s[%d]", subPath, index)); } /** * キー付きのパスを1つ下位に移動します。 * @param subPath * @param key * @return * @throws IllegalArgumentException subPath is empty. */ public void pushNestedPath(final String subPath, final String key) { pushNestedPath(String.format("%s[%s]", subPath, key)); } /** * パスを1つ上位に移動します。 * @return * @throws IllegalStateException path stask is empty. */ public String popNestedPath() { if(nestedPathStack.isEmpty()) { throw new IllegalStateException("Cannot pop nested path: no nested path on stack"); } final String subPath = nestedPathStack.pop(); this.currentPath = buildPath(); return subPath; } /** * パスを組み立てる。 * <p>ルートの時は空文字を返します。 * @return */ private String buildPath() { return Utils.join(nestedPathStack, PATH_SEPARATOR); } /** * 現在のパスを取得します。 * <p>ルートの時は空文字を返します。 * @return */ public String getCurrentPath() { return currentPath; } /** * 現在のパスに引数で指定したフィールド名を追加した値を返す。 * @param fieldName * @return */ public String buildFieldPath(final String fieldName) { if(Utils.isEmpty(getCurrentPath())) { return fieldName; } else { return Utils.join(new String[]{getCurrentPath(), fieldName}, PATH_SEPARATOR); } } /** * 全てのエラーをリセットする。 * @since 0.5 */ public void clearAllErrors() { this.errors.clear(); } /** * エラーを追加する * @param error */ public void addError(final ObjectError error) { this.errors.add(error); } /** * エラーを全て追加する。 * @param errors */ public void addAllErrors(final Collection<ObjectError> errors) { this.errors.addAll(errors); } /** * 全てのエラーを取得する * @return */ public List<ObjectError> getAllErrors() { return new ArrayList<ObjectError>(errors); } /** * エラーがあるか確かめる。 * @return true:エラーがある。 */ public boolean hasErrors() { return !getAllErrors().isEmpty(); } /** * グローバルエラーを取得する * @return エラーがない場合は空のリストを返す */ public List<ObjectError> getGlobalErrors() { final List<ObjectError> list = new ArrayList<ObjectError>(); for(ObjectError item : this.errors) { if(!(item instanceof FieldError)) { list.add(item); } } return list; } /** * 先頭のグローバルエラーを取得する。 * @return 存在しない場合は、nullを返す。 */ public ObjectError getFirstGlobalError() { for(ObjectError item : this.errors) { if(!(item instanceof FieldError)) { return item; } } return null; } /** * グローバルエラーがあるか確かめる。 * @return */ public boolean hasGlobalErrors() { return !getGlobalErrors().isEmpty(); } /** * グローバルエラーの件数を取得する * @return */ public int getGlobalErrorCount() { return getGlobalErrors().size(); } /** * グローバルエラーを取得する * @return エラーがない場合は空のリストを返す */ public List<SheetObjectError> getSheetGlobalErrors() { final List<SheetObjectError> list = new ArrayList<SheetObjectError>(); for(ObjectError item : this.errors) { if(item instanceof SheetObjectError) { list.add((SheetObjectError) item); } } return list; } /** * 先頭のグローバルエラーを取得する。 * @param sheetName シート名 * @return 存在しない場合は、nullを返す。 */ public SheetObjectError getFirstSheetGlobalError() { for(SheetObjectError item : getSheetGlobalErrors()) { return (SheetObjectError)item; } return null; } /** * シートに関するグローバルエラーがあるか確かめる。 * @return true:シートに関するグローバルエラー。 */ public boolean hasSheetGlobalErrors() { return !getSheetGlobalErrors().isEmpty(); } /** * シートに関するグローバルエラーの件数を取得する。 * @return */ public int getSheetGlobalErrorCount() { return getSheetGlobalErrors().size(); } /** * フィールドエラーを取得する * @return エラーがない場合は空のリストを返す */ public List<FieldError> getFieldErrors() { final List<FieldError> list = new ArrayList<FieldError>(); for(ObjectError item : this.errors) { if(item instanceof FieldError) { list.add((FieldError) item); } } return list; } /** * 先頭のフィールドエラーを取得する * @return エラーがない場合は空のリストを返す */ public FieldError getFirstFieldError() { for(ObjectError item : this.errors) { if(item instanceof FieldError) { return (FieldError) item; } } return null; } /** * フィールドエラーが存在するか確かめる。 * @return true:フィールドエラーを持つ。 */ public boolean hasFieldErrors() { return !getFieldErrors().isEmpty(); } /** * フィールドエラーの件数を取得する。 * @return */ public int getFieldErrorCount() { return getFieldErrors().size(); } /** * パスを指定してフィールドエラーを取得する * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return */ public List<FieldError> getFieldErrors(final String path) { final String fullPath = buildFieldPath(path); final List<FieldError> list = new ArrayList<FieldError>(); for(ObjectError item : this.errors) { if(item instanceof FieldError && isMatchingFieldError(fullPath, (FieldError) item)) { list.add((FieldError) item); } } return list; } /** * パスを指定して先頭のフィールドエラーを取得する * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return エラーがない場合は空のリストを返す */ public FieldError getFirstFieldError(final String path) { final String fullPath = buildFieldPath(path); for(ObjectError item : this.errors) { if(item instanceof FieldError && isMatchingFieldError(fullPath, (FieldError) item)) { return (FieldError) item; } } return null; } /** * 指定したパスのフィィールドエラーが存在するか確かめる。 * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return true:エラーがある場合。 */ public boolean hasFieldErrors(final String path) { return !getFieldErrors(path).isEmpty(); } /** * 指定したパスのフィィールドエラーの件数を取得する。 * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return */ public int getFieldErrorCount(final String path) { return getFieldErrors(path).size(); } /** * セルのフィールドエラーを取得する * @return エラーがない場合は空のリストを返す */ public List<CellFieldError> getCellFieldErrors() { final List<CellFieldError> list = new ArrayList<CellFieldError>(); for(ObjectError item : this.errors) { if(item instanceof CellFieldError) { list.add((CellFieldError) item); } } return list; } /** * 先頭のセルフィールドエラーを取得する * @return エラーがない場合は空のリストを返す */ public CellFieldError getCellFirstFieldError() { for(ObjectError item : this.errors) { if(item instanceof CellFieldError) { return (CellFieldError) item; } } return null; } /** * セルフィールドエラーが存在するか確かめる。 * @return true:フィールドエラーを持つ。 */ public boolean hasCellFieldErrors() { return !getCellFieldErrors().isEmpty(); } /** * セルフィールドエラーの件数を取得する。 * @return */ public int getCellFieldErrorCount() { return getCellFieldErrors().size(); } /** * パスを指定してセルフィールドエラーを取得する * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return */ public List<CellFieldError> getCellFieldErrors(final String path) { final String fullPath = buildFieldPath(path); final List<CellFieldError> list = new ArrayList<CellFieldError>(); for(ObjectError item : this.errors) { if(item instanceof CellFieldError && isMatchingFieldError(fullPath, (CellFieldError) item)) { list.add((CellFieldError) item); } } return list; } /** * パスを指定して先頭のセルフィールドエラーを取得する * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return エラーがない場合はnullを返す。 */ public CellFieldError getFirstCellFieldError(final String path) { final String fullPath = buildFieldPath(path); for(ObjectError item : this.errors) { if(item instanceof CellFieldError && isMatchingFieldError(fullPath, (CellFieldError) item)) { return (CellFieldError) item; } } return null; } /** * 指定したパスのセルフィィールドエラーが存在するか確かめる。 * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return true:エラーがある場合。 */ public boolean hasCellFieldErrors(final String path) { return !getCellFieldErrors(path).isEmpty(); } /** * 指定したパスのセルフィィールドエラーの件数を取得する。 * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return */ public int getCellFieldErrorCount(final String path) { return getCellFieldErrors(path).size(); } /** * 指定したパスがフィールドエラーのパスと一致するかチェックするかどうか。 * @param path * @param fieldError * @return true: 一致する場合。 */ protected boolean isMatchingFieldError(final String path, final FieldError fieldError) { if (fieldError.getFieldPath().equals(path)) { return true; } if(path.endsWith("*")) { String subPath = path.substring(0, path.length()-1); return fieldError.getFieldPath().startsWith(subPath); } return false; } /** * 現在のシート名を取得する。 * @return */ public String getSheetName() { return sheetName; } /** * 現在のシート名を設定します。 * @param sheetName * @return */ public SheetBindingErrors setSheetName(final String sheetName) { this.sheetName = sheetName; return this; } /** * エラーコードを指定してグローバルエラーを登録します。 * @param errorCode エラーコード */ public void reject(final String errorCode) { addError(new ObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), new Object[]{})); } /** * エラーコードとデフォルトメッセージを指定してグローバルエラーを登録します。 * @param errorCode エラーコード * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void reject(final String errorCode, final String defaultMessage) { addError(new ObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), new Object[]{}) .setDefaultMessage(defaultMessage)); } /** * エラーコードとメッセージ引数の値を指定してグローバルエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param errorCode エラーコード * @param errorArgs メッセージ引数。 */ public void reject(final String errorCode, final Object[] errorArgs) { addError(new ObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), errorArgs)); } /** * エラーコードとメッセージ引数の値を指定してグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorArgs メッセージ引数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void reject(final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(new ObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), errorArgs) .setDefaultMessage(defaultMessage)); } /** * エラーコードとメッセージ変数の値を指定してグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorVars メッセージ変数。 */ public void reject(final String errorCode, final Map<String, Object> errorVars) { addError(new ObjectError( getObjectName(), generateMessageCodes(errorCode), errorVars)); } /** * エラーコードとメッセージ変数の値を指定してグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorVars メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void reject(final String errorCode, final Map<String, Object> errorVars, final String defaultMessage) { addError(new ObjectError( getObjectName(), generateMessageCodes(errorCode), errorVars) .setDefaultMessage(defaultMessage)); } /** * エラーコードを指定してシートのグローバルエラーを登録します。 * @param errorCode エラーコード。 */ public void rejectSheet(final String errorCode) { addError(new SheetObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), new Object[]{}, getSheetName())); } /** * エラーコードとデフォルトメッセージを指定してシートのグローバルエラーを登録します。 * @param errorCode エラーコード。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheet(final String errorCode, final String defaultMessage) { addError(new SheetObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), new Object[]{}, getSheetName()) .setDefaultMessage(defaultMessage)); } /** * エラーコードとメッセージ引数を指定してシートのグローバルエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param errorCode エラーコード * @param errorArgs メッセージ引数 */ public void rejectSheet(final String errorCode, final Object[] errorArgs) { addError(new SheetObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), errorArgs, getSheetName())); } /** * エラーコードとメッセージ引数を指定してシートのグローバルエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param errorCode エラーコード * @param errorArgs メッセージ引数 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheet(final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(new SheetObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), errorArgs, getSheetName()) .setDefaultMessage(defaultMessage)); } /** * エラーコードとメッセージ変数を指定してシートのグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorVars メッセージ変数 */ public void rejectSheet(final String errorCode, final Map<String, Object> errorVars) { addError(new SheetObjectError( getObjectName(), generateMessageCodes(errorCode), errorVars, getSheetName())); } /** * エラーコードとメッセージ変数を指定してシートのグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorVars メッセージ変数 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheet(final String errorCode, final Map<String, Object> errorVars, final String defaultMessage) { addError(new SheetObjectError( getObjectName(), generateMessageCodes(errorCode), errorVars, getSheetName()) .setDefaultMessage(defaultMessage)); } /** * エラーコードを指定してフィールドエラーを登録します。 * @param field フィールドパス。 * @param errorCode エラーコード。 */ public void rejectValue(final String field, final String errorCode) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field)) .build()); } /** * エラーコードを指定してフィールドエラーを登録します。 * @param field フィールドパス。 * @param errorCode エラーコード。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectValue(final String field, final String errorCode, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field)) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとメッセージ引数を指定してフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param errorCode エラーコード。 * @param errorArgs メッセージ引数。 */ public void rejectValue(final String field, final String errorCode, final Object[] errorArgs) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorArgs) .build()); } /** * エラーコードとメッセージ引数を指定してフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param errorCode エラーコード。 * @param errorArgs メッセージ引数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectValue(final String field, final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorArgs) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとメッセージ引数を指定してフィールドエラーを登録します。 * @param field フィールドパス。 * @param errorCode エラーコード。 * @param errorVars メッセージ変数。 */ public void rejectValue(final String field, final String errorCode, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorVars) .build()); } /** * エラーコードを指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field)) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ引数を指定してフィールドエラーを登録します。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param errorCode エラーコード。 * @param errorVars メッセージ変数。 */ public void rejectValue(final String field, final Object fieldValue, final Class<?> fieldType, final String errorCode, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorVars) .build()); } /** * エラーコードを指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType)) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとデフォルトメッセージを指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field)) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとメッセージ引数を指定してシートのフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorArgs メッセージ変数。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final Object[] errorArgs) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorArgs) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ引数を指定してシートのフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorArgs メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorArgs) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとデメッセージ変数を指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorVars メッセージ変数。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ変数を指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorVars メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final Map<String, Object> errorVars, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとメッセージ引数を指定してシートのフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorArgs メッセージ変数。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode, final Object[] errorArgs) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorArgs) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ引数を指定してシートのフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorArgs メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorArgs) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとデメッセージ変数を指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorVars メッセージ変数。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ変数を指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorVars メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode, final Map<String, Object> errorVars, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * メッセージ変数付きのフィールド型変換エラーを指定する。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param errorVars メッセージ変数 */ public void rejectTypeBind(final String field, final Object fieldValue, final Class<?> fieldType, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .typeBindFailure(true) .codes(getMessageCodeGenerator().generateTypeMismatchCodes(getObjectName(), field, fieldType), errorVars) .build()); } /** * メッセージ変数付きのシートのフィールド型変換エラーを指定する。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param errorVars メッセージ変数 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param label フィールドのラベル。 */ public void rejectSheetTypeBind(final String field, final Object fieldValue, final Class<?> fieldType, final Map<String, Object> errorVars, final Point cellAddress, final String label) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .typeBindFailure(true) .codes(getMessageCodeGenerator().generateTypeMismatchCodes(getObjectName(), field, fieldType), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .label(label) .build()); } /** * フィールド型変換エラーを指定する。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 */ public void rejectTypeBind(final String field, final Object fieldValue, final Class<?> fieldType) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .typeBindFailure(true) .codes(getMessageCodeGenerator().generateTypeMismatchCodes(getObjectName(), field, fieldType)) .build()); } /** * シートのフィールド型変換エラーを指定する。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param label フィールドのラベル。 */ public void rejectSheetTypeBind(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String label) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .typeBindFailure(true) .codes(getMessageCodeGenerator().generateTypeMismatchCodes(getObjectName(), field, fieldType)) .sheetName(getSheetName()).cellAddress(cellAddress) .label(label) .build()); } public MessageCodeGenerator getMessageCodeGenerator() { return messageCodeGenerator; } public void setMessageCodeGenerator(MessageCodeGenerator messageCodeGenerator) { this.messageCodeGenerator = messageCodeGenerator; } public String[] generateMessageCodes(final String code) { return getMessageCodeGenerator().generateCodes(code, getObjectName()); } public String[] generateMessageCodes(final String code, final String field) { return getMessageCodeGenerator().generateCodes(code, getObjectName(), field, null); } public String[] generateMessageCodes(final String code, final String field, final Class<?> fieldType) { return getMessageCodeGenerator().generateCodes(code, getObjectName(), field, fieldType); } }
src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java
package com.gh.mygreen.xlsmapper.validation; import java.awt.Point; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Stack; import com.gh.mygreen.xlsmapper.Utils; /** * シートのエラー情報を処理するためのクラス。 * * @version 0.5 * @author T.TSUCHIE * */ public class SheetBindingErrors { /** パスの区切り文字 */ public static final String PATH_SEPARATOR = "."; /** シート名 */ private String sheetName; /** オブジェクト名 */ private final String objectName; /** 現在のパス。キャッシュ用。 */ private String currentPath; /** 検証対象のオブジェクトの現在のパス */ private Stack<String> nestedPathStack = new Stack<String>(); /** エラーオブジェクト */ private final List<ObjectError> errors = new ArrayList<ObjectError>(); /** エラーコードの候補を生成するクラス */ private MessageCodeGenerator messageCodeGenerator = new MessageCodeGenerator(); public String getObjectName() { return objectName; } public SheetBindingErrors(final String objectName) { this.objectName = objectName; } /** * クラス名をオブジェクト名として設定します。 * @param clazz * @return */ public SheetBindingErrors(final Class<?> clazz) { this.objectName = clazz.getCanonicalName(); } /** * 指定したパスで現在のパスを初期化します。 * <p>nullまたは空文字を与えると、トップに移動します。 * @param nestedPath */ public void setNestedPath(final String nestedPath) { final String canonicalPath = getCanonicalPath(nestedPath); this.nestedPathStack.clear(); if(!canonicalPath.isEmpty()) { pushNestedPath(canonicalPath); } } /** * パスのルートに移動します。 */ public void setRootPath() { setNestedPath(null); } /** * パスを標準化する。 * <ol> * <li>トリムする。 * <li>値がnullの場合は、空文字を返す。 * <li>最後に'.'がついている場合、除去する。 * @param subPath * @return */ private String getCanonicalPath(String subPath) { if(subPath == null) { return ""; } String value = subPath.trim(); if(value.isEmpty()) { return value; } if(value.startsWith(PATH_SEPARATOR)) { value = value.substring(1); } if(value.endsWith(PATH_SEPARATOR)) { value = value.substring(0, value.length()-1); } return value; } /** * パスを1つ下位に移動します。 * @param subPath * @return * @throws IllegalArgumentException subPath is empty. */ public void pushNestedPath(final String subPath) { final String canonicalPath = getCanonicalPath(subPath); if(canonicalPath.isEmpty()) { throw new IllegalArgumentException(String.format("subPath is invalid path : '%s'", subPath)); } this.nestedPathStack.push(canonicalPath); this.currentPath = buildPath(); } /** * インデックス付きのパスを1つ下位に移動します。 * @param subPath * @param index * @return * @throws IllegalArgumentException subPath is empty. */ public void pushNestedPath(final String subPath, final int index) { pushNestedPath(String.format("%s[%d]", subPath, index)); } /** * キー付きのパスを1つ下位に移動します。 * @param subPath * @param key * @return * @throws IllegalArgumentException subPath is empty. */ public void pushNestedPath(final String subPath, final String key) { pushNestedPath(String.format("%s[%s]", subPath, key)); } /** * パスを1つ上位に移動します。 * @return * @throws IllegalStateException path stask is empty. */ public String popNestedPath() { if(nestedPathStack.isEmpty()) { throw new IllegalStateException("Cannot pop nested path: no nested path on stack"); } final String subPath = nestedPathStack.pop(); this.currentPath = buildPath(); return subPath; } /** * パスを組み立てる。 * <p>ルートの時は空文字を返します。 * @return */ private String buildPath() { return Utils.join(nestedPathStack, PATH_SEPARATOR); } /** * 現在のパスを取得します。 * <p>ルートの時は空文字を返します。 * @return */ public String getCurrentPath() { return currentPath; } /** * 現在のパスに引数で指定したフィールド名を追加した値を返す。 * @param fieldName * @return */ public String buildFieldPath(final String fieldName) { if(Utils.isEmpty(getCurrentPath())) { return fieldName; } else { return Utils.join(new String[]{getCurrentPath(), fieldName}, PATH_SEPARATOR); } } /** * 全てのエラーをリセットする。 * @since 0.5 */ public void clearAllErrors() { this.errors.clear(); } /** * エラーを追加する * @param error */ public void addError(final ObjectError error) { this.errors.add(error); } /** * エラーを全て追加する。 * @param errors */ public void addAllErrors(final Collection<ObjectError> errors) { this.errors.addAll(errors); } /** * 全てのエラーを取得する * @return */ public List<ObjectError> getAllErrors() { return new ArrayList<ObjectError>(errors); } /** * エラーがあるか確かめる。 * @return true:エラーがある。 */ public boolean hasErrors() { return !getAllErrors().isEmpty(); } /** * グローバルエラーを取得する * @return エラーがない場合は空のリストを返す */ public List<ObjectError> getGlobalErrors() { final List<ObjectError> list = new ArrayList<ObjectError>(); for(ObjectError item : this.errors) { if(!(item instanceof FieldError)) { list.add(item); } } return list; } /** * 先頭のグローバルエラーを取得する。 * @return 存在しない場合は、nullを返す。 */ public ObjectError getFistGlobalError() { for(ObjectError item : this.errors) { if(!(item instanceof FieldError)) { return item; } } return null; } /** * グローバルエラーがあるか確かめる。 * @return */ public boolean hasGlobalErrors() { return !getGlobalErrors().isEmpty(); } /** * グローバルエラーの件数を取得する * @return */ public int getGlobalErrorCount() { return getGlobalErrors().size(); } /** * グローバルエラーを取得する * @return エラーがない場合は空のリストを返す */ public List<SheetObjectError> getSheetGlobalErrors() { final List<SheetObjectError> list = new ArrayList<SheetObjectError>(); for(ObjectError item : this.errors) { if(item instanceof SheetObjectError) { list.add((SheetObjectError) item); } } return list; } /** * 先頭のグローバルエラーを取得する。 * @param sheetName シート名 * @return 存在しない場合は、nullを返す。 */ public SheetObjectError getFistSheetGlobalError() { for(SheetObjectError item : getSheetGlobalErrors()) { return (SheetObjectError)item; } return null; } /** * シートに関するグローバルエラーがあるか確かめる。 * @return true:シートに関するグローバルエラー。 */ public boolean hasSheetGlobalErrors() { return !getSheetGlobalErrors().isEmpty(); } /** * シートに関するグローバルエラーの件数を取得する。 * @return */ public int getSheetGlobalErrorCount() { return getSheetGlobalErrors().size(); } /** * フィールドエラーを取得する * @return エラーがない場合は空のリストを返す */ public List<FieldError> getFieldErrors() { final List<FieldError> list = new ArrayList<FieldError>(); for(ObjectError item : this.errors) { if(item instanceof FieldError) { list.add((FieldError) item); } } return list; } /** * 先頭のフィールドエラーを取得する * @return エラーがない場合は空のリストを返す */ public FieldError getFirstFieldError() { for(ObjectError item : this.errors) { if(item instanceof FieldError) { return (FieldError) item; } } return null; } /** * フィールドエラーが存在するか確かめる。 * @return true:フィールドエラーを持つ。 */ public boolean hasFieldErrors() { return !getFieldErrors().isEmpty(); } /** * フィールドエラーの件数を取得する。 * @return */ public int getFieldErrorCount() { return getFieldErrors().size(); } /** * パスを指定してフィールドエラーを取得する * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return */ public List<FieldError> getFieldErrors(final String path) { final String fullPath = buildFieldPath(path); final List<FieldError> list = new ArrayList<FieldError>(); for(ObjectError item : this.errors) { if(item instanceof FieldError && isMatchingFieldError(fullPath, (FieldError) item)) { list.add((FieldError) item); } } return list; } /** * パスを指定して先頭のフィールドエラーを取得する * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return エラーがない場合は空のリストを返す */ public FieldError getFirstFieldError(final String path) { final String fullPath = buildFieldPath(path); for(ObjectError item : this.errors) { if(item instanceof FieldError && isMatchingFieldError(fullPath, (FieldError) item)) { return (FieldError) item; } } return null; } /** * 指定したパスのフィィールドエラーが存在するか確かめる。 * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return true:エラーがある場合。 */ public boolean hasFieldErrors(final String path) { return !getFieldErrors(path).isEmpty(); } /** * 指定したパスのフィィールドエラーの件数を取得する。 * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return */ public int getFieldErrorCount(final String path) { return getFieldErrors(path).size(); } /** * セルのフィールドエラーを取得する * @return エラーがない場合は空のリストを返す */ public List<CellFieldError> getCellFieldErrors() { final List<CellFieldError> list = new ArrayList<CellFieldError>(); for(ObjectError item : this.errors) { if(item instanceof CellFieldError) { list.add((CellFieldError) item); } } return list; } /** * 先頭のセルフィールドエラーを取得する * @return エラーがない場合は空のリストを返す */ public CellFieldError getCellFirstFieldError() { for(ObjectError item : this.errors) { if(item instanceof CellFieldError) { return (CellFieldError) item; } } return null; } /** * セルフィールドエラーが存在するか確かめる。 * @return true:フィールドエラーを持つ。 */ public boolean hasCellFieldErrors() { return !getCellFieldErrors().isEmpty(); } /** * セルフィールドエラーの件数を取得する。 * @return */ public int getCellFieldErrorCount() { return getCellFieldErrors().size(); } /** * パスを指定してセルフィールドエラーを取得する * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return */ public List<CellFieldError> getCellFieldErrors(final String path) { final String fullPath = buildFieldPath(path); final List<CellFieldError> list = new ArrayList<CellFieldError>(); for(ObjectError item : this.errors) { if(item instanceof CellFieldError && isMatchingFieldError(fullPath, (CellFieldError) item)) { list.add((CellFieldError) item); } } return list; } /** * パスを指定して先頭のセルフィールドエラーを取得する * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return エラーがない場合はnullを返す。 */ public CellFieldError getFirstCellFieldError(final String path) { final String fullPath = buildFieldPath(path); for(ObjectError item : this.errors) { if(item instanceof CellFieldError && isMatchingFieldError(fullPath, (CellFieldError) item)) { return (CellFieldError) item; } } return null; } /** * 指定したパスのセルフィィールドエラーが存在するか確かめる。 * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return true:エラーがある場合。 */ public boolean hasCellFieldErrors(final String path) { return !getCellFieldErrors(path).isEmpty(); } /** * 指定したパスのセルフィィールドエラーの件数を取得する。 * @param path 最後に'*'を付けるとワイルドカードが指定可能。 * @return */ public int getCellFieldErrorCount(final String path) { return getCellFieldErrors(path).size(); } /** * 指定したパスがフィールドエラーのパスと一致するかチェックするかどうか。 * @param path * @param fieldError * @return true: 一致する場合。 */ protected boolean isMatchingFieldError(final String path, final FieldError fieldError) { if (fieldError.getFieldPath().equals(path)) { return true; } if(path.endsWith("*")) { String subPath = path.substring(0, path.length()-1); return fieldError.getFieldPath().startsWith(subPath); } return false; } /** * 現在のシート名を取得する。 * @return */ public String getSheetName() { return sheetName; } /** * 現在のシート名を設定します。 * @param sheetName * @return */ public SheetBindingErrors setSheetName(final String sheetName) { this.sheetName = sheetName; return this; } /** * エラーコードを指定してグローバルエラーを登録します。 * @param errorCode エラーコード */ public void reject(final String errorCode) { addError(new ObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), new Object[]{})); } /** * エラーコードとデフォルトメッセージを指定してグローバルエラーを登録します。 * @param errorCode エラーコード * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void reject(final String errorCode, final String defaultMessage) { addError(new ObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), new Object[]{}) .setDefaultMessage(defaultMessage)); } /** * エラーコードとメッセージ引数の値を指定してグローバルエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param errorCode エラーコード * @param errorArgs メッセージ引数。 */ public void reject(final String errorCode, final Object[] errorArgs) { addError(new ObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), errorArgs)); } /** * エラーコードとメッセージ引数の値を指定してグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorArgs メッセージ引数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void reject(final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(new ObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), errorArgs) .setDefaultMessage(defaultMessage)); } /** * エラーコードとメッセージ変数の値を指定してグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorVars メッセージ変数。 */ public void reject(final String errorCode, final Map<String, Object> errorVars) { addError(new ObjectError( getObjectName(), generateMessageCodes(errorCode), errorVars)); } /** * エラーコードとメッセージ変数の値を指定してグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorVars メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void reject(final String errorCode, final Map<String, Object> errorVars, final String defaultMessage) { addError(new ObjectError( getObjectName(), generateMessageCodes(errorCode), errorVars) .setDefaultMessage(defaultMessage)); } /** * エラーコードを指定してシートのグローバルエラーを登録します。 * @param errorCode エラーコード。 */ public void rejectSheet(final String errorCode) { addError(new SheetObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), new Object[]{}, getSheetName())); } /** * エラーコードとデフォルトメッセージを指定してシートのグローバルエラーを登録します。 * @param errorCode エラーコード。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheet(final String errorCode, final String defaultMessage) { addError(new SheetObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), new Object[]{}, getSheetName()) .setDefaultMessage(defaultMessage)); } /** * エラーコードとメッセージ引数を指定してシートのグローバルエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param errorCode エラーコード * @param errorArgs メッセージ引数 */ public void rejectSheet(final String errorCode, final Object[] errorArgs) { addError(new SheetObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), errorArgs, getSheetName())); } /** * エラーコードとメッセージ引数を指定してシートのグローバルエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param errorCode エラーコード * @param errorArgs メッセージ引数 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheet(final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(new SheetObjectError( getObjectName(), getMessageCodeGenerator().generateCodes(errorCode, getObjectName(), null, null), errorArgs, getSheetName()) .setDefaultMessage(defaultMessage)); } /** * エラーコードとメッセージ変数を指定してシートのグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorVars メッセージ変数 */ public void rejectSheet(final String errorCode, final Map<String, Object> errorVars) { addError(new SheetObjectError( getObjectName(), generateMessageCodes(errorCode), errorVars, getSheetName())); } /** * エラーコードとメッセージ変数を指定してシートのグローバルエラーを登録します。 * @param errorCode エラーコード * @param errorVars メッセージ変数 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheet(final String errorCode, final Map<String, Object> errorVars, final String defaultMessage) { addError(new SheetObjectError( getObjectName(), generateMessageCodes(errorCode), errorVars, getSheetName()) .setDefaultMessage(defaultMessage)); } /** * エラーコードを指定してフィールドエラーを登録します。 * @param field フィールドパス。 * @param errorCode エラーコード。 */ public void rejectValue(final String field, final String errorCode) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field)) .build()); } /** * エラーコードを指定してフィールドエラーを登録します。 * @param field フィールドパス。 * @param errorCode エラーコード。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectValue(final String field, final String errorCode, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field)) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとメッセージ引数を指定してフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param errorCode エラーコード。 * @param errorArgs メッセージ引数。 */ public void rejectValue(final String field, final String errorCode, final Object[] errorArgs) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorArgs) .build()); } /** * エラーコードとメッセージ引数を指定してフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param errorCode エラーコード。 * @param errorArgs メッセージ引数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectValue(final String field, final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorArgs) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとメッセージ引数を指定してフィールドエラーを登録します。 * @param field フィールドパス。 * @param errorCode エラーコード。 * @param errorVars メッセージ変数。 */ public void rejectValue(final String field, final String errorCode, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorVars) .build()); } /** * エラーコードを指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field)) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ引数を指定してフィールドエラーを登録します。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param errorCode エラーコード。 * @param errorVars メッセージ変数。 */ public void rejectValue(final String field, final Object fieldValue, final Class<?> fieldType, final String errorCode, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorVars) .build()); } /** * エラーコードを指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType)) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとデフォルトメッセージを指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field)) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとメッセージ引数を指定してシートのフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorArgs メッセージ変数。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final Object[] errorArgs) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorArgs) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ引数を指定してシートのフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorArgs メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorArgs) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとデメッセージ変数を指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorVars メッセージ変数。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ変数を指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorVars メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Point cellAddress, final String errorCode, final Map<String, Object> errorVars, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .codes(generateMessageCodes(errorCode, field), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとメッセージ引数を指定してシートのフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorArgs メッセージ変数。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode, final Object[] errorArgs) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorArgs) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ引数を指定してシートのフィールドエラーを登録します。 * <p>メッセージ中の変数はインデックス形式で指定する必要がります。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorArgs メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode, final Object[] errorArgs, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorArgs) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * エラーコードとデメッセージ変数を指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorVars メッセージ変数。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .build()); } /** * エラーコードとメッセージ変数を指定してシートのフィールドエラーを登録します。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param errorCode メッセージコード。 * @param errorVars メッセージ変数。 * @param defaultMessage デフォルトメッセージ。指定したエラーコードに対するメッセージが見つからないときに使用する値です。 */ public void rejectSheetValue(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String errorCode, final Map<String, Object> errorVars, final String defaultMessage) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .codes(generateMessageCodes(errorCode, field, fieldType), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .defaultMessage(defaultMessage) .build()); } /** * メッセージ変数付きのフィールド型変換エラーを指定する。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param errorVars メッセージ変数 */ public void rejectTypeBind(final String field, final Object fieldValue, final Class<?> fieldType, final Map<String, Object> errorVars) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .typeBindFailure(true) .codes(getMessageCodeGenerator().generateTypeMismatchCodes(getObjectName(), field, fieldType), errorVars) .build()); } /** * メッセージ変数付きのシートのフィールド型変換エラーを指定する。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param errorVars メッセージ変数 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param label フィールドのラベル。 */ public void rejectSheetTypeBind(final String field, final Object fieldValue, final Class<?> fieldType, final Map<String, Object> errorVars, final Point cellAddress, final String label) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .typeBindFailure(true) .codes(getMessageCodeGenerator().generateTypeMismatchCodes(getObjectName(), field, fieldType), errorVars) .sheetName(getSheetName()).cellAddress(cellAddress) .label(label) .build()); } /** * フィールド型変換エラーを指定する。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 */ public void rejectTypeBind(final String field, final Object fieldValue, final Class<?> fieldType) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .typeBindFailure(true) .codes(getMessageCodeGenerator().generateTypeMismatchCodes(getObjectName(), field, fieldType)) .build()); } /** * シートのフィールド型変換エラーを指定する。 * @param field フィールドパス。 * @param fieldValue フィールドの値。 * @param fieldType フィールドのクラスタイプ。 * @param cellAddress セルのアドレス。x座標が列番号です。y座標が行番号です。列番号、行番号は0から始まります。 * @param label フィールドのラベル。 */ public void rejectSheetTypeBind(final String field, final Object fieldValue, final Class<?> fieldType, final Point cellAddress, final String label) { addError(FieldErrorBuilder.create() .objectName(getObjectName()).fieldPath(buildFieldPath(field)) .fieldValue(fieldValue).fieldType(fieldType) .typeBindFailure(true) .codes(getMessageCodeGenerator().generateTypeMismatchCodes(getObjectName(), field, fieldType)) .sheetName(getSheetName()).cellAddress(cellAddress) .label(label) .build()); } public MessageCodeGenerator getMessageCodeGenerator() { return messageCodeGenerator; } public void setMessageCodeGenerator(MessageCodeGenerator messageCodeGenerator) { this.messageCodeGenerator = messageCodeGenerator; } public String[] generateMessageCodes(final String code) { return getMessageCodeGenerator().generateCodes(code, getObjectName()); } public String[] generateMessageCodes(final String code, final String field) { return getMessageCodeGenerator().generateCodes(code, getObjectName(), field, null); } public String[] generateMessageCodes(final String code, final String field, final Class<?> fieldType) { return getMessageCodeGenerator().generateCodes(code, getObjectName(), field, fieldType); } }
メソッド名のタイポ。fist=>first
src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java
メソッド名のタイポ。fist=>first
<ide><path>rc/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java <ide> return objectName; <ide> } <ide> <add> /** <add> * オブジェクト名を指定しするコンストラクタ。 <add> * <p>エラーメッセージを組み立てる際に、パスのルートとなる。 <add> * @param objectName オブジェクト名 <add> */ <ide> public SheetBindingErrors(final String objectName) { <ide> this.objectName = objectName; <ide> } <ide> <ide> /** <del> * クラス名をオブジェクト名として設定します。 <del> * @param clazz <del> * @return <add> * クラス名をオブジェクト名とするコンストラクタ。 <add> * @param clazz クラス名 <ide> */ <ide> public SheetBindingErrors(final Class<?> clazz) { <del> this.objectName = clazz.getCanonicalName(); <add> this(clazz.getCanonicalName()); <ide> } <ide> <ide> /** <ide> public void setNestedPath(final String nestedPath) { <ide> final String canonicalPath = getCanonicalPath(nestedPath); <ide> this.nestedPathStack.clear(); <del> if(!canonicalPath.isEmpty()) { <add> if(canonicalPath.isEmpty()) { <add> this.currentPath = buildPath(); <add> } else { <ide> pushNestedPath(canonicalPath); <ide> } <ide> } <ide> * @param subPath <ide> * @return <ide> */ <del> private String getCanonicalPath(String subPath) { <add> private String getCanonicalPath(final String subPath) { <ide> if(subPath == null) { <ide> return ""; <ide> } <ide> * 先頭のグローバルエラーを取得する。 <ide> * @return 存在しない場合は、nullを返す。 <ide> */ <del> public ObjectError getFistGlobalError() { <add> public ObjectError getFirstGlobalError() { <ide> for(ObjectError item : this.errors) { <ide> if(!(item instanceof FieldError)) { <ide> return item; <ide> * @param sheetName シート名 <ide> * @return 存在しない場合は、nullを返す。 <ide> */ <del> public SheetObjectError getFistSheetGlobalError() { <add> public SheetObjectError getFirstSheetGlobalError() { <ide> for(SheetObjectError item : getSheetGlobalErrors()) { <ide> return (SheetObjectError)item; <ide> }
JavaScript
agpl-3.0
58d22bb35bc9c24ebe4895291b6fd989293eb4bb
0
initiatived21/d21,initiatived21/d21,initiatived21/d21
/** * Synchronous function * Crop image function * Used for image crop tool * * https://gist.github.com/DominicTobias/b1fb501349893922ec7f * * Returns image data uri, not the loaded image */ function cropImage(originalImg, crop, maxWidth, maxHeight) { const imageWidth = originalImg.naturalWidth, imageHeight = originalImg.naturalHeight, cropX = Math.round((crop.x / 100) * imageWidth), cropY = Math.round((crop.y / 100) * imageHeight), cropWidth = Math.round((crop.width / 100) * imageWidth), cropHeight = Math.round((crop.height / 100) * imageHeight) let destWidth = cropWidth, destHeight = cropHeight if (maxWidth || maxHeight) { // Scale the crop. const scaledCrop = scale({ width: cropWidth, height: cropHeight, maxWidth: maxWidth, maxHeight: maxHeight }) /* NEVER USED: Waiting for answer from original author on why it's in it. */ // Scale the image based on the crop scale. // const scaledImage = scale({ // scale: scaledCrop.scale, // width: imageWidth, // height: imageHeight // }) destWidth = Math.round(scaledCrop.width) destHeight = Math.round(scaledCrop.height) } const canvas = document.createElement('canvas') canvas.width = destWidth canvas.height = destHeight const ctx = canvas.getContext('2d') ctx.drawImage(originalImg, cropX, cropY, cropWidth, cropHeight, 0, 0, destWidth, destHeight) const imgDest = canvas.toDataURL('image/jpeg') return imgDest } function scale(options) { let scale = options.scale || Math.min(options.maxWidth/options.width, options.maxHeight/options.height) scale = Math.min(scale, options.maxScale || 1) return { scale, width: options.width * scale, height: options.height * scale } } export default cropImage
client/app/lib/image_processing/cropImage.js
/** * Synchronous function * Crop image function * Used for image crop tool * * Returns image data uri, not the loaded image */ function cropImage(originalImg, crop, maxWidth, maxHeight) { const imageWidth = originalImg.naturalWidth, imageHeight = originalImg.naturalHeight, cropX = (crop.x / 100) * imageWidth, cropY = (crop.y / 100) * imageHeight, cropWidth = (crop.width / 100) * imageWidth, cropHeight = (crop.height / 100) * imageHeight let destWidth = cropWidth, destHeight = cropHeight if (maxWidth || maxHeight) { // Scale the crop. const scaledCrop = scale({ width: cropWidth, height: cropHeight, maxWidth: maxWidth, maxHeight: maxHeight }) // Scale the image based on the crop scale. const scaledImage = scale({ scale: scaledCrop.scale, width: imageWidth, height: imageHeight }) destWidth = scaledCrop.width destHeight = scaledCrop.height } const canvas = document.createElement('canvas') canvas.width = destWidth canvas.height = destHeight const ctx = canvas.getContext('2d') ctx.drawImage(originalImg, cropX, cropY, cropWidth, cropHeight, 0, 0, destWidth, destHeight) const imgDest = canvas.toDataURL('image/jpeg') return imgDest } function scale(options) { let scale = options.scale || Math.min(options.maxWidth/options.width, options.maxHeight/options.height) scale = Math.min(scale, options.maxScale || 1) return { scale, width: options.width * scale, height: options.height * scale } } export default cropImage
Possible fix for IE11 bug for #237
client/app/lib/image_processing/cropImage.js
Possible fix for IE11 bug for #237
<ide><path>lient/app/lib/image_processing/cropImage.js <ide> * Synchronous function <ide> * Crop image function <ide> * Used for image crop tool <add> * <add> * https://gist.github.com/DominicTobias/b1fb501349893922ec7f <ide> * <ide> * Returns image data uri, not the loaded image <ide> */ <ide> imageWidth = originalImg.naturalWidth, <ide> imageHeight = originalImg.naturalHeight, <ide> <del> cropX = (crop.x / 100) * imageWidth, <del> cropY = (crop.y / 100) * imageHeight, <add> cropX = Math.round((crop.x / 100) * imageWidth), <add> cropY = Math.round((crop.y / 100) * imageHeight), <ide> <del> cropWidth = (crop.width / 100) * imageWidth, <del> cropHeight = (crop.height / 100) * imageHeight <add> cropWidth = Math.round((crop.width / 100) * imageWidth), <add> cropHeight = Math.round((crop.height / 100) * imageHeight) <ide> <ide> let <ide> destWidth = cropWidth, <ide> maxHeight: maxHeight <ide> }) <ide> <add> /* NEVER USED: Waiting for answer from original author on why it's in it. */ <ide> // Scale the image based on the crop scale. <del> const scaledImage = scale({ <del> scale: scaledCrop.scale, <del> width: imageWidth, <del> height: imageHeight <del> }) <add> // const scaledImage = scale({ <add> // scale: scaledCrop.scale, <add> // width: imageWidth, <add> // height: imageHeight <add> // }) <ide> <del> destWidth = scaledCrop.width <del> destHeight = scaledCrop.height <add> destWidth = Math.round(scaledCrop.width) <add> destHeight = Math.round(scaledCrop.height) <ide> } <ide> <ide> const canvas = document.createElement('canvas') <ide> canvas.height = destHeight <ide> <ide> const ctx = canvas.getContext('2d') <add> <ide> ctx.drawImage(originalImg, cropX, cropY, cropWidth, cropHeight, 0, 0, destWidth, destHeight) <ide> <ide> const imgDest = canvas.toDataURL('image/jpeg')
Java
bsd-3-clause
a9b4d537c3e604453b296324ba1ace6b78a66eb6
0
iamedu/dari,iamedu/dari,iamedu/dari,iamedu/dari
package com.psddev.dari.db; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.psddev.dari.util.AsyncQueue; import com.psddev.dari.util.DebugFilter; import com.psddev.dari.util.StringUtils; import com.psddev.dari.util.TaskExecutor; import com.psddev.dari.util.UuidUtils; import com.psddev.dari.util.WebPageContext; /** Debug servlet for running bulk database operations. */ @DebugFilter.Path("db-bulk") @SuppressWarnings("serial") public class BulkDebugServlet extends HttpServlet { public static final String INDEXER_PREFIX = "Database: Indexer: "; public static final String COPIER_PREFIX = "Database: Copier: "; // --- HttpServlet support --- @Override protected void service( final HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { @SuppressWarnings("all") final WebPageContext wp = new WebPageContext(this, request, response); Database selectedDatabase = Database.Static.getDefault(); final List<ObjectType> types = new ArrayList<ObjectType>(selectedDatabase.getEnvironment().getTypes()); Collections.sort(types, new ObjectFieldComparator("internalName", false)); if (wp.isFormPost()) { String action = wp.param(String.class, "action"); UUID selectedTypeId = wp.param(UUID.class, "typeId"); ObjectType selectedType = null; for (ObjectType type : types) { if (type.getId().equals(selectedTypeId)) { selectedType = type; break; } } int writersCount = wp.paramOrDefault(int.class, "writersCount", 5); int commitSize = wp.paramOrDefault(int.class, "commitSize", 50); if ("index".equals(action)) { String executor = INDEXER_PREFIX + (selectedType != null ? selectedType.getInternalName() : "ALL"); AsyncQueue<Object> queue = new AsyncQueue<Object>(); Query<Object> query = Query. fromType(selectedType). resolveToReferenceOnly(); query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false); new AsyncDatabaseReader<Object>( executor, queue, selectedDatabase, query). submit(); queue.closeAutomatically(); for (int i = 0; i < writersCount; ++ i) { new AsyncDatabaseWriter<Object>( executor, queue, selectedDatabase, WriteOperation.INDEX, commitSize, true). submit(); } } else if ("copy".equals(action)) { Database source = Database.Static.getInstance(wp.param(String.class, "source")); Database destination = Database.Static.getInstance(wp.param(String.class, "destination")); String executor = COPIER_PREFIX + " from " + source + " to " + destination; AsyncQueue<Object> queue = new AsyncQueue<Object>(); Query<Object> query = Query. fromType(selectedType). resolveToReferenceOnly(); query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false); if (wp.param(boolean.class, "isResumable") && source instanceof SqlDatabase) { String resumeIdStr = wp.param(String.class, "resumeId"); if (!StringUtils.isEmpty(resumeIdStr)) { UUID resumeId = UuidUtils.fromString(resumeIdStr); if (resumeId != null) { query.where("_id >= ?", resumeId); } } } if (wp.param(boolean.class, "deleteDestination")) { destination.deleteByQuery(query); } (new AsyncDatabaseReader<Object>( executor, queue, source, query) { @Override protected Object produce() { Object obj = super.produce(); if (obj instanceof Record) { this.setProgress(this.getProgress() + " (last: " + ((Record) obj).getId() + ")"); } return obj; } }).submit(); queue.closeAutomatically(); for (int i = 0; i < writersCount; ++ i) { new AsyncDatabaseWriter<Object>( executor, queue, destination, WriteOperation.SAVE_UNSAFELY, commitSize, true). submit(); } } wp.redirect(null); return; } final List<TaskExecutor> indexExecutors = new ArrayList<TaskExecutor>(); final List<TaskExecutor> copyExecutors = new ArrayList<TaskExecutor>(); for (TaskExecutor executor : TaskExecutor.Static.getAll()) { if (executor.getName().startsWith(INDEXER_PREFIX)) { indexExecutors.add(executor); } else if (executor.getName().startsWith(COPIER_PREFIX)) { copyExecutors.add(executor); } } new DebugFilter.PageWriter(getServletContext(), request, response) { { startPage("Database", "Bulk Operations"); writeStart("h2").writeHtml("Index").writeEnd(); writeStart("p"); writeHtml("Use this when you add "); writeStart("code").writeHtml("@Indexed").writeEnd(); writeHtml(" to your model or if queries are returning unexpected results."); writeEnd(); writeStart("form", "action", "", "class", "form-horizontal", "method", "post"); writeElement("input", "name", "action", "type", "hidden", "value", "index"); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label").writeHtml("Type").writeEnd(); writeStart("div", "class", "controls"); writeStart("select", "name", "typeId"); writeStart("option", "value", "").writeHtml("All").writeEnd(); for (ObjectType type : types) { if (!type.isEmbedded()) { writeStart("option", "value", type.getId()); writeHtml(type.getInternalName()); writeEnd(); } } writeEnd(); writeEnd(); writeEnd(); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("# Of Writers").writeEnd(); writeStart("div", "class", "controls"); writeElement("input", "name", "writersCount", "type", "text", "value", 5); writeEnd(); writeEnd(); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("Commit Size").writeEnd(); writeStart("div", "class", "controls"); writeElement("input", "name", "commitSize", "type", "text", "value", 50); writeEnd(); writeEnd(); writeStart("div", "class", "form-actions"); writeElement("input", "type", "submit", "class", "btn btn-success", "value", "Start"); writeEnd(); writeEnd(); if (!indexExecutors.isEmpty()) { writeStart("h3").writeHtml("Ongoing Tasks").writeEnd(); writeStart("ul"); for (TaskExecutor executor : indexExecutors) { writeStart("li"); writeStart("a", "href", "task"); writeHtml(executor.getName()); writeEnd(); writeEnd(); } writeEnd(); } writeStart("h2").writeHtml("Copy").writeEnd(); writeStart("p"); writeHtml("Use this to copy objects from one database to another."); writeEnd(); writeStart("form", "action", "", "class", "form-horizontal", "method", "post"); writeElement("input", "name", "action", "type", "hidden", "value", "copy"); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label").writeHtml("Type").writeEnd(); writeStart("div", "class", "controls"); writeStart("select", "name", "typeId"); writeStart("option", "value", "").writeHtml("All").writeEnd(); for (ObjectType type : types) { if (!type.isEmbedded()) { writeStart("option", "value", type.getId()); writeHtml(type.getInternalName()); writeEnd(); } } writeEnd(); writeEnd(); writeEnd(); List<Database> databases = Database.Static.getAll(); String resumeIdControlId = wp.createId(); String resumableControlId = wp.createId(); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("Source").writeEnd(); writeStart("div", "class", "controls"); writeStart("select", "class", "span3", "id", wp.getId(), "name", "source"); writeStart("option", "value", "").writeHtml("").writeEnd(); for (Database database : databases) { if (!(database instanceof Iterable)) { writeStart("option", "value", database.getName(), "className", database.getClass().getName()); writeHtml(database); writeEnd(); } } writeEnd(); writeStart("label", "class", "checkbox", "style", "margin-top: 5px;", "id", resumableControlId); writeElement("input", "name", "isResumable", "type", "checkbox", "value", "true"); writeHtml("Resumable"); writeEnd(); writeEnd(); writeEnd(); writeStart("div", "class", "control-group", "id", resumeIdControlId); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("Resume With ID").writeEnd(); writeStart("div", "class", "controls"); writeElement("input", "name", "resumeId", "type", "text"); writeEnd(); writeEnd(); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("Destination").writeEnd(); writeStart("div", "class", "controls"); writeStart("select", "class", "span3", "id", wp.getId(), "name", "destination"); writeStart("option", "value", "").writeHtml("").writeEnd(); for (Database database : databases) { if (!(database instanceof Iterable)) { writeStart("option", "value", database.getName(), "className", database.getClass().getName()); writeHtml(database); writeEnd(); } } writeEnd(); writeStart("label", "class", "checkbox", "style", "margin-top: 5px;"); writeElement("input", "name", "deleteDestination", "type", "checkbox", "value", "true"); writeHtml("Delete before copy"); writeEnd(); writeEnd(); writeEnd(); writeStart("div", "class", "form-actions"); writeElement("input", "type", "submit", "class", "btn btn-success", "value", "Start"); writeEnd(); writeEnd(); writeStart("script", "type", "text/javascript"); write("$(document).ready(function() {"); write("$('#" + resumableControlId + "').hide();"); write("$('[name=source]').change(function() {"); write("if ($('option:selected', this).attr('className') == '" + SqlDatabase.class.getName() + "') {"); write("$('#" + resumableControlId + "').show();"); write("} else {"); write("$('#" + resumableControlId + "').hide();"); write("}"); write("});"); write("$('#" + resumeIdControlId + "').hide();"); write("$('[name=isResumable]').change(function() {"); write("if ($(this).is(':checked')) {"); write("$('#" + resumeIdControlId + "').show();"); write("} else {"); write("$('#" + resumeIdControlId + "').hide();"); write("}"); write("})"); write("})"); writeEnd(); if (!copyExecutors.isEmpty()) { writeStart("h3").writeHtml("Ongoing Tasks").writeEnd(); writeStart("ul"); for (TaskExecutor executor : copyExecutors) { writeStart("li"); writeStart("a", "href", "task"); writeHtml(executor.getName()); writeEnd(); writeEnd(); } writeEnd(); } endPage(); } }; } }
db/src/main/java/com/psddev/dari/db/BulkDebugServlet.java
package com.psddev.dari.db; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.psddev.dari.util.AsyncQueue; import com.psddev.dari.util.DebugFilter; import com.psddev.dari.util.StringUtils; import com.psddev.dari.util.TaskExecutor; import com.psddev.dari.util.UuidUtils; import com.psddev.dari.util.WebPageContext; /** Debug servlet for running bulk database operations. */ @DebugFilter.Path("db-bulk") @SuppressWarnings("serial") public class BulkDebugServlet extends HttpServlet { public static final String INDEXER_PREFIX = "Database: Indexer: "; public static final String COPIER_PREFIX = "Database: Copier: "; // --- HttpServlet support --- @Override protected void service( final HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { @SuppressWarnings("all") final WebPageContext wp = new WebPageContext(this, request, response); Database selectedDatabase = Database.Static.getDefault(); final List<ObjectType> types = new ArrayList<ObjectType>(selectedDatabase.getEnvironment().getTypes()); Collections.sort(types, new ObjectFieldComparator("internalName", false)); if (wp.isFormPost()) { String action = wp.param(String.class, "action"); UUID selectedTypeId = wp.param(UUID.class, "typeId"); ObjectType selectedType = null; for (ObjectType type : types) { if (type.getId().equals(selectedTypeId)) { selectedType = type; break; } } int writersCount = wp.paramOrDefault(int.class, "writersCount", 5); int commitSize = wp.paramOrDefault(int.class, "commitSize", 50); if ("index".equals(action)) { String executor = INDEXER_PREFIX + (selectedType != null ? selectedType.getInternalName() : "ALL"); AsyncQueue<Object> queue = new AsyncQueue<Object>(); Query<Object> query = Query. fromType(selectedType). resolveToReferenceOnly(); new AsyncDatabaseReader<Object>( executor, queue, selectedDatabase, query). submit(); queue.closeAutomatically(); for (int i = 0; i < writersCount; ++ i) { new AsyncDatabaseWriter<Object>( executor, queue, selectedDatabase, WriteOperation.INDEX, commitSize, true). submit(); } } else if ("copy".equals(action)) { Database source = Database.Static.getInstance(wp.param(String.class, "source")); Database destination = Database.Static.getInstance(wp.param(String.class, "destination")); String executor = COPIER_PREFIX + " from " + source + " to " + destination; AsyncQueue<Object> queue = new AsyncQueue<Object>(); Query<Object> query = Query. fromType(selectedType). resolveToReferenceOnly(); if (wp.param(boolean.class, "isResumable") && source instanceof SqlDatabase) { query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false); String resumeIdStr = wp.param(String.class, "resumeId"); if (!StringUtils.isEmpty(resumeIdStr)) { UUID resumeId = UuidUtils.fromString(resumeIdStr); if (resumeId != null) { query.where("_id >= ?", resumeId); } } } if (wp.param(boolean.class, "deleteDestination")) { destination.deleteByQuery(query); } (new AsyncDatabaseReader<Object>( executor, queue, source, query) { @Override protected Object produce() { Object obj = super.produce(); if (obj instanceof Record) { this.setProgress(this.getProgress() + " (last: " + ((Record) obj).getId() + ")"); } return obj; } }).submit(); queue.closeAutomatically(); for (int i = 0; i < writersCount; ++ i) { new AsyncDatabaseWriter<Object>( executor, queue, destination, WriteOperation.SAVE_UNSAFELY, commitSize, true). submit(); } } wp.redirect(null); return; } final List<TaskExecutor> indexExecutors = new ArrayList<TaskExecutor>(); final List<TaskExecutor> copyExecutors = new ArrayList<TaskExecutor>(); for (TaskExecutor executor : TaskExecutor.Static.getAll()) { if (executor.getName().startsWith(INDEXER_PREFIX)) { indexExecutors.add(executor); } else if (executor.getName().startsWith(COPIER_PREFIX)) { copyExecutors.add(executor); } } new DebugFilter.PageWriter(getServletContext(), request, response) { { startPage("Database", "Bulk Operations"); writeStart("h2").writeHtml("Index").writeEnd(); writeStart("p"); writeHtml("Use this when you add "); writeStart("code").writeHtml("@Indexed").writeEnd(); writeHtml(" to your model or if queries are returning unexpected results."); writeEnd(); writeStart("form", "action", "", "class", "form-horizontal", "method", "post"); writeElement("input", "name", "action", "type", "hidden", "value", "index"); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label").writeHtml("Type").writeEnd(); writeStart("div", "class", "controls"); writeStart("select", "name", "typeId"); writeStart("option", "value", "").writeHtml("All").writeEnd(); for (ObjectType type : types) { if (!type.isEmbedded()) { writeStart("option", "value", type.getId()); writeHtml(type.getInternalName()); writeEnd(); } } writeEnd(); writeEnd(); writeEnd(); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("# Of Writers").writeEnd(); writeStart("div", "class", "controls"); writeElement("input", "name", "writersCount", "type", "text", "value", 5); writeEnd(); writeEnd(); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("Commit Size").writeEnd(); writeStart("div", "class", "controls"); writeElement("input", "name", "commitSize", "type", "text", "value", 50); writeEnd(); writeEnd(); writeStart("div", "class", "form-actions"); writeElement("input", "type", "submit", "class", "btn btn-success", "value", "Start"); writeEnd(); writeEnd(); if (!indexExecutors.isEmpty()) { writeStart("h3").writeHtml("Ongoing Tasks").writeEnd(); writeStart("ul"); for (TaskExecutor executor : indexExecutors) { writeStart("li"); writeStart("a", "href", "task"); writeHtml(executor.getName()); writeEnd(); writeEnd(); } writeEnd(); } writeStart("h2").writeHtml("Copy").writeEnd(); writeStart("p"); writeHtml("Use this to copy objects from one database to another."); writeEnd(); writeStart("form", "action", "", "class", "form-horizontal", "method", "post"); writeElement("input", "name", "action", "type", "hidden", "value", "copy"); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label").writeHtml("Type").writeEnd(); writeStart("div", "class", "controls"); writeStart("select", "name", "typeId"); writeStart("option", "value", "").writeHtml("All").writeEnd(); for (ObjectType type : types) { if (!type.isEmbedded()) { writeStart("option", "value", type.getId()); writeHtml(type.getInternalName()); writeEnd(); } } writeEnd(); writeEnd(); writeEnd(); List<Database> databases = Database.Static.getAll(); String resumeIdControlId = wp.createId(); String resumableControlId = wp.createId(); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("Source").writeEnd(); writeStart("div", "class", "controls"); writeStart("select", "class", "span3", "id", wp.getId(), "name", "source"); writeStart("option", "value", "").writeHtml("").writeEnd(); for (Database database : databases) { if (!(database instanceof Iterable)) { writeStart("option", "value", database.getName(), "className", database.getClass().getName()); writeHtml(database); writeEnd(); } } writeEnd(); writeStart("label", "class", "checkbox", "style", "margin-top: 5px;", "id", resumableControlId); writeElement("input", "name", "isResumable", "type", "checkbox", "value", "true"); writeHtml("Resumable"); writeEnd(); writeEnd(); writeEnd(); writeStart("div", "class", "control-group", "id", resumeIdControlId); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("Resume With ID").writeEnd(); writeStart("div", "class", "controls"); writeElement("input", "name", "resumeId", "type", "text"); writeEnd(); writeEnd(); writeStart("div", "class", "control-group"); writeStart("label", "class", "control-label", "id", wp.createId()).writeHtml("Destination").writeEnd(); writeStart("div", "class", "controls"); writeStart("select", "class", "span3", "id", wp.getId(), "name", "destination"); writeStart("option", "value", "").writeHtml("").writeEnd(); for (Database database : databases) { if (!(database instanceof Iterable)) { writeStart("option", "value", database.getName(), "className", database.getClass().getName()); writeHtml(database); writeEnd(); } } writeEnd(); writeStart("label", "class", "checkbox", "style", "margin-top: 5px;"); writeElement("input", "name", "deleteDestination", "type", "checkbox", "value", "true"); writeHtml("Delete before copy"); writeEnd(); writeEnd(); writeEnd(); writeStart("div", "class", "form-actions"); writeElement("input", "type", "submit", "class", "btn btn-success", "value", "Start"); writeEnd(); writeEnd(); writeStart("script", "type", "text/javascript"); write("$(document).ready(function() {"); write("$('#" + resumableControlId + "').hide();"); write("$('[name=source]').change(function() {"); write("if ($('option:selected', this).attr('className') == '" + SqlDatabase.class.getName() + "') {"); write("$('#" + resumableControlId + "').show();"); write("} else {"); write("$('#" + resumableControlId + "').hide();"); write("}"); write("});"); write("$('#" + resumeIdControlId + "').hide();"); write("$('[name=isResumable]').change(function() {"); write("if ($(this).is(':checked')) {"); write("$('#" + resumeIdControlId + "').show();"); write("} else {"); write("$('#" + resumeIdControlId + "').hide();"); write("}"); write("})"); write("})"); writeEnd(); if (!copyExecutors.isEmpty()) { writeStart("h3").writeHtml("Ongoing Tasks").writeEnd(); writeStart("ul"); for (TaskExecutor executor : copyExecutors) { writeStart("li"); writeStart("a", "href", "task"); writeHtml(executor.getName()); writeEnd(); writeEnd(); } writeEnd(); } endPage(); } }; } }
Add USE_JDBC_FETCH_SIZE_QUERY_OPTION=false to all bulk queries. This prevents the SQL query from being killed if it runs longer than the removeAbandonedTimeout.
db/src/main/java/com/psddev/dari/db/BulkDebugServlet.java
Add USE_JDBC_FETCH_SIZE_QUERY_OPTION=false to all bulk queries.
<ide><path>b/src/main/java/com/psddev/dari/db/BulkDebugServlet.java <ide> fromType(selectedType). <ide> resolveToReferenceOnly(); <ide> <add> query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false); <add> <ide> new AsyncDatabaseReader<Object>( <ide> executor, queue, selectedDatabase, query). <ide> submit(); <ide> fromType(selectedType). <ide> resolveToReferenceOnly(); <ide> <add> query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false); <add> <ide> if (wp.param(boolean.class, "isResumable") && source instanceof SqlDatabase) { <del> query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false); <ide> String resumeIdStr = wp.param(String.class, "resumeId"); <ide> if (!StringUtils.isEmpty(resumeIdStr)) { <ide> UUID resumeId = UuidUtils.fromString(resumeIdStr);
Java
bsd-3-clause
a7233a51ef08d20f2fd14f4071909535618c2234
0
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
/* * Copyright (c) 2017, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.calls; import android.support.annotation.NonNull; import org.hisp.dhis.android.core.category.Category; import org.hisp.dhis.android.core.category.CategoryCombo; import org.hisp.dhis.android.core.category.CategoryComboEndpointCall; import org.hisp.dhis.android.core.category.CategoryEndpointCall; import org.hisp.dhis.android.core.common.BasicCallFactory; import org.hisp.dhis.android.core.common.D2CallException; import org.hisp.dhis.android.core.common.D2CallExecutor; import org.hisp.dhis.android.core.common.ForeignKeyCleaner; import org.hisp.dhis.android.core.common.GenericCallData; import org.hisp.dhis.android.core.common.GenericCallFactory; import org.hisp.dhis.android.core.common.SyncCall; import org.hisp.dhis.android.core.common.UidsHelper; import org.hisp.dhis.android.core.data.database.DatabaseAdapter; import org.hisp.dhis.android.core.dataset.DataSetParentCall; import org.hisp.dhis.android.core.organisationunit.OrganisationUnit; import org.hisp.dhis.android.core.organisationunit.OrganisationUnitCall; import org.hisp.dhis.android.core.program.Program; import org.hisp.dhis.android.core.program.ProgramParentCall; import org.hisp.dhis.android.core.settings.SystemSetting; import org.hisp.dhis.android.core.settings.SystemSettingCall; import org.hisp.dhis.android.core.systeminfo.SystemInfo; import org.hisp.dhis.android.core.systeminfo.SystemInfoCall; import org.hisp.dhis.android.core.user.User; import org.hisp.dhis.android.core.user.UserCall; import java.util.List; import java.util.concurrent.Callable; import retrofit2.Retrofit; public class MetadataCall extends SyncCall<Void> { private final DatabaseAdapter databaseAdapter; private final Retrofit retrofit; private final BasicCallFactory<SystemInfo> systemInfoCallFactory; private final GenericCallFactory<SystemSetting> systemSettingCallFactory; private final GenericCallFactory<User> userCallFactory; private final GenericCallFactory<List<Category>> categoryCallFactory; private final GenericCallFactory<List<CategoryCombo>> categoryComboCallFactory; private final GenericCallFactory<List<Program>> programParentCallFactory; private final OrganisationUnitCall.Factory organisationUnitCallFactory; private final DataSetParentCall.Factory dataSetParentCallFactory; public MetadataCall(@NonNull DatabaseAdapter databaseAdapter, @NonNull Retrofit retrofit, @NonNull BasicCallFactory<SystemInfo> systemInfoCallFactory, @NonNull GenericCallFactory<SystemSetting> systemSettingCallFactory, @NonNull GenericCallFactory<User> userCallFactory, @NonNull GenericCallFactory<List<Category>> categoryCallFactory, @NonNull GenericCallFactory<List<CategoryCombo>> categoryComboCallFactory, @NonNull GenericCallFactory<List<Program>> programParentCallFactory, @NonNull OrganisationUnitCall.Factory organisationUnitCallFactory, @NonNull DataSetParentCall.Factory dataSetParentCallFactory) { this.databaseAdapter = databaseAdapter; this.retrofit = retrofit; this.systemInfoCallFactory = systemInfoCallFactory; this.systemSettingCallFactory = systemSettingCallFactory; this.userCallFactory = userCallFactory; this.categoryCallFactory = categoryCallFactory; this.categoryComboCallFactory = categoryComboCallFactory; this.programParentCallFactory = programParentCallFactory; this.organisationUnitCallFactory = organisationUnitCallFactory; this.dataSetParentCallFactory = dataSetParentCallFactory; } @Override public Void call() throws Exception { setExecuted(); final D2CallExecutor executor = new D2CallExecutor(); return executor.executeD2CallTransactionally(databaseAdapter, new Callable<Void>() { @Override public Void call() throws D2CallException { SystemInfo systemInfo = executor.executeD2Call( systemInfoCallFactory.create(databaseAdapter, retrofit)); GenericCallData genericCallData = GenericCallData.create(databaseAdapter, retrofit, systemInfo.serverDate()); executor.executeD2Call(systemSettingCallFactory.create(genericCallData)); User user = executor.executeD2Call(userCallFactory.create(genericCallData)); executor.executeD2Call(categoryCallFactory.create(genericCallData)); executor.executeD2Call(categoryComboCallFactory.create(genericCallData)); List<Program> programs = executor.executeD2Call( programParentCallFactory.create(genericCallData)); List<OrganisationUnit> organisationUnits = executor.executeD2Call(organisationUnitCallFactory.create(genericCallData, user, UidsHelper.getUids(programs))); executor.executeD2Call(dataSetParentCallFactory.create(user, genericCallData, organisationUnits)); new ForeignKeyCleaner(databaseAdapter).cleanForeignKeyErrors(); return null; } }); } public static MetadataCall create(DatabaseAdapter databaseAdapter, Retrofit retrofit) { return new MetadataCall( databaseAdapter, retrofit, SystemInfoCall.FACTORY, SystemSettingCall.FACTORY, UserCall.FACTORY, CategoryEndpointCall.FACTORY, CategoryComboEndpointCall.FACTORY, ProgramParentCall.FACTORY, OrganisationUnitCall.FACTORY, DataSetParentCall.FACTORY ); } }
core/src/main/java/org/hisp/dhis/android/core/calls/MetadataCall.java
/* * Copyright (c) 2017, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.calls; import android.support.annotation.NonNull; import org.hisp.dhis.android.core.category.Category; import org.hisp.dhis.android.core.category.CategoryCombo; import org.hisp.dhis.android.core.category.CategoryComboEndpointCall; import org.hisp.dhis.android.core.category.CategoryEndpointCall; import org.hisp.dhis.android.core.common.BasicCallFactory; import org.hisp.dhis.android.core.common.D2CallException; import org.hisp.dhis.android.core.common.D2CallExecutor; import org.hisp.dhis.android.core.common.ForeignKeyCleaner; import org.hisp.dhis.android.core.common.GenericCallData; import org.hisp.dhis.android.core.common.GenericCallFactory; import org.hisp.dhis.android.core.common.SyncCall; import org.hisp.dhis.android.core.common.UidsHelper; import org.hisp.dhis.android.core.data.database.DatabaseAdapter; import org.hisp.dhis.android.core.dataset.DataSetParentCall; import org.hisp.dhis.android.core.organisationunit.OrganisationUnit; import org.hisp.dhis.android.core.organisationunit.OrganisationUnitCall; import org.hisp.dhis.android.core.program.Program; import org.hisp.dhis.android.core.program.ProgramParentCall; import org.hisp.dhis.android.core.settings.SystemSetting; import org.hisp.dhis.android.core.settings.SystemSettingCall; import org.hisp.dhis.android.core.systeminfo.SystemInfo; import org.hisp.dhis.android.core.systeminfo.SystemInfoCall; import org.hisp.dhis.android.core.user.User; import org.hisp.dhis.android.core.user.UserCall; import org.hisp.dhis.android.core.user.UserCredentialsStoreImpl; import java.util.List; import java.util.concurrent.Callable; import retrofit2.Retrofit; public class MetadataCall extends SyncCall<Void> { private final DatabaseAdapter databaseAdapter; private final Retrofit retrofit; private final BasicCallFactory<SystemInfo> systemInfoCallFactory; private final GenericCallFactory<SystemSetting> systemSettingCallFactory; private final GenericCallFactory<User> userCallFactory; private final GenericCallFactory<List<Category>> categoryCallFactory; private final GenericCallFactory<List<CategoryCombo>> categoryComboCallFactory; private final GenericCallFactory<List<Program>> programParentCallFactory; private final OrganisationUnitCall.Factory organisationUnitCallFactory; private final DataSetParentCall.Factory dataSetParentCallFactory; public MetadataCall(@NonNull DatabaseAdapter databaseAdapter, @NonNull Retrofit retrofit, @NonNull BasicCallFactory<SystemInfo> systemInfoCallFactory, @NonNull GenericCallFactory<SystemSetting> systemSettingCallFactory, @NonNull GenericCallFactory<User> userCallFactory, @NonNull GenericCallFactory<List<Category>> categoryCallFactory, @NonNull GenericCallFactory<List<CategoryCombo>> categoryComboCallFactory, @NonNull GenericCallFactory<List<Program>> programParentCallFactory, @NonNull OrganisationUnitCall.Factory organisationUnitCallFactory, @NonNull DataSetParentCall.Factory dataSetParentCallFactory) { this.databaseAdapter = databaseAdapter; this.retrofit = retrofit; this.systemInfoCallFactory = systemInfoCallFactory; this.systemSettingCallFactory = systemSettingCallFactory; this.userCallFactory = userCallFactory; this.categoryCallFactory = categoryCallFactory; this.categoryComboCallFactory = categoryComboCallFactory; this.programParentCallFactory = programParentCallFactory; this.organisationUnitCallFactory = organisationUnitCallFactory; this.dataSetParentCallFactory = dataSetParentCallFactory; } @Override public Void call() throws Exception { setExecuted(); final D2CallExecutor executor = new D2CallExecutor(); return executor.executeD2CallTransactionally(databaseAdapter, new Callable<Void>() { @Override public Void call() throws D2CallException { SystemInfo systemInfo = executor.executeD2Call( systemInfoCallFactory.create(databaseAdapter, retrofit)); GenericCallData genericCallData = GenericCallData.create(databaseAdapter, retrofit, systemInfo.serverDate()); executor.executeD2Call(systemSettingCallFactory.create(genericCallData)); User user = executor.executeD2Call(userCallFactory.create(genericCallData)); executor.executeD2Call(categoryCallFactory.create(genericCallData)); executor.executeD2Call(categoryComboCallFactory.create(genericCallData)); List<Program> programs = executor.executeD2Call( programParentCallFactory.create(genericCallData)); List<OrganisationUnit> organisationUnits = executor.executeD2Call(organisationUnitCallFactory.create(genericCallData, user, UidsHelper.getUids(programs))); executor.executeD2Call(dataSetParentCallFactory.create(user, genericCallData, organisationUnits)); new ForeignKeyCleaner(databaseAdapter).cleanForeignKeyErrors(); return null; } }); } public static MetadataCall create(DatabaseAdapter databaseAdapter, Retrofit retrofit) { return new MetadataCall( databaseAdapter, retrofit, SystemInfoCall.FACTORY, SystemSettingCall.FACTORY, UserCall.FACTORY, CategoryEndpointCall.FACTORY, CategoryComboEndpointCall.FACTORY, ProgramParentCall.FACTORY, OrganisationUnitCall.FACTORY, DataSetParentCall.FACTORY ); } }
foreign-key-cleaner: remove imports
core/src/main/java/org/hisp/dhis/android/core/calls/MetadataCall.java
foreign-key-cleaner: remove imports
<ide><path>ore/src/main/java/org/hisp/dhis/android/core/calls/MetadataCall.java <ide> import org.hisp.dhis.android.core.systeminfo.SystemInfoCall; <ide> import org.hisp.dhis.android.core.user.User; <ide> import org.hisp.dhis.android.core.user.UserCall; <del>import org.hisp.dhis.android.core.user.UserCredentialsStoreImpl; <ide> <ide> import java.util.List; <ide> import java.util.concurrent.Callable;
Java
mit
error: pathspec 'java/leetcode/most-frequent-subtree-sum-508.java' did not match any file(s) known to git
61f6100e6d66bae9eaa93795ed3d61bd199550bf
1
vinnyoodles/algorithms,vinnyoodles/algorithms,vinnyoodles/algorithms
/** * Given the root of a tree, you are asked to find the most frequent subtree sum. * The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). * So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order. * * Solution: Use DFS + recursion and hashmap to maintain frequency * Complexity: O(N) time and space. */ public class Solution { public int[] findFrequentTreeSum(TreeNode root) { if (root == null) return new int[0]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); populateMap(root, map); int max = 0; for (int i : map.keySet()) { max = Math.max(max, map.get(i)); } List<Integer> list = new ArrayList<Integer>(); for (int i : map.keySet()) { if (map.get(i) == max) list.add(i); } int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i ++) res[i] = list.get(i); return res; } public int populateMap(TreeNode node, HashMap<Integer, Integer> map) { if (node == null) return 0; if (node.left == null && node.right == null) { map.put(node.val, map.getOrDefault(node.val, 0) + 1); return node.val; } int left = populateMap(node.left, map); int right = populateMap(node.right, map); int sum = left + right + node.val; map.put(sum, map.getOrDefault(sum, 0) + 1); return sum; } }
java/leetcode/most-frequent-subtree-sum-508.java
Add frequent subtree sum
java/leetcode/most-frequent-subtree-sum-508.java
Add frequent subtree sum
<ide><path>ava/leetcode/most-frequent-subtree-sum-508.java <add>/** <add> * Given the root of a tree, you are asked to find the most frequent subtree sum. <add> * The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). <add> * So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order. <add> * <add> * Solution: Use DFS + recursion and hashmap to maintain frequency <add> * Complexity: O(N) time and space. <add> */ <add>public class Solution { <add> public int[] findFrequentTreeSum(TreeNode root) { <add> if (root == null) return new int[0]; <add> HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); <add> populateMap(root, map); <add> int max = 0; <add> for (int i : map.keySet()) { <add> max = Math.max(max, map.get(i)); <add> } <add> <add> List<Integer> list = new ArrayList<Integer>(); <add> for (int i : map.keySet()) { <add> if (map.get(i) == max) list.add(i); <add> } <add> <add> int[] res = new int[list.size()]; <add> for (int i = 0; i < list.size(); i ++) res[i] = list.get(i); <add> return res; <add> } <add> <add> public int populateMap(TreeNode node, HashMap<Integer, Integer> map) { <add> if (node == null) return 0; <add> if (node.left == null && node.right == null) { <add> map.put(node.val, map.getOrDefault(node.val, 0) + 1); <add> return node.val; <add> } <add> int left = populateMap(node.left, map); <add> int right = populateMap(node.right, map); <add> int sum = left + right + node.val; <add> map.put(sum, map.getOrDefault(sum, 0) + 1); <add> return sum; <add> } <add>}
JavaScript
mit
ac314914b3e406ac2589e2d5ac9298b0c4fd1114
0
Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2
import { createMuiTheme } from '@material-ui/core/styles'; import grey from '@material-ui/core/colors/grey'; import deepmerge from 'deepmerge'; import isPlainObject from 'is-plain-object'; const monoStack = [ '"Liberation Mono"', 'Menlo', 'Courier', 'monospace' ].join(',') export const linkStyle = ({theme, underlinePosition="97%", background}) => { return ({ color: theme.palette.secondary.main, backgroundImage: `linear-gradient(to right, ${theme.palette.secondary.main} 72%, transparent 72%)`, backgroundSize: "4px 1px", backgroundRepeat: "repeat-x", backgroundPosition: `0% ${underlinePosition}`, textShadow: ` .03em 0 ${background || theme.palette.background.default}, -.03em 0 ${background || theme.palette.background.default}, 0 .03em ${background || theme.palette.background.default}, 0 -.03em ${background || theme.palette.background.default}, .06em 0 ${background || theme.palette.background.default}, -.06em 0 ${background || theme.palette.background.default}, .09em 0 ${background || theme.palette.background.default}, -.09em 0 ${background || theme.palette.background.default}, .12em 0 ${background || theme.palette.background.default}, -.12em 0 ${background || theme.palette.background.default}, .15em 0 ${background || theme.palette.background.default}, -.15em 0 ${background || theme.palette.background.default} `, textDecoration: "none", "*, *:after, &:after, *:before, &:before": { textShadow: "none" }, }) } const createLWTheme = (theme) => { // Defines sensible typography defaults that can be // cleanly overriden const body1FontSize = { fontSize: '1.4rem', lineHeight: '2rem' } const body2FontSize = { fontSize: '1.1rem', lineHeight: '1.5rem', } const spacingUnit = 8 const typography = theme.typography || {} const defaultLWTheme = { breakpoints: { values: { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1400, }, }, spacing: { unit: spacingUnit }, typography: { postStyle: { fontFamily: typography.fontFamily, }, body1: body1FontSize, body2: { fontWeight: 400, linkUnderlinePosition: "72%", ...body2FontSize }, display1: { color: grey[800], fontSize: '2rem', marginTop: '1em' }, display2: { color: grey[800], fontSize: '2.8rem', marginTop: '1em' }, display3: { color: grey[800], marginTop: '1.2em', fontSize: '3rem' }, display4: { color: grey[800], }, title: { fontSize: 18, fontWeight: 400, marginBottom: 3, }, caption: { fontSize: ".9rem" }, blockquote: { fontWeight: 400, paddingTop: spacingUnit*2, paddingRight: spacingUnit*2, paddingBottom: spacingUnit*2, paddingLeft: spacingUnit*2, borderLeft: `solid 3px ${grey[300]}`, margin: 0, ...body1FontSize }, commentBlockquote: { fontWeight: 400, paddingTop: spacingUnit, paddingRight: spacingUnit*3, paddingBottom: spacingUnit, paddingLeft: spacingUnit*2, borderLeft: `solid 3px ${grey[300]}`, margin: 0, marginLeft: spacingUnit*1.5, ...body2FontSize }, codeblock: { backgroundColor: grey[100], borderRadius: "5px", border: `solid 1px ${grey[300]}`, padding: '1rem', whiteSpace: 'pre-wrap', margin: "1em 0", '& a, & a:hover, & a:active': { ...linkStyle({ theme, underlinePosition: (typography.codeblock && typography.codeblock.linkUnderlinePosition) || "97%", background: (typography.codeblock && typography.codeblock.backgroundColor) || grey[100] }), }, }, code: { fontFamily: monoStack, fontSize: ".9em", fontWeight: 400, backgroundColor: grey[100], borderRadius: 2, paddingTop: 3, paddingBottom: 3, lineHeight: 1.42 }, li: { marginBottom: '.5rem', }, commentHeader: { fontSize: '1.5rem', marginTop: '.5em', fontWeight:500, }, subheading: { fontSize:15, color: grey[600] }, subtitle: { fontSize: 16, fontWeight: 600, marginBottom: ".5rem" }, uiLink: { color: grey[500], '&:hover': { color:grey[300] } } }, zIndexes: { continueReadingImage: -1, commentsMenu: 1, sequencesPageContent: 1, sequencesImageScrim: 1, postsVote: 1, singleLineCommentMeta: 2, postItemTitle: 2, sidebarHoverOver: 2, singleLineCommentHover: 3, questionPageWhitescreen: 3, textbox: 4, nextUnread: 999, sunshineSidebar: 1000, postItemMenu: 1001, layout: 1100, tabNavigation: 1101, searchResults: 1102, header: 1300, karmaChangeNotifier: 1400, notificationsMenu: 1500, searchBar: 100000, }, voting: { strongVoteDelay: 1000, } } const mergedTheme = deepmerge(defaultLWTheme, theme, {isMergeableObject:isPlainObject}) const newTheme = createMuiTheme(mergedTheme) return newTheme } export default createLWTheme
packages/lesswrong/themes/createThemeDefaults.js
import { createMuiTheme } from '@material-ui/core/styles'; import grey from '@material-ui/core/colors/grey'; import deepmerge from 'deepmerge'; import isPlainObject from 'is-plain-object'; const monoStack = [ '"Liberation Mono"', 'Menlo', 'Courier', 'monospace' ].join(',') export const linkStyle = ({theme, underlinePosition="97%", background}) => { return ({ color: theme.palette.secondary.main, backgroundImage: `linear-gradient(to right, ${theme.palette.secondary.main} 72%, transparent 72%)`, backgroundSize: "4px 1px", backgroundRepeat: "repeat-x", backgroundPosition: `0% ${underlinePosition}`, textShadow: ` .03em 0 ${background || theme.palette.background.default}, -.03em 0 ${background || theme.palette.background.default}, 0 .03em ${background || theme.palette.background.default}, 0 -.03em ${background || theme.palette.background.default}, .06em 0 ${background || theme.palette.background.default}, -.06em 0 ${background || theme.palette.background.default}, .09em 0 ${background || theme.palette.background.default}, -.09em 0 ${background || theme.palette.background.default}, .12em 0 ${background || theme.palette.background.default}, -.12em 0 ${background || theme.palette.background.default}, .15em 0 ${background || theme.palette.background.default}, -.15em 0 ${background || theme.palette.background.default} `, textDecoration: "none", "*, *:after, &:after, *:before, &:before": { textShadow: "none" }, }) } const createLWTheme = (theme) => { // Defines sensible typography defaults that can be // cleanly overriden const body1FontSize = { fontSize: '1.4rem', lineHeight: '2rem' } const body2FontSize = { fontSize: '1.1rem', lineHeight: '1.5rem', } const spacingUnit = 8 const typography = theme.typography || {} const defaultLWTheme = { breakpoints: { values: { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1400, }, }, spacing: { unit: spacingUnit }, typography: { postStyle: { fontFamily: typography.fontFamily, }, body1: body1FontSize, body2: { fontWeight: 400, linkUnderlinePosition: "72%", ...body2FontSize }, display1: { color: grey[800], fontSize: '2rem', marginTop: '1em' }, display2: { color: grey[800], fontSize: '2.8rem', marginTop: '1em' }, display3: { color: grey[800], marginTop: '1.2em', fontSize: '3rem' }, display4: { color: grey[800], }, title: { fontSize: 18, fontWeight: 400, marginBottom: 3, }, caption: { fontSize: ".9rem" }, blockquote: { fontWeight: 400, paddingTop: spacingUnit*2, paddingRight: spacingUnit*2, paddingBottom: spacingUnit*2, paddingLeft: spacingUnit*2, borderLeft: `solid 3px ${grey[300]}`, margin: 0, ...body1FontSize }, commentBlockquote: { fontWeight: 400, paddingTop: spacingUnit, paddingRight: spacingUnit*3, paddingBottom: spacingUnit, paddingLeft: spacingUnit*2, borderLeft: `solid 3px ${grey[300]}`, margin: 0, marginLeft: spacingUnit*1.5, ...body2FontSize }, codeblock: { backgroundColor: grey[100], borderRadius: "5px", border: `solid 1px ${grey[300]}`, padding: '1rem', whiteSpace: 'pre-wrap', margin: "1em 0", '& a, & a:hover, & a:active': { ...linkStyle({ theme, underlinePosition: (typography.codeblock && typography.codeblock.linkUnderlinePosition) || "97%", background: (typography.codeblock && typography.codeblock.backgroundColor) || grey[100] }), }, }, code: { fontFamily: monoStack, fontSize: ".9em", fontWeight: 400, backgroundColor: grey[100], borderRadius: 2, padding: 3, lineHeight: 1.42 }, li: { marginBottom: '.5rem', }, commentHeader: { fontSize: '1.5rem', marginTop: '.5em', fontWeight:500, }, subheading: { fontSize:15, color: grey[600] }, subtitle: { fontSize: 16, fontWeight: 600, marginBottom: ".5rem" }, uiLink: { color: grey[500], '&:hover': { color:grey[300] } } }, zIndexes: { continueReadingImage: -1, commentsMenu: 1, sequencesPageContent: 1, sequencesImageScrim: 1, postsVote: 1, singleLineCommentMeta: 2, postItemTitle: 2, sidebarHoverOver: 2, singleLineCommentHover: 3, questionPageWhitescreen: 3, textbox: 4, nextUnread: 999, sunshineSidebar: 1000, postItemMenu: 1001, layout: 1100, tabNavigation: 1101, searchResults: 1102, header: 1300, karmaChangeNotifier: 1400, notificationsMenu: 1500, searchBar: 100000, }, voting: { strongVoteDelay: 1000, } } const mergedTheme = deepmerge(defaultLWTheme, theme, {isMergeableObject:isPlainObject}) const newTheme = createMuiTheme(mergedTheme) return newTheme } export default createLWTheme
Fix misaligned first lines of code blocks
packages/lesswrong/themes/createThemeDefaults.js
Fix misaligned first lines of code blocks
<ide><path>ackages/lesswrong/themes/createThemeDefaults.js <ide> fontWeight: 400, <ide> backgroundColor: grey[100], <ide> borderRadius: 2, <del> padding: 3, <add> paddingTop: 3, <add> paddingBottom: 3, <ide> lineHeight: 1.42 <ide> }, <ide> li: {
Java
apache-2.0
d3ae45450fba5a574af02576d970d74b3d23a719
0
Gigaspaces/xap-mule
/* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.itest.esb.mule.pu; import org.openspaces.core.GigaSpace; import org.openspaces.core.GigaSpaceConfigurer; import org.openspaces.core.space.UrlSpaceConfigurer; import org.openspaces.itest.esb.mule.SimpleMessage; import org.springframework.test.AbstractDependencyInjectionSpringContextTests; /** * Test the ability to run PU with mule embedded in it. * * @author yitzhaki */ public class PUEmbedMuleRef2Tests extends AbstractDependencyInjectionSpringContextTests { protected String[] getConfigLocations() { return new String[]{"org/openspaces/itest/esb/mule/pu/puembedmuleref2.xml"}; } public void testTakeSingleFromSpace() throws Exception { GigaSpace gigaSpace = new GigaSpaceConfigurer(new UrlSpaceConfigurer("jini://*/*/space").lookupGroups(System.getProperty("user.name")).space()).gigaSpace(); gigaSpace.clear(null); int numberOfMsgs = 10; for (int i = 0; i < numberOfMsgs; i++) { SimpleMessage message = new SimpleMessage("Hello World " + i, false); gigaSpace.write(message); } //blocking wait untill the mule writes back the messages to the space after reading them. for (int i = 0; i < numberOfMsgs; i++) { SimpleMessage template = new SimpleMessage("Hello World " + i, true); SimpleMessage message = gigaSpace.take(template, 5000); assertNotNull(message); } assertEquals(0, gigaSpace.count(new SimpleMessage())); } }
mule-latest/src/test/java/org/openspaces/itest/esb/mule/pu/PUEmbedMuleRef2Tests.java
/* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.itest.esb.mule.pu; import org.openspaces.core.GigaSpace; import org.openspaces.core.GigaSpaceConfigurer; import org.openspaces.core.space.UrlSpaceConfigurer; import org.openspaces.itest.esb.mule.SimpleMessage; import org.springframework.test.AbstractDependencyInjectionSpringContextTests; /** * Test the ability to run PU with mule imbedded in it. * * @author yitzhaki */ public class PUEmbedMuleRef2Tests extends AbstractDependencyInjectionSpringContextTests { protected String[] getConfigLocations() { return new String[]{"org/openspaces/itest/esb/mule/pu/puembedmuleref2.xml"}; } public void testTakeSingleFromSpace() throws Exception { GigaSpace gigaSpace = new GigaSpaceConfigurer(new UrlSpaceConfigurer("jini://*/*/space").lookupGroups(System.getProperty("user.name")).space()).gigaSpace(); gigaSpace.clear(null); int numberOfMsgs = 10; for (int i = 0; i < numberOfMsgs; i++) { SimpleMessage message = new SimpleMessage("Hello World " + i, false); gigaSpace.write(message); } //blocking wait untill the mule writes back the messages to the space after reading them. for (int i = 0; i < numberOfMsgs; i++) { SimpleMessage template = new SimpleMessage("Hello World " + i, true); SimpleMessage message = gigaSpace.take(template, 5000); assertNotNull(message); } assertEquals(0, gigaSpace.count(new SimpleMessage())); } }
Fix typos git-svn-id: 05e4ff1a4c848ee86df763ec182ab9b6b2f55dc8@129937 eb64e737-3616-4df0-8941-5ee2ae88103d
mule-latest/src/test/java/org/openspaces/itest/esb/mule/pu/PUEmbedMuleRef2Tests.java
Fix typos
<ide><path>ule-latest/src/test/java/org/openspaces/itest/esb/mule/pu/PUEmbedMuleRef2Tests.java <ide> import org.springframework.test.AbstractDependencyInjectionSpringContextTests; <ide> <ide> /** <del> * Test the ability to run PU with mule imbedded in it. <add> * Test the ability to run PU with mule embedded in it. <ide> * <ide> * @author yitzhaki <ide> */
JavaScript
mit
ccf9d39bb48e64a755553f8cd3d7266d6a3b112a
0
AlloyTeam/AlloyTouch,AlloyTeam/AlloyTouch
/* AlloyTouch * By AlloyTeam http://www.alloyteam.com/ * Github: https://github.com/AlloyTeam/AlloyTouch * MIT Licensed. */ ; (function () { (function () { var lastTime = 0; var vendors = ['webkit', 'moz']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function (callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function (id) { clearTimeout(id); }; }()); //many thanks to http://greweb.me/2012/02/bezier-curve-based-easing-functions-from-concept-to-implementation/ function KeySpline(mX1, mY1, mX2, mY2) { this.get = function (aX) { if (mX1 == mY1 && mX2 == mY2) return aX; // linear return CalcBezier(GetTForX(aX), mY1, mY2); } function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; } function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; } function C(aA1) { return 3.0 * aA1; } // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. function CalcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; } // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. function GetSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); } function GetTForX(aX) { // Newton raphson iteration var aGuessT = aX; for (var i = 0; i < 4; ++i) { var currentSlope = GetSlope(aGuessT, mX1, mX2); if (currentSlope == 0.0) return aGuessT; var currentX = CalcBezier(aGuessT, mX1, mX2) - aX; aGuessT -= currentX / currentSlope; } return aGuessT; } } function bind(element, type, callback) { element.addEventListener(type, callback, false); } //http://kmdjs.github.io/dnt/demo43/index.html function iosEase(x) { return Math.sqrt(1 - Math.pow(x - 1, 2)); } function preventDefaultTest (el, exceptions) { for (var i in exceptions) { if (exceptions[i].test(el[i])) { return true; } } return false; } var AlloyTouch = function (option) { this.scroller = option.target; this.element = typeof option.touch === "string" ? document.querySelector(option.touch) : option.touch; this.vertical = option.vertical === undefined ? true : option.vertical; this.property = option.property; this.tickID = 0; this.preX; this.preY; this.sensitivity = option.sensitivity === undefined ? 1 : option.sensitivity; this.factor = option.factor === undefined ? 1 : option.factor; this.sMf = this.sensitivity * this.factor; //拖动时候的摩擦因子 this.factor1 = 1; this.min = option.min; this.max = option.max; this.startTime; this.start; this.easing = new KeySpline(0.1, 0.57, 0.1, 1); this.recording = false; this.deceleration = 0.0006; this.change = option.change || function () { }; this.touchEnd = option.touchEnd || function () { }; this.touchStart = option.touchStart || function () { }; this.touchMove = option.touchMove || function () { }; this.reboundEnd = option.reboundEnd || function () { }; this.preventDefaultException = { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ }; this.hasMin = !(this.min === undefined); this.hasMax = !(this.max === undefined); this.isTouchStart = false; this.step = option.step; this.spring = option.spring === undefined ? true : false; bind(this.element, "touchstart", this._start.bind(this)); bind(window, "touchmove", this._move.bind(this)); bind(window, "touchend", this._end.bind(this)); } AlloyTouch.prototype = { _start: function (evt) { this.isTouchStart = true; this.touchStart(this.scroller[this.property]); cancelAnimationFrame(this.tickID); this.startTime = new Date().getTime(); this.preX = evt.touches[0].pageX; this.preY = evt.touches[0].pageY; this.start = this.vertical ? this.preY : this.preX; if (!preventDefaultTest(evt.target, this.preventDefaultException)) { evt.preventDefault(); } }, _move: function (evt) { if (this.isTouchStart) { var d = (this.vertical ? evt.touches[0].pageY - this.preY : evt.touches[0].pageX - this.preX) * this.sMf; if (this.hasMax && this.scroller[this.property] > this.max && d > 0) { this.factor1 = 0.3; } else if (this.hasMin && this.scroller[this.property] < this.min && d < 0) { this.factor1 = 0.3; } else { this.factor1 = 1; } d *= this.factor1; this.preX = evt.touches[0].pageX; this.preY = evt.touches[0].pageY; this.scroller[this.property] += d; this.change(this.scroller[this.property]); var timestamp = new Date().getTime(); if (timestamp - this.startTime > 300) { this.startTime = timestamp; this.start = this.vertical ? this.preY : this.preX; } this.touchMove(this.scroller[this.property]); evt.preventDefault(); } }, _end: function (evt) { if (this.isTouchStart) { var self = this; this.touchEnd(this.scroller[this.property]); if (this.hasMax && this.scroller[this.property] > this.max) { this.to(this.scroller, this.property, this.max, 200, iosEase, this.change, this.reboundEnd); } else if (this.hasMin && this.scroller[this.property] < this.min) { this.to(this.scroller, this.property, this.min, 200, iosEase, this.change, this.reboundEnd); } else { //var y = evt.changedTouches[0].pageY; var duration = new Date().getTime() - this.startTime; if (duration < 300) { var distance = ((this.vertical ? evt.changedTouches[0].pageY : evt.changedTouches[0].pageX) - this.start) * this.sensitivity, speed = Math.abs(distance) / duration, speed2 = this.factor * speed, destination = this.scroller[this.property] + (speed2 * speed2) / (2 * this.deceleration) * (distance < 0 ? -1 : 1); self.to(this.scroller, this.property, Math.round(destination), Math.round(speed / self.deceleration), self.easing.get, function (value) { if (self.spring) { if (self.hasMax && self.scroller[self.property] > self.max) { setTimeout(function () { cancelAnimationFrame(self.tickID); self.to(self.scroller, self.property, self.max, 200, iosEase, self.change); }, 50); } else if (self.hasMin && self.scroller[self.property] < self.min) { setTimeout(function () { cancelAnimationFrame(self.tickID); self.to(self.scroller, self.property, self.min, 200, iosEase, self.change); }, 50); } } else { if (self.hasMax && self.scroller[self.property] > self.max) { cancelAnimationFrame(self.tickID); self.scroller[self.property] = self.max; } else if (self.hasMin && self.scroller[self.property] < self.min) { cancelAnimationFrame(self.tickID); self.scroller[self.property] = self.min; } } self.change(self.scroller[self.property]); }, function () { if (self.step) { self.correction(self.scroller, self.property); } }); } else { if (self.step) { self.correction(self.scroller, self.property); } } } if (!preventDefaultTest(evt.target, this.preventDefaultException)) { evt.preventDefault(); } this.isTouchStart = false; } }, to: function (el, property, value, time, ease, onChange, onEnd) { var current = el[property]; var dv = value - current; var beginTime = new Date(); var self = this; var toTick = function () { var dt = new Date() - beginTime; if (dt >= time) { el[property] = value; onChange && onChange(value); onEnd && onEnd(value); return; } el[property] = Math.round(dv * ease(dt / time) + current); self.tickID = requestAnimationFrame(toTick); //cancelAnimationFrame必须在 tickID = requestAnimationFrame(toTick);的后面 onChange && onChange(el[property]); } toTick(); }, correction: function (el, property) { var value = el[property]; var rpt = Math.floor(Math.abs(value / this.step)); var dy = value % this.step; if (Math.abs(dy) > this.step / 2) { this.to(el, property, (value < 0 ? -1 : 1) * (rpt + 1) * this.step, 400, iosEase, this.change); } else { this.to(el, property, (value < 0 ? -1 : 1) * rpt * this.step, 400, iosEase, this.change); } } } window.AlloyTouch = AlloyTouch; })();
alloy_touch.js
/* AlloyTouch * By AlloyTeam http://www.alloyteam.com/ * Github: https://github.com/AlloyTeam/AlloyTouch * MIT Licensed. */ ; (function () { (function () { var lastTime = 0; var vendors = ['webkit', 'moz']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function (callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function (id) { clearTimeout(id); }; }()); //many thanks to http://greweb.me/2012/02/bezier-curve-based-easing-functions-from-concept-to-implementation/ function KeySpline(mX1, mY1, mX2, mY2) { this.get = function (aX) { if (mX1 == mY1 && mX2 == mY2) return aX; // linear return CalcBezier(GetTForX(aX), mY1, mY2); } function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; } function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; } function C(aA1) { return 3.0 * aA1; } // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. function CalcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; } // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. function GetSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); } function GetTForX(aX) { // Newton raphson iteration var aGuessT = aX; for (var i = 0; i < 4; ++i) { var currentSlope = GetSlope(aGuessT, mX1, mX2); if (currentSlope == 0.0) return aGuessT; var currentX = CalcBezier(aGuessT, mX1, mX2) - aX; aGuessT -= currentX / currentSlope; } return aGuessT; } } function bind(element, type, callback) { element.addEventListener(type, callback, false); } //http://kmdjs.github.io/dnt/demo43/index.html function iosEase(x) { return Math.sqrt(1 - Math.pow(x - 1, 2)); } function preventDefaultTest (el, exceptions) { for (var i in exceptions) { if (exceptions[i].test(el[i])) { return true; } } return false; } var AlloyTouch = function (option) { this.scroller = option.target; this.element = typeof option.touch === "string" ? document.querySelector(option.touch) : option.touch; this.vertical = option.vertical === undefined ? true : option.vertical; this.property = option.property; this.tickID = 0; this.preX; this.preY; this.sensitivity = option.sensitivity === undefined ? 1 : option.sensitivity; this.factor = option.factor === undefined ? 1 : option.factor; this.sMf = this.sensitivity * this.factor; //拖动时候的摩擦因子 this.factor1 = 1; this.min = option.min; this.max = option.max; this.startTime; this.start; this.easing = new KeySpline(0.1, 0.57, 0.1, 1); this.recording = false; this.deceleration = 0.0006; this.change = option.change || function () { }; this.touchEnd = option.touchEnd || function () { }; this.touchStart = option.touchStart || function () { }; this.touchMove = option.touchMove || function () { }; this.reboundEnd = option.reboundEnd || function () { }; this.preventDefaultException = { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ }; this.hasMin = !(this.min === undefined); this.hasMax = !(this.max === undefined); this.isTouchStart = false; this.step = option.step; this.spring = option.spring === undefined ? true : false; bind(this.element, "touchstart", this._start.bind(this)); bind(window, "touchmove", this._move.bind(this)); bind(window, "touchend", this._end.bind(this)); } AlloyTouch.prototype = { _start: function (evt) { this.isTouchStart = true; this.touchStart(this.scroller[this.property]); cancelAnimationFrame(this.tickID); this.startTime = new Date().getTime(); this.preX = evt.touches[0].pageX; this.preY = evt.touches[0].pageY; this.start = this.vertical ? this.preY : this.preX; if (!preventDefaultTest(evt.target, this.preventDefaultException)) { evt.preventDefault(); } }, _move: function (evt) { if (this.isTouchStart) { var d = (this.vertical ? evt.touches[0].pageY - this.preY : evt.touches[0].pageX - this.preX) * this.sMf; if (this.hasMax && this.scroller[this.property] > this.max && d > 0) { this.factor1 = 0.3; } else if (this.hasMin && this.scroller[this.property] < this.min && d < 0) { this.factor1 = 0.3; } else { this.factor1 = 1; } d *= this.factor1; this.preX = evt.touches[0].pageX; this.preY = evt.touches[0].pageY; this.scroller[this.property] += d; this.change(this.scroller[this.property]); var timestamp = new Date().getTime(); if (timestamp - this.startTime > 300) { this.startTime = timestamp; this.start = this.vertical ? this.preY : this.preX; } this.touchMove(this.scroller[this.property]); evt.preventDefault(); } }, _end: function (evt) { if (this.isTouchStart) { this.touchEnd(this.scroller[this.property]); if (this.hasMax && this.scroller[this.property] > this.max) { this.to(this.scroller, this.property, this.max, 200, iosEase, this.change, this.reboundEnd); } else if (this.hasMin && this.scroller[this.property] < this.min) { this.to(this.scroller, this.property, this.min, 200, iosEase, this.change, this.reboundEnd); } else { //var y = evt.changedTouches[0].pageY; var duration = new Date().getTime() - this.startTime; if (duration < 300) { var distance = ((this.vertical ? evt.changedTouches[0].pageY : evt.changedTouches[0].pageX) - this.start) * this.sensitivity, speed = Math.abs(distance) / duration, speed2 = this.factor * speed, destination = this.scroller[this.property] + (speed2 * speed2) / (2 * this.deceleration) * (distance < 0 ? -1 : 1), self = this; self.to(this.scroller, this.property, Math.round(destination), Math.round(speed / self.deceleration), self.easing.get, function (value) { if (self.spring) { if (self.hasMax && self.scroller[self.property] > self.max) { setTimeout(function () { cancelAnimationFrame(self.tickID); self.to(self.scroller, self.property, self.max, 200, iosEase, self.change); }, 50); } else if (self.hasMin && self.scroller[self.property] < self.min) { setTimeout(function () { cancelAnimationFrame(self.tickID); self.to(self.scroller, self.property, self.min, 200, iosEase, self.change); }, 50); } } else { if (self.hasMax && self.scroller[self.property] > self.max) { cancelAnimationFrame(self.tickID); self.scroller[self.property] = self.max; } else if (self.hasMin && self.scroller[self.property] < self.min) { cancelAnimationFrame(self.tickID); self.scroller[self.property] = self.min; } } self.change(self.scroller[self.property]); }, function () { if (self.step) { self.correction(self.scroller, self.property); } }); } else { if (self.step) { self.correction(self.scroller, self.property); } } } if (!preventDefaultTest(evt.target, this.preventDefaultException)) { evt.preventDefault(); } this.isTouchStart = false; } }, to: function (el, property, value, time, ease, onChange, onEnd) { var current = el[property]; var dv = value - current; var beginTime = new Date(); var self = this; var toTick = function () { var dt = new Date() - beginTime; if (dt >= time) { el[property] = value; onChange && onChange(value); onEnd && onEnd(value); return; } el[property] = Math.round(dv * ease(dt / time) + current); self.tickID = requestAnimationFrame(toTick); //cancelAnimationFrame必须在 tickID = requestAnimationFrame(toTick);的后面 onChange && onChange(el[property]); } toTick(); }, correction: function (el, property) { var value = el[property]; var rpt = Math.floor(Math.abs(value / this.step)); var dy = value % this.step; if (Math.abs(dy) > this.step / 2) { this.to(el, property, (value < 0 ? -1 : 1) * (rpt + 1) * this.step, 400, iosEase, this.change); } else { this.to(el, property, (value < 0 ? -1 : 1) * rpt * this.step, 400, iosEase, this.change); } } } window.AlloyTouch = AlloyTouch; })();
fix self
alloy_touch.js
fix self
<ide><path>lloy_touch.js <ide> }, <ide> _end: function (evt) { <ide> if (this.isTouchStart) { <add> var self = this; <ide> this.touchEnd(this.scroller[this.property]); <ide> if (this.hasMax && this.scroller[this.property] > this.max) { <ide> this.to(this.scroller, this.property, this.max, 200, iosEase, this.change, this.reboundEnd); <ide> var distance = ((this.vertical ? evt.changedTouches[0].pageY : evt.changedTouches[0].pageX) - this.start) * this.sensitivity, <ide> speed = Math.abs(distance) / duration, <ide> speed2 = this.factor * speed, <del> destination = this.scroller[this.property] + (speed2 * speed2) / (2 * this.deceleration) * (distance < 0 ? -1 : 1), <del> self = this; <add> destination = this.scroller[this.property] + (speed2 * speed2) / (2 * this.deceleration) * (distance < 0 ? -1 : 1); <add> <ide> self.to(this.scroller, this.property, Math.round(destination), Math.round(speed / self.deceleration), self.easing.get, function (value) { <ide> <ide> if (self.spring) {
Java
apache-2.0
8bf379eadb10c632480614df7a849f0f6acaa276
0
emre-aydin/hazelcast,emrahkocaman/hazelcast,Donnerbart/hazelcast,tkountis/hazelcast,Donnerbart/hazelcast,mdogan/hazelcast,dbrimley/hazelcast,tufangorel/hazelcast,tombujok/hazelcast,emre-aydin/hazelcast,emrahkocaman/hazelcast,dsukhoroslov/hazelcast,Donnerbart/hazelcast,mesutcelik/hazelcast,dbrimley/hazelcast,mdogan/hazelcast,lmjacksoniii/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,tufangorel/hazelcast,juanavelez/hazelcast,mesutcelik/hazelcast,lmjacksoniii/hazelcast,tkountis/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,tombujok/hazelcast,mdogan/hazelcast,juanavelez/hazelcast,tkountis/hazelcast,tufangorel/hazelcast
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.web; import com.hazelcast.config.Config; import com.hazelcast.config.MapConfig; import com.hazelcast.core.EntryEvent; import com.hazelcast.core.EntryListener; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.logging.ILogger; import com.hazelcast.logging.Logger; import com.hazelcast.util.UuidUtil; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; @SuppressWarnings("deprecation") public class WebFilter implements Filter { protected static final String HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR = "::hz::"; private static final ILogger LOGGER = Logger.getLogger(WebFilter.class); private static final LocalCacheEntry NULL_ENTRY = new LocalCacheEntry(); private static final String HAZELCAST_REQUEST = "*hazelcast-request"; private static final String HAZELCAST_SESSION_COOKIE_NAME = "hazelcast.sessionId"; private static final ConcurrentMap<String, String> MAP_ORIGINAL_SESSIONS = new ConcurrentHashMap<String, String>(1000); private static final ConcurrentMap<String, HazelcastHttpSession> MAP_SESSIONS = new ConcurrentHashMap<String, HazelcastHttpSession>(1000); protected ServletContext servletContext; protected FilterConfig filterConfig; private String sessionCookieName = HAZELCAST_SESSION_COOKIE_NAME; private HazelcastInstance hazelcastInstance; private String clusterMapName = "none"; private String sessionCookieDomain; private boolean sessionCookieSecure; private boolean sessionCookieHttpOnly; private boolean stickySession = true; private boolean shutdownOnDestroy = true; private boolean deferredWrite; private Properties properties; public WebFilter() { } public WebFilter(Properties properties) { this(); this.properties = properties; } static void destroyOriginalSession(HttpSession originalSession) { String hazelcastSessionId = MAP_ORIGINAL_SESSIONS.remove(originalSession.getId()); if (hazelcastSessionId != null) { HazelcastHttpSession hazelSession = MAP_SESSIONS.remove(hazelcastSessionId); if (hazelSession != null) { hazelSession.webFilter.destroySession(hazelSession, false); } } } private static synchronized String generateSessionId() { final String id = UuidUtil.buildRandomUuidString(); final StringBuilder sb = new StringBuilder("HZ"); final char[] chars = id.toCharArray(); for (final char c : chars) { if (c != '-') { if (Character.isLetter(c)) { sb.append(Character.toUpperCase(c)); } else { sb.append(c); } } } return sb.toString(); } public final void init(final FilterConfig config) throws ServletException { filterConfig = config; servletContext = config.getServletContext(); initInstance(); String mapName = getParam("map-name"); if (mapName != null) { clusterMapName = mapName; } else { clusterMapName = "_web_" + servletContext.getServletContextName(); } try { Config hzConfig = hazelcastInstance.getConfig(); String sessionTTL = getParam("session-ttl-seconds"); if (sessionTTL != null) { MapConfig mapConfig = hzConfig.getMapConfig(clusterMapName); mapConfig.setTimeToLiveSeconds(Integer.parseInt(sessionTTL)); hzConfig.addMapConfig(mapConfig); } } catch (UnsupportedOperationException ignored) { LOGGER.info("client cannot access Config."); } initCookieParams(); initParams(); if (!stickySession) { getClusterMap().addEntryListener(new EntryListener<String, Object>() { public void entryAdded(EntryEvent<String, Object> entryEvent) { } public void entryRemoved(EntryEvent<String, Object> entryEvent) { if (entryEvent.getMember() == null || !entryEvent.getMember().localMember()) { removeSessionLocally(entryEvent.getKey()); } } public void entryUpdated(EntryEvent<String, Object> entryEvent) { } public void entryEvicted(EntryEvent<String, Object> entryEvent) { entryRemoved(entryEvent); } }, false); } if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("sticky:" + stickySession + ", shutdown-on-destroy: " + shutdownOnDestroy + ", map-name: " + clusterMapName); } } private void initParams() { String stickySessionParam = getParam("sticky-session"); if (stickySessionParam != null) { stickySession = Boolean.valueOf(stickySessionParam); } String shutdownOnDestroyParam = getParam("shutdown-on-destroy"); if (shutdownOnDestroyParam != null) { shutdownOnDestroy = Boolean.valueOf(shutdownOnDestroyParam); } String deferredWriteParam = getParam("deferred-write"); if (deferredWriteParam != null) { deferredWrite = Boolean.parseBoolean(deferredWriteParam); } } private void initCookieParams() { String cookieName = getParam("cookie-name"); if (cookieName != null) { sessionCookieName = cookieName; } String cookieDomain = getParam("cookie-domain"); if (cookieDomain != null) { sessionCookieDomain = cookieDomain; } String cookieSecure = getParam("cookie-secure"); if (cookieSecure != null) { sessionCookieSecure = Boolean.valueOf(cookieSecure); } String cookieHttpOnly = getParam("cookie-http-only"); if (cookieHttpOnly != null) { sessionCookieHttpOnly = Boolean.valueOf(cookieHttpOnly); } } private void initInstance() throws ServletException { if (properties == null) { properties = new Properties(); } setProperty(HazelcastInstanceLoader.CONFIG_LOCATION); setProperty(HazelcastInstanceLoader.INSTANCE_NAME); setProperty(HazelcastInstanceLoader.USE_CLIENT); setProperty(HazelcastInstanceLoader.CLIENT_CONFIG_LOCATION); hazelcastInstance = getInstance(properties); } private void setProperty(String propertyName) { String value = getParam(propertyName); if (value != null) { properties.setProperty(propertyName, value); } } private void removeSessionLocally(String sessionId) { HazelcastHttpSession hazelSession = MAP_SESSIONS.remove(sessionId); if (hazelSession != null) { MAP_ORIGINAL_SESSIONS.remove(hazelSession.originalSession.getId()); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("Destroying session locally " + hazelSession); } hazelSession.destroy(); } } private String extractAttributeKey(String key) { return key.substring(key.indexOf(HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR) + HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR.length()); } private HazelcastHttpSession createNewSession(RequestWrapper requestWrapper, String existingSessionId) { String id = existingSessionId != null ? existingSessionId : generateSessionId(); if (requestWrapper.getOriginalSession(false) != null) { LOGGER.finest("Original session exists!!!"); } HttpSession originalSession = requestWrapper.getOriginalSession(true); HazelcastHttpSession hazelcastSession = new HazelcastHttpSession(WebFilter.this, id, originalSession, deferredWrite); MAP_SESSIONS.put(hazelcastSession.getId(), hazelcastSession); String oldHazelcastSessionId = MAP_ORIGINAL_SESSIONS.put(originalSession.getId(), hazelcastSession.getId()); if (oldHazelcastSessionId != null) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("!!! Overriding an existing hazelcastSessionId " + oldHazelcastSessionId); } } if (LOGGER.isFinestEnabled()) { LOGGER.finest("Created new session with id: " + id); LOGGER.finest(MAP_SESSIONS.size() + " is sessions.size and originalSessions.size: " + MAP_ORIGINAL_SESSIONS.size()); } addSessionCookie(requestWrapper, id); if (deferredWrite) { loadHazelcastSession(hazelcastSession); } return hazelcastSession; } private void loadHazelcastSession(HazelcastHttpSession hazelcastSession) { Set<Entry<String, Object>> entrySet = getClusterMap().entrySet(new SessionAttributePredicate(hazelcastSession.getId())); Map<String, LocalCacheEntry> cache = hazelcastSession.localCache; for (Entry<String, Object> entry : entrySet) { String attributeKey = extractAttributeKey(entry.getKey()); LocalCacheEntry cacheEntry = cache.get(attributeKey); if (cacheEntry == null) { cacheEntry = new LocalCacheEntry(); cache.put(attributeKey, cacheEntry); } if (LOGGER.isFinestEnabled()) { LOGGER.finest("Storing " + attributeKey + " on session " + hazelcastSession.getId()); } cacheEntry.value = entry.getValue(); cacheEntry.dirty = false; } } private void prepareReloadingSession(HazelcastHttpSession hazelcastSession) { if (deferredWrite && hazelcastSession != null) { Map<String, LocalCacheEntry> cache = hazelcastSession.localCache; for (LocalCacheEntry cacheEntry : cache.values()) { cacheEntry.reload = true; } } } /** * Destroys a session, determining if it should be destroyed clusterwide automatically or via expiry. * * @param session The session to be destroyed * @param removeGlobalSession boolean value - true if the session should be destroyed irrespective of active time */ private void destroySession(HazelcastHttpSession session, boolean removeGlobalSession) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("Destroying local session: " + session.getId()); } MAP_SESSIONS.remove(session.getId()); MAP_ORIGINAL_SESSIONS.remove(session.originalSession.getId()); session.destroy(); if (removeGlobalSession) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("Destroying cluster session: " + session.getId() + " => Ignore-timeout: true"); } IMap<String, Object> clusterMap = getClusterMap(); clusterMap.delete(session.getId()); clusterMap.executeOnEntries(new InvalidateEntryProcessor(session.getId())); } } private IMap<String, Object> getClusterMap() { return hazelcastInstance.getMap(clusterMapName); } private HazelcastHttpSession getSessionWithId(final String sessionId) { HazelcastHttpSession session = MAP_SESSIONS.get(sessionId); if (session != null && !session.isValid()) { destroySession(session, true); session = null; } return session; } private void addSessionCookie(final RequestWrapper req, final String sessionId) { final Cookie sessionCookie = new Cookie(sessionCookieName, sessionId); String path = req.getContextPath(); if ("".equals(path)) { path = "/"; } sessionCookie.setPath(path); sessionCookie.setMaxAge(-1); if (sessionCookieDomain != null) { sessionCookie.setDomain(sessionCookieDomain); } try { sessionCookie.setHttpOnly(sessionCookieHttpOnly); } catch (NoSuchMethodError e) { LOGGER.info("must be servlet spec before 3.0, don't worry about it!"); } sessionCookie.setSecure(sessionCookieSecure); req.res.addCookie(sessionCookie); } private String getSessionCookie(final RequestWrapper req) { final Cookie[] cookies = req.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { final String name = cookie.getName(); final String value = cookie.getValue(); if (name.equalsIgnoreCase(sessionCookieName)) { return value; } } } return null; } public final void doFilter(ServletRequest req, ServletResponse res, final FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest)) { chain.doFilter(req, res); } else { if (req instanceof RequestWrapper) { LOGGER.finest("Request is instance of RequestWrapper! Continue..."); chain.doFilter(req, res); return; } HttpServletRequest httpReq = (HttpServletRequest) req; RequestWrapper existingReq = (RequestWrapper) req.getAttribute(HAZELCAST_REQUEST); final ResponseWrapper resWrapper = new ResponseWrapper((HttpServletResponse) res); final RequestWrapper reqWrapper = new RequestWrapper(httpReq, resWrapper); if (existingReq != null) { reqWrapper.setHazelcastSession(existingReq.hazelcastSession, existingReq.requestedSessionId); } chain.doFilter(reqWrapper, resWrapper); if (existingReq != null) { return; } HazelcastHttpSession session = reqWrapper.getSession(false); if (session != null && session.isValid() && (session.sessionChanged() || !deferredWrite)) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("PUTTING SESSION " + session.getId()); } session.sessionDeferredWrite(); } } } public final void destroy() { MAP_SESSIONS.clear(); MAP_ORIGINAL_SESSIONS.clear(); shutdownInstance(); } protected HazelcastInstance getInstance(Properties properties) throws ServletException { return HazelcastInstanceLoader.createInstance(filterConfig, properties); } protected void shutdownInstance() { if (shutdownOnDestroy && hazelcastInstance != null) { hazelcastInstance.getLifecycleService().shutdown(); } } private String getParam(String name) { if (properties != null && properties.containsKey(name)) { return properties.getProperty(name); } else { return filterConfig.getInitParameter(name); } } private static class ResponseWrapper extends HttpServletResponseWrapper { public ResponseWrapper(final HttpServletResponse original) { super(original); } } private static class LocalCacheEntry { volatile boolean dirty; volatile boolean reload; boolean removed; private Object value; } private class RequestWrapper extends HttpServletRequestWrapper { final ResponseWrapper res; HazelcastHttpSession hazelcastSession; String requestedSessionId; public RequestWrapper(final HttpServletRequest req, final ResponseWrapper res) { super(req); this.res = res; req.setAttribute(HAZELCAST_REQUEST, this); } public void setHazelcastSession(HazelcastHttpSession hazelcastSession, String requestedSessionId) { this.hazelcastSession = hazelcastSession; this.requestedSessionId = requestedSessionId; } HttpSession getOriginalSession(boolean create) { return super.getSession(create); } @Override public RequestDispatcher getRequestDispatcher(final String path) { final ServletRequest original = getRequest(); return new RequestDispatcher() { public void forward(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { original.getRequestDispatcher(path).forward(servletRequest, servletResponse); } public void include(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { original.getRequestDispatcher(path).include(servletRequest, servletResponse); } }; } public HazelcastHttpSession fetchHazelcastSession() { if (requestedSessionId == null) { requestedSessionId = getSessionCookie(this); } if (requestedSessionId == null) { requestedSessionId = getParameter(HAZELCAST_SESSION_COOKIE_NAME); } if (requestedSessionId != null) { hazelcastSession = getSessionWithId(requestedSessionId); if (hazelcastSession == null) { final Boolean existing = (Boolean) getClusterMap().get(requestedSessionId); if (existing != null && existing) { // we already have the session in the cluster loading it... hazelcastSession = createNewSession(RequestWrapper.this, requestedSessionId); } } } return hazelcastSession; } @Override public HttpSession getSession() { return getSession(true); } @Override public HazelcastHttpSession getSession(final boolean create) { if (hazelcastSession != null && !hazelcastSession.isValid()) { LOGGER.finest("Session is invalid!"); destroySession(hazelcastSession, true); hazelcastSession = null; } else if (hazelcastSession != null) { return hazelcastSession; } HttpSession originalSession = getOriginalSession(false); if (originalSession != null) { String hazelcastSessionId = MAP_ORIGINAL_SESSIONS.get(originalSession.getId()); if (hazelcastSessionId != null) { hazelcastSession = MAP_SESSIONS.get(hazelcastSessionId); return hazelcastSession; } MAP_ORIGINAL_SESSIONS.remove(originalSession.getId()); originalSession.invalidate(); } hazelcastSession = fetchHazelcastSession(); if (hazelcastSession == null && create) { hazelcastSession = createNewSession(RequestWrapper.this, null); } if (deferredWrite) { prepareReloadingSession(hazelcastSession); } return hazelcastSession; } } // END of RequestWrapper private class HazelcastHttpSession implements HttpSession { volatile boolean valid = true; final String id; final HttpSession originalSession; final WebFilter webFilter; private final Map<String, LocalCacheEntry> localCache; private final boolean deferredWrite; public HazelcastHttpSession(WebFilter webFilter, final String sessionId, HttpSession originalSession, boolean deferredWrite) { this.webFilter = webFilter; this.id = sessionId; this.originalSession = originalSession; this.deferredWrite = deferredWrite; this.localCache = deferredWrite ? new ConcurrentHashMap<String, LocalCacheEntry>() : null; } public Object getAttribute(final String name) { IMap<String, Object> clusterMap = getClusterMap(); if (deferredWrite) { LocalCacheEntry cacheEntry = localCache.get(name); if (cacheEntry == null || cacheEntry.reload) { Object value = clusterMap.get(buildAttributeName(name)); if (value == null) { cacheEntry = NULL_ENTRY; } else { cacheEntry = new LocalCacheEntry(); cacheEntry.value = value; cacheEntry.reload = false; } localCache.put(name, cacheEntry); } return cacheEntry != NULL_ENTRY ? cacheEntry.value : null; } return clusterMap.get(buildAttributeName(name)); } public Enumeration<String> getAttributeNames() { final Set<String> keys = selectKeys(); return new Enumeration<String>() { private final String[] elements = keys.toArray(new String[keys.size()]); private int index; @Override public boolean hasMoreElements() { return index < elements.length; } @Override public String nextElement() { return elements[index++]; } }; } public String getId() { return id; } public ServletContext getServletContext() { return servletContext; } public HttpSessionContext getSessionContext() { return originalSession.getSessionContext(); } public Object getValue(final String name) { return getAttribute(name); } public String[] getValueNames() { final Set<String> keys = selectKeys(); return keys.toArray(new String[keys.size()]); } public void invalidate() { originalSession.invalidate(); destroySession(this, true); } public boolean isNew() { return originalSession.isNew(); } public void putValue(final String name, final Object value) { setAttribute(name, value); } public void removeAttribute(final String name) { if (deferredWrite) { LocalCacheEntry entry = localCache.get(name); if (entry != null && entry != NULL_ENTRY) { entry.value = null; entry.removed = true; // dirty needs to be set as last value for memory visibility reasons! entry.dirty = true; } } else { getClusterMap().delete(buildAttributeName(name)); } } public void setAttribute(final String name, final Object value) { if (name == null) { throw new NullPointerException("name must not be null"); } if (value == null) { removeAttribute(name); } if (deferredWrite) { LocalCacheEntry entry = localCache.get(name); if (entry == null || entry == NULL_ENTRY) { entry = new LocalCacheEntry(); localCache.put(name, entry); } entry.value = value; entry.dirty = true; } else { getClusterMap().put(buildAttributeName(name), value); } } public void removeValue(final String name) { removeAttribute(name); } public boolean sessionChanged() { if (!deferredWrite) { return false; } for (Entry<String, LocalCacheEntry> entry : localCache.entrySet()) { if (entry.getValue().dirty) { return true; } } return false; } public long getCreationTime() { return originalSession.getCreationTime(); } public long getLastAccessedTime() { return originalSession.getLastAccessedTime(); } public int getMaxInactiveInterval() { return originalSession.getMaxInactiveInterval(); } public void setMaxInactiveInterval(int maxInactiveSeconds) { originalSession.setMaxInactiveInterval(maxInactiveSeconds); } void destroy() { valid = false; } public boolean isValid() { return valid; } private String buildAttributeName(String name) { return id + HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR + name; } private void sessionDeferredWrite() { IMap<String, Object> clusterMap = getClusterMap(); if (deferredWrite) { Iterator<Entry<String, LocalCacheEntry>> iterator = localCache.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, LocalCacheEntry> entry = iterator.next(); if (entry.getValue().dirty) { LocalCacheEntry cacheEntry = entry.getValue(); if (cacheEntry.removed) { clusterMap.delete(buildAttributeName(entry.getKey())); iterator.remove(); } else { clusterMap.put(buildAttributeName(entry.getKey()), cacheEntry.value); cacheEntry.dirty = false; } } } } if (!clusterMap.containsKey(id)) { clusterMap.put(id, Boolean.TRUE); } } private Set<String> selectKeys() { Set<String> keys = new HashSet<String>(); if (!deferredWrite) { for (String qualifiedAttributeKey : getClusterMap().keySet(new SessionAttributePredicate(id))) { keys.add(extractAttributeKey(qualifiedAttributeKey)); } } else { for (Entry<String, LocalCacheEntry> entry : localCache.entrySet()) { if (!entry.getValue().removed && entry.getValue() != NULL_ENTRY) { keys.add(entry.getKey()); } } } return keys; } } // END of HazelSession } // END of WebFilter
hazelcast-wm/src/main/java/com/hazelcast/web/WebFilter.java
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.web; import com.hazelcast.config.Config; import com.hazelcast.config.MapConfig; import com.hazelcast.core.EntryEvent; import com.hazelcast.core.EntryListener; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.logging.ILogger; import com.hazelcast.logging.Logger; import com.hazelcast.util.UuidUtil; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; @SuppressWarnings("deprecation") public class WebFilter implements Filter { protected static final String HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR = "::hz::"; private static final ILogger LOGGER = Logger.getLogger(WebFilter.class); private static final LocalCacheEntry NULL_ENTRY = new LocalCacheEntry(); private static final String HAZELCAST_REQUEST = "*hazelcast-request"; private static final String HAZELCAST_SESSION_COOKIE_NAME = "hazelcast.sessionId"; private static final ConcurrentMap<String, String> MAP_ORIGINAL_SESSIONS = new ConcurrentHashMap<String, String>(1000); private static final ConcurrentMap<String, HazelcastHttpSession> MAP_SESSIONS = new ConcurrentHashMap<String, HazelcastHttpSession>(1000); protected ServletContext servletContext; protected FilterConfig filterConfig; private String sessionCookieName = HAZELCAST_SESSION_COOKIE_NAME; private HazelcastInstance hazelcastInstance; private String clusterMapName = "none"; private String sessionCookieDomain; private boolean sessionCookieSecure; private boolean sessionCookieHttpOnly; private boolean stickySession = true; private boolean shutdownOnDestroy = true; private boolean deferredWrite; private Properties properties; public WebFilter() { } public WebFilter(Properties properties) { this(); this.properties = properties; } static void destroyOriginalSession(HttpSession originalSession) { String hazelcastSessionId = MAP_ORIGINAL_SESSIONS.remove(originalSession.getId()); if (hazelcastSessionId != null) { HazelcastHttpSession hazelSession = MAP_SESSIONS.remove(hazelcastSessionId); if (hazelSession != null) { hazelSession.webFilter.destroySession(hazelSession, false); } } } private static synchronized String generateSessionId() { final String id = UuidUtil.buildRandomUuidString(); final StringBuilder sb = new StringBuilder("HZ"); final char[] chars = id.toCharArray(); for (final char c : chars) { if (c != '-') { if (Character.isLetter(c)) { sb.append(Character.toUpperCase(c)); } else { sb.append(c); } } } return sb.toString(); } public final void init(final FilterConfig config) throws ServletException { filterConfig = config; servletContext = config.getServletContext(); initInstance(); String mapName = getParam("map-name"); if (mapName != null) { clusterMapName = mapName; } else { clusterMapName = "_web_" + servletContext.getServletContextName(); } try { Config hzConfig = hazelcastInstance.getConfig(); String sessionTTL = getParam("session-ttl-seconds"); if (sessionTTL != null) { MapConfig mapConfig = hzConfig.getMapConfig(clusterMapName); mapConfig.setTimeToLiveSeconds(Integer.parseInt(sessionTTL)); hzConfig.addMapConfig(mapConfig); } } catch (UnsupportedOperationException ignored) { LOGGER.info("client cannot access Config."); } initCookieParams(); initParams(); if (!stickySession) { getClusterMap().addEntryListener(new EntryListener<String, Object>() { public void entryAdded(EntryEvent<String, Object> entryEvent) { } public void entryRemoved(EntryEvent<String, Object> entryEvent) { if (entryEvent.getMember() == null || !entryEvent.getMember().localMember()) { removeSessionLocally(entryEvent.getKey()); } } public void entryUpdated(EntryEvent<String, Object> entryEvent) { } public void entryEvicted(EntryEvent<String, Object> entryEvent) { entryRemoved(entryEvent); } }, false); } if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("sticky:" + stickySession + ", shutdown-on-destroy: " + shutdownOnDestroy + ", map-name: " + clusterMapName); } } private void initParams() { String stickySessionParam = getParam("sticky-session"); if (stickySessionParam != null) { stickySession = Boolean.valueOf(stickySessionParam); } String shutdownOnDestroyParam = getParam("shutdown-on-destroy"); if (shutdownOnDestroyParam != null) { shutdownOnDestroy = Boolean.valueOf(shutdownOnDestroyParam); } String deferredWriteParam = getParam("deferred-write"); if (deferredWriteParam != null) { deferredWrite = Boolean.parseBoolean(deferredWriteParam); } } private void initCookieParams() { String cookieName = getParam("cookie-name"); if (cookieName != null) { sessionCookieName = cookieName; } String cookieDomain = getParam("cookie-domain"); if (cookieDomain != null) { sessionCookieDomain = cookieDomain; } String cookieSecure = getParam("cookie-secure"); if (cookieSecure != null) { sessionCookieSecure = Boolean.valueOf(cookieSecure); } String cookieHttpOnly = getParam("cookie-http-only"); if (cookieHttpOnly != null) { sessionCookieHttpOnly = Boolean.valueOf(cookieHttpOnly); } } private void initInstance() throws ServletException { if (properties == null) { properties = new Properties(); } setProperty(HazelcastInstanceLoader.CONFIG_LOCATION); setProperty(HazelcastInstanceLoader.INSTANCE_NAME); setProperty(HazelcastInstanceLoader.USE_CLIENT); setProperty(HazelcastInstanceLoader.CLIENT_CONFIG_LOCATION); hazelcastInstance = getInstance(properties); } private void setProperty(String propertyName) { String value = getParam(propertyName); if (value != null) { properties.setProperty(propertyName, value); } } private void removeSessionLocally(String sessionId) { HazelcastHttpSession hazelSession = MAP_SESSIONS.remove(sessionId); if (hazelSession != null) { MAP_ORIGINAL_SESSIONS.remove(hazelSession.originalSession.getId()); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("Destroying session locally " + hazelSession); } hazelSession.destroy(); } } private String extractAttributeKey(String key) { return key.substring(key.indexOf(HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR) + HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR.length()); } private HazelcastHttpSession createNewSession(RequestWrapper requestWrapper, String existingSessionId) { String id = existingSessionId != null ? existingSessionId : generateSessionId(); if (requestWrapper.getOriginalSession(false) != null) { LOGGER.finest("Original session exists!!!"); } HttpSession originalSession = requestWrapper.getOriginalSession(true); HazelcastHttpSession hazelcastSession = new HazelcastHttpSession(WebFilter.this, id, originalSession, deferredWrite); MAP_SESSIONS.put(hazelcastSession.getId(), hazelcastSession); String oldHazelcastSessionId = MAP_ORIGINAL_SESSIONS.put(originalSession.getId(), hazelcastSession.getId()); if (oldHazelcastSessionId != null) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("!!! Overriding an existing hazelcastSessionId " + oldHazelcastSessionId); } } if (LOGGER.isFinestEnabled()) { LOGGER.finest("Created new session with id: " + id); LOGGER.finest(MAP_SESSIONS.size() + " is sessions.size and originalSessions.size: " + MAP_ORIGINAL_SESSIONS.size()); } addSessionCookie(requestWrapper, id); if (deferredWrite) { loadHazelcastSession(hazelcastSession); } return hazelcastSession; } private void loadHazelcastSession(HazelcastHttpSession hazelcastSession) { Set<Entry<String, Object>> entrySet = getClusterMap().entrySet(new SessionAttributePredicate(hazelcastSession.getId())); Map<String, LocalCacheEntry> cache = hazelcastSession.localCache; for (Entry<String, Object> entry : entrySet) { String attributeKey = extractAttributeKey(entry.getKey()); LocalCacheEntry cacheEntry = cache.get(attributeKey); if (cacheEntry == null) { cacheEntry = new LocalCacheEntry(); cache.put(attributeKey, cacheEntry); } if (LOGGER.isFinestEnabled()) { LOGGER.finest("Storing " + attributeKey + " on session " + hazelcastSession.getId()); } cacheEntry.value = entry.getValue(); cacheEntry.dirty = false; } } private void prepareReloadingSession(HazelcastHttpSession hazelcastSession) { if (deferredWrite && hazelcastSession != null) { Map<String, LocalCacheEntry> cache = hazelcastSession.localCache; for (LocalCacheEntry cacheEntry : cache.values()) { cacheEntry.reload = true; } } } /** * Destroys a session, determining if it should be destroyed clusterwide automatically or via expiry. * * @param session The session to be destroyed * @param removeGlobalSession boolean value - true if the session should be destroyed irrespective of active time */ private void destroySession(HazelcastHttpSession session, boolean removeGlobalSession) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("Destroying local session: " + session.getId()); } MAP_SESSIONS.remove(session.getId()); MAP_ORIGINAL_SESSIONS.remove(session.originalSession.getId()); session.destroy(); if (removeGlobalSession) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("Destroying cluster session: " + session.getId() + " => Ignore-timeout: true"); } IMap<String, Object> clusterMap = getClusterMap(); clusterMap.delete(session.getId()); clusterMap.executeOnEntries(new InvalidateEntryProcessor(session.getId())); } } private IMap<String, Object> getClusterMap() { return hazelcastInstance.getMap(clusterMapName); } private HazelcastHttpSession getSessionWithId(final String sessionId) { HazelcastHttpSession session = MAP_SESSIONS.get(sessionId); if (session != null && !session.isValid()) { destroySession(session, true); session = null; } return session; } private void addSessionCookie(final RequestWrapper req, final String sessionId) { final Cookie sessionCookie = new Cookie(sessionCookieName, sessionId); String path = req.getContextPath(); if ("".equals(path)) { path = "/"; } sessionCookie.setPath(path); sessionCookie.setMaxAge(-1); if (sessionCookieDomain != null) { sessionCookie.setDomain(sessionCookieDomain); } try { sessionCookie.setHttpOnly(sessionCookieHttpOnly); } catch (NoSuchMethodError e) { LOGGER.info("must be servlet spec before 3.0, don't worry about it!"); } sessionCookie.setSecure(sessionCookieSecure); req.res.addCookie(sessionCookie); } private String getSessionCookie(final RequestWrapper req) { final Cookie[] cookies = req.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { final String name = cookie.getName(); final String value = cookie.getValue(); if (name.equalsIgnoreCase(sessionCookieName)) { return value; } } } return null; } public final void doFilter(ServletRequest req, ServletResponse res, final FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest)) { chain.doFilter(req, res); } else { if (req instanceof RequestWrapper) { LOGGER.finest("Request is instance of RequestWrapper! Continue..."); chain.doFilter(req, res); return; } HttpServletRequest httpReq = (HttpServletRequest) req; RequestWrapper existingReq = (RequestWrapper) req.getAttribute(HAZELCAST_REQUEST); final ResponseWrapper resWrapper = new ResponseWrapper((HttpServletResponse) res); final RequestWrapper reqWrapper = new RequestWrapper(httpReq, resWrapper); if (existingReq != null) { reqWrapper.setHazelcastSession(existingReq.hazelcastSession, existingReq.requestedSessionId); } chain.doFilter(reqWrapper, resWrapper); if (existingReq != null) { return; } HazelcastHttpSession session = reqWrapper.getSession(false); if (session != null && session.isValid() && (session.sessionChanged() || !deferredWrite)) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("PUTTING SESSION " + session.getId()); } session.sessionDeferredWrite(); } } } public final void destroy() { MAP_SESSIONS.clear(); MAP_ORIGINAL_SESSIONS.clear(); shutdownInstance(); } protected HazelcastInstance getInstance(Properties properties) throws ServletException { return HazelcastInstanceLoader.createInstance(filterConfig, properties); } protected void shutdownInstance() { if (shutdownOnDestroy && hazelcastInstance != null) { hazelcastInstance.getLifecycleService().shutdown(); } } private String getParam(String name) { if (properties != null && properties.containsKey(name)) { return properties.getProperty(name); } else { return filterConfig.getInitParameter(name); } } private static class ResponseWrapper extends HttpServletResponseWrapper { public ResponseWrapper(final HttpServletResponse original) { super(original); } } private static class LocalCacheEntry { volatile boolean dirty; volatile boolean reload; boolean removed; private Object value; } private class RequestWrapper extends HttpServletRequestWrapper { final ResponseWrapper res; HazelcastHttpSession hazelcastSession; String requestedSessionId; public RequestWrapper(final HttpServletRequest req, final ResponseWrapper res) { super(req); this.res = res; req.setAttribute(HAZELCAST_REQUEST, this); } public void setHazelcastSession(HazelcastHttpSession hazelcastSession, String requestedSessionId) { this.hazelcastSession = hazelcastSession; this.requestedSessionId = requestedSessionId; } HttpSession getOriginalSession(boolean create) { return super.getSession(create); } @Override public RequestDispatcher getRequestDispatcher(final String path) { final ServletRequest original = getRequest(); return new RequestDispatcher() { public void forward(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { original.getRequestDispatcher(path).forward(servletRequest, servletResponse); } public void include(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { original.getRequestDispatcher(path).include(servletRequest, servletResponse); } }; } public HazelcastHttpSession fetchHazelcastSession() { if (requestedSessionId == null) { requestedSessionId = getSessionCookie(this); } if (requestedSessionId == null) { requestedSessionId = getParameter(HAZELCAST_SESSION_COOKIE_NAME); } if (requestedSessionId != null) { hazelcastSession = getSessionWithId(requestedSessionId); if (hazelcastSession == null) { final Boolean existing = (Boolean) getClusterMap().get(requestedSessionId); if (existing != null && existing) { // we already have the session in the cluster loading it... hazelcastSession = createNewSession(RequestWrapper.this, requestedSessionId); } } } return hazelcastSession; } @Override public HttpSession getSession() { return getSession(true); } @Override public HazelcastHttpSession getSession(final boolean create) { if (hazelcastSession != null && !hazelcastSession.isValid()) { LOGGER.finest("Session is invalid!"); destroySession(hazelcastSession, true); hazelcastSession = null; } else if (hazelcastSession != null) { return hazelcastSession; } HttpSession originalSession = getOriginalSession(false); if (originalSession != null) { String hazelcastSessionId = MAP_ORIGINAL_SESSIONS.get(originalSession.getId()); if (hazelcastSessionId != null) { hazelcastSession = MAP_SESSIONS.get(hazelcastSessionId); return hazelcastSession; } MAP_ORIGINAL_SESSIONS.remove(originalSession.getId()); originalSession.invalidate(); } hazelcastSession = fetchHazelcastSession(); if (hazelcastSession == null && create) { hazelcastSession = createNewSession(RequestWrapper.this, null); } if (deferredWrite) { prepareReloadingSession(hazelcastSession); } return hazelcastSession; } } // END of RequestWrapper private class HazelcastHttpSession implements HttpSession { volatile boolean valid = true; final String id; final HttpSession originalSession; final WebFilter webFilter; private final Map<String, LocalCacheEntry> localCache; private final boolean deferredWrite; public HazelcastHttpSession(WebFilter webFilter, final String sessionId, HttpSession originalSession, boolean deferredWrite) { this.webFilter = webFilter; this.id = sessionId; this.originalSession = originalSession; this.deferredWrite = deferredWrite; this.localCache = deferredWrite ? new ConcurrentHashMap<String, LocalCacheEntry>() : null; } public Object getAttribute(final String name) { IMap<String, Object> clusterMap = getClusterMap(); if (deferredWrite) { LocalCacheEntry cacheEntry = localCache.get(name); if (cacheEntry == null || cacheEntry.reload) { Object value = clusterMap.get(buildAttributeName(name)); if (value == null) { cacheEntry = NULL_ENTRY; } else { cacheEntry = new LocalCacheEntry(); cacheEntry.value = value; cacheEntry.reload = false; } localCache.put(name, cacheEntry); } return cacheEntry != NULL_ENTRY ? cacheEntry.value : null; } return clusterMap.get(buildAttributeName(name)); } public Enumeration<String> getAttributeNames() { final Set<String> keys = selectKeys(); return new Enumeration<String>() { private final String[] elements = keys.toArray(new String[keys.size()]); private int index; @Override public boolean hasMoreElements() { return index < elements.length; } @Override public String nextElement() { return elements[index++]; } }; } public String getId() { return id; } public ServletContext getServletContext() { return servletContext; } public HttpSessionContext getSessionContext() { return originalSession.getSessionContext(); } public Object getValue(final String name) { return getAttribute(name); } public String[] getValueNames() { final Set<String> keys = selectKeys(); return keys.toArray(new String[keys.size()]); } public void invalidate() { originalSession.invalidate(); destroySession(this, true); } public boolean isNew() { return originalSession.isNew(); } public void putValue(final String name, final Object value) { setAttribute(name, value); } public void removeAttribute(final String name) { if (deferredWrite) { LocalCacheEntry entry = localCache.get(name); if (entry != null && entry != NULL_ENTRY) { entry.value = null; entry.removed = true; // dirty needs to be set as last value for memory visibility reasons! entry.dirty = true; } } else { getClusterMap().delete(buildAttributeName(name)); } } public void setAttribute(final String name, final Object value) { if (name == null) { throw new NullPointerException("name must not be null"); } if (value == null) { throw new IllegalArgumentException("value must not be null"); } if (deferredWrite) { LocalCacheEntry entry = localCache.get(name); if (entry == null || entry == NULL_ENTRY) { entry = new LocalCacheEntry(); localCache.put(name, entry); } entry.value = value; entry.dirty = true; } else { getClusterMap().put(buildAttributeName(name), value); } } public void removeValue(final String name) { removeAttribute(name); } public boolean sessionChanged() { if (!deferredWrite) { return false; } for (Entry<String, LocalCacheEntry> entry : localCache.entrySet()) { if (entry.getValue().dirty) { return true; } } return false; } public long getCreationTime() { return originalSession.getCreationTime(); } public long getLastAccessedTime() { return originalSession.getLastAccessedTime(); } public int getMaxInactiveInterval() { return originalSession.getMaxInactiveInterval(); } public void setMaxInactiveInterval(int maxInactiveSeconds) { originalSession.setMaxInactiveInterval(maxInactiveSeconds); } void destroy() { valid = false; } public boolean isValid() { return valid; } private String buildAttributeName(String name) { return id + HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR + name; } private void sessionDeferredWrite() { IMap<String, Object> clusterMap = getClusterMap(); if (deferredWrite) { Iterator<Entry<String, LocalCacheEntry>> iterator = localCache.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, LocalCacheEntry> entry = iterator.next(); if (entry.getValue().dirty) { LocalCacheEntry cacheEntry = entry.getValue(); if (cacheEntry.removed) { clusterMap.delete(buildAttributeName(entry.getKey())); iterator.remove(); } else { clusterMap.put(buildAttributeName(entry.getKey()), cacheEntry.value); cacheEntry.dirty = false; } } } } if (!clusterMap.containsKey(id)) { clusterMap.put(id, Boolean.TRUE); } } private Set<String> selectKeys() { Set<String> keys = new HashSet<String>(); if (!deferredWrite) { for (String qualifiedAttributeKey : getClusterMap().keySet(new SessionAttributePredicate(id))) { keys.add(extractAttributeKey(qualifiedAttributeKey)); } } else { for (Entry<String, LocalCacheEntry> entry : localCache.entrySet()) { if (!entry.getValue().removed && entry.getValue() != NULL_ENTRY) { keys.add(entry.getKey()); } } } return keys; } } // END of HazelSession } // END of WebFilter
Fix HazelcastHttpSession's setAttribute() with null value HttpSession.setAttribute() should work with null value the same as removeAttribute(). Changed from throwing an exception to delegate call to removeAttribute()
hazelcast-wm/src/main/java/com/hazelcast/web/WebFilter.java
Fix HazelcastHttpSession's setAttribute() with null value
<ide><path>azelcast-wm/src/main/java/com/hazelcast/web/WebFilter.java <ide> throw new NullPointerException("name must not be null"); <ide> } <ide> if (value == null) { <del> throw new IllegalArgumentException("value must not be null"); <add> removeAttribute(name); <ide> } <ide> if (deferredWrite) { <ide> LocalCacheEntry entry = localCache.get(name);
Java
bsd-2-clause
dccbc9bfe7fff926122e4d870f9c29b4ee2eb0c1
0
jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu
/* * Copyright (c) 2014, Absolute Performance, Inc. http://www.absolute-performance.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ublu.command; import ublu.util.ArgArray; import ublu.util.DataSink; import ublu.util.Generics.ThingArrayList; import ublu.util.Tuple; import com.ibm.as400.access.AS400SecurityException; import com.ibm.as400.access.ErrorCompletingRequestException; import com.ibm.as400.access.ObjectDoesNotExistException; import com.ibm.as400.access.RequestNotSupportedException; import java.io.IOException; import java.sql.SQLException; import java.util.Collection; import java.util.Enumeration; import java.util.logging.Level; import ublu.util.Generics.StringArrayList; /** * Create and manage lists * * @author jwoehr */ public class CmdList extends Command { { setNameAndDescription("list", "/0 [-to datasink] [--,-list @list] [[-instance] | [-source ~@enumeration|~@collection|~@string|-@array] | [-add ~@object ] | [-addstr ~@{ some string }] | [-clear] | [-get ~@{intindex}] | [-set ~@{intindex} ~@object] | [-remove ~@object] | [-removeat ~@{intindex}] | [-size] | [-toarray]]: create and manage lists of objects"); } /** * Operations */ protected enum OPERATIONS { /** * Add object to list */ ADD, /** * Add string to list */ ADDSTR, /** * Empty list */ CLEAR, /** * Get object from list */ GET, /** * Set object to list at index */ SET, /** * Remove object from list */ REMOVE, /** * Remove object at index from list */ REMOVEAT, /** * Create list */ INSTANCE, /** * Source enum or collection */ SOURCE, /** * Size of list */ SIZE, /** * Convert to Object[] */ TOARRAY } /** * The list command * * @param argArray * @return remnant of argArray */ public ArgArray doCmdList(ArgArray argArray) { OPERATIONS operation = OPERATIONS.INSTANCE; ThingArrayList myThingArrayList = null; Tuple talTuple = null; Tuple toAddRemove = null; Integer toGetSet = null; String stringToAdd = null; Tuple sourceTuple = null; int removeIndex = 0; while (argArray.hasDashCommand()) { String dashCommand = argArray.parseDashCommand(); switch (dashCommand) { case "-to": String destName = argArray.next(); setDataDest(DataSink.fromSinkName(destName)); break; case "--": case "-list": talTuple = argArray.nextTupleOrPop(); break; case "-instance": operation = OPERATIONS.INSTANCE; break; case "-source": operation = OPERATIONS.SOURCE; sourceTuple = argArray.nextTupleOrPop(); break; case "-add": toAddRemove = argArray.nextTupleOrPop(); operation = OPERATIONS.ADD; break; case "-addstr": stringToAdd = argArray.nextMaybeQuotationTuplePopString(); operation = OPERATIONS.ADDSTR; break; case "-clear": operation = OPERATIONS.CLEAR; break; case "-get": operation = OPERATIONS.GET; toGetSet = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-set": toGetSet = argArray.nextIntMaybeQuotationTuplePopString(); toAddRemove = argArray.nextTupleOrPop(); operation = OPERATIONS.SET; break; case "-remove": toAddRemove = argArray.nextTupleOrPop(); operation = OPERATIONS.REMOVE; break; case "-removeat": removeIndex = argArray.nextIntMaybeQuotationTuplePopString(); operation = OPERATIONS.REMOVEAT; break; case "-size": operation = OPERATIONS.SIZE; break; case "-toarray": operation = OPERATIONS.TOARRAY; break; default: unknownDashCommand(dashCommand); } } if (havingUnknownDashCommand()) { setCommandResult(COMMANDRESULT.FAILURE); } else { if (talTuple != null) { Object maybeList = talTuple.getValue(); if (maybeList instanceof ThingArrayList) { myThingArrayList = ThingArrayList.class.cast(maybeList); } } switch (operation) { case ADD: if (myThingArrayList == null) { noListError(); } else if (toAddRemove == null) { myThingArrayList.add(null); } else { myThingArrayList.add(toAddRemove.getValue()); } break; case ADDSTR: if (myThingArrayList == null) { noListError(); } else { myThingArrayList.add(stringToAdd); } break; case CLEAR: if (myThingArrayList == null) { noListError(); } else { myThingArrayList.clear(); } break; case GET: if (myThingArrayList == null) { noListError(); } else { Object o = myThingArrayList.get(toGetSet); try { put(o); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting Object in get from List in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case SET: if (myThingArrayList == null) { noListError(); } else { Object o = myThingArrayList.set(toGetSet, toAddRemove); try { put(o); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting Object in set from List in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case INSTANCE: try { put(new ThingArrayList()); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting List instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } break; case REMOVE: if (myThingArrayList == null) { noListError(); } else if (toAddRemove == null) { getLogger().log(Level.SEVERE, "Null tuple to remove from List in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { put(myThingArrayList.remove(toAddRemove.getValue())); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting removed " + toAddRemove.getValue() + " from List in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case REMOVEAT: if (myThingArrayList == null) { noListError(); } else { try { put(myThingArrayList.remove(removeIndex)); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting removed " + toAddRemove.getValue() + " from List in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case SOURCE: if (sourceTuple == null) { getLogger().log(Level.SEVERE, "Null tuple for List source in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { Object sourceObj = sourceTuple.getValue(); myThingArrayList = listFromSource(sourceObj); try { put(myThingArrayList); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting List instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case SIZE: if (myThingArrayList == null) { noListError(); } else { try { put(myThingArrayList.size()); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting List size in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case TOARRAY: if (myThingArrayList == null) { noListError(); } else { try { put(myThingArrayList.toArray()); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting List as an Object Array in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; default: getLogger().log(Level.SEVERE, "Unknown operation unhandled in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } } return argArray; } private void noListError() { getLogger().log(Level.SEVERE, "No List in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } private static final Object MODELARRAY[] = new Object[0]; private static final Class ARRAYCLASS = MODELARRAY.getClass(); private ThingArrayList listFromSource(Object o) { ThingArrayList tal = null; if (o instanceof Collection) { tal = new ThingArrayList(Collection.class .cast(o)); } else if (o instanceof Enumeration) { tal = new ThingArrayList(Enumeration.class .cast(o)); } else if (o instanceof String) { tal = new ThingArrayList(new StringArrayList(String.class.cast(o))); } else if (o.getClass().equals(ARRAYCLASS)) { tal = new ThingArrayList((Object [])o); } else { getLogger().log(Level.SEVERE, "Cannot create List from {0} in {1}", new Object[]{o, getNameAndDescription()}); setCommandResult(COMMANDRESULT.FAILURE); } return tal; } @Override public ArgArray cmd(ArgArray args) { reinit(); return doCmdList(args); } @Override public COMMANDRESULT getResult() { return getCommandResult(); } }
src/ublu/command/CmdList.java
/* * Copyright (c) 2014, Absolute Performance, Inc. http://www.absolute-performance.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ublu.command; import ublu.util.ArgArray; import ublu.util.DataSink; import ublu.util.Generics.ThingArrayList; import ublu.util.Tuple; import com.ibm.as400.access.AS400SecurityException; import com.ibm.as400.access.ErrorCompletingRequestException; import com.ibm.as400.access.ObjectDoesNotExistException; import com.ibm.as400.access.RequestNotSupportedException; import java.io.IOException; import java.sql.SQLException; import java.util.Collection; import java.util.Enumeration; import java.util.logging.Level; import ublu.util.Generics.StringArrayList; /** * Create and manage lists * * @author jwoehr */ public class CmdList extends Command { { setNameAndDescription("list", "/0 [-to datasink] [--,-list @list] [[-instance] | [-source ~@enumeration|~@collection|~@string] | [-add ~@object ] | [-addstr ~@{ some string }] | [-clear] | [-get ~@{intindex}] | [-set ~@{intindex} ~@object] | [-remove ~@object] | [-removeat ~@{intindex}] | [-size]]: create and manage lists of objects"); } /** * Operations */ protected enum OPERATIONS { /** * Add object to list */ ADD, /** * Add string to list */ ADDSTR, /** * Empty list */ CLEAR, /** * Get object from list */ GET, /** * Set object to list at index */ SET, /** * Remove object from list */ REMOVE, /** * Remove object at index from list */ REMOVEAT, /** * Create list */ INSTANCE, /** * Source enum or collection */ SOURCE, /** * Size of list */ SIZE } /** * The list command * * @param argArray * @return remnant of argArray */ public ArgArray doCmdList(ArgArray argArray) { OPERATIONS operation = OPERATIONS.INSTANCE; ThingArrayList myThingArrayList = null; Tuple talTuple = null; Tuple toAddRemove = null; Integer toGetSet = null; String stringToAdd = null; Tuple sourceTuple = null; int removeIndex = 0; while (argArray.hasDashCommand()) { String dashCommand = argArray.parseDashCommand(); switch (dashCommand) { case "-to": String destName = argArray.next(); setDataDest(DataSink.fromSinkName(destName)); break; case "--": case "-list": talTuple = argArray.nextTupleOrPop(); break; case "-instance": operation = OPERATIONS.INSTANCE; break; case "-source": operation = OPERATIONS.SOURCE; sourceTuple = argArray.nextTupleOrPop(); break; case "-add": toAddRemove = argArray.nextTupleOrPop(); operation = OPERATIONS.ADD; break; case "-addstr": stringToAdd = argArray.nextMaybeQuotationTuplePopString(); operation = OPERATIONS.ADDSTR; break; case "-clear": operation = OPERATIONS.CLEAR; break; case "-get": operation = OPERATIONS.GET; toGetSet = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-set": toGetSet = argArray.nextIntMaybeQuotationTuplePopString(); toAddRemove = argArray.nextTupleOrPop(); operation = OPERATIONS.SET; break; case "-remove": toAddRemove = argArray.nextTupleOrPop(); operation = OPERATIONS.REMOVE; break; case "-removeat": removeIndex = argArray.nextIntMaybeQuotationTuplePopString(); operation = OPERATIONS.REMOVEAT; break; case "-size": operation = OPERATIONS.SIZE; break; default: unknownDashCommand(dashCommand); } } if (havingUnknownDashCommand()) { setCommandResult(COMMANDRESULT.FAILURE); } else { if (talTuple != null) { Object maybeList = talTuple.getValue(); if (maybeList instanceof ThingArrayList) { myThingArrayList = ThingArrayList.class.cast(maybeList); } } switch (operation) { case ADD: if (myThingArrayList == null) { noListError(); } else { if (toAddRemove == null) { myThingArrayList.add(null); } else { myThingArrayList.add(toAddRemove.getValue()); } } break; case ADDSTR: if (myThingArrayList == null) { noListError(); } else { myThingArrayList.add(stringToAdd); } break; case CLEAR: if (myThingArrayList == null) { noListError(); } else { myThingArrayList.clear(); } break; case GET: if (myThingArrayList == null) { noListError(); } else { Object o = myThingArrayList.get(toGetSet); try { put(o); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting Object in get from List in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case SET: if (myThingArrayList == null) { noListError(); } else { Object o = myThingArrayList.set(toGetSet, toAddRemove); try { put(o); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting Object in set from List in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case INSTANCE: try { put(new ThingArrayList()); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting List instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } break; case REMOVE: if (myThingArrayList == null) { noListError(); } else if (toAddRemove == null) { getLogger().log(Level.SEVERE, "Null tuple to remove from List in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { try { put(myThingArrayList.remove(toAddRemove.getValue())); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting removed " + toAddRemove.getValue() + " from List in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case REMOVEAT: if (myThingArrayList == null) { noListError(); } else { try { put(myThingArrayList.remove(removeIndex)); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting removed " + toAddRemove.getValue() + " from List in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case SOURCE: if (sourceTuple == null) { getLogger().log(Level.SEVERE, "Null tuple for List source in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } else { Object sourceObj = sourceTuple.getValue(); myThingArrayList = listFromSource(sourceObj); try { put(myThingArrayList); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting List instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case SIZE: if (myThingArrayList == null) { noListError(); } else { try { put(myThingArrayList.size()); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Error putting List size in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; default: getLogger().log(Level.SEVERE, "Unknown operation unhandled in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } } return argArray; } private void noListError() { getLogger().log(Level.SEVERE, "No List in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } private ThingArrayList listFromSource(Object o) { ThingArrayList tal = null; if (o instanceof Collection) { tal = new ThingArrayList(Collection.class .cast(o)); } else if (o instanceof Enumeration) { tal = new ThingArrayList(Enumeration.class .cast(o)); } else if (o instanceof String) { tal = new ThingArrayList(new StringArrayList(String.class.cast(o))); } else { getLogger().log(Level.SEVERE, "Cannot create List from {0} in {1}", new Object[]{o, getNameAndDescription()}); setCommandResult(COMMANDRESULT.FAILURE); } return tal; } @Override public ArgArray cmd(ArgArray args) { reinit(); return doCmdList(args); } @Override public COMMANDRESULT getResult() { return getCommandResult(); } }
CmdList now supports Object [] and the -toarray dash-command
src/ublu/command/CmdList.java
CmdList now supports Object [] and the -toarray dash-command
<ide><path>rc/ublu/command/CmdList.java <ide> <ide> { <ide> setNameAndDescription("list", <del> "/0 [-to datasink] [--,-list @list] [[-instance] | [-source ~@enumeration|~@collection|~@string] | [-add ~@object ] | [-addstr ~@{ some string }] | [-clear] | [-get ~@{intindex}] | [-set ~@{intindex} ~@object] | [-remove ~@object] | [-removeat ~@{intindex}] | [-size]]: create and manage lists of objects"); <add> "/0 [-to datasink] [--,-list @list] [[-instance] | [-source ~@enumeration|~@collection|~@string|-@array] | [-add ~@object ] | [-addstr ~@{ some string }] | [-clear] | [-get ~@{intindex}] | [-set ~@{intindex} ~@object] | [-remove ~@object] | [-removeat ~@{intindex}] | [-size] | [-toarray]]: create and manage lists of objects"); <ide> } <ide> <ide> /** <ide> /** <ide> * Size of list <ide> */ <del> SIZE <add> SIZE, <add> /** <add> * Convert to Object[] <add> */ <add> TOARRAY <ide> } <ide> <ide> /** <ide> case "-size": <ide> operation = OPERATIONS.SIZE; <ide> break; <add> case "-toarray": <add> operation = OPERATIONS.TOARRAY; <add> break; <ide> default: <ide> unknownDashCommand(dashCommand); <ide> } <ide> case ADD: <ide> if (myThingArrayList == null) { <ide> noListError(); <del> } else { <del> if (toAddRemove == null) { <del> myThingArrayList.add(null); <del> } else { <del> myThingArrayList.add(toAddRemove.getValue()); <del> } <add> } else if (toAddRemove == null) { <add> myThingArrayList.add(null); <add> } else { <add> myThingArrayList.add(toAddRemove.getValue()); <ide> } <ide> break; <ide> case ADDSTR: <ide> } <ide> } <ide> break; <add> case TOARRAY: <add> if (myThingArrayList == null) { <add> noListError(); <add> } else { <add> try { <add> put(myThingArrayList.toArray()); <add> } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { <add> getLogger().log(Level.SEVERE, "Error putting List as an Object Array in " + getNameAndDescription(), ex); <add> setCommandResult(COMMANDRESULT.FAILURE); <add> } <add> } <add> break; <ide> default: <ide> getLogger().log(Level.SEVERE, "Unknown operation unhandled in {0}", getNameAndDescription()); <ide> setCommandResult(COMMANDRESULT.FAILURE); <ide> getLogger().log(Level.SEVERE, "No List in {0}", getNameAndDescription()); <ide> setCommandResult(COMMANDRESULT.FAILURE); <ide> } <add> <add> private static final Object MODELARRAY[] = new Object[0]; <add> private static final Class ARRAYCLASS = MODELARRAY.getClass(); <ide> <ide> private ThingArrayList listFromSource(Object o) { <ide> ThingArrayList tal = null; <ide> .cast(o)); <ide> } else if (o instanceof String) { <ide> tal = new ThingArrayList(new StringArrayList(String.class.cast(o))); <add> } else if (o.getClass().equals(ARRAYCLASS)) { <add> tal = new ThingArrayList((Object [])o); <ide> } else { <ide> getLogger().log(Level.SEVERE, "Cannot create List from {0} in {1}", new Object[]{o, getNameAndDescription()}); <ide> setCommandResult(COMMANDRESULT.FAILURE);
Java
apache-2.0
cd554cdb3016ac6e0a14d88a29bde0027016bdee
0
awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples
import com.example.cognito.*; import org.junit.jupiter.api.*; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import java.io.*; import java.util.*; import static org.junit.jupiter.api.Assertions.*; @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CognitoServiceIntegrationTest { private static CognitoIdentityProviderClient cognitoclient; private static CognitoIdentityProviderClient cognitoIdentityProviderClient ; private static CognitoIdentityClient cognitoIdclient ; private static String userPoolName=""; private static String userPoolId="" ; //set in test 2 private static String identityPoolId =""; //set in test 5 private static String username=""; private static String email=""; private static String clientName=""; private static String identityPoolName=""; @BeforeAll public static void setUp() throws IOException { // Run tests on Real AWS Resources Region region = Region.US_EAST_1; cognitoclient = CognitoIdentityProviderClient.builder() .region(Region.US_EAST_1) .build(); cognitoIdclient = CognitoIdentityClient.builder() .region(Region.US_EAST_1) .build(); cognitoIdentityProviderClient = CognitoIdentityProviderClient.builder() .region(Region.US_EAST_1) .build(); try (InputStream input = CognitoServiceIntegrationTest.class.getClassLoader().getResourceAsStream("config.properties")) { Properties prop = new Properties(); if (input == null) { System.out.println("Sorry, unable to find config.properties"); return; } //load a properties file from class path, inside static method prop.load(input); // Populate the data members required for all tests userPoolName = prop.getProperty("userPoolName"); username= prop.getProperty("username"); email= prop.getProperty("email"); clientName = prop.getProperty("clientName"); identityPoolName = prop.getProperty("identityPoolName"); } catch (IOException ex) { ex.printStackTrace(); } } @Test @Order(1) public void whenInitializingAWSS3Service_thenNotNull() { assertNotNull(cognitoclient); assertNotNull(cognitoIdclient); assertNotNull(cognitoIdentityProviderClient); System.out.println("Test 1 passed"); } @Test @Order(2) public void CreateUserPool() { userPoolId = CreateUserPool.createPool(cognitoclient, userPoolName); assertTrue(!userPoolId.isEmpty()); System.out.println("Test 2 passed"); } @Test @Order(3) public void CreateAdminUser() { CreateAdminUser.createAdmin(cognitoclient,userPoolId ,username, email); System.out.println("Test 2 passed"); } @Test @Order(4) public void CreateUserPoolClient() { CreateUserPoolClient.createPoolClient(cognitoclient,clientName, userPoolId); System.out.println("Test 4 passed"); } @Test @Order(5) public void CreateIdentityPool() { identityPoolId = CreateIdentityPool.createIdPool(cognitoIdclient, identityPoolName); assertTrue(!identityPoolId.isEmpty()); System.out.println("Test 5 passed"); } @Test @Order(6) public void ListUserPools() { ListUserPools.listAllUserPools(cognitoclient); System.out.println("Test 6 passed"); } @Test @Order(7) public void ListUserPoolClients() { ListUserPoolClients.listAllUserPoolClients(cognitoIdentityProviderClient, userPoolId); System.out.println("Test 7 passed"); } @Test @Order(8) public void ListUsers() { ListUsers.listAllUsers(cognitoclient, userPoolId); System.out.println("Test 8 passed"); } @Test @Order(9) public void AddLoginProvider() { AddLoginProvider.setLoginProvider(cognitoIdclient, userPoolId, identityPoolName, identityPoolId); System.out.println("Test 9 passed"); } @Test @Order(10) public void DeleteUserPool() { DeleteUserPool.deletePool(cognitoclient, userPoolId); System.out.println("Test 10 passed"); } }
javav2/example_code/cognito/src/test/java/CognitoServiceIntegrationTest.java
import com.example.cognito.*; import org.junit.jupiter.api.*; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import java.io.*; import java.util.*; import static org.junit.jupiter.api.Assertions.*; @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CognitoServiceIntegrationTest { private static CognitoIdentityProviderClient cognitoclient; private static CognitoIdentityProviderClient cognitoIdentityProviderClient ; private static CognitoIdentityClient cognitoIdclient ; private static String userPoolName=""; private static String userPoolId="" ; //set in test 2 private static String identityPoolId =""; //set in test 5 private static String username=""; private static String email=""; private static String clientName=""; private static String identityPoolName=""; @BeforeAll public static void setUp() throws IOException { // Run tests on Real AWS Resources Region region = Region.US_EAST_1; cognitoclient = CognitoIdentityProviderClient.builder() .region(Region.US_EAST_1) .build(); cognitoIdclient = CognitoIdentityClient.builder() .region(Region.US_EAST_1) .build(); cognitoIdentityProviderClient = CognitoIdentityProviderClient.builder() .region(Region.US_EAST_1) .build(); try (InputStream input = CognitoServiceIntegrationTest.class.getClassLoader().getResourceAsStream("config.properties")) { Properties prop = new Properties(); if (input == null) { System.out.println("Sorry, unable to find config.properties"); return; } //load a properties file from class path, inside static method prop.load(input); // Populate the data members required for all tests userPoolName = prop.getProperty("userPoolName"); username= prop.getProperty("username"); email= prop.getProperty("email"); clientName = prop.getProperty("clientName"); identityPoolName = prop.getProperty("identityPoolName"); } catch (IOException ex) { ex.printStackTrace(); } } @Test @Order(1) public void whenInitializingAWSS3Service_thenNotNull() { assertNotNull(cognitoclient); assertNotNull(cognitoIdclient); assertNotNull(cognitoIdentityProviderClient); System.out.println("Test 1 passed"); } @Test @Order(2) public void CreateUserPool() { try{ userPoolId = CreateUserPool.createPool(cognitoclient, userPoolName); assertTrue(!userPoolId.isEmpty()); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 2 passed"); } @Test @Order(3) public void CreateAdminUser() { try{ CreateAdminUser.createAdmin(cognitoclient,userPoolId ,username, email); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 2 passed"); } @Test @Order(4) public void CreateUserPoolClient() { try{ CreateUserPoolClient.createPoolClient(cognitoclient,clientName, userPoolId); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 4 passed"); } @Test @Order(5) public void CreateIdentityPool() { try{ identityPoolId = CreateIdentityPool.createIdPool(cognitoIdclient, identityPoolName); assertTrue(!identityPoolId.isEmpty()); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 5 passed"); } @Test @Order(6) public void ListUserPools() { try{ ListUserPools.listAllUserPools(cognitoclient); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 6 passed"); } @Test @Order(7) public void ListUserPoolClients() { try{ ListUserPoolClients.listAllUserPoolClients(cognitoIdentityProviderClient, userPoolId); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 7 passed"); } @Test @Order(8) public void ListUsers() { try{ ListUsers.listAllUsers(cognitoclient, userPoolId); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 8 passed"); } @Test @Order(9) public void AddLoginProvider() { try{ AddLoginProvider.setLoginProvider(cognitoIdclient, userPoolId, identityPoolName, identityPoolId); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 9 passed"); } @Test @Order(10) public void DeleteUserPool() { try{ DeleteUserPool.deletePool(cognitoclient, userPoolId); } catch (CognitoIdentityProviderException e){ System.err.println(e.getMessage()); System.exit(1); } System.out.println("Test 10 passed"); } }
Update CognitoServiceIntegrationTest.java
javav2/example_code/cognito/src/test/java/CognitoServiceIntegrationTest.java
Update CognitoServiceIntegrationTest.java
<ide><path>avav2/example_code/cognito/src/test/java/CognitoServiceIntegrationTest.java <ide> import software.amazon.awssdk.regions.Region; <ide> import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; <ide> import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; <del>import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; <ide> import java.io.*; <ide> import java.util.*; <ide> <ide> clientName = prop.getProperty("clientName"); <ide> identityPoolName = prop.getProperty("identityPoolName"); <ide> <del> <del> <del> <ide> } catch (IOException ex) { <ide> ex.printStackTrace(); <ide> } <ide> @Test <ide> @Order(2) <ide> public void CreateUserPool() { <del> try{ <del> userPoolId = CreateUserPool.createPool(cognitoclient, userPoolName); <del> assertTrue(!userPoolId.isEmpty()); <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <del> <add> userPoolId = CreateUserPool.createPool(cognitoclient, userPoolName); <add> assertTrue(!userPoolId.isEmpty()); <ide> System.out.println("Test 2 passed"); <ide> } <ide> <ide> @Test <ide> @Order(3) <ide> public void CreateAdminUser() { <del> try{ <del> CreateAdminUser.createAdmin(cognitoclient,userPoolId ,username, email); <ide> <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <del> <add> CreateAdminUser.createAdmin(cognitoclient,userPoolId ,username, email); <ide> System.out.println("Test 2 passed"); <ide> } <ide> <ide> @Order(4) <ide> public void CreateUserPoolClient() { <ide> <del> try{ <del> CreateUserPoolClient.createPoolClient(cognitoclient,clientName, userPoolId); <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <del> <add> CreateUserPoolClient.createPoolClient(cognitoclient,clientName, userPoolId); <ide> System.out.println("Test 4 passed"); <ide> } <ide> <ide> @Order(5) <ide> public void CreateIdentityPool() { <ide> <del> try{ <del> identityPoolId = CreateIdentityPool.createIdPool(cognitoIdclient, identityPoolName); <del> assertTrue(!identityPoolId.isEmpty()); <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <del> <add> identityPoolId = CreateIdentityPool.createIdPool(cognitoIdclient, identityPoolName); <add> assertTrue(!identityPoolId.isEmpty()); <ide> System.out.println("Test 5 passed"); <ide> } <ide> <ide> @Order(6) <ide> public void ListUserPools() { <ide> <del> try{ <del> ListUserPools.listAllUserPools(cognitoclient); <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <add> ListUserPools.listAllUserPools(cognitoclient); <ide> System.out.println("Test 6 passed"); <ide> } <ide> <ide> @Order(7) <ide> public void ListUserPoolClients() { <ide> <del> try{ <del> ListUserPoolClients.listAllUserPoolClients(cognitoIdentityProviderClient, userPoolId); <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <del> System.out.println("Test 7 passed"); <add> ListUserPoolClients.listAllUserPoolClients(cognitoIdentityProviderClient, userPoolId); <add> System.out.println("Test 7 passed"); <ide> } <ide> <ide> @Test <ide> @Order(8) <ide> public void ListUsers() { <ide> <del> try{ <del> ListUsers.listAllUsers(cognitoclient, userPoolId); <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <del> System.out.println("Test 8 passed"); <add> ListUsers.listAllUsers(cognitoclient, userPoolId); <add> System.out.println("Test 8 passed"); <ide> } <ide> <ide> @Test <ide> @Order(9) <ide> public void AddLoginProvider() { <ide> <del> try{ <del> AddLoginProvider.setLoginProvider(cognitoIdclient, userPoolId, identityPoolName, identityPoolId); <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <del> System.out.println("Test 9 passed"); <add> AddLoginProvider.setLoginProvider(cognitoIdclient, userPoolId, identityPoolName, identityPoolId); <add> System.out.println("Test 9 passed"); <ide> } <del> <del> <ide> <ide> @Test <ide> @Order(10) <ide> public void DeleteUserPool() { <ide> <del> try{ <del> DeleteUserPool.deletePool(cognitoclient, userPoolId); <del> } catch (CognitoIdentityProviderException e){ <del> System.err.println(e.getMessage()); <del> System.exit(1); <del> } <del> System.out.println("Test 10 passed"); <add> DeleteUserPool.deletePool(cognitoclient, userPoolId); <add> System.out.println("Test 10 passed"); <ide> } <ide> <ide> }
Java
apache-2.0
17a848f1d3940fe01e3c8854e9e7ad37ebae880b
0
hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak
package com.sequenceiq.it.cloudbreak.testcase.e2e.sdx; import static com.sequenceiq.it.cloudbreak.context.RunningParameter.key; import static java.lang.String.format; import java.util.concurrent.atomic.AtomicReference; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import com.sequenceiq.it.cloudbreak.client.SdxTestClient; import com.sequenceiq.it.cloudbreak.context.Description; import com.sequenceiq.it.cloudbreak.context.TestContext; import com.sequenceiq.it.cloudbreak.dto.ClouderaManagerTestDto; import com.sequenceiq.it.cloudbreak.dto.ClusterTestDto; import com.sequenceiq.it.cloudbreak.dto.ImageSettingsTestDto; import com.sequenceiq.it.cloudbreak.dto.imagecatalog.ImageCatalogTestDto; import com.sequenceiq.it.cloudbreak.dto.sdx.SdxInternalTestDto; import com.sequenceiq.it.cloudbreak.dto.stack.StackTestDto; import com.sequenceiq.it.cloudbreak.exception.TestFailException; import com.sequenceiq.it.cloudbreak.log.Log; import com.sequenceiq.it.cloudbreak.testcase.e2e.BasicSdxTests; import com.sequenceiq.it.cloudbreak.util.wait.WaitUtil; import com.sequenceiq.sdx.api.model.SdxClusterStatusResponse; public class SdxBaseImageTests extends BasicSdxTests { private static final Logger LOGGER = LoggerFactory.getLogger(SdxBaseImageTests.class); @Inject private SdxTestClient sdxTestClient; @Inject private WaitUtil waitUtil; @Override protected void setupTest(TestContext testContext) { createDefaultUser(testContext); createDefaultCredential(testContext); createEnvironmentForSdx(testContext); initializeDefaultBlueprints(testContext); } @Ignore("This should be re-enabled once CB-6103 is fixed") @Test(dataProvider = TEST_CONTEXT) @Description( given = "there is a running Cloudbreak", when = "a valid SDX create request is sent (latest Base Image)", then = "SDX should be available AND deletable" ) public void testSDXWithBaseImageCanBeCreatedSuccessfully(TestContext testContext) { String sdxInternal = resourcePropertyProvider().getName(); String cluster = resourcePropertyProvider().getName(); String clouderaManager = resourcePropertyProvider().getName(); String imageSettings = resourcePropertyProvider().getName(); String imageCatalog = resourcePropertyProvider().getName(); String stack = resourcePropertyProvider().getName(); AtomicReference<String> selectedImageID = new AtomicReference<>(); testContext .given(imageCatalog, ImageCatalogTestDto.class) .when((tc, dto, client) -> { selectedImageID.set(testContext.getCloudProvider().getLatestBaseImageID(tc, dto, client)); return dto; }) .given(imageSettings, ImageSettingsTestDto.class) .given(clouderaManager, ClouderaManagerTestDto.class) .given(cluster, ClusterTestDto.class).withClouderaManager(clouderaManager) .given(stack, StackTestDto.class).withCluster(cluster).withImageSettings(imageSettings) .given(sdxInternal, SdxInternalTestDto.class).withStackRequest(stack, cluster) .when(sdxTestClient.createInternal(), key(sdxInternal)) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.RUNNING) .then((tc, testDto, client) -> { return waitUtil.waitForSdxInstancesStatus(testDto, client, getSdxInstancesHealthyState()); }) .then((tc, dto, client) -> { Log.log(LOGGER, format(" Image Catalog Name: %s ", dto.getResponse().getStackV4Response().getImage().getCatalogName())); Log.log(LOGGER, format(" Image Catalog URL: %s ", dto.getResponse().getStackV4Response().getImage().getCatalogUrl())); Log.log(LOGGER, format(" Image ID: %s ", dto.getResponse().getStackV4Response().getImage().getId())); if (!dto.getResponse().getStackV4Response().getImage().getId().equals(selectedImageID.get())) { throw new TestFailException(" The selected image ID is: " + dto.getResponse().getStackV4Response().getImage().getId() + " instead of: " + selectedImageID.get()); } return dto; }) .validate(); } }
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/testcase/e2e/sdx/SdxBaseImageTests.java
package com.sequenceiq.it.cloudbreak.testcase.e2e.sdx; import static com.sequenceiq.it.cloudbreak.context.RunningParameter.key; import static java.lang.String.format; import java.util.concurrent.atomic.AtomicReference; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; import com.sequenceiq.it.cloudbreak.client.SdxTestClient; import com.sequenceiq.it.cloudbreak.context.Description; import com.sequenceiq.it.cloudbreak.context.TestContext; import com.sequenceiq.it.cloudbreak.dto.ClouderaManagerTestDto; import com.sequenceiq.it.cloudbreak.dto.ClusterTestDto; import com.sequenceiq.it.cloudbreak.dto.ImageSettingsTestDto; import com.sequenceiq.it.cloudbreak.dto.imagecatalog.ImageCatalogTestDto; import com.sequenceiq.it.cloudbreak.dto.sdx.SdxInternalTestDto; import com.sequenceiq.it.cloudbreak.dto.stack.StackTestDto; import com.sequenceiq.it.cloudbreak.exception.TestFailException; import com.sequenceiq.it.cloudbreak.log.Log; import com.sequenceiq.it.cloudbreak.testcase.e2e.BasicSdxTests; import com.sequenceiq.it.cloudbreak.util.wait.WaitUtil; import com.sequenceiq.sdx.api.model.SdxClusterStatusResponse; public class SdxBaseImageTests extends BasicSdxTests { private static final Logger LOGGER = LoggerFactory.getLogger(SdxBaseImageTests.class); @Inject private SdxTestClient sdxTestClient; @Inject private WaitUtil waitUtil; @Override protected void setupTest(TestContext testContext) { createDefaultUser(testContext); createDefaultCredential(testContext); createEnvironmentForSdx(testContext); initializeDefaultBlueprints(testContext); } @Test(dataProvider = TEST_CONTEXT) @Description( given = "there is a running Cloudbreak", when = "a valid SDX create request is sent (latest Base Image)", then = "SDX should be available AND deletable" ) public void testSDXWithBaseImageCanBeCreatedSuccessfully(TestContext testContext) { String sdxInternal = resourcePropertyProvider().getName(); String cluster = resourcePropertyProvider().getName(); String clouderaManager = resourcePropertyProvider().getName(); String imageSettings = resourcePropertyProvider().getName(); String imageCatalog = resourcePropertyProvider().getName(); String stack = resourcePropertyProvider().getName(); AtomicReference<String> selectedImageID = new AtomicReference<>(); testContext .given(imageCatalog, ImageCatalogTestDto.class) .when((tc, dto, client) -> { selectedImageID.set(testContext.getCloudProvider().getLatestBaseImageID(tc, dto, client)); return dto; }) .given(imageSettings, ImageSettingsTestDto.class) .given(clouderaManager, ClouderaManagerTestDto.class) .given(cluster, ClusterTestDto.class).withClouderaManager(clouderaManager) .given(stack, StackTestDto.class).withCluster(cluster).withImageSettings(imageSettings) .given(sdxInternal, SdxInternalTestDto.class).withStackRequest(stack, cluster) .when(sdxTestClient.createInternal(), key(sdxInternal)) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.RUNNING) .then((tc, testDto, client) -> { return waitUtil.waitForSdxInstancesStatus(testDto, client, getSdxInstancesHealthyState()); }) .then((tc, dto, client) -> { Log.log(LOGGER, format(" Image Catalog Name: %s ", dto.getResponse().getStackV4Response().getImage().getCatalogName())); Log.log(LOGGER, format(" Image Catalog URL: %s ", dto.getResponse().getStackV4Response().getImage().getCatalogUrl())); Log.log(LOGGER, format(" Image ID: %s ", dto.getResponse().getStackV4Response().getImage().getId())); if (!dto.getResponse().getStackV4Response().getImage().getId().equals(selectedImageID.get())) { throw new TestFailException(" The selected image ID is: " + dto.getResponse().getStackV4Response().getImage().getId() + " instead of: " + selectedImageID.get()); } return dto; }) .validate(); } }
CB-6101 Ignore SdxBaseImageTests temporarily
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/testcase/e2e/sdx/SdxBaseImageTests.java
CB-6101 Ignore SdxBaseImageTests temporarily
<ide><path>ntegration-test/src/main/java/com/sequenceiq/it/cloudbreak/testcase/e2e/sdx/SdxBaseImageTests.java <ide> <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <add>import org.testng.annotations.Ignore; <ide> import org.testng.annotations.Test; <ide> <ide> import com.sequenceiq.it.cloudbreak.client.SdxTestClient; <ide> initializeDefaultBlueprints(testContext); <ide> } <ide> <add> @Ignore("This should be re-enabled once CB-6103 is fixed") <ide> @Test(dataProvider = TEST_CONTEXT) <ide> @Description( <ide> given = "there is a running Cloudbreak",
Java
apache-2.0
1683e6e949b16601f1aef195cf73404dce2efe7f
0
apache/incubator-apex-malhar,apache/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,tweise/apex-malhar,brightchen/apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/apex-malhar,tweise/apex-malhar,tweise/apex-malhar,tushargosavi/incubator-apex-malhar,vrozov/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/apex-malhar,tushargosavi/incubator-apex-malhar,trusli/apex-malhar,tushargosavi/incubator-apex-malhar,davidyan74/apex-malhar,trusli/apex-malhar,trusli/apex-malhar,yogidevendra/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,patilvikram/apex-malhar,patilvikram/apex-malhar,vrozov/incubator-apex-malhar,vrozov/incubator-apex-malhar,patilvikram/apex-malhar,davidyan74/apex-malhar,vrozov/apex-malhar,ananthc/apex-malhar,ananthc/apex-malhar,DataTorrent/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,davidyan74/apex-malhar,brightchen/apex-malhar,ananthc/apex-malhar,tweise/incubator-apex-malhar,ananthc/apex-malhar,prasannapramod/apex-malhar,tweise/apex-malhar,patilvikram/apex-malhar,ananthc/apex-malhar,vrozov/apex-malhar,tweise/incubator-apex-malhar,trusli/apex-malhar,apache/incubator-apex-malhar,vrozov/incubator-apex-malhar,yogidevendra/apex-malhar,patilvikram/apex-malhar,tweise/incubator-apex-malhar,vrozov/incubator-apex-malhar,trusli/apex-malhar,vrozov/apex-malhar,yogidevendra/apex-malhar,tushargosavi/incubator-apex-malhar,davidyan74/apex-malhar,yogidevendra/incubator-apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,yogidevendra/incubator-apex-malhar,tweise/incubator-apex-malhar,yogidevendra/apex-malhar,yogidevendra/incubator-apex-malhar,davidyan74/apex-malhar,prasannapramod/apex-malhar,trusli/apex-malhar,davidyan74/apex-malhar,yogidevendra/apex-malhar,tweise/incubator-apex-malhar,vrozov/apex-malhar,apache/incubator-apex-malhar,apache/incubator-apex-malhar,patilvikram/apex-malhar,tushargosavi/incubator-apex-malhar,vrozov/apex-malhar,brightchen/apex-malhar,vrozov/incubator-apex-malhar,tweise/incubator-apex-malhar,prasannapramod/apex-malhar,patilvikram/apex-malhar,brightchen/apex-malhar,yogidevendra/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,tweise/apex-malhar,brightchen/apex-malhar,apache/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,vrozov/incubator-apex-malhar,apache/incubator-apex-malhar,prasannapramod/apex-malhar,tweise/apex-malhar,ananthc/apex-malhar,brightchen/apex-malhar,vrozov/apex-malhar,tweise/incubator-apex-malhar,prasannapramod/apex-malhar,brightchen/apex-malhar
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.lib.db.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.Callable; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.apache.hadoop.conf.Configuration; import com.datatorrent.api.Context; import com.datatorrent.api.DAG; import com.datatorrent.api.DefaultOutputPort; import com.datatorrent.api.InputOperator; import com.datatorrent.api.LocalMode; import com.datatorrent.api.StreamingApplication; import com.datatorrent.common.util.BaseOperator; import com.datatorrent.stram.StramLocalCluster; public class JdbcPojoOperatorApplicationTest extends JdbcOperatorTest { public static int TupleCount; public int getNumOfRowsinTable(String tableName) { Connection con; try { con = DriverManager.getConnection(URL); Statement stmt = con.createStatement(); String countQuery = "SELECT count(*) from " + tableName; ResultSet resultSet = stmt.executeQuery(countQuery); resultSet.next(); return resultSet.getInt(1); } catch (SQLException e) { throw new RuntimeException("fetching count", e); } } @Test public void testApplication() throws Exception { try { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); conf.addResource(this.getClass().getResourceAsStream("/JdbcProperties.xml")); lma.prepareDAG(new JdbcPojoOperatorApplication(), conf); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(false); ((StramLocalCluster)lc).setExitCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return getNumOfRowsinTable(TABLE_POJO_NAME) == 10; } }); lc.run(10000);// runs for 10 seconds and quits Assert.assertEquals("rows in db", 10, getNumOfRowsinTable(TABLE_POJO_NAME)); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } } public static class JdbcPojoOperatorApplication implements StreamingApplication { @Override public void populateDAG(DAG dag, Configuration configuration) { JdbcPOJOInsertOutputOperator jdbc = dag.addOperator("JdbcOutput", new JdbcPOJOInsertOutputOperator()); JdbcTransactionalStore outputStore = new JdbcTransactionalStore(); outputStore.setDatabaseDriver(DB_DRIVER); outputStore.setDatabaseUrl(URL); jdbc.setStore(outputStore); jdbc.setBatchSize(3); jdbc.setTablename(TABLE_POJO_NAME); dag.getMeta(jdbc).getMeta(jdbc.input).getAttributes().put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class); cleanTable(); JdbcPojoEmitterOperator input = dag.addOperator("data", new JdbcPojoEmitterOperator()); dag.addStream("pojo", input.output, jdbc.input); } } public static class JdbcPojoEmitterOperator extends BaseOperator implements InputOperator { public static int emitTuple = 10; public final transient DefaultOutputPort<TestPOJOEvent> output = new DefaultOutputPort<TestPOJOEvent>(); @Override public void emitTuples() { if (emitTuple > 0) { output.emit(new TestPOJOEvent(emitTuple,"test" + emitTuple)); emitTuple--; TupleCount++; } } @Override public void setup(Context.OperatorContext context) { TupleCount = 0; } } }
library/src/test/java/com/datatorrent/lib/db/jdbc/JdbcPojoOperatorApplicationTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.lib.db.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.Callable; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.apache.hadoop.conf.Configuration; import com.datatorrent.api.Context; import com.datatorrent.api.DAG; import com.datatorrent.api.DefaultOutputPort; import com.datatorrent.api.InputOperator; import com.datatorrent.api.LocalMode; import com.datatorrent.api.StreamingApplication; import com.datatorrent.common.util.BaseOperator; import com.datatorrent.stram.StramLocalCluster; public class JdbcPojoOperatorApplicationTest extends JdbcOperatorTest { public static int TupleCount; public static com.datatorrent.lib.parser.XmlParserTest.EmployeeBean obj; public int getNumOfRowsinTable(String tableName) { Connection con; try { con = DriverManager.getConnection(URL); Statement stmt = con.createStatement(); String countQuery = "SELECT count(*) from " + tableName; ResultSet resultSet = stmt.executeQuery(countQuery); resultSet.next(); return resultSet.getInt(1); } catch (SQLException e) { throw new RuntimeException("fetching count", e); } } @Test public void testApplication() throws Exception { try { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); conf.addResource(this.getClass().getResourceAsStream("/JdbcProperties.xml")); lma.prepareDAG(new JdbcPojoOperatorApplication(), conf); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(false); ((StramLocalCluster)lc).setExitCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return TupleCount == 10; } }); lc.run(10000);// runs for 10 seconds and quits Assert.assertEquals("rows in db", 10, getNumOfRowsinTable(TABLE_POJO_NAME)); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } } public static class JdbcPojoOperatorApplication implements StreamingApplication { @Override public void populateDAG(DAG dag, Configuration configuration) { JdbcPOJOInsertOutputOperator jdbc = dag.addOperator("JdbcOutput", new JdbcPOJOInsertOutputOperator()); JdbcTransactionalStore outputStore = new JdbcTransactionalStore(); outputStore.setDatabaseDriver(DB_DRIVER); outputStore.setDatabaseUrl(URL); jdbc.setStore(outputStore); jdbc.setBatchSize(3); jdbc.setTablename(TABLE_POJO_NAME); dag.getMeta(jdbc).getMeta(jdbc.input).getAttributes().put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class); cleanTable(); JdbcPojoEmitterOperator input = dag.addOperator("data", new JdbcPojoEmitterOperator()); dag.addStream("pojo", input.output, jdbc.input); } } public static class JdbcPojoEmitterOperator extends BaseOperator implements InputOperator { public static int emitTuple = 10; public final transient DefaultOutputPort<TestPOJOEvent> output = new DefaultOutputPort<TestPOJOEvent>(); @Override public void emitTuples() { if (emitTuple > 0) { output.emit(new TestPOJOEvent(emitTuple,"test" + emitTuple)); emitTuple--; TupleCount++; } } @Override public void setup(Context.OperatorContext context) { TupleCount = 0; } } }
APEXMALHAR-2357 changing exit condition for JdbcPojoOperatorApplicationTest, due to which it was failing intermittently
library/src/test/java/com/datatorrent/lib/db/jdbc/JdbcPojoOperatorApplicationTest.java
APEXMALHAR-2357 changing exit condition for JdbcPojoOperatorApplicationTest, due to which it was failing intermittently
<ide><path>ibrary/src/test/java/com/datatorrent/lib/db/jdbc/JdbcPojoOperatorApplicationTest.java <ide> public class JdbcPojoOperatorApplicationTest extends JdbcOperatorTest <ide> { <ide> public static int TupleCount; <del> public static com.datatorrent.lib.parser.XmlParserTest.EmployeeBean obj; <ide> <ide> public int getNumOfRowsinTable(String tableName) <ide> { <ide> @Override <ide> public Boolean call() throws Exception <ide> { <del> return TupleCount == 10; <add> return getNumOfRowsinTable(TABLE_POJO_NAME) == 10; <ide> } <ide> }); <ide> lc.run(10000);// runs for 10 seconds and quits
JavaScript
mit
cd6770d4c5afe8b756363937de689e348331a545
0
rossta/webpacker,rails/webpacker,rossta/webpacker,gauravtiwari/webpacker,gauravtiwari/webpacker,gauravtiwari/webpacker,rossta/webpacker,rails/webpacker,rossta/webpacker
module.exports = { test: /\.vue(\.erb)?$/, use: [{ loader: 'vue-loader' }] }
lib/install/loaders/vue.js
const { dev_server: devServer } = require('@rails/webpacker').config const isProduction = process.env.NODE_ENV === 'production' const inDevServer = process.argv.find(v => v.includes('webpack-dev-server')) module.exports = { test: /\.vue(\.erb)?$/, use: [{ loader: 'vue-loader' }] }
Remove unused code for vue-loader (#1518)
lib/install/loaders/vue.js
Remove unused code for vue-loader (#1518)
<ide><path>ib/install/loaders/vue.js <del>const { dev_server: devServer } = require('@rails/webpacker').config <del> <del>const isProduction = process.env.NODE_ENV === 'production' <del>const inDevServer = process.argv.find(v => v.includes('webpack-dev-server')) <del> <ide> module.exports = { <ide> test: /\.vue(\.erb)?$/, <ide> use: [{
Java
epl-1.0
1d10693a30ebd5f28a522d2894c9ca2830675d4a
0
Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse
package org.eclipse.scanning.event.queues; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.eclipse.scanning.api.event.EventException; import org.eclipse.scanning.api.event.IEventService; import org.eclipse.scanning.api.event.alive.KillBean; import org.eclipse.scanning.api.event.core.IProcessCreator; import org.eclipse.scanning.api.event.core.IPublisher; import org.eclipse.scanning.api.event.core.ISubmitter; import org.eclipse.scanning.api.event.queues.IHeartbeatMonitor; import org.eclipse.scanning.api.event.queues.IQueue; import org.eclipse.scanning.api.event.queues.IQueueService; import org.eclipse.scanning.api.event.queues.QueueStatus; import org.eclipse.scanning.api.event.queues.beans.QueueAtom; import org.eclipse.scanning.api.event.queues.beans.QueueBean; import org.eclipse.scanning.api.event.queues.beans.Queueable; import org.eclipse.scanning.api.event.status.Status; import org.eclipse.scanning.event.queues.processors.AtomQueueProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * AtomQueueService provides an implementation of IQueueService interface, * specifically acting on {@link QueueBean}s and {@link QueueAtom}s. The * service is dependent on the {@link IEventService} to provide the * underlying queue architecture. * * A single top-level job-queue {@link IQueue} instance - a queue of beans * extending {@link QueueBean}s - is created on initialisation. The generic * {@link QueueProcessorCreator} is used to create a bean processor dependent * on the type of bean passed to it. Processing only begins when the service is * started. * * Methods are also provided for the on-the-fly creation/disposal of * active-queues - {@link IQueue} instances containing beans extending * {@link QueueAtom}s. Again the generic {@link QueueProcessorCreator} is used * for processor creation. Again processing only happens when the active-queue * is started. * * At shutdown, queues should be first stopped (with or without force) before * being disposed. Stopping the queue leads to a termination of any running * processes. The disposeService() method will stop and dispose all queues in * the service working through the active-queues and then the job-queue. * * It is expected that the {@link AtomQueueProcessor} will call the * registerNewActiveQueue() method to create child queues. The processor will * then be responsible for submitting, starting, stopping etc. of that queue. * The number of active-queues is only limited by the maximum value of an int * (2^32). * * Methods are provided on the queue service to allow external processes to * interrogate the running of the queues. * * @author Michael Wharmby * */ public class AtomQueueService implements IQueueService { private static final Logger logger = LoggerFactory.getLogger(AtomQueueService.class); private static IEventService eventService; private URI uri; private String queueRoot, heartbeatTopicName, commandTopicName; private int nrActiveQueues = 0; private IProcessCreator<QueueAtom> activeQueueProcessor = new QueueProcessCreator<QueueAtom>(true); private IProcessCreator<QueueBean> jobQueueProcessor = new QueueProcessCreator<QueueBean>(true); private IQueue<QueueBean> jobQueue; private Map<String, IQueue<QueueAtom>> activeQueues = new HashMap<String, IQueue<QueueAtom>>(); private boolean alive = false; public AtomQueueService() { } /** * For use in testing! * @param evServ - class implementing IEventService */ public synchronized void setEventService(IEventService evServ) { eventService = evServ; } public synchronized void unsetEventService(IEventService evServ) { try { if (alive) stop(true); } catch (Exception ex) { logger.error("Error stopping the queue service"); } eventService = null; } public IEventService getEventService() { return eventService; } @Override public void init() throws EventException { if (eventService == null) throw new IllegalStateException("EventService not set"); if (queueRoot == null) throw new IllegalStateException("Queue root has not been specified"); if (uri == null) throw new IllegalStateException("URI has not been specified"); //Set the service heartbeat topic heartbeatTopicName = queueRoot+HEARTBEAT_TOPIC_SUFFIX; commandTopicName = queueRoot+COMMAND_TOPIC_SUFFIX; //Determine ID of Job Queue String jqID = queueRoot+"."+JOB_QUEUE; //Create a fully configured job queue & set the runner jobQueue = new Queue<QueueBean>(jqID, heartbeatTopicName, commandTopicName, uri); jobQueue.setProcessRunner(jobQueueProcessor); } @Override public void disposeService() throws EventException { //Stop the job queue if service is up if (alive) stop(true); //Remove any remaining active queues for (String aqID : getAllActiveQueueIDs()) { deRegisterActiveQueue(aqID, true); } //Dispose the job queue disposeQueue(getJobQueueID(), true); } @Override public void start() throws EventException { if (!jobQueue.getQueueStatus().isStartable()) { throw new EventException("Job queue not startable - Status: " + jobQueue.getQueueStatus()); } if (jobQueue.getQueueStatus().isActive()) { logger.warn("Job queue is already active."); return; } //Last step is to start the job queue and mark the service alive jobQueue.getConsumer().start(); jobQueue.setQueueStatus(QueueStatus.STARTED); //Mark service as up alive = true; } @Override public void stop(boolean force) throws EventException { if (!jobQueue.getQueueStatus().isActive()) { logger.warn("Job queue is not active."); return; } //Deregister all existing active queues. if (!activeQueues.isEmpty()) { //Create a new HashSet here as the deRegister method changes activeQueues Set<String> qIDSet = new HashSet<String>(activeQueues.keySet()); for (String qID : qIDSet) { deRegisterActiveQueue(qID, force); } } //Kill/stop the job queue if (force) { killQueue(getJobQueueID(), true, false); } else { jobQueue.getConsumer().stop(); jobQueue.setQueueStatus(QueueStatus.STOPPED); } //Mark the service as down alive = false; } @Override public String registerNewActiveQueue() throws EventException { if (!alive) throw new EventException("Queue service not started."); //Get an ID and the queue names for new active queue String aqID = generateActiveQueueID(); //Create a fully configured active queue, purge queues for safety & set runner IQueue<QueueAtom> activeQueue = new Queue<QueueAtom>(aqID, heartbeatTopicName, commandTopicName, uri); activeQueue.clearQueues(); activeQueue.setProcessRunner(activeQueueProcessor); //Add to registry and increment number of registered queues activeQueues.put(aqID, activeQueue); nrActiveQueues = activeQueues.size(); return aqID; } @Override public void deRegisterActiveQueue(String queueID, boolean force) throws EventException { if (!alive) throw new EventException("Queue service not started."); //Get the queue and check that it's not started IQueue<QueueAtom> activeQueue = getActiveQueue(queueID); if (activeQueue.getQueueStatus().isActive()) { logger.warn("Stopping active queue " + queueID + " whilst still active."); stopActiveQueue(queueID, force); } //Disconnect remaining queue processes and remove from map disposeQueue(queueID, true); activeQueues.remove(queueID); nrActiveQueues = activeQueues.size(); } @Override public void startActiveQueue(String queueID) throws EventException { IQueue<QueueAtom> activeQueue = getActiveQueue(queueID); if (!activeQueue.getQueueStatus().isStartable()) { throw new EventException("Active queue not startable - Status: " + activeQueue.getQueueStatus()); } if (activeQueue.getQueueStatus().isActive()) { logger.warn("Active queue is already active."); return; } activeQueue.getConsumer().start(); activeQueue.setQueueStatus(QueueStatus.STARTED); } @Override public void stopActiveQueue(String queueID, boolean force) throws EventException { IQueue<QueueAtom> activeQueue = getActiveQueue(queueID); if (!activeQueue.getQueueStatus().isActive()) { logger.warn("Active queue is not active."); return; } //Kill/stop the job queue if (force) { killQueue(queueID, true, false); } else { activeQueue.getConsumer().stop(); activeQueue.setQueueStatus(QueueStatus.STOPPED); } } @Override public QueueStatus getQueueStatus(String queueID) { return getQueueFromString(queueID).getQueueStatus(); } @Override public void disposeQueue(String queueID, boolean nullify) throws EventException { //Ensures consumer and subscriber are both disconnected IQueue<? extends Queueable> queue = getQueueFromString(queueID); if (queue.getQueueStatus().isActive()) throw new EventException("Queue is currently running. Cannot dispose."); //In previous iteration found that... queue.clearQueues(); //...status queue clear, but submit not... queue.disconnect(); boolean isClear = queue.clearQueues();//... submit queue now clear. if (!isClear) throw new EventException("Failed to clear queues when disposing "+queueID); queue.setQueueStatus(QueueStatus.DISPOSED); if (nullify) { if (queueID.equals(jobQueue.getQueueID())) jobQueue = null; else if (activeQueues.containsKey(queueID)) {//Prevent adding "non-existent queueID" = null activeQueues.put(queueID, null); } } } @Override public void killQueue(String queueID, boolean disconnect, boolean exitProcess) throws EventException { IPublisher<KillBean> killer; //Get the consumer ID for this queue UUID consumerID = getQueueFromString(queueID).getConsumerID(); KillBean knife = new KillBean(); knife.setConsumerId(consumerID); knife.setDisconnect(disconnect); knife.setExitProcess(exitProcess); killer = eventService.createPublisher(uri, commandTopicName); killer.broadcast(knife); killer.disconnect(); getQueueFromString(queueID).setQueueStatus(QueueStatus.KILLED); } @Override public <T extends Queueable> void submit(T atomBean, String submitQ) throws EventException { //Prepare the atom/bean for submission atomBean.setStatus(Status.SUBMITTED); try { //FIXME Only set if not set already atomBean.setHostName(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException ex) { throw new EventException("Failed to set hostname on bean. " + ex.getMessage()); } //Create a submitter and submit the atom ISubmitter<T> submitter = eventService.createSubmitter(uri, submitQ); submitter.submit(atomBean); submitter.disconnect(); } @Override public <T extends Queueable> void terminate(T atomBean, String statusT) throws EventException { //Set up a publisher to send terminated beans with IPublisher<T> terminator = eventService.createPublisher(uri, statusT); //Set the bean status, publish it & get rid of the terminator atomBean.setStatus(Status.REQUEST_TERMINATE); terminator.broadcast(atomBean); terminator.disconnect(); } @Override public IProcessCreator<QueueBean> getJobQueueProcessor() { return jobQueueProcessor; } @Override public void setJobQueueProcessor(IProcessCreator<QueueBean> proCreate) throws EventException { if (alive) throw new EventException("Cannot change job-queue processor when service started."); jobQueueProcessor = proCreate; } @Override public IProcessCreator<QueueAtom> getActiveQueueProcessor() { return activeQueueProcessor; } @Override public void setActiveQueueProcessor(IProcessCreator<QueueAtom> proCreate) throws EventException { if (alive) throw new EventException("Cannot change active-queue processor when service started."); activeQueueProcessor = proCreate; } @Override public List<QueueBean> getJobQueueStatusSet() throws EventException { return jobQueue.getConsumer().getStatusSet(); } @Override public List<QueueAtom> getActiveQueueStatusSet(String queueID) throws EventException { return getActiveQueue(queueID).getConsumer().getStatusSet(); } @Override public IHeartbeatMonitor getHeartMonitor(String queueID) throws EventException { return new HeartbeatMonitor(uri, heartbeatTopicName, queueID, this); } @Override public IQueue<QueueBean> getJobQueue() { return jobQueue; } @Override public String getJobQueueID() { return jobQueue.getQueueID(); } @Override public List<String> getAllActiveQueueIDs() { return new ArrayList<String>(activeQueues.keySet()); } @Override public boolean isActiveQueueRegistered(String queueID) { return activeQueues.containsKey(queueID); } @Override public IQueue<QueueAtom> getActiveQueue(String queueID) { if (isActiveQueueRegistered(queueID)) return activeQueues.get(queueID); throw new IllegalArgumentException("Queue ID not found in registry"); } @Override public Map<String, IQueue<QueueAtom>> getAllActiveQueues() { return activeQueues; } @Override public String getQueueRoot() { return queueRoot; } @Override public void setQueueRoot(String queueRoot) throws EventException { if (alive) throw new UnsupportedOperationException("Cannot change queue root whilst queue service is running"); this.queueRoot = queueRoot; //Update the command & heartbeat topics too heartbeatTopicName = queueRoot+HEARTBEAT_TOPIC_SUFFIX; commandTopicName = queueRoot+COMMAND_TOPIC_SUFFIX; } @Override public String getHeartbeatTopicName() { return heartbeatTopicName; } @Override public String getCommandTopicName() { return commandTopicName; } @Override public URI getURI() { return uri; } @Override public void setURI(URI uri) throws EventException { if (alive) throw new UnsupportedOperationException("Cannot change URI whilst queue service is running"); this.uri = uri; } private String generateActiveQueueID() { nrActiveQueues = activeQueues.size(); return queueRoot + "." + ACTIVE_QUEUE + "-" + nrActiveQueues; } private IQueue<? extends Queueable> getQueueFromString(String queueID) { if (queueID.equals(getJobQueueID())) { return getJobQueue(); } else if (isActiveQueueRegistered(queueID)) { return getActiveQueue(queueID); } else { throw new IllegalArgumentException("Queue ID not found in registry"); } } }
org.eclipse.scanning.event/src/org/eclipse/scanning/event/queues/AtomQueueService.java
package org.eclipse.scanning.event.queues; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.eclipse.scanning.api.event.EventException; import org.eclipse.scanning.api.event.IEventService; import org.eclipse.scanning.api.event.alive.IHeartbeatListener; import org.eclipse.scanning.api.event.alive.KillBean; import org.eclipse.scanning.api.event.core.IConsumer; import org.eclipse.scanning.api.event.core.IProcessCreator; import org.eclipse.scanning.api.event.core.IPublisher; import org.eclipse.scanning.api.event.core.ISubmitter; import org.eclipse.scanning.api.event.core.ISubscriber; import org.eclipse.scanning.api.event.queues.IQueue; import org.eclipse.scanning.api.event.queues.IQueueService; import org.eclipse.scanning.api.event.queues.QueueNameMap; import org.eclipse.scanning.api.event.queues.QueueStatus; import org.eclipse.scanning.api.event.queues.beans.QueueAtom; import org.eclipse.scanning.api.event.queues.beans.QueueBean; import org.eclipse.scanning.api.event.queues.beans.Queueable; import org.eclipse.scanning.api.event.status.Status; import org.eclipse.scanning.event.queues.processors.AtomQueueProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * AtomQueueService provides an implementation of IQueueService interface, * specifically acting on {@link QueueBean}s and {@link QueueAtom}s. The * service is dependent on the {@link IEventService} to provide the * underlying queue architecture. * * A single top-level job-queue {@link IQueue} instance - a queue of beans * extending {@link QueueBean}s - is created on initialisation. The generic * {@link QueueProcessorCreator} is used to create a bean processor dependent * on the type of bean passed to it. Processing only begins when the service is * started. * * Methods are also provided for the on-the-fly creation/disposal of * active-queues - {@link IQueue} instances containing beans extending * {@link QueueAtom}s. Again the generic {@link QueueProcessorCreator} is used * for processor creation. Again processing only happens when the active-queue * is started. * * At shutdown, queues should be first stopped (with or without force) before * being disposed. Stopping the queue leads to a termination of any running * processes. The disposeService() method will stop and dispose all queues in * the service working through the active-queues and then the job-queue. * * It is expected that the {@link AtomQueueProcessor} will call the * registerNewActiveQueue() method to create child queues. The processor will * then be responsible for submitting, starting, stopping etc. of that queue. * The number of active-queues is only limited by the maximum value of an int * (2^32). * * Methods are provided on the queue service to allow external processes to * interrogate the running of the queues. * * @author Michael Wharmby * */ public class AtomQueueService implements IQueueService { private static final Logger logger = LoggerFactory.getLogger(AtomQueueService.class); private static IEventService eventService; private URI uri; private String queueRoot, heartbeatTopic, killTopic; private int nrActiveQueues = 0; private IProcessCreator<QueueAtom> activeQueueProcessor = new QueueProcessCreator<QueueAtom>(true); private IProcessCreator<QueueBean> jobQueueProcessor = new QueueProcessCreator<QueueBean>(true); private IQueue<QueueBean> jobQueue; private Map<String, IQueue<QueueAtom>> activeQueues = new HashMap<String, IQueue<QueueAtom>>(); private boolean alive = false; public AtomQueueService() { } /** * For use in testing! * @param evServ - class implementing IEventService */ public synchronized void setEventService(IEventService evServ) { eventService = evServ; } public synchronized void unsetEventService(IEventService evServ) { try { if (alive) stop(true); } catch (Exception ex) { logger.error("Error stopping the queue service"); } eventService = null; } public IEventService getEventService() { return eventService; } @Override public void init() throws EventException { if (eventService == null) throw new IllegalStateException("EventService not set"); if (queueRoot == null) throw new IllegalStateException("Queue root has not been specified"); if (uri == null) throw new IllegalStateException("URI has not been specified"); //Set the service heartbeat topic heartbeatTopic = queueRoot+HEARTBEAT_TOPIC_SUFFIX; killTopic = queueRoot+KILL_TOPIC_SUFFIX; //Determine ID and queuenames of Job Queue; create the queue objects String jqID = queueRoot+"."+JOB_QUEUE; QueueNameMap jqNames = new QueueNameMap(jqID, heartbeatTopic, killTopic); //Create a fully configured job queue & set the runner IConsumer<QueueBean> cons = makeQueueConsumer(jqNames); ISubscriber<IHeartbeatListener> mon = makeQueueSubscriber(heartbeatTopic); jobQueue = new Queue<QueueBean>(jqID, jqNames, cons, mon); jobQueue.setProcessRunner(jobQueueProcessor); } @Override public void disposeService() throws EventException { //Stop the job queue if service is up if (alive) stop(true); //Remove any remaining active queues for (String aqID : getAllActiveQueueIDs()) { deRegisterActiveQueue(aqID, true); } //Dispose the job queue disposeQueue(getJobQueueID(), true); } @Override public void start() throws EventException { if (!jobQueue.getQueueStatus().isStartable()) { throw new EventException("Job queue not startable - Status: " + jobQueue.getQueueStatus()); } if (jobQueue.getQueueStatus().isActive()) { logger.warn("Job queue is already active."); return; } //Last step is to start the job queue and mark the service alive jobQueue.getConsumer().start(); jobQueue.setQueueStatus(QueueStatus.STARTED); //Mark service as up alive = true; } @Override public void stop(boolean force) throws EventException { if (!jobQueue.getQueueStatus().isActive()) { logger.warn("Job queue is not active."); return; } //Deregister all existing active queues. if (!activeQueues.isEmpty()) { //Create a new HashSet here as the deRegister method changes activeQueues Set<String> qIDSet = new HashSet<String>(activeQueues.keySet()); for (String qID : qIDSet) { deRegisterActiveQueue(qID, force); } } //Kill/stop the job queue if (force) { killQueue(getJobQueueID(), true, false); } else { jobQueue.getConsumer().stop(); jobQueue.setQueueStatus(QueueStatus.STOPPED); } //Mark the service as down alive = false; } @Override public String registerNewActiveQueue() throws EventException { if (!alive) throw new EventException("Queue service not started."); //Get an ID and the queue names for new active queue String aqID = generateActiveQueueID(); QueueNameMap aqNames = new QueueNameMap(aqID, heartbeatTopic, killTopic); //Create a fully configured active queue, purge queues for safety & set runner IConsumer<QueueAtom> cons = makeQueueConsumer(aqNames); ISubscriber<IHeartbeatListener> mon = makeQueueSubscriber(heartbeatTopic); IQueue<QueueAtom> activeQueue = new Queue<QueueAtom>(aqID, aqNames, cons, mon); activeQueue.clearQueues(); activeQueue.setProcessRunner(activeQueueProcessor); //Add to registry and increment number of registered queues activeQueues.put(aqID, activeQueue); nrActiveQueues = activeQueues.size(); return aqID; } @Override public void deRegisterActiveQueue(String queueID, boolean force) throws EventException { if (!alive) throw new EventException("Queue service not started."); //Get the queue and check that it's not started IQueue<QueueAtom> activeQueue = getActiveQueue(queueID); if (activeQueue.getQueueStatus().isActive()) { logger.warn("Stopping active queue " + queueID + " whilst still active."); stopActiveQueue(queueID, force); } //Disconnect remaining queue processes and remove from map disposeQueue(queueID, true); activeQueues.remove(queueID); nrActiveQueues = activeQueues.size(); } @Override public void startActiveQueue(String queueID) throws EventException { IQueue<QueueAtom> activeQueue = getActiveQueue(queueID); if (!activeQueue.getQueueStatus().isStartable()) { throw new EventException("Active queue not startable - Status: " + activeQueue.getQueueStatus()); } if (activeQueue.getQueueStatus().isActive()) { logger.warn("Active queue is already active."); return; } activeQueue.getConsumer().start(); activeQueue.setQueueStatus(QueueStatus.STARTED); } @Override public void stopActiveQueue(String queueID, boolean force) throws EventException { IQueue<QueueAtom> activeQueue = getActiveQueue(queueID); if (!activeQueue.getQueueStatus().isActive()) { logger.warn("Active queue is not active."); return; } //Kill/stop the job queue if (force) { killQueue(queueID, true, false); } else { activeQueue.getConsumer().stop(); activeQueue.setQueueStatus(QueueStatus.STOPPED); } } @Override public QueueStatus getQueueStatus(String queueID) { return getQueueFromString(queueID).getQueueStatus(); } @Override public void disposeQueue(String queueID, boolean nullify) throws EventException { //Ensures consumer and subscriber are both disconnected IQueue<? extends Queueable> queue = getQueueFromString(queueID); if (queue.getQueueStatus().isActive()) throw new EventException("Queue is currently running. Cannot dispose."); //In previous iteration found that... queue.clearQueues(); //...status queue clear, but submit not... queue.disconnect(); boolean isClear = queue.clearQueues();//... submit queue now clear. if (!isClear) throw new EventException("Failed to clear queues when disposing "+queueID); queue.setQueueStatus(QueueStatus.DISPOSED); if (nullify) { if (queueID.equals(jobQueue.getQueueID())) jobQueue = null; else if (activeQueues.containsKey(queueID)) {//Prevent adding "non-existent queueID" = null activeQueues.put(queueID, null); } } } @Override public void killQueue(String queueID, boolean disconnect, boolean exitProcess) throws EventException { IPublisher<KillBean> killer; //Get the consumer ID for this queue UUID consumerID = getQueueFromString(queueID).getConsumerID(); KillBean knife = new KillBean(); knife.setConsumerId(consumerID); knife.setDisconnect(disconnect); knife.setExitProcess(exitProcess); killer = eventService.createPublisher(uri, killTopic); killer.broadcast(knife); killer.disconnect(); getQueueFromString(queueID).setQueueStatus(QueueStatus.KILLED); } @Override public void jobQueueSubmit(QueueBean bean) throws EventException { submit(bean, jobQueue.getSubmissionQueueName()); } @Override public void activeQueueSubmit(QueueAtom atom, String queueID) throws EventException { submit(atom, getActiveQueue(queueID).getSubmissionQueueName()); } private <T extends Queueable> void submit(T atomBean, String submitQ) throws EventException{ //Prepare the atom/bean for submission atomBean.setStatus(Status.SUBMITTED); try { //FIXME Only set if not set already atomBean.setHostName(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException ex) { throw new EventException("Failed to set hostname on bean. " + ex.getMessage()); } //Create a submitter and submit the atom ISubmitter<T> submitter = eventService.createSubmitter(uri, submitQ); submitter.submit(atomBean); submitter.disconnect(); } @Override public void jobQueueTerminate(QueueBean bean) throws EventException { terminate(bean, getJobQueue().getQueueNames().getStatusTopicName()); } @Override public void activeQueueTerminate(QueueAtom atom, String queueID) throws EventException { terminate(atom, getActiveQueue(queueID).getQueueNames().getStatusTopicName()); } private <T extends Queueable> void terminate(T atomBean, String statusT) throws EventException { //Set up a publisher to send terminated beans with IPublisher<T> terminator = eventService.createPublisher(uri, statusT); //Set the bean status, publish it & get rid of the terminator atomBean.setStatus(Status.REQUEST_TERMINATE); terminator.broadcast(atomBean); terminator.disconnect(); } @Override public IProcessCreator<QueueBean> getJobQueueProcessor() { return jobQueueProcessor; } @Override public void setJobQueueProcessor(IProcessCreator<QueueBean> proCreate) throws EventException { if (alive) throw new EventException("Cannot change job-queue processor when service started."); jobQueueProcessor = proCreate; } @Override public IProcessCreator<QueueAtom> getActiveQueueProcessor() { return activeQueueProcessor; } @Override public void setActiveQueueProcessor(IProcessCreator<QueueAtom> proCreate) throws EventException { if (alive) throw new EventException("Cannot change active-queue processor when service started."); activeQueueProcessor = proCreate; } @Override public List<QueueBean> getJobQueueStatusSet() throws EventException { return jobQueue.getConsumer().getStatusSet(); } @Override public List<QueueAtom> getActiveQueueStatusSet(String queueID) throws EventException { return getActiveQueue(queueID).getConsumer().getStatusSet(); } @Override public ISubscriber<IHeartbeatListener> getHeartMonitor(String queueID) { IQueue<? extends Queueable> queue = getQueueFromString(queueID); //TODO Expand this to listen only for heartbeats from the given consumer return makeQueueSubscriber(queue.getQueueNames().getHeartbeatTopicName()); } @Override public IQueue<QueueBean> getJobQueue() { return jobQueue; } @Override public String getJobQueueID() { return jobQueue.getQueueID(); } @Override public List<String> getAllActiveQueueIDs() { return new ArrayList<String>(activeQueues.keySet()); } @Override public boolean isActiveQueueRegistered(String queueID) { return activeQueues.containsKey(queueID); } @Override public IQueue<QueueAtom> getActiveQueue(String queueID) { if (isActiveQueueRegistered(queueID)) return activeQueues.get(queueID); throw new IllegalArgumentException("Queue ID not found in registry"); } @Override public Map<String, IQueue<QueueAtom>> getAllActiveQueues() { return activeQueues; } @Override public String getQueueRoot() { return queueRoot; } @Override public void setQueueRoot(String queueRoot) throws EventException { if (alive) throw new UnsupportedOperationException("Cannot change queue root whilst queue service is running"); this.queueRoot = queueRoot; } @Override public URI getURI() { return uri; } @Override public void setURI(URI uri) throws EventException { if (alive) throw new UnsupportedOperationException("Cannot change URI whilst queue service is running"); this.uri = uri; } // private <T extends Queueable> IConsumer<T> makeQueueConsumer(QueueNameMap qNames) throws EventException { // return eventService.createConsumer(uri, qNames.getSubmissionQueueName(), // qNames.getStatusQueueName(), qNames.getStatusTopicName(), qNames.getHeartbeatTopicName(), // qNames.getCommandTopicName()); // } private <T extends Queueable> IConsumer<T> makeQueueConsumer(QueueNameMap qNames) throws EventException { return eventService.createConsumer(uri, qNames.getSubmissionQueueName(), qNames.getStatusQueueName(), qNames.getStatusTopicName(), qNames.getHeartbeatTopicName(), qNames.getCommandTopicName()); } private <T extends EventListener> ISubscriber<T> makeQueueSubscriber(String topicName) { return eventService.createSubscriber(uri, topicName); } private String generateActiveQueueID() { nrActiveQueues = activeQueues.size(); return queueRoot + "." + ACTIVE_QUEUE + "-" + nrActiveQueues; } private IQueue<? extends Queueable> getQueueFromString(String queueID) { if (queueID.equals(getJobQueueID())) { return getJobQueue(); } else if (isActiveQueueRegistered(queueID)) { return getActiveQueue(queueID); } else { throw new IllegalArgumentException("Queue ID not found in registry"); } } }
Update name of killTopic to commandTopic. Implements getters for heartbeat & command topics. Remove all references to QueueNameMap. Remove creation of consumer and ISubscriber objects to follow new Queue creation model. Remove submit/terminate methods now set as default on interface & change access of the generic methods to public. Update getHeartmonitor to return an IHeartbeatMonitor. Signed-off-by: Michael Wharmby <[email protected]>
org.eclipse.scanning.event/src/org/eclipse/scanning/event/queues/AtomQueueService.java
Update name of killTopic to commandTopic. Implements getters for heartbeat & command topics. Remove all references to QueueNameMap. Remove creation of consumer and ISubscriber objects to follow new Queue creation model. Remove submit/terminate methods now set as default on interface & change access of the generic methods to public. Update getHeartmonitor to return an IHeartbeatMonitor.
<ide><path>rg.eclipse.scanning.event/src/org/eclipse/scanning/event/queues/AtomQueueService.java <ide> import java.net.URI; <ide> import java.net.UnknownHostException; <ide> import java.util.ArrayList; <del>import java.util.EventListener; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.List; <ide> <ide> import org.eclipse.scanning.api.event.EventException; <ide> import org.eclipse.scanning.api.event.IEventService; <del>import org.eclipse.scanning.api.event.alive.IHeartbeatListener; <ide> import org.eclipse.scanning.api.event.alive.KillBean; <del>import org.eclipse.scanning.api.event.core.IConsumer; <ide> import org.eclipse.scanning.api.event.core.IProcessCreator; <ide> import org.eclipse.scanning.api.event.core.IPublisher; <ide> import org.eclipse.scanning.api.event.core.ISubmitter; <del>import org.eclipse.scanning.api.event.core.ISubscriber; <add>import org.eclipse.scanning.api.event.queues.IHeartbeatMonitor; <ide> import org.eclipse.scanning.api.event.queues.IQueue; <ide> import org.eclipse.scanning.api.event.queues.IQueueService; <del>import org.eclipse.scanning.api.event.queues.QueueNameMap; <ide> import org.eclipse.scanning.api.event.queues.QueueStatus; <ide> import org.eclipse.scanning.api.event.queues.beans.QueueAtom; <ide> import org.eclipse.scanning.api.event.queues.beans.QueueBean; <ide> private static IEventService eventService; <ide> private URI uri; <ide> <del> private String queueRoot, heartbeatTopic, killTopic; <add> private String queueRoot, heartbeatTopicName, commandTopicName; <ide> private int nrActiveQueues = 0; <ide> private IProcessCreator<QueueAtom> activeQueueProcessor = new QueueProcessCreator<QueueAtom>(true); <ide> private IProcessCreator<QueueBean> jobQueueProcessor = new QueueProcessCreator<QueueBean>(true); <ide> if (uri == null) throw new IllegalStateException("URI has not been specified"); <ide> <ide> //Set the service heartbeat topic <del> heartbeatTopic = queueRoot+HEARTBEAT_TOPIC_SUFFIX; <del> killTopic = queueRoot+KILL_TOPIC_SUFFIX; <del> <del> //Determine ID and queuenames of Job Queue; create the queue objects <add> heartbeatTopicName = queueRoot+HEARTBEAT_TOPIC_SUFFIX; <add> commandTopicName = queueRoot+COMMAND_TOPIC_SUFFIX; <add> <add> //Determine ID of Job Queue <ide> String jqID = queueRoot+"."+JOB_QUEUE; <del> QueueNameMap jqNames = new QueueNameMap(jqID, heartbeatTopic, killTopic); <ide> <ide> //Create a fully configured job queue & set the runner <del> IConsumer<QueueBean> cons = makeQueueConsumer(jqNames); <del> ISubscriber<IHeartbeatListener> mon = makeQueueSubscriber(heartbeatTopic); <del> jobQueue = new Queue<QueueBean>(jqID, jqNames, cons, mon); <add> jobQueue = new Queue<QueueBean>(jqID, heartbeatTopicName, commandTopicName, uri); <ide> jobQueue.setProcessRunner(jobQueueProcessor); <ide> } <ide> <ide> <ide> //Get an ID and the queue names for new active queue <ide> String aqID = generateActiveQueueID(); <del> QueueNameMap aqNames = new QueueNameMap(aqID, heartbeatTopic, killTopic); <ide> <ide> //Create a fully configured active queue, purge queues for safety & set runner <del> IConsumer<QueueAtom> cons = makeQueueConsumer(aqNames); <del> ISubscriber<IHeartbeatListener> mon = makeQueueSubscriber(heartbeatTopic); <del> IQueue<QueueAtom> activeQueue = new Queue<QueueAtom>(aqID, aqNames, cons, mon); <add> IQueue<QueueAtom> activeQueue = new Queue<QueueAtom>(aqID, heartbeatTopicName, commandTopicName, uri); <ide> activeQueue.clearQueues(); <ide> activeQueue.setProcessRunner(activeQueueProcessor); <ide> <ide> knife.setDisconnect(disconnect); <ide> knife.setExitProcess(exitProcess); <ide> <del> killer = eventService.createPublisher(uri, killTopic); <add> killer = eventService.createPublisher(uri, commandTopicName); <ide> killer.broadcast(knife); <ide> killer.disconnect(); <ide> <ide> } <ide> <ide> @Override <del> public void jobQueueSubmit(QueueBean bean) throws EventException { <del> submit(bean, jobQueue.getSubmissionQueueName()); <del> } <del> <del> @Override <del> public void activeQueueSubmit(QueueAtom atom, String queueID) throws EventException { <del> submit(atom, getActiveQueue(queueID).getSubmissionQueueName()); <del> } <del> <del> private <T extends Queueable> void submit(T atomBean, String submitQ) throws EventException{ <add> public <T extends Queueable> void submit(T atomBean, String submitQ) throws EventException { <ide> //Prepare the atom/bean for submission <ide> atomBean.setStatus(Status.SUBMITTED); <ide> try { <ide> } <ide> <ide> @Override <del> public void jobQueueTerminate(QueueBean bean) throws EventException { <del> terminate(bean, getJobQueue().getQueueNames().getStatusTopicName()); <del> } <del> <del> @Override <del> public void activeQueueTerminate(QueueAtom atom, String queueID) throws EventException { <del> terminate(atom, getActiveQueue(queueID).getQueueNames().getStatusTopicName()); <del> } <del> <del> private <T extends Queueable> void terminate(T atomBean, String statusT) throws EventException { <add> public <T extends Queueable> void terminate(T atomBean, String statusT) throws EventException { <ide> //Set up a publisher to send terminated beans with <ide> IPublisher<T> terminator = eventService.createPublisher(uri, statusT); <ide> <ide> } <ide> <ide> @Override <del> public ISubscriber<IHeartbeatListener> getHeartMonitor(String queueID) { <del> IQueue<? extends Queueable> queue = getQueueFromString(queueID); <del> //TODO Expand this to listen only for heartbeats from the given consumer <del> return makeQueueSubscriber(queue.getQueueNames().getHeartbeatTopicName()); <add> public IHeartbeatMonitor getHeartMonitor(String queueID) throws EventException { <add> return new HeartbeatMonitor(uri, heartbeatTopicName, queueID, this); <ide> } <ide> <ide> @Override <ide> public void setQueueRoot(String queueRoot) throws EventException { <ide> if (alive) throw new UnsupportedOperationException("Cannot change queue root whilst queue service is running"); <ide> this.queueRoot = queueRoot; <add> <add> //Update the command & heartbeat topics too <add> heartbeatTopicName = queueRoot+HEARTBEAT_TOPIC_SUFFIX; <add> commandTopicName = queueRoot+COMMAND_TOPIC_SUFFIX; <add> } <add> <add> @Override <add> public String getHeartbeatTopicName() { <add> return heartbeatTopicName; <add> } <add> <add> @Override <add> public String getCommandTopicName() { <add> return commandTopicName; <ide> } <ide> <ide> @Override <ide> public void setURI(URI uri) throws EventException { <ide> if (alive) throw new UnsupportedOperationException("Cannot change URI whilst queue service is running"); <ide> this.uri = uri; <del> } <del> <del>// private <T extends Queueable> IConsumer<T> makeQueueConsumer(QueueNameMap qNames) throws EventException { <del>// return eventService.createConsumer(uri, qNames.getSubmissionQueueName(), <del>// qNames.getStatusQueueName(), qNames.getStatusTopicName(), qNames.getHeartbeatTopicName(), <del>// qNames.getCommandTopicName()); <del>// } <del> <del> private <T extends Queueable> IConsumer<T> makeQueueConsumer(QueueNameMap qNames) throws EventException { <del> return eventService.createConsumer(uri, qNames.getSubmissionQueueName(), <del> qNames.getStatusQueueName(), qNames.getStatusTopicName(), qNames.getHeartbeatTopicName(), <del> qNames.getCommandTopicName()); <del>} <del> <del> private <T extends EventListener> ISubscriber<T> makeQueueSubscriber(String topicName) { <del> return eventService.createSubscriber(uri, topicName); <ide> } <ide> <ide> private String generateActiveQueueID() {
Java
agpl-3.0
2d72dd76d07f1333524c192392fbd5277a348bc4
0
ColostateResearchServices/kc,ColostateResearchServices/kc,ColostateResearchServices/kc
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.excon.project; import org.drools.core.util.StringUtils; import org.kuali.coeus.common.framework.person.KcPersonService; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.excon.document.ExconProjectDocument; import org.kuali.coeus.common.framework.mail.KcEmailService; import org.kuali.coeus.common.framework.mail.EmailAttachment; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.membership.MemberType; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.group.GroupMember; import org.kuali.rice.kim.api.group.GroupService; import org.kuali.rice.kns.util.KNSGlobalVariables; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; import java.io.Serializable; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; /** * This is the base class for handling ExconProjectEvents */ public class ExconProjectEmailBean implements Serializable { private static final long serialVersionUID = 238453457L; protected ExconProjectEmailContent newBody; protected ExconProjectEmailContent newAttachment; protected ExconProjectEmailContent newAgenda; protected ExconProjectForm exconProjectForm; private transient BusinessObjectService businessObjectService; public ExconProjectEmailBean(ExconProjectForm exconProjectForm) { this.exconProjectForm = exconProjectForm; init(); } public ExconProjectEmailContent getNewBody() { return newBody; } public ExconProjectEmailContent getNewAttachment() { return newAttachment; } public ExconProjectEmailContent getNewAgenda(){ return newAgenda; } public ExconProjectEmailContent getBodyObj() { HashMap<String,String> criteriaMap=new HashMap<String,String>(); criteriaMap.put("contentCode", newBody.getContentCode()); return (ExconProjectEmailContent)getBusinessObjectService().findByPrimaryKey(ExconProjectEmailContent.class, criteriaMap); } public ExconProjectEmailContent getAttachmentObj() { HashMap<String,String> criteriaMap=new HashMap<String,String>(); criteriaMap.put("contentCode", newAttachment.getContentCode()); return (ExconProjectEmailContent)getBusinessObjectService().findByPrimaryKey(ExconProjectEmailContent.class, criteriaMap); } public ExconProjectEmailContent getAgendaObj() { HashMap<String,String> criteriaMap=new HashMap<String,String>(); criteriaMap.put("contentCode", newAgenda.getContentCode()); return (ExconProjectEmailContent)getBusinessObjectService().findByPrimaryKey(ExconProjectEmailContent.class, criteriaMap); } public void sendTravelerEmail() { ExconProject exconProject=getExconProject(); String destStr=""; ArrayList<EmailAttachment> attachments=new ArrayList<EmailAttachment>(); for (ExconProjectDestination destination:exconProject.getExconProjectDestinations()) { if (!StringUtils.isEmpty(destStr)) { destStr+=", "; } destStr+=destination.getDestinationCountryName(); } // String currentEnv=getConfigurationService().getPropertyValueAsString("environment"); // String prodEnv=getConfigurationService().getPropertyValueAsString("production.environment.code"); String senderEmail=getPersonService().getKcPersonByUserName(GlobalVariables.getUserSession().getPrincipalName()).getEmailAddress(); String recipEmail=senderEmail; String prodEmail=""; String firstName="Traveler"; ExconProjectPerson traveler=exconProject.getTraveler(); if (traveler!=null) { prodEmail=traveler.getPerson().getEmailAddress(); if (!StringUtils.isEmpty(traveler.getPerson().getFirstName())) { firstName=traveler.getPerson().getFirstName(); } } if (GlobalVariables.getUserSession().isProductionEnvironment()) { recipEmail=prodEmail; } else { destStr+=" (to "+prodEmail+" in production)"; } HashSet<String> recipSet=new HashSet<String>(); recipSet.add(recipEmail); HashSet<String> bccSet=new HashSet<String>(); bccSet.add(senderEmail); Group approverGroup = getGroupService().getGroupByNamespaceCodeAndName("KC-WKFLW", "Export Control Project Approvers"); if (approverGroup!=null) { for (GroupMember member : getGroupService().getMembersOfGroup(approverGroup.getId())) { if (member.isActive() && member.getType().compareTo(MemberType.PRINCIPAL)==0) { bccSet.add(getPersonService().getKcPersonByPersonId(member.getMemberId()).getEmailAddress()); } } } EmailAttachment attachment=new EmailAttachment(); ExconProjectEmailContent bodyContent=getBodyObj(); ExconProjectEmailContent attachmentContent=getAttachmentObj(); attachment.setContents(attachmentContent.getAttachmentContent()); attachment.setFileName(attachmentContent.getFileName()); attachment.setMimeType(attachmentContent.getContentType()); attachments.add(attachment); String bodyStr=new String(bodyContent.getAttachmentContent()); bodyStr=bodyStr.replace("[firstName]", firstName); getEmailService().sendEmailWithAttachments(senderEmail,recipSet, "Regarding your upcoming trip to: "+destStr, null, bccSet, bodyStr, true, attachments); ExconProjectEvent newEvent=new ExconProjectEvent(); newEvent.setProjectEventTypeCode("TVA"); newEvent.setEventDate(new Date(System.currentTimeMillis())); exconProject.add(newEvent); if (traveler!=null) { ExconProjectTravelerCommunication newCommunication=new ExconProjectTravelerCommunication(); newCommunication.setEmailBodyContentCode(bodyContent.getContentCodeBody()); newCommunication.setEmailAttachmentContentCode(attachmentContent.getContentCodeAttachment()); newCommunication.setPersonId(traveler.getPersonId().toString()); newCommunication.setCommunicationDate(new Date(System.currentTimeMillis())); exconProject.getTravelerCommunications().add(newCommunication); } KNSGlobalVariables.getMessageList().add("info.exconProjectTravelerEmail.sent", recipEmail); return; } private KcEmailService getEmailService() { return KcServiceLocator.getService(KcEmailService.class); } private GroupService getGroupService() { return KcServiceLocator.getService(GroupService.class); } private KcPersonService getPersonService() { return KcServiceLocator.getService(KcPersonService.class); } private ConfigurationService getConfigurationService() { return KcServiceLocator.getService(ConfigurationService.class); } /** * @return */ protected BusinessObjectService getBusinessObjectService() { if(businessObjectService == null) { businessObjectService = (BusinessObjectService) KcServiceLocator.getService(BusinessObjectService.class); } return businessObjectService; } protected void init() { this.newBody = new ExconProjectEmailContent(); this.newAttachment = new ExconProjectEmailContent(); this.newAgenda = new ExconProjectEmailContent(); } protected ExconProject getExconProject() { return getDocument().getExconProject(); } protected ExconProjectDocument getDocument() { return exconProjectForm.getExconProjectDocument(); } void setBusinessObjectService(BusinessObjectService bos) { businessObjectService = bos; } public void addTravelerMeetingAgenda() { ExconProject exconProject=getExconProject(); ExconProjectEvent newEvent=new ExconProjectEvent(); newEvent.setProjectEventTypeCode("TVA"); newEvent.setEventDate(new Date(System.currentTimeMillis())); exconProject.add(newEvent); ExconProjectPerson traveler = exconProject.getTraveler(); ExconProjectEmailContent agendaContent = getAgendaObj(); if (traveler!=null) { ExconProjectTravelerCommunication newCommunication = new ExconProjectTravelerCommunication(); newCommunication.setAgendaContentCode(agendaContent.getContentCodeBody()); newCommunication.setPersonId(traveler.getPersonId()); newCommunication.setCommunicationDate(new Date(System.currentTimeMillis())); exconProject.getTravelerCommunications().add(newCommunication); } KNSGlobalVariables.getMessageList().add("info.exconProjectTravelerAgenda.added"); } }
coeus-impl/src/main/java/org/kuali/kra/excon/project/ExconProjectEmailBean.java
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.excon.project; import org.drools.core.util.StringUtils; import org.kuali.coeus.common.framework.person.KcPersonService; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.excon.document.ExconProjectDocument; import org.kuali.coeus.common.framework.mail.KcEmailService; import org.kuali.coeus.common.framework.mail.EmailAttachment; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.membership.MemberType; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.group.GroupMember; import org.kuali.rice.kim.api.group.GroupService; import org.kuali.rice.kns.util.KNSGlobalVariables; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; import java.io.Serializable; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; /** * This is the base class for handling ExconProjectEvents */ public class ExconProjectEmailBean implements Serializable { private static final long serialVersionUID = 238453457L; protected ExconProjectEmailContent newBody; protected ExconProjectEmailContent newAttachment; protected ExconProjectEmailContent newAgenda; protected ExconProjectForm exconProjectForm; private transient BusinessObjectService businessObjectService; public ExconProjectEmailBean(ExconProjectForm exconProjectForm) { this.exconProjectForm = exconProjectForm; init(); } public ExconProjectEmailContent getNewBody() { return newBody; } public ExconProjectEmailContent getNewAttachment() { return newAttachment; } public ExconProjectEmailContent getNewAgenda(){ return newAgenda; } public ExconProjectEmailContent getBodyObj() { HashMap<String,String> criteriaMap=new HashMap<String,String>(); criteriaMap.put("contentCode", newBody.getContentCode()); return (ExconProjectEmailContent)getBusinessObjectService().findByPrimaryKey(ExconProjectEmailContent.class, criteriaMap); } public ExconProjectEmailContent getAttachmentObj() { HashMap<String,String> criteriaMap=new HashMap<String,String>(); criteriaMap.put("contentCode", newAttachment.getContentCode()); return (ExconProjectEmailContent)getBusinessObjectService().findByPrimaryKey(ExconProjectEmailContent.class, criteriaMap); } public ExconProjectEmailContent getAgendaObj() { HashMap<String,String> criteriaMap=new HashMap<String,String>(); criteriaMap.put("contentCode", newAgenda.getContentCode()); return (ExconProjectEmailContent)getBusinessObjectService().findByPrimaryKey(ExconProjectEmailContent.class, criteriaMap); } public void sendTravelerEmail() { ExconProject exconProject=getExconProject(); String destStr=""; ArrayList<EmailAttachment> attachments=new ArrayList<EmailAttachment>(); for (ExconProjectDestination destination:exconProject.getExconProjectDestinations()) { if (!StringUtils.isEmpty(destStr)) { destStr+=", "; } destStr+=destination.getDestinationCountryName(); } String currentEnv=getConfigurationService().getPropertyValueAsString("environment"); String prodEnv=getConfigurationService().getPropertyValueAsString("production.environment.code"); String senderEmail=getPersonService().getKcPersonByUserName(GlobalVariables.getUserSession().getPrincipalName()).getEmailAddress(); String recipEmail=senderEmail; String prodEmail=""; String firstName="Traveler"; ExconProjectPerson traveler=exconProject.getTraveler(); if (traveler!=null) { prodEmail=traveler.getPerson().getEmailAddress(); if (!StringUtils.isEmpty(traveler.getPerson().getFirstName())) { firstName=traveler.getPerson().getFirstName(); } } if (currentEnv.equals(prodEnv)) { recipEmail=prodEmail; } else { destStr+=" (to "+prodEmail+" in production)"; } HashSet<String> recipSet=new HashSet<String>(); recipSet.add(recipEmail); HashSet<String> bccSet=new HashSet<String>(); bccSet.add(senderEmail); Group approverGroup = getGroupService().getGroupByNamespaceCodeAndName("KC-WKFLW", "Export Control Project Approvers"); if (approverGroup!=null) { for (GroupMember member : getGroupService().getMembersOfGroup(approverGroup.getId())) { if (member.isActive() && member.getType().compareTo(MemberType.PRINCIPAL)==0) { bccSet.add(getPersonService().getKcPersonByPersonId(member.getMemberId()).getEmailAddress()); } } } EmailAttachment attachment=new EmailAttachment(); ExconProjectEmailContent bodyContent=getBodyObj(); ExconProjectEmailContent attachmentContent=getAttachmentObj(); attachment.setContents(attachmentContent.getAttachmentContent()); attachment.setFileName(attachmentContent.getFileName()); attachment.setMimeType(attachmentContent.getContentType()); attachments.add(attachment); String bodyStr=new String(bodyContent.getAttachmentContent()); bodyStr=bodyStr.replace("[firstName]", firstName); getEmailService().sendEmailWithAttachments(senderEmail,recipSet, "Regarding your upcoming trip to: "+destStr, null, bccSet, bodyStr, true, attachments); ExconProjectEvent newEvent=new ExconProjectEvent(); newEvent.setProjectEventTypeCode("TVA"); newEvent.setEventDate(new Date(System.currentTimeMillis())); exconProject.add(newEvent); if (traveler!=null) { ExconProjectTravelerCommunication newCommunication=new ExconProjectTravelerCommunication(); newCommunication.setEmailBodyContentCode(bodyContent.getContentCodeBody()); newCommunication.setEmailAttachmentContentCode(attachmentContent.getContentCodeAttachment()); newCommunication.setPersonId(traveler.getPersonId().toString()); newCommunication.setCommunicationDate(new Date(System.currentTimeMillis())); exconProject.getTravelerCommunications().add(newCommunication); } KNSGlobalVariables.getMessageList().add("info.exconProjectTravelerEmail.sent", recipEmail); return; } private KcEmailService getEmailService() { return KcServiceLocator.getService(KcEmailService.class); } private GroupService getGroupService() { return KcServiceLocator.getService(GroupService.class); } private KcPersonService getPersonService() { return KcServiceLocator.getService(KcPersonService.class); } private ConfigurationService getConfigurationService() { return KcServiceLocator.getService(ConfigurationService.class); } /** * @return */ protected BusinessObjectService getBusinessObjectService() { if(businessObjectService == null) { businessObjectService = (BusinessObjectService) KcServiceLocator.getService(BusinessObjectService.class); } return businessObjectService; } protected void init() { this.newBody = new ExconProjectEmailContent(); this.newAttachment = new ExconProjectEmailContent(); this.newAgenda = new ExconProjectEmailContent(); } protected ExconProject getExconProject() { return getDocument().getExconProject(); } protected ExconProjectDocument getDocument() { return exconProjectForm.getExconProjectDocument(); } void setBusinessObjectService(BusinessObjectService bos) { businessObjectService = bos; } public void addTravelerMeetingAgenda() { ExconProject exconProject=getExconProject(); ExconProjectEvent newEvent=new ExconProjectEvent(); newEvent.setProjectEventTypeCode("TVA"); newEvent.setEventDate(new Date(System.currentTimeMillis())); exconProject.add(newEvent); ExconProjectPerson traveler = exconProject.getTraveler(); ExconProjectEmailContent agendaContent = getAgendaObj(); if (traveler!=null) { ExconProjectTravelerCommunication newCommunication = new ExconProjectTravelerCommunication(); newCommunication.setAgendaContentCode(agendaContent.getContentCodeBody()); newCommunication.setPersonId(traveler.getPersonId()); newCommunication.setCommunicationDate(new Date(System.currentTimeMillis())); exconProject.getTravelerCommunications().add(newCommunication); } KNSGlobalVariables.getMessageList().add("info.exconProjectTravelerAgenda.added"); } }
Fixed bug related to determining whether the application is in a production environment.
coeus-impl/src/main/java/org/kuali/kra/excon/project/ExconProjectEmailBean.java
Fixed bug related to determining whether the application is in a production environment.
<ide><path>oeus-impl/src/main/java/org/kuali/kra/excon/project/ExconProjectEmailBean.java <ide> } <ide> destStr+=destination.getDestinationCountryName(); <ide> } <del> String currentEnv=getConfigurationService().getPropertyValueAsString("environment"); <del> String prodEnv=getConfigurationService().getPropertyValueAsString("production.environment.code"); <add>// String currentEnv=getConfigurationService().getPropertyValueAsString("environment"); <add>// String prodEnv=getConfigurationService().getPropertyValueAsString("production.environment.code"); <ide> String senderEmail=getPersonService().getKcPersonByUserName(GlobalVariables.getUserSession().getPrincipalName()).getEmailAddress(); <ide> String recipEmail=senderEmail; <ide> String prodEmail=""; <ide> } <ide> } <ide> <del> if (currentEnv.equals(prodEnv)) { <add> if (GlobalVariables.getUserSession().isProductionEnvironment()) { <ide> recipEmail=prodEmail; <ide> } <ide> else
Java
apache-2.0
4ea0dfff9945595754e74d6aa8fb53b240860107
0
endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS
package org.endeavourhealth.queuereader; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.apache.commons.csv.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.endeavourhealth.common.cache.ObjectMapperPool; import org.endeavourhealth.common.config.ConfigManager; import org.endeavourhealth.common.fhir.*; import org.endeavourhealth.common.utility.FileHelper; import org.endeavourhealth.common.utility.SlackHelper; import org.endeavourhealth.core.configuration.ConfigDeserialiser; import org.endeavourhealth.core.configuration.PostMessageToExchangeConfig; import org.endeavourhealth.core.configuration.QueueReaderConfiguration; import org.endeavourhealth.core.csv.CsvHelper; import org.endeavourhealth.core.database.dal.DalProvider; import org.endeavourhealth.core.database.dal.admin.ServiceDalI; import org.endeavourhealth.core.database.dal.admin.models.Service; import org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI; import org.endeavourhealth.core.database.dal.audit.ExchangeDalI; import org.endeavourhealth.core.database.dal.audit.models.*; import org.endeavourhealth.core.database.dal.eds.PatientSearchDalI; import org.endeavourhealth.core.database.dal.ehr.ResourceDalI; import org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper; import org.endeavourhealth.core.database.dal.subscriberTransform.EnterpriseIdDalI; import org.endeavourhealth.core.database.rdbms.ConnectionManager; import org.endeavourhealth.core.exceptions.TransformException; import org.endeavourhealth.core.fhirStorage.FhirSerializationHelper; import org.endeavourhealth.core.fhirStorage.FhirStorageService; import org.endeavourhealth.core.fhirStorage.JsonServiceInterfaceEndpoint; import org.endeavourhealth.core.messaging.pipeline.components.PostMessageToExchange; import org.endeavourhealth.core.queueing.QueueHelper; import org.endeavourhealth.core.xml.TransformErrorSerializer; import org.endeavourhealth.core.xml.transformError.TransformError; import org.endeavourhealth.transform.common.*; import org.endeavourhealth.transform.emis.EmisCsvToFhirTransformer; import org.endeavourhealth.transform.emis.csv.helpers.EmisCsvHelper; import org.hibernate.internal.SessionImpl; import org.hl7.fhir.instance.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.sql.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; public class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { String configId = args[0]; LOG.info("Initialising config manager"); ConfigManager.initialize("queuereader", configId); /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixEncounters")) { String table = args[1]; fixEncounters(table); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("CreateHomertonSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createHomertonSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateAdastraSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createAdastraSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateVisionSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createVisionSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateTppSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createTppSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateBartsSubset")) { String sourceDirPath = args[1]; UUID serviceUuid = UUID.fromString(args[2]); UUID systemUuid = UUID.fromString(args[3]); String samplePatientsFile = args[4]; createBartsSubset(sourceDirPath, serviceUuid, systemUuid, samplePatientsFile); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixBartsOrgs")) { String serviceId = args[1]; fixBartsOrgs(serviceId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("TestPreparedStatements")) { String url = args[1]; String user = args[2]; String pass = args[3]; String serviceId = args[4]; testPreparedStatements(url, user, pass, serviceId); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("ExportFhirToCsv")) { UUID serviceId = UUID.fromString(args[1]); String path = args[2]; exportFhirToCsv(serviceId, path); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("TestBatchInserts")) { String url = args[1]; String user = args[2]; String pass = args[3]; String num = args[4]; String batchSize = args[5]; testBatchInserts(url, user, pass, num, batchSize); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("ApplyEmisAdminCaches")) { applyEmisAdminCaches(); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixSubscribers")) { fixSubscriberDbs(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixEmisProblems")) { String serviceId = args[1]; String systemId = args[2]; fixEmisProblems(UUID.fromString(serviceId), UUID.fromString(systemId)); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("FixEmisProblems3ForPublisher")) { String publisherId = args[1]; String systemId = args[2]; fixEmisProblems3ForPublisher(publisherId, UUID.fromString(systemId)); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixEmisProblems3")) { String serviceId = args[1]; String systemId = args[2]; fixEmisProblems3(UUID.fromString(serviceId), UUID.fromString(systemId)); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CheckDeletedObs")) { String serviceId = args[1]; String systemId = args[2]; checkDeletedObs(UUID.fromString(serviceId), UUID.fromString(systemId)); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixPersonsNoNhsNumber")) { fixPersonsNoNhsNumber(); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("ConvertExchangeBody")) { String systemId = args[1]; convertExchangeBody(UUID.fromString(systemId)); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixReferrals")) { fixReferralRequests(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PopulateNewSearchTable")) { String table = args[1]; populateNewSearchTable(table); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixBartsEscapes")) { String filePath = args[1]; fixBartsEscapedFiles(filePath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PostToInbound")) { String serviceId = args[1]; String systemId = args[2]; String filePath = args[3]; postToInboundFromFile(UUID.fromString(serviceId), UUID.fromString(systemId), filePath); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("FixDisabledExtract")) { String serviceId = args[1]; String systemId = args[2]; String sharedStoragePath = args[3]; String tempDir = args[4]; fixDisabledEmisExtract(serviceId, systemId, sharedStoragePath, tempDir); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("TestSlack")) { testSlack(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PostToInbound")) { String serviceId = args[1]; boolean all = Boolean.parseBoolean(args[2]); postToInbound(UUID.fromString(serviceId), all); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixPatientSearch")) { String serviceId = args[1]; fixPatientSearch(serviceId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("Exit")) { String exitCode = args[1]; LOG.info("Exiting with error code " + exitCode); int exitCodeInt = Integer.parseInt(exitCode); System.exit(exitCodeInt); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("RunSql")) { String host = args[1]; String username = args[2]; String password = args[3]; String sqlFile = args[4]; runSql(host, username, password, sqlFile); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PopulateProtocolQueue")) { String serviceId = null; if (args.length > 1) { serviceId = args[1]; } String startingExchangeId = null; if (args.length > 2) { startingExchangeId = args[2]; } populateProtocolQueue(serviceId, startingExchangeId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FindEncounterTerms")) { String path = args[1]; String outputPath = args[2]; findEncounterTerms(path, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FindEmisStartDates")) { String path = args[1]; String outputPath = args[2]; findEmisStartDates(path, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("ExportHl7Encounters")) { String sourceCsvPpath = args[1]; String outputPath = args[2]; exportHl7Encounters(sourceCsvPpath, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixExchangeBatches")) { fixExchangeBatches(); System.exit(0); }*/ /*if (args.length >= 0 && args[0].equalsIgnoreCase("FindCodes")) { findCodes(); System.exit(0); }*/ /*if (args.length >= 0 && args[0].equalsIgnoreCase("FindDeletedOrgs")) { findDeletedOrgs(); System.exit(0); }*/ if (args.length != 1) { LOG.error("Usage: queuereader config_id"); return; } LOG.info("--------------------------------------------------"); LOG.info("EDS Queue Reader " + configId); LOG.info("--------------------------------------------------"); LOG.info("Fetching queuereader configuration"); String configXml = ConfigManager.getConfiguration(configId); QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); /*LOG.info("Registering shutdown hook"); registerShutdownHook();*/ // Instantiate rabbit handler LOG.info("Creating EDS queue reader"); RabbitHandler rabbitHandler = new RabbitHandler(configuration, configId); // Begin consume rabbitHandler.start(); LOG.info("EDS Queue reader running (kill file location " + TransformConfig.instance().getKillFileLocation() + ")"); } private static void fixPersonsNoNhsNumber() { LOG.info("Fixing persons with no NHS number"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); EntityManager entityManager = ConnectionManager.getEdsEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection patientSearchConnection = session.connection(); Statement patientSearchStatement = patientSearchConnection.createStatement(); for (Service service: services) { LOG.info("Doing " + service.getName() + " " + service.getId()); int checked = 0; int fixedPersons = 0; int fixedSearches = 0; String sql = "SELECT patient_id, nhs_number FROM patient_search WHERE service_id = '" + service.getId() + "' AND (nhs_number IS NULL or CHAR_LENGTH(nhs_number) != 10)"; ResultSet rs = patientSearchStatement.executeQuery(sql); while (rs.next()) { String patientId = rs.getString(1); String nhsNumber = rs.getString(2); //find matched person ID String personIdSql = "SELECT person_id FROM patient_link WHERE patient_id = '" + patientId + "'"; Statement s = patientSearchConnection.createStatement(); ResultSet rsPersonId = s.executeQuery(personIdSql); String personId = null; if (rsPersonId.next()) { personId = rsPersonId.getString(1); } rsPersonId.close(); s.close(); if (Strings.isNullOrEmpty(personId)) { LOG.error("Patient " + patientId + " has no person ID"); continue; } //see whether person ID used NHS number to match String patientLinkSql = "SELECT nhs_number FROM patient_link_person WHERE person_id = '" + personId + "'"; s = patientSearchConnection.createStatement(); ResultSet rsPatientLink = s.executeQuery(patientLinkSql); String matchingNhsNumber = null; if (rsPatientLink.next()) { matchingNhsNumber = rsPatientLink.getString(1); } rsPatientLink.close(); s.close(); //if patient link person has a record for this nhs number, update the person link if (!Strings.isNullOrEmpty(matchingNhsNumber)) { String newPersonId = UUID.randomUUID().toString(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String createdAtStr = sdf.format(new Date()); s = patientSearchConnection.createStatement(); //new record in patient link history String patientHistorySql = "INSERT INTO patient_link_history VALUES ('" + patientId + "', '" + service.getId() + "', '" + createdAtStr + "', '" + newPersonId + "', '" + personId + "')"; //LOG.debug(patientHistorySql); s.execute(patientHistorySql); //update patient link String patientLinkUpdateSql = "UPDATE patient_link SET person_id = '" + newPersonId + "' WHERE patient_id = '" + patientId + "'"; s.execute(patientLinkUpdateSql); patientSearchConnection.commit(); s.close(); fixedPersons ++; } //if patient search has an invalid NHS number, update it if (!Strings.isNullOrEmpty(nhsNumber)) { ResourceDalI resourceDal = DalProvider.factoryResourceDal(); Patient patient = (Patient)resourceDal.getCurrentVersionAsResource(service.getId(), ResourceType.Patient, patientId); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); patientSearchDal.update(service.getId(), patient); fixedSearches ++; } checked ++; if (checked % 50 == 0) { LOG.info("Checked " + checked + ", FixedPersons = " + fixedPersons + ", FixedSearches = " + fixedSearches); } } LOG.info("Checked " + checked + ", FixedPersons = " + fixedPersons + ", FixedSearches = " + fixedSearches); rs.close(); } patientSearchStatement.close(); entityManager.close(); LOG.info("Finished fixing persons with no NHS number"); } catch (Throwable t) { LOG.error("", t); } } private static void checkDeletedObs(UUID serviceId, UUID systemId) { LOG.info("Checking Observations for " + serviceId); try { ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); List<ResourceType> potentialResourceTypes = new ArrayList<>(); potentialResourceTypes.add(ResourceType.Procedure); potentialResourceTypes.add(ResourceType.AllergyIntolerance); potentialResourceTypes.add(ResourceType.FamilyMemberHistory); potentialResourceTypes.add(ResourceType.Immunization); potentialResourceTypes.add(ResourceType.DiagnosticOrder); potentialResourceTypes.add(ResourceType.Specimen); potentialResourceTypes.add(ResourceType.DiagnosticReport); potentialResourceTypes.add(ResourceType.ReferralRequest); potentialResourceTypes.add(ResourceType.Condition); potentialResourceTypes.add(ResourceType.Observation); List<String> subscriberConfigs = new ArrayList<>(); subscriberConfigs.add("ceg_data_checking"); subscriberConfigs.add("ceg_enterprise"); subscriberConfigs.add("hurley_data_checking"); subscriberConfigs.add("hurley_deidentified"); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceId, systemId, Integer.MAX_VALUE); for (Exchange exchange : exchanges) { List<ExchangePayloadFile> payload = ExchangeHelper.parseExchangeBody(exchange.getBody()); //String version = EmisCsvToFhirTransformer.determineVersion(payload); //if we've reached the point before we process data for this practice, break out if (!EmisCsvToFhirTransformer.shouldProcessPatientData(payload)) { break; } ExchangePayloadFile firstItem = payload.get(0); String name = FilenameUtils.getBaseName(firstItem.getPath()); String[] toks = name.split("_"); String agreementId = toks[4]; LOG.info("Doing exchange containing " + firstItem.getPath()); EmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchange.getId(), agreementId, true); Map<UUID, ExchangeBatch> hmBatchesByPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchange.getId()); for (ExchangeBatch batch : batches) { if (batch.getEdsPatientId() != null) { hmBatchesByPatient.put(batch.getEdsPatientId(), batch); } } for (ExchangePayloadFile item : payload) { String type = item.getType(); if (type.equals("CareRecord_Observation")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String deleted = record.get("Deleted"); if (deleted.equalsIgnoreCase("true")) { String patientId = record.get("PatientGuid"); String observationId = record.get("ObservationGuid"); //find observation UUID UUID uuid = IdHelper.getEdsResourceId(serviceId, ResourceType.Observation, patientId + ":" + observationId); if (uuid == null) { continue; } //find TRUE resource type Reference edsReference = ReferenceHelper.createReference(ResourceType.Observation, uuid.toString()); if (fixReference(serviceId, csvHelper, edsReference, potentialResourceTypes)) { ReferenceComponents comps = ReferenceHelper.getReferenceComponents(edsReference); ResourceType newType = comps.getResourceType(); String newId = comps.getId(); //delete resource if not already done ResourceWrapper resourceWrapper = resourceDal.getCurrentVersion(serviceId, newType.toString(), UUID.fromString(newId)); if (resourceWrapper.isDeleted()) { continue; } LOG.debug("Fixing " + edsReference.getReference()); //create file of IDs to delete for each subscriber DB for (String subscriberConfig : subscriberConfigs) { EnterpriseIdDalI subscriberDal = DalProvider.factoryEnterpriseIdDal(subscriberConfig); Long enterpriseId = subscriberDal.findEnterpriseId(newType.toString(), newId); if (enterpriseId == null) { continue; } String sql = null; if (newType == ResourceType.AllergyIntolerance) { sql = "DELETE FROM allergy_intolerance WHERE id = " + enterpriseId; } else if (newType == ResourceType.ReferralRequest) { sql = "DELETE FROM referral_request WHERE id = " + enterpriseId; } else { sql = "DELETE FROM observation WHERE id = " + enterpriseId; } sql += "\n"; File f = new File(subscriberConfig + ".sql"); Files.write(f.toPath(), sql.getBytes(), StandardOpenOption.APPEND); } ExchangeBatch batch = hmBatchesByPatient.get(resourceWrapper.getPatientId()); resourceWrapper.setDeleted(true); resourceWrapper.setResourceData(null); resourceWrapper.setExchangeBatchId(batch.getBatchId()); resourceWrapper.setVersion(UUID.randomUUID()); resourceWrapper.setCreatedAt(new Date()); resourceWrapper.setExchangeId(exchange.getId()); resourceDal.delete(resourceWrapper); } } } parser.close(); } else { //no problem link } } } LOG.info("Finished Checking Observations for " + serviceId); } catch (Exception ex) { LOG.error("", ex); } } private static void testBatchInserts(String url, String user, String pass, String num, String batchSizeStr) { LOG.info("Testing Batch Inserts"); try { int inserts = Integer.parseInt(num); int batchSize = Integer.parseInt(batchSizeStr); LOG.info("Openning Connection"); Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", pass); Connection conn = DriverManager.getConnection(url, props); //String sql = "INSERT INTO drewtest.insert_test VALUES (?, ?, ?);"; String sql = "INSERT INTO drewtest.insert_test VALUES (?, ?, ?)"; PreparedStatement ps = conn.prepareStatement(sql); if (batchSize == 1) { LOG.info("Testing non-batched inserts"); long start = System.currentTimeMillis(); for (int i = 0; i < inserts; i++) { int col = 1; ps.setString(col++, UUID.randomUUID().toString()); ps.setString(col++, UUID.randomUUID().toString()); ps.setString(col++, randomStr()); ps.execute(); } long end = System.currentTimeMillis(); LOG.info("Done " + inserts + " in " + (end - start) + " ms"); } else { LOG.info("Testing batched inserts with batch size " + batchSize); long start = System.currentTimeMillis(); for (int i = 0; i < inserts; i++) { int col = 1; ps.setString(col++, UUID.randomUUID().toString()); ps.setString(col++, UUID.randomUUID().toString()); ps.setString(col++, randomStr()); ps.addBatch(); if ((i + 1) % batchSize == 0 || i + 1 >= inserts) { ps.executeBatch(); } } long end = System.currentTimeMillis(); LOG.info("Done " + inserts + " in " + (end - start) + " ms"); } ps.close(); conn.close(); LOG.info("Finished Testing Batch Inserts"); } catch (Exception ex) { LOG.error("", ex); } } private static String randomStr() { StringBuffer sb = new StringBuffer(); Random r = new Random(System.currentTimeMillis()); while (sb.length() < 1100) { sb.append(r.nextLong()); } return sb.toString(); } /*private static void fixEmisProblems(UUID serviceId, UUID systemId) { LOG.info("Fixing Emis Problems for " + serviceId); try { Map<String, List<String>> hmReferences = new HashMap<>(); Set<String> patientIds = new HashSet<>(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); FhirResourceFiler filer = new FhirResourceFiler(null, serviceId, systemId, null, null); LOG.info("Caching problem links"); //Go through all files to work out problem children for every problem ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceId, systemId, Integer.MAX_VALUE); for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); List<ExchangePayloadFile> payload = ExchangeHelper.parseExchangeBody(exchange.getBody()); //String version = EmisCsvToFhirTransformer.determineVersion(payload); ExchangePayloadFile firstItem = payload.get(0); String name = FilenameUtils.getBaseName(firstItem.getPath()); String[] toks = name.split("_"); String agreementId = toks[4]; LOG.info("Doing exchange containing " + firstItem.getPath()); EmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchange.getId(), agreementId, true); for (ExchangePayloadFile item: payload) { String type = item.getType(); if (type.equals("CareRecord_Observation")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String parentProblemId = record.get("ProblemGuid"); String patientId = record.get("PatientGuid"); patientIds.add(patientId); if (!Strings.isNullOrEmpty(parentProblemId)) { String observationId = record.get("ObservationGuid"); String localId = patientId + ":" + observationId; ResourceType resourceType = ObservationTransformer.findOriginalTargetResourceType(filer, CsvCell.factoryDummyWrapper(patientId), CsvCell.factoryDummyWrapper(observationId)); Reference localReference = ReferenceHelper.createReference(resourceType, localId); Reference globalReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localReference, csvHelper); String localProblemId = patientId + ":" + parentProblemId; Reference localProblemReference = ReferenceHelper.createReference(ResourceType.Condition, localProblemId); Reference globalProblemReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localProblemReference, csvHelper); String globalProblemId = ReferenceHelper.getReferenceId(globalProblemReference); List<String> problemChildren = hmReferences.get(globalProblemId); if (problemChildren == null) { problemChildren = new ArrayList<>(); hmReferences.put(globalProblemId, problemChildren); } problemChildren.add(globalReference.getReference()); } } parser.close(); } else if (type.equals("Prescribing_DrugRecord")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String parentProblemId = record.get("ProblemObservationGuid"); String patientId = record.get("PatientGuid"); patientIds.add(patientId); if (!Strings.isNullOrEmpty(parentProblemId)) { String observationId = record.get("DrugRecordGuid"); String localId = patientId + ":" + observationId; Reference localReference = ReferenceHelper.createReference(ResourceType.MedicationStatement, localId); Reference globalReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localReference, csvHelper); String localProblemId = patientId + ":" + parentProblemId; Reference localProblemReference = ReferenceHelper.createReference(ResourceType.Condition, localProblemId); Reference globalProblemReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localProblemReference, csvHelper); String globalProblemId = ReferenceHelper.getReferenceId(globalProblemReference); List<String> problemChildren = hmReferences.get(globalProblemId); if (problemChildren == null) { problemChildren = new ArrayList<>(); hmReferences.put(globalProblemId, problemChildren); } problemChildren.add(globalReference.getReference()); } } parser.close(); } else if (type.equals("Prescribing_IssueRecord")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String parentProblemId = record.get("ProblemObservationGuid"); String patientId = record.get("PatientGuid"); patientIds.add(patientId); if (!Strings.isNullOrEmpty(parentProblemId)) { String observationId = record.get("IssueRecordGuid"); String localId = patientId + ":" + observationId; Reference localReference = ReferenceHelper.createReference(ResourceType.MedicationOrder, localId); String localProblemId = patientId + ":" + parentProblemId; Reference localProblemReference = ReferenceHelper.createReference(ResourceType.Condition, localProblemId); Reference globalProblemReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localProblemReference, csvHelper); Reference globalReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localReference, csvHelper); String globalProblemId = ReferenceHelper.getReferenceId(globalProblemReference); List<String> problemChildren = hmReferences.get(globalProblemId); if (problemChildren == null) { problemChildren = new ArrayList<>(); hmReferences.put(globalProblemId, problemChildren); } problemChildren.add(globalReference.getReference()); } } parser.close(); } else { //no problem link } } } LOG.info("Finished caching problem links, finding " + patientIds.size() + " patients"); int done = 0; int fixed = 0; for (String localPatientId: patientIds) { Reference localPatientReference = ReferenceHelper.createReference(ResourceType.Patient, localPatientId); Reference globalPatientReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localPatientReference, filer); String patientUuid = ReferenceHelper.getReferenceId(globalPatientReference); List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(serviceId, UUID.fromString(patientUuid), ResourceType.Condition.toString()); for (ResourceWrapper wrapper: wrappers) { if (wrapper.isDeleted()) { continue; } String originalJson = wrapper.getResourceData(); Condition condition = (Condition)FhirSerializationHelper.deserializeResource(originalJson); ConditionBuilder conditionBuilder = new ConditionBuilder(condition); //sort out the nested extension references Extension outerExtension = ExtensionConverter.findExtension(condition, FhirExtensionUri.PROBLEM_LAST_REVIEWED); if (outerExtension != null) { Extension innerExtension = ExtensionConverter.findExtension(outerExtension, FhirExtensionUri._PROBLEM_LAST_REVIEWED__PERFORMER); if (innerExtension != null) { Reference performerReference = (Reference)innerExtension.getValue(); String value = performerReference.getReference(); if (value.endsWith("}")) { Reference globalPerformerReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(performerReference, filer); innerExtension.setValue(globalPerformerReference); } } } //sort out the contained list of children ContainedListBuilder listBuilder = new ContainedListBuilder(conditionBuilder); //remove any existing children listBuilder.removeContainedList(); //add all the new ones we've found List<String> localChildReferences = hmReferences.get(wrapper.getResourceId().toString()); if (localChildReferences != null) { for (String localChildReference: localChildReferences) { Reference reference = ReferenceHelper.createReference(localChildReference); listBuilder.addContainedListItem(reference); } } //save the updated condition String newJson = FhirSerializationHelper.serializeResource(condition); if (!newJson.equals(originalJson)) { wrapper.setResourceData(newJson); saveResourceWrapper(serviceId, wrapper); fixed ++; } } done ++; if (done % 1000 == 0) { LOG.info("Done " + done + " patients and fixed " + fixed + " problems"); } } LOG.info("Done " + done + " patients and fixed " + fixed + " problems"); LOG.info("Finished Emis Problems for " + serviceId); } catch (Exception ex) { LOG.error("", ex); } }*/ private static void fixEmisProblems3ForPublisher(String publisher, UUID systemId) { try { LOG.info("Doing fix for " + publisher); ServiceDalI dal = DalProvider.factoryServiceDal(); List<Service> all = dal.getAll(); for (Service service: all) { if (service.getPublisherConfigName() != null && service.getPublisherConfigName().equals(publisher)) { fixEmisProblems3(service.getId(), systemId); } } LOG.info("Done fix for " + publisher); } catch (Throwable t) { LOG.error("", t); } } private static void fixEmisProblems3(UUID serviceId, UUID systemId) { LOG.info("Fixing Emis Problems 3 for " + serviceId); try { Set<String> patientIds = new HashSet<>(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); FhirResourceFiler filer = new FhirResourceFiler(null, serviceId, systemId, null, null); LOG.info("Finding patients"); //Go through all files to work out problem children for every problem ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceId, systemId, Integer.MAX_VALUE); for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); List<ExchangePayloadFile> payload = ExchangeHelper.parseExchangeBody(exchange.getBody()); for (ExchangePayloadFile item: payload) { String type = item.getType(); if (type.equals("Admin_Patient")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String patientId = record.get("PatientGuid"); patientIds.add(patientId); } parser.close(); } } } LOG.info("Finished checking files, finding " + patientIds.size() + " patients"); int done = 0; int fixed = 0; for (String localPatientId: patientIds) { Reference localPatientReference = ReferenceHelper.createReference(ResourceType.Patient, localPatientId); Reference globalPatientReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localPatientReference, filer); String patientUuid = ReferenceHelper.getReferenceId(globalPatientReference); List<ResourceType> potentialResourceTypes = new ArrayList<>(); potentialResourceTypes.add(ResourceType.Procedure); potentialResourceTypes.add(ResourceType.AllergyIntolerance); potentialResourceTypes.add(ResourceType.FamilyMemberHistory); potentialResourceTypes.add(ResourceType.Immunization); potentialResourceTypes.add(ResourceType.DiagnosticOrder); potentialResourceTypes.add(ResourceType.Specimen); potentialResourceTypes.add(ResourceType.DiagnosticReport); potentialResourceTypes.add(ResourceType.ReferralRequest); potentialResourceTypes.add(ResourceType.Condition); potentialResourceTypes.add(ResourceType.Observation); for (ResourceType resourceType: potentialResourceTypes) { List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(serviceId, UUID.fromString(patientUuid), resourceType.toString()); for (ResourceWrapper wrapper : wrappers) { if (wrapper.isDeleted()) { continue; } String originalJson = wrapper.getResourceData(); DomainResource resource = (DomainResource)FhirSerializationHelper.deserializeResource(originalJson); //Also go through all observation records and any that have parent observations - these need fixing too??? Extension extension = ExtensionConverter.findExtension(resource, FhirExtensionUri.PARENT_RESOURCE); if (extension != null) { Reference reference = (Reference)extension.getValue(); fixReference(serviceId, filer, reference, potentialResourceTypes); } if (resource instanceof Observation) { Observation obs = (Observation)resource; if (obs.hasRelated()) { for (Observation.ObservationRelatedComponent related: obs.getRelated()) { if (related.hasTarget()) { Reference reference = related.getTarget(); fixReference(serviceId, filer, reference, potentialResourceTypes); } } } } if (resource instanceof DiagnosticReport) { DiagnosticReport diag = (DiagnosticReport)resource; if (diag.hasResult()) { for (Reference reference: diag.getResult()) { fixReference(serviceId, filer, reference, potentialResourceTypes); } } } //Go through all patients, go through all problems, for any child that's Observation, find the true resource type then update and save if (resource instanceof Condition) { if (resource.hasContained()) { for (Resource contained: resource.getContained()) { if (contained.getId().equals("Items")) { List_ containedList = (List_)contained; if (containedList.hasEntry()) { for (List_.ListEntryComponent entry: containedList.getEntry()) { Reference reference = entry.getItem(); fixReference(serviceId, filer, reference, potentialResourceTypes); } } } } } //sort out the nested extension references Extension outerExtension = ExtensionConverter.findExtension(resource, FhirExtensionUri.PROBLEM_RELATED); if (outerExtension != null) { Extension innerExtension = ExtensionConverter.findExtension(outerExtension, FhirExtensionUri._PROBLEM_RELATED__TARGET); if (innerExtension != null) { Reference performerReference = (Reference)innerExtension.getValue(); String value = performerReference.getReference(); if (value.endsWith("}")) { Reference globalPerformerReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(performerReference, filer); innerExtension.setValue(globalPerformerReference); } } } } //save the updated condition String newJson = FhirSerializationHelper.serializeResource(resource); if (!newJson.equals(originalJson)) { wrapper.setResourceData(newJson); saveResourceWrapper(serviceId, wrapper); fixed++; } } } done ++; if (done % 1000 == 0) { LOG.info("Done " + done + " patients and fixed " + fixed + " problems"); } } LOG.info("Done " + done + " patients and fixed " + fixed + " problems"); LOG.info("Finished Emis Problems 3 for " + serviceId); } catch (Exception ex) { LOG.error("", ex); } } private static boolean fixReference(UUID serviceId, HasServiceSystemAndExchangeIdI csvHelper, Reference reference, List<ResourceType> potentialResourceTypes) throws Exception { //if it's already something other than observation, we're OK ReferenceComponents comps = ReferenceHelper.getReferenceComponents(reference); if (comps.getResourceType() != ResourceType.Observation) { return false; } Reference sourceReference = IdHelper.convertEdsReferenceToLocallyUniqueReference(csvHelper, reference); String sourceId = ReferenceHelper.getReferenceId(sourceReference); String newReferenceValue = findTrueResourceType(serviceId, potentialResourceTypes, sourceId); if (newReferenceValue == null) { return false; } reference.setReference(newReferenceValue); return true; } private static String findTrueResourceType(UUID serviceId, List<ResourceType> potentials, String sourceId) throws Exception { ResourceDalI dal = DalProvider.factoryResourceDal(); for (ResourceType resourceType: potentials) { UUID uuid = IdHelper.getEdsResourceId(serviceId, resourceType, sourceId); if (uuid == null) { continue; } ResourceWrapper wrapper = dal.getCurrentVersion(serviceId, resourceType.toString(), uuid); if (wrapper != null) { return ReferenceHelper.createResourceReference(resourceType, uuid.toString()); } } return null; } /*private static void convertExchangeBody(UUID systemUuid) { try { LOG.info("Converting exchange bodies for system " + systemUuid); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemUuid, Integer.MAX_VALUE); if (exchanges.isEmpty()) { continue; } LOG.debug("doing " + service.getName() + " with " + exchanges.size() + " exchanges"); for (Exchange exchange: exchanges) { String exchangeBody = exchange.getBody(); try { //already done ExchangePayloadFile[] files = JsonSerializer.deserialize(exchangeBody, ExchangePayloadFile[].class); continue; } catch (JsonSyntaxException ex) { //if the JSON can't be parsed, then it'll be the old format of body that isn't JSON } List<ExchangePayloadFile> newFiles = new ArrayList<>(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); for (String file: files) { ExchangePayloadFile fileObj = new ExchangePayloadFile(); String fileWithoutSharedStorage = file.substring(TransformConfig.instance().getSharedStoragePath().length()+1); fileObj.setPath(fileWithoutSharedStorage); //size List<FileInfo> fileInfos = FileHelper.listFilesInSharedStorageWithInfo(file); for (FileInfo info: fileInfos) { if (info.getFilePath().equals(file)) { long size = info.getSize(); fileObj.setSize(new Long(size)); } } //type if (systemUuid.toString().equalsIgnoreCase("991a9068-01d3-4ff2-86ed-249bd0541fb3") //live || systemUuid.toString().equalsIgnoreCase("55c08fa5-ef1e-4e94-aadc-e3d6adc80774")) { //dev //emis String name = FilenameUtils.getName(file); String[] toks = name.split("_"); String first = toks[1]; String second = toks[2]; fileObj.setType(first + "_" + second); *//* } else if (systemUuid.toString().equalsIgnoreCase("e517fa69-348a-45e9-a113-d9b59ad13095") || systemUuid.toString().equalsIgnoreCase("b0277098-0b6c-4d9d-86ef-5f399fb25f34")) { //dev //cerner String name = FilenameUtils.getName(file); if (Strings.isNullOrEmpty(name)) { continue; } try { String type = BartsCsvToFhirTransformer.identifyFileType(name); fileObj.setType(type); } catch (Exception ex2) { throw new Exception("Failed to parse file name " + name + " on exchange " + exchange.getId()); }*//* } else { throw new Exception("Unknown system ID " + systemUuid); } newFiles.add(fileObj); } String json = JsonSerializer.serialize(newFiles); exchange.setBody(json); exchangeDal.save(exchange); } } LOG.info("Finished Converting exchange bodies for system " + systemUuid); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixBartsOrgs(String serviceId) { try { LOG.info("Fixing Barts orgs"); ResourceDalI dal = DalProvider.factoryResourceDal(); List<ResourceWrapper> wrappers = dal.getResourcesByService(UUID.fromString(serviceId), ResourceType.Organization.toString()); LOG.debug("Found " + wrappers.size() + " resources"); int done = 0; int fixed = 0; for (ResourceWrapper wrapper: wrappers) { if (!wrapper.isDeleted()) { List<ResourceWrapper> history = dal.getResourceHistory(UUID.fromString(serviceId), wrapper.getResourceType(), wrapper.getResourceId()); ResourceWrapper mostRecent = history.get(0); String json = mostRecent.getResourceData(); Organization org = (Organization)FhirSerializationHelper.deserializeResource(json); String odsCode = IdentifierHelper.findOdsCode(org); if (Strings.isNullOrEmpty(odsCode) && org.hasIdentifier()) { boolean hasBeenFixed = false; for (Identifier identifier: org.getIdentifier()) { if (identifier.getSystem().equals(FhirIdentifierUri.IDENTIFIER_SYSTEM_ODS_CODE) && identifier.hasId()) { odsCode = identifier.getId(); identifier.setValue(odsCode); identifier.setId(null); hasBeenFixed = true; } } if (hasBeenFixed) { String newJson = FhirSerializationHelper.serializeResource(org); mostRecent.setResourceData(newJson); LOG.debug("Fixed Organization " + org.getId()); *//*LOG.debug(json); LOG.debug(newJson);*//* saveResourceWrapper(UUID.fromString(serviceId), mostRecent); fixed ++; } } } done ++; if (done % 100 == 0) { LOG.debug("Done " + done + ", Fixed " + fixed); } } LOG.debug("Done " + done + ", Fixed " + fixed); LOG.info("Finished Barts orgs"); } catch (Throwable t) { LOG.error("", t); } }*/ /*private static void testPreparedStatements(String url, String user, String pass, String serviceId) { try { LOG.info("Testing Prepared Statements"); LOG.info("Url: " + url); LOG.info("user: " + user); LOG.info("pass: " + pass); //open connection Class.forName("com.mysql.cj.jdbc.Driver"); //create connection Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", pass); Connection conn = DriverManager.getConnection(url, props); String sql = "SELECT * FROM internal_id_map WHERE service_id = ? AND id_type = ? AND source_id = ?"; long start = System.currentTimeMillis(); for (int i=0; i<10000; i++) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setString(1, serviceId); ps.setString(2, "MILLPERSIDtoMRN"); ps.setString(3, UUID.randomUUID().toString()); ResultSet rs = ps.executeQuery(); while (rs.next()) { //do nothing } } finally { if (ps != null) { ps.close(); } } } long end = System.currentTimeMillis(); LOG.info("Took " + (end-start) + " ms"); //close connection conn.close(); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixEncounters(String table) { LOG.info("Fixing encounters from " + table); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date cutoff = sdf.parse("2018-03-14 11:42"); EntityManager entityManager = ConnectionManager.getAdminEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); List<UUID> serviceIds = new ArrayList<>(); Map<UUID, UUID> hmSystems = new HashMap<>(); String sql = "SELECT service_id, system_id FROM " + table + " WHERE done = 0"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { UUID serviceId = UUID.fromString(rs.getString(1)); UUID systemId = UUID.fromString(rs.getString(2)); serviceIds.add(serviceId); hmSystems.put(serviceId, systemId); } rs.close(); statement.close(); entityManager.close(); for (UUID serviceId: serviceIds) { UUID systemId = hmSystems.get(serviceId); LOG.info("Doing service " + serviceId + " and system " + systemId); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, systemId); List<UUID> exchangeIdsToProcess = new ArrayList<>(); for (UUID exchangeId: exchangeIds) { List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId); for (ExchangeTransformAudit audit: audits) { Date d = audit.getStarted(); if (d.after(cutoff)) { exchangeIdsToProcess.add(exchangeId); break; } } } Map<String, ReferenceList> consultationNewChildMap = new HashMap<>(); Map<String, ReferenceList> observationChildMap = new HashMap<>(); Map<String, ReferenceList> newProblemChildren = new HashMap<>(); for (UUID exchangeId: exchangeIdsToProcess) { Exchange exchange = exchangeDal.getExchange(exchangeId); String[] files = ExchangeHelper.parseExchangeBodyIntoFileList(exchange.getBody()); String version = EmisCsvToFhirTransformer.determineVersion(files); List<String> interestingFiles = new ArrayList<>(); for (String file: files) { if (file.indexOf("CareRecord_Consultation") > -1 || file.indexOf("CareRecord_Observation") > -1 || file.indexOf("CareRecord_Diary") > -1 || file.indexOf("Prescribing_DrugRecord") > -1 || file.indexOf("Prescribing_IssueRecord") > -1 || file.indexOf("CareRecord_Problem") > -1) { interestingFiles.add(file); } } files = interestingFiles.toArray(new String[0]); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.createParsers(serviceId, systemId, exchangeId, files, version, parsers); String dataSharingAgreementGuid = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(parsers); EmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchangeId, dataSharingAgreementGuid, true); Consultation consultationParser = (Consultation)parsers.get(Consultation.class); while (consultationParser.nextRecord()) { CsvCell consultationGuid = consultationParser.getConsultationGuid(); CsvCell patientGuid = consultationParser.getPatientGuid(); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); consultationNewChildMap.put(sourceId, new ReferenceList()); } Problem problemParser = (Problem)parsers.get(Problem.class); while (problemParser.nextRecord()) { CsvCell problemGuid = problemParser.getObservationGuid(); CsvCell patientGuid = problemParser.getPatientGuid(); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); newProblemChildren.put(sourceId, new ReferenceList()); } //run this pre-transformer to pre-cache some stuff in the csv helper, which //is needed when working out the resource type that each observation would be saved as ObservationPreTransformer.transform(version, parsers, null, csvHelper); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { CsvCell observationGuid = observationParser.getObservationGuid(); CsvCell patientGuid = observationParser.getPatientGuid(); String obSourceId = EmisCsvHelper.createUniqueId(patientGuid, observationGuid); CsvCell codeId = observationParser.getCodeId(); if (codeId.isEmpty()) { continue; } ResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper); UUID obUuid = IdHelper.getEdsResourceId(serviceId, resourceType, obSourceId); if (obUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + resourceType + " and source ID " + obSourceId); //resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper); } Reference obReference = ReferenceHelper.createReference(resourceType, obUuid.toString()); CsvCell consultationGuid = observationParser.getConsultationGuid(); if (!consultationGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); ReferenceList referenceList = consultationNewChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); consultationNewChildMap.put(sourceId, referenceList); } referenceList.add(obReference); } CsvCell problemGuid = observationParser.getProblemGuid(); if (!problemGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(obReference); } CsvCell parentObGuid = observationParser.getParentObservationGuid(); if (!parentObGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, parentObGuid); ReferenceList referenceList = observationChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); observationChildMap.put(sourceId, referenceList); } referenceList.add(obReference); } } Diary diaryParser = (Diary)parsers.get(Diary.class); while (diaryParser.nextRecord()) { CsvCell consultationGuid = diaryParser.getConsultationGuid(); if (!consultationGuid.isEmpty()) { CsvCell diaryGuid = diaryParser.getDiaryGuid(); CsvCell patientGuid = diaryParser.getPatientGuid(); String diarySourceId = EmisCsvHelper.createUniqueId(patientGuid, diaryGuid); UUID diaryUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.ProcedureRequest, diarySourceId); if (diaryUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.ProcedureRequest + " and source ID " + diarySourceId); } Reference diaryReference = ReferenceHelper.createReference(ResourceType.ProcedureRequest, diaryUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); ReferenceList referenceList = consultationNewChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); consultationNewChildMap.put(sourceId, referenceList); } referenceList.add(diaryReference); } } IssueRecord issueRecordParser = (IssueRecord)parsers.get(IssueRecord.class); while (issueRecordParser.nextRecord()) { CsvCell problemGuid = issueRecordParser.getProblemObservationGuid(); if (!problemGuid.isEmpty()) { CsvCell issueRecordGuid = issueRecordParser.getIssueRecordGuid(); CsvCell patientGuid = issueRecordParser.getPatientGuid(); String issueRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, issueRecordGuid); UUID issueRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationOrder, issueRecordSourceId); if (issueRecordUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.MedicationOrder + " and source ID " + issueRecordSourceId); } Reference issueRecordReference = ReferenceHelper.createReference(ResourceType.MedicationOrder, issueRecordUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(issueRecordReference); } } DrugRecord drugRecordParser = (DrugRecord)parsers.get(DrugRecord.class); while (drugRecordParser.nextRecord()) { CsvCell problemGuid = drugRecordParser.getProblemObservationGuid(); if (!problemGuid.isEmpty()) { CsvCell drugRecordGuid = drugRecordParser.getDrugRecordGuid(); CsvCell patientGuid = drugRecordParser.getPatientGuid(); String drugRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, drugRecordGuid); UUID drugRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationStatement, drugRecordSourceId); if (drugRecordUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.MedicationStatement + " and source ID " + drugRecordSourceId); } Reference drugRecordReference = ReferenceHelper.createReference(ResourceType.MedicationStatement, drugRecordUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(drugRecordReference); } } for (AbstractCsvParser parser : parsers.values()) { try { parser.close(); } catch (IOException ex) { //don't worry if this fails, as we're done anyway } } } ResourceDalI resourceDal = DalProvider.factoryResourceDal(); LOG.info("Found " + consultationNewChildMap.size() + " Encounters to fix"); for (String encounterSourceId: consultationNewChildMap.keySet()) { ReferenceList childReferences = consultationNewChildMap.get(encounterSourceId); //map to UUID UUID encounterId = IdHelper.getEdsResourceId(serviceId, ResourceType.Encounter, encounterSourceId); if (encounterId == null) { continue; } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, ResourceType.Encounter.toString(), encounterId); if (history.isEmpty()) { continue; //throw new Exception("Empty history for Encounter " + encounterId); } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (wrapper.getResourceData() != null) { Encounter encounter = (Encounter) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); EncounterBuilder encounterBuilder = new EncounterBuilder(encounter); ContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder); List<Reference> previousChildren = containedListBuilder.getContainedListItems(); childReferences.add(previousChildren); } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Encounter encounter = (Encounter)FhirSerializationHelper.deserializeResource(currentState.getResourceData()); EncounterBuilder encounterBuilder = new EncounterBuilder(encounter); ContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder); containedListBuilder.addReferences(childReferences); String newJson = FhirSerializationHelper.serializeResource(encounter); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState);*//* } LOG.info("Found " + observationChildMap.size() + " Parent Observations to fix"); for (String sourceId: observationChildMap.keySet()) { ReferenceList childReferences = observationChildMap.get(sourceId); //map to UUID ResourceType resourceType = null; UUID resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.Observation, sourceId); if (resourceId != null) { resourceType = ResourceType.Observation; } else { resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.DiagnosticReport, sourceId); if (resourceId != null) { resourceType = ResourceType.DiagnosticReport; } else { continue; } } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, resourceType.toString(), resourceId); if (history.isEmpty()) { //throw new Exception("Empty history for " + resourceType + " " + resourceId); continue; } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (resourceType == ResourceType.Observation) { if (wrapper.getResourceData() != null) { Observation observation = (Observation) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); if (observation.hasRelated()) { for (Observation.ObservationRelatedComponent related : observation.getRelated()) { Reference reference = related.getTarget(); childReferences.add(reference); } } } } else { if (wrapper.getResourceData() != null) { DiagnosticReport report = (DiagnosticReport) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); if (report.hasResult()) { for (Reference reference : report.getResult()) { childReferences.add(reference); } } } } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Resource resource = FhirSerializationHelper.deserializeResource(currentState.getResourceData()); boolean changed = false; if (resourceType == ResourceType.Observation) { ObservationBuilder resourceBuilder = new ObservationBuilder((Observation)resource); for (int i=0; i<childReferences.size(); i++) { Reference reference = childReferences.getReference(i); if (resourceBuilder.addChildObservation(reference)) { changed = true; } } } else { DiagnosticReportBuilder resourceBuilder = new DiagnosticReportBuilder((DiagnosticReport)resource); for (int i=0; i<childReferences.size(); i++) { Reference reference = childReferences.getReference(i); if (resourceBuilder.addResult(reference)) { changed = true; } } } if (changed) { String newJson = FhirSerializationHelper.serializeResource(resource); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); }*//* } LOG.info("Found " + newProblemChildren.size() + " Problems to fix"); for (String sourceId: newProblemChildren.keySet()) { ReferenceList childReferences = newProblemChildren.get(sourceId); //map to UUID UUID conditionId = IdHelper.getEdsResourceId(serviceId, ResourceType.Condition, sourceId); if (conditionId == null) { continue; } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, ResourceType.Condition.toString(), conditionId); if (history.isEmpty()) { continue; //throw new Exception("Empty history for Condition " + conditionId); } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (wrapper.getResourceData() != null) { Condition previousVersion = (Condition) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); ConditionBuilder conditionBuilder = new ConditionBuilder(previousVersion); ContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder); List<Reference> previousChildren = containedListBuilder.getContainedListItems(); childReferences.add(previousChildren); } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Condition condition = (Condition)FhirSerializationHelper.deserializeResource(currentState.getResourceData()); ConditionBuilder conditionBuilder = new ConditionBuilder(condition); ContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder); containedListBuilder.addReferences(childReferences); String newJson = FhirSerializationHelper.serializeResource(condition); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState);*//* } //mark as done String updateSql = "UPDATE " + table + " SET done = 1 WHERE service_id = '" + serviceId + "';"; entityManager = ConnectionManager.getAdminEntityManager(); session = (SessionImpl)entityManager.getDelegate(); connection = session.connection(); statement = connection.createStatement(); entityManager.getTransaction().begin(); statement.executeUpdate(updateSql); entityManager.getTransaction().commit(); } *//** * For each practice: Go through all files processed since 14 March Cache all links as above Cache all Encounters saved too For each Encounter referenced at all: Retrieve latest version from resource current Retrieve version prior to 14 March Update current version with old references plus new ones For each parent observation: Retrieve latest version (could be observation or diagnostic report) For each problem: Retrieve latest version from resource current Check if still a problem: Retrieve version prior to 14 March Update current version with old references plus new ones *//* LOG.info("Finished Fixing encounters from " + table); } catch (Throwable t) { LOG.error("", t); } }*/ private static void saveResourceWrapper(UUID serviceId, ResourceWrapper wrapper) throws Exception { if (wrapper.getResourceData() != null) { long checksum = FhirStorageService.generateChecksum(wrapper.getResourceData()); wrapper.setResourceChecksum(new Long(checksum)); } EntityManager entityManager = ConnectionManager.getEhrEntityManager(serviceId); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); entityManager.getTransaction().begin(); String json = wrapper.getResourceData(); json = json.replace("'", "''"); json = json.replace("\\", "\\\\"); String patientId = ""; if (wrapper.getPatientId() != null) { patientId = wrapper.getPatientId().toString(); } String updateSql = "UPDATE resource_current" + " SET resource_data = '" + json + "'," + " resource_checksum = " + wrapper.getResourceChecksum() + " WHERE service_id = '" + wrapper.getServiceId() + "'" + " AND patient_id = '" + patientId + "'" + " AND resource_type = '" + wrapper.getResourceType() + "'" + " AND resource_id = '" + wrapper.getResourceId() + "'"; statement.executeUpdate(updateSql); //LOG.debug(updateSql); //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS"); //String createdAtStr = sdf.format(wrapper.getCreatedAt()); updateSql = "UPDATE resource_history" + " SET resource_data = '" + json + "'," + " resource_checksum = " + wrapper.getResourceChecksum() + " WHERE resource_id = '" + wrapper.getResourceId() + "'" + " AND resource_type = '" + wrapper.getResourceType() + "'" //+ " AND created_at = '" + createdAtStr + "'" + " AND version = '" + wrapper.getVersion() + "'"; statement.executeUpdate(updateSql); //LOG.debug(updateSql); entityManager.getTransaction().commit(); } /*private static void populateNewSearchTable(String table) { LOG.info("Populating New Search Table"); try { EntityManager entityManager = ConnectionManager.getEdsEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); List<String> patientIds = new ArrayList<>(); Map<String, String> serviceIds = new HashMap<>(); String sql = "SELECT patient_id, service_id FROM " + table + " WHERE done = 0"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String patientId = rs.getString(1); String serviceId = rs.getString(2); patientIds.add(patientId); serviceIds.put(patientId, serviceId); } rs.close(); statement.close(); entityManager.close(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearch2Dal(); LOG.info("Found " + patientIds.size() + " to do"); for (int i=0; i<patientIds.size(); i++) { String patientIdStr = patientIds.get(i); UUID patientId = UUID.fromString(patientIdStr); String serviceIdStr = serviceIds.get(patientIdStr); UUID serviceId = UUID.fromString(serviceIdStr); Patient patient = (Patient)resourceDal.getCurrentVersionAsResource(serviceId, ResourceType.Patient, patientIdStr); if (patient != null) { patientSearchDal.update(serviceId, patient); //find episode of care List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(serviceId, null, patientId, ResourceType.EpisodeOfCare.toString()); for (ResourceWrapper wrapper: wrappers) { if (!wrapper.isDeleted()) { EpisodeOfCare episodeOfCare = (EpisodeOfCare)FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); patientSearchDal.update(serviceId, episodeOfCare); } } } String updateSql = "UPDATE " + table + " SET done = 1 WHERE patient_id = '" + patientIdStr + "' AND service_id = '" + serviceIdStr + "';"; entityManager = ConnectionManager.getEdsEntityManager(); session = (SessionImpl)entityManager.getDelegate(); connection = session.connection(); statement = connection.createStatement(); entityManager.getTransaction().begin(); statement.executeUpdate(updateSql); entityManager.getTransaction().commit(); if (i % 5000 == 0) { LOG.info("Done " + (i+1) + " of " + patientIds.size()); } } entityManager.close(); LOG.info("Finished Populating New Search Table"); } catch (Exception ex) { LOG.error("", ex); } }*/ private static void createBartsSubset(String sourceDir, UUID serviceUuid, UUID systemUuid, String samplePatientsFile) { LOG.info("Creating Barts Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } createBartsSubsetForFile(sourceDir, serviceUuid, systemUuid, personIds); LOG.info("Finished Creating Barts Subset"); } catch (Throwable t) { LOG.error("", t); } } /*private static void createBartsSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { for (File sourceFile: sourceDir.listFiles()) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } LOG.info("Doing dir " + sourceFile); createBartsSubsetForFile(sourceFile, destFile, personIds); } else { //we have some bad partial files in, so ignore them String ext = FilenameUtils.getExtension(name); if (ext.equalsIgnoreCase("filepart")) { continue; } //if the file is empty, we still need the empty file in the filtered directory, so just copy it if (sourceFile.length() == 0) { LOG.info("Copying empty file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } continue; } String baseName = FilenameUtils.getBaseName(name); String fileType = BartsCsvToFhirTransformer.identifyFileType(baseName); if (isCerner22File(fileType)) { LOG.info("Checking 2.2 file " + sourceFile); if (destFile.exists()) { destFile.delete(); } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); int lineIndex = -1; PrintWriter pw = null; int personIdColIndex = -1; int expectedCols = -1; while (true) { String line = br.readLine(); if (line == null) { break; } lineIndex ++; if (lineIndex == 0) { if (fileType.equalsIgnoreCase("FAMILYHISTORY")) { //this file has no headers, so needs hard-coding personIdColIndex = 5; } else { //check headings for PersonID col String[] toks = line.split("\\|", -1); expectedCols = toks.length; for (int i=0; i<expectedCols; i++) { String col = toks[i]; if (col.equalsIgnoreCase("PERSON_ID") || col.equalsIgnoreCase("#PERSON_ID")) { personIdColIndex = i; break; } } //if no person ID, then just copy the entire file if (personIdColIndex == -1) { br.close(); br = null; LOG.info(" Copying 2.2 file to " + destFile); copyFile(sourceFile, destFile); break; } else { LOG.info(" Filtering 2.2 file to " + destFile + ", person ID col at " + personIdColIndex); } } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } else { //filter on personID String[] toks = line.split("\\|", -1); if (expectedCols != -1 && toks.length != expectedCols) { throw new Exception("Line " + (lineIndex+1) + " has " + toks.length + " cols but expecting " + expectedCols); } else { String personId = toks[personIdColIndex]; if (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes && !personIds.contains(personId)) { continue; } } } pw.println(line); } if (br != null) { br.close(); } if (pw != null) { pw.flush(); pw.close(); } } else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } } } } }*/ private static void createBartsSubsetForFile(String sourceDir, UUID serviceUuid, UUID systemUuid, Set<String> personIds) throws Exception { ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE); for (Exchange exchange: exchanges) { List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(exchange.getBody()); for (ExchangePayloadFile fileObj : files) { String filePathWithoutSharedStorage = fileObj.getPath().substring(TransformConfig.instance().getSharedStoragePath().length()+1); String sourceFilePath = FilenameUtils.concat(sourceDir, filePathWithoutSharedStorage); File sourceFile = new File(sourceFilePath); String destFilePath = fileObj.getPath(); File destFile = new File(destFilePath); File destDir = destFile.getParentFile(); if (!destDir.exists()) { destDir.mkdirs(); } //if the file is empty, we still need the empty file in the filtered directory, so just copy it if (sourceFile.length() == 0) { LOG.info("Copying empty file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } continue; } String fileType = fileObj.getType(); if (isCerner22File(fileType)) { LOG.info("Checking 2.2 file " + sourceFile); if (destFile.exists()) { destFile.delete(); } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); int lineIndex = -1; PrintWriter pw = null; int personIdColIndex = -1; int expectedCols = -1; while (true) { String line = br.readLine(); if (line == null) { break; } lineIndex++; if (lineIndex == 0) { if (fileType.equalsIgnoreCase("FAMILYHISTORY")) { //this file has no headers, so needs hard-coding personIdColIndex = 5; } else { //check headings for PersonID col String[] toks = line.split("\\|", -1); expectedCols = toks.length; for (int i = 0; i < expectedCols; i++) { String col = toks[i]; if (col.equalsIgnoreCase("PERSON_ID") || col.equalsIgnoreCase("#PERSON_ID")) { personIdColIndex = i; break; } } //if no person ID, then just copy the entire file if (personIdColIndex == -1) { br.close(); br = null; LOG.info(" Copying 2.2 file to " + destFile); copyFile(sourceFile, destFile); break; } else { LOG.info(" Filtering 2.2 file to " + destFile + ", person ID col at " + personIdColIndex); } } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } else { //filter on personID String[] toks = line.split("\\|", -1); if (expectedCols != -1 && toks.length != expectedCols) { throw new Exception("Line " + (lineIndex + 1) + " has " + toks.length + " cols but expecting " + expectedCols); } else { String personId = toks[personIdColIndex]; if (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes && !personIds.contains(personId)) { continue; } } } pw.println(line); } if (br != null) { br.close(); } if (pw != null) { pw.flush(); pw.close(); } } else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } } } } } private static void copyFile(File src, File dst) throws Exception { FileInputStream fis = new FileInputStream(src); BufferedInputStream bis = new BufferedInputStream(fis); Files.copy(bis, dst.toPath()); bis.close(); } private static boolean isCerner22File(String fileType) throws Exception { if (fileType.equalsIgnoreCase("PPATI") || fileType.equalsIgnoreCase("PPREL") || fileType.equalsIgnoreCase("CDSEV") || fileType.equalsIgnoreCase("PPATH") || fileType.equalsIgnoreCase("RTTPE") || fileType.equalsIgnoreCase("AEATT") || fileType.equalsIgnoreCase("AEINV") || fileType.equalsIgnoreCase("AETRE") || fileType.equalsIgnoreCase("OPREF") || fileType.equalsIgnoreCase("OPATT") || fileType.equalsIgnoreCase("EALEN") || fileType.equalsIgnoreCase("EALSU") || fileType.equalsIgnoreCase("EALOF") || fileType.equalsIgnoreCase("HPSSP") || fileType.equalsIgnoreCase("IPEPI") || fileType.equalsIgnoreCase("IPWDS") || fileType.equalsIgnoreCase("DELIV") || fileType.equalsIgnoreCase("BIRTH") || fileType.equalsIgnoreCase("SCHAC") || fileType.equalsIgnoreCase("APPSL") || fileType.equalsIgnoreCase("DIAGN") || fileType.equalsIgnoreCase("PROCE") || fileType.equalsIgnoreCase("ORDER") || fileType.equalsIgnoreCase("DOCRP") || fileType.equalsIgnoreCase("DOCREF") || fileType.equalsIgnoreCase("CNTRQ") || fileType.equalsIgnoreCase("LETRS") || fileType.equalsIgnoreCase("LOREF") || fileType.equalsIgnoreCase("ORGREF") || fileType.equalsIgnoreCase("PRSNLREF") || fileType.equalsIgnoreCase("CVREF") || fileType.equalsIgnoreCase("NOMREF") || fileType.equalsIgnoreCase("EALIP") || fileType.equalsIgnoreCase("CLEVE") || fileType.equalsIgnoreCase("ENCNT") || fileType.equalsIgnoreCase("RESREF") || fileType.equalsIgnoreCase("PPNAM") || fileType.equalsIgnoreCase("PPADD") || fileType.equalsIgnoreCase("PPPHO") || fileType.equalsIgnoreCase("PPALI") || fileType.equalsIgnoreCase("PPINF") || fileType.equalsIgnoreCase("PPAGP") || fileType.equalsIgnoreCase("SURCC") || fileType.equalsIgnoreCase("SURCP") || fileType.equalsIgnoreCase("SURCA") || fileType.equalsIgnoreCase("SURCD") || fileType.equalsIgnoreCase("PDRES") || fileType.equalsIgnoreCase("PDREF") || fileType.equalsIgnoreCase("ABREF") || fileType.equalsIgnoreCase("CEPRS") || fileType.equalsIgnoreCase("ORDDT") || fileType.equalsIgnoreCase("STATREF") || fileType.equalsIgnoreCase("STATA") || fileType.equalsIgnoreCase("ENCINF") || fileType.equalsIgnoreCase("SCHDETAIL") || fileType.equalsIgnoreCase("SCHOFFER") || fileType.equalsIgnoreCase("PPGPORG") || fileType.equalsIgnoreCase("FAMILYHISTORY")) { return true; } else { return false; } } /*private static void fixSubscriberDbs() { LOG.info("Fixing Subscriber DBs"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); Date dateError = new SimpleDateFormat("yyyy-MM-dd").parse("2018-05-11"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); boolean needsFixing = false; for (UUID exchangeId: exchangeIds) { if (!needsFixing) { List<ExchangeTransformAudit> transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId); for (ExchangeTransformAudit audit: transformAudits) { Date transfromStart = audit.getStarted(); if (!transfromStart.before(dateError)) { needsFixing = true; break; } } } if (!needsFixing) { continue; } List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); LOG.info(" Posting exchange " + exchangeId + " with " + batches.size() + " batches"); List<UUID> batchIds = new ArrayList<>(); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } UUID batchId = batch.getBatchId(); batchIds.add(batchId); } String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } LOG.info("Finished Fixing Subscriber DBs"); } catch (Throwable t) { LOG.error("", t); } }*/ /*private static void fixReferralRequests() { LOG.info("Fixing Referral Requests"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); Date dateError = new SimpleDateFormat("yyyy-MM-dd").parse("2018-04-24"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); boolean needsFixing = false; Set<UUID> patientIdsToPost = new HashSet<>(); for (UUID exchangeId: exchangeIds) { if (!needsFixing) { List<ExchangeTransformAudit> transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId); for (ExchangeTransformAudit audit: transformAudits) { Date transfromStart = audit.getStarted(); if (!transfromStart.before(dateError)) { needsFixing = true; break; } } } if (!needsFixing) { continue; } List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); LOG.info("Checking exchange " + exchangeId + " with " + batches.size() + " batches"); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } UUID batchId = batch.getBatchId(); List<ResourceWrapper> wrappers = resourceDal.getResourcesForBatch(serviceId, batchId); for (ResourceWrapper wrapper: wrappers) { String resourceType = wrapper.getResourceType(); if (!resourceType.equals(ResourceType.ReferralRequest.toString()) || wrapper.isDeleted()) { continue; } String json = wrapper.getResourceData(); ReferralRequest referral = (ReferralRequest)FhirSerializationHelper.deserializeResource(json); *//*if (!referral.hasServiceRequested()) { continue; } CodeableConcept reason = referral.getServiceRequested().get(0); referral.setReason(reason); referral.getServiceRequested().clear();*//* if (!referral.hasReason()) { continue; } CodeableConcept reason = referral.getReason(); referral.setReason(null); referral.addServiceRequested(reason); json = FhirSerializationHelper.serializeResource(referral); wrapper.setResourceData(json); saveResourceWrapper(serviceId, wrapper); //add to the set of patients we know need sending on to the protocol queue patientIdsToPost.add(patientId); LOG.info("Fixed " + resourceType + " " + wrapper.getResourceId() + " in batch " + batchId); } //if our patient has just been fixed or was fixed before, post onto the protocol queue if (patientIdsToPost.contains(patientId)) { List<UUID> batchIds = new ArrayList<>(); batchIds.add(batchId); String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } } } LOG.info("Finished Fixing Referral Requests"); } catch (Throwable t) { LOG.error("", t); } }*/ private static void applyEmisAdminCaches() { LOG.info("Applying Emis Admin Caches"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } if (!exchangeDal.isServiceStarted(serviceId, endpointSystemId)) { LOG.info(" Service not started, so skipping"); continue; } //get exchanges List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); if (exchangeIds.isEmpty()) { LOG.info(" No exchanges found, so skipping"); continue; } UUID firstExchangeId = exchangeIds.get(0); List<ExchangeEvent> events = exchangeDal.getExchangeEvents(firstExchangeId); boolean appliedAdminCache = false; for (ExchangeEvent event: events) { if (event.getEventDesc().equals("Applied Emis Admin Resource Cache")) { appliedAdminCache = true; } } if (appliedAdminCache) { LOG.info(" Have already applied admin cache, so skipping"); continue; } Exchange exchange = exchangeDal.getExchange(firstExchangeId); String body = exchange.getBody(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(body); if (files.length == 0) { LOG.info(" No files in exchange " + firstExchangeId + " so skipping"); continue; } String firstFilePath = files[0]; String name = FilenameUtils.getBaseName(firstFilePath); //file name without extension String[] toks = name.split("_"); if (toks.length != 5) { throw new TransformException("Failed to extract data sharing agreement GUID from filename " + firstFilePath); } String sharingAgreementGuid = toks[4]; List<UUID> batchIds = new ArrayList<>(); TransformError transformError = new TransformError(); FhirResourceFiler fhirResourceFiler = new FhirResourceFiler(firstExchangeId, serviceId, endpointSystemId, transformError, batchIds); EmisCsvHelper csvHelper = new EmisCsvHelper(fhirResourceFiler.getServiceId(), fhirResourceFiler.getSystemId(), fhirResourceFiler.getExchangeId(), sharingAgreementGuid, true); ExchangeTransformAudit transformAudit = new ExchangeTransformAudit(); transformAudit.setServiceId(serviceId); transformAudit.setSystemId(endpointSystemId); transformAudit.setExchangeId(firstExchangeId); transformAudit.setId(UUID.randomUUID()); transformAudit.setStarted(new Date()); LOG.info(" Going to apply admin resource cache"); csvHelper.applyAdminResourceCache(fhirResourceFiler); fhirResourceFiler.waitToFinish(); for (UUID batchId: batchIds) { LOG.info(" Created batch ID " + batchId + " for exchange " + firstExchangeId); } transformAudit.setEnded(new Date()); transformAudit.setNumberBatchesCreated(new Integer(batchIds.size())); boolean hadError = false; if (transformError.getError().size() > 0) { transformAudit.setErrorXml(TransformErrorSerializer.writeToXml(transformError)); hadError = true; } exchangeDal.save(transformAudit); //clear down the cache of reference mappings since they won't be of much use for the next Exchange IdHelper.clearCache(); if (hadError) { LOG.error(" <<<<<<Error applying resource cache!"); continue; } //add the event to say we've applied the cache AuditWriter.writeExchangeEvent(firstExchangeId, "Applied Emis Admin Resource Cache"); //post that ONE new batch ID onto the protocol queue String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } LOG.info("Finished Applying Emis Admin Caches"); } catch (Throwable t) { LOG.error("", t); } } /*private static void fixBartsEscapedFiles(String filePath) { LOG.info("Fixing Barts Escaped Files in " + filePath); try { fixBartsEscapedFilesInDir(new File(filePath)); LOG.info("Finished fixing Barts Escaped Files in " + filePath); } catch (Throwable t) { LOG.error("", t); } } /** * fixes Emis extract(s) when a practice was disabled then subsequently re-bulked, by * replacing the "delete" extracts with newly generated deltas that can be processed * before the re-bulk is done */ private static void fixDisabledEmisExtract(String serviceId, String systemId, String sharedStoragePath, String tempDir) { LOG.info("Fixing Disabled Emis Extracts Prior to Re-bulk for service " + serviceId); try { /*File tempDirLast = new File(tempDir, "last"); if (!tempDirLast.exists()) { if (!tempDirLast.mkdirs()) { throw new Exception("Failed to create temp dir " + tempDirLast); } tempDirLast.mkdirs(); } File tempDirEmpty = new File(tempDir, "empty"); if (!tempDirEmpty.exists()) { if (!tempDirEmpty.mkdirs()) { throw new Exception("Failed to create temp dir " + tempDirEmpty); } tempDirEmpty.mkdirs(); }*/ UUID serviceUuid = UUID.fromString(serviceId); UUID systemUuid = UUID.fromString(systemId); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); //get all the exchanges, which are returned in reverse order, so reverse for simplicity List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE); //sorting by timestamp seems unreliable when exchanges were posted close together? List<Exchange> tmp = new ArrayList<>(); for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); tmp.add(exchange); } exchanges = tmp; /*exchanges.sort((o1, o2) -> { Date d1 = o1.getTimestamp(); Date d2 = o2.getTimestamp(); return d1.compareTo(d2); });*/ LOG.info("Found " + exchanges.size() + " exchanges"); //continueOrQuit(); //find the files for each exchange Map<Exchange, List<String>> hmExchangeFiles = new HashMap<>(); Map<Exchange, List<String>> hmExchangeFilesWithoutStoragePrefix = new HashMap<>(); for (Exchange exchange: exchanges) { //populate a map of the files with the shared storage prefix String exchangeBody = exchange.getBody(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); List<String> fileList = Lists.newArrayList(files); hmExchangeFiles.put(exchange, fileList); //populate a map of the same files without the prefix files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); for (int i=0; i<files.length; i++) { String file = files[i].substring(sharedStoragePath.length() + 1); files[i] = file; } fileList = Lists.newArrayList(files); hmExchangeFilesWithoutStoragePrefix.put(exchange, fileList); } LOG.info("Cached files for each exchange"); int indexDisabled = -1; int indexRebulked = -1; int indexOriginallyBulked = -1; //go back through them to find the extract where the re-bulk is and when it was disabled for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); boolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles); if (disabled) { indexDisabled = i; } else { if (indexDisabled == -1) { indexRebulked = i; } else { //if we've found a non-disabled extract older than the disabled ones, //then we've gone far enough back break; } } } //go back from when disabled to find the previous bulk load (i.e. the first one or one after it was previously not disabled) for (int i=indexDisabled-1; i>=0; i--) { Exchange exchange = exchanges.get(i); boolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles); if (disabled) { break; } indexOriginallyBulked = i; } if (indexDisabled == -1 || indexRebulked == -1 || indexOriginallyBulked == -1) { throw new Exception("Failed to find exchanges for disabling (" + indexDisabled + "), re-bulking (" + indexRebulked + ") or original bulk (" + indexOriginallyBulked + ")"); } Exchange exchangeDisabled = exchanges.get(indexDisabled); LOG.info("Disabled on " + findExtractDate(exchangeDisabled, hmExchangeFiles) + " " + exchangeDisabled.getId()); Exchange exchangeRebulked = exchanges.get(indexRebulked); LOG.info("Rebulked on " + findExtractDate(exchangeRebulked, hmExchangeFiles) + " " + exchangeRebulked.getId()); Exchange exchangeOriginallyBulked = exchanges.get(indexOriginallyBulked); LOG.info("Originally bulked on " + findExtractDate(exchangeOriginallyBulked, hmExchangeFiles) + " " + exchangeOriginallyBulked.getId()); //continueOrQuit(); List<String> rebulkFiles = hmExchangeFiles.get(exchangeRebulked); List<String> tempFilesCreated = new ArrayList<>(); Set<String> patientGuidsDeletedOrTooOld = new HashSet<>(); for (String rebulkFile: rebulkFiles) { String fileType = findFileType(rebulkFile); if (!isPatientFile(fileType)) { continue; } LOG.info("Doing " + fileType); String guidColumnName = getGuidColumnName(fileType); //find all the guids in the re-bulk Set<String> idsInRebulk = new HashSet<>(); InputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(rebulkFile); CSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); String[] headers = null; try { headers = CsvHelper.getHeaderMapAsArray(csvParser); Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); //get the patient and row guid out of the file and cache in our set String id = record.get("PatientGuid"); if (!Strings.isNullOrEmpty(guidColumnName)) { id += "//" + record.get(guidColumnName); } idsInRebulk.add(id); } } finally { csvParser.close(); } LOG.info("Found " + idsInRebulk.size() + " IDs in re-bulk file: " + rebulkFile); //create a replacement file for the exchange the service was disabled String replacementDisabledFile = null; List<String> disabledFiles = hmExchangeFilesWithoutStoragePrefix.get(exchangeDisabled); for (String s: disabledFiles) { String disabledFileType = findFileType(s); if (disabledFileType.equals(fileType)) { replacementDisabledFile = FilenameUtils.concat(tempDir, s); File dir = new File(replacementDisabledFile).getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("Failed to create directory " + dir); } } tempFilesCreated.add(s); LOG.info("Created replacement file " + replacementDisabledFile); } } FileWriter fileWriter = new FileWriter(replacementDisabledFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers)); csvPrinter.flush(); Set<String> pastIdsProcessed = new HashSet<>(); //now go through all files of the same type PRIOR to the service was disabled //to find any rows that we'll need to explicitly delete because they were deleted while //the extract was disabled for (int i=indexDisabled-1; i>=indexOriginallyBulked; i--) { Exchange exchange = exchanges.get(i); String originalFile = null; List<String> files = hmExchangeFiles.get(exchange); for (String s: files) { String originalFileType = findFileType(s); if (originalFileType.equals(fileType)) { originalFile = s; break; } } if (originalFile == null) { continue; } LOG.info(" Reading " + originalFile); reader = FileHelper.readFileReaderFromSharedStorage(originalFile); csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); try { Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String patientGuid = record.get("PatientGuid"); //get the patient and row guid out of the file and cache in our set String uniqueId = patientGuid; if (!Strings.isNullOrEmpty(guidColumnName)) { uniqueId += "//" + record.get(guidColumnName); } //if we're already handled this record in a more recent extract, then skip it if (pastIdsProcessed.contains(uniqueId)) { continue; } pastIdsProcessed.add(uniqueId); //if this ID isn't deleted and isn't in the re-bulk then it means //it WAS deleted in Emis Web but we didn't receive the delete, because it was deleted //from Emis Web while the extract feed was disabled //if the record is deleted, then we won't expect it in the re-bulk boolean deleted = Boolean.parseBoolean(record.get("Deleted")); if (deleted) { //if it's the Patient file, stick the patient GUID in a set so we know full patient record deletes if (fileType.equals("Admin_Patient")) { patientGuidsDeletedOrTooOld.add(patientGuid); } continue; } //if it's not the patient file and we refer to a patient that we know //has been deleted, then skip this row, since we know we're deleting the entire patient record if (patientGuidsDeletedOrTooOld.contains(patientGuid)) { continue; } //if the re-bulk contains a record matching this one, then it's OK if (idsInRebulk.contains(uniqueId)) { continue; } //the rebulk won't contain any data for patients that are now too old (i.e. deducted or deceased > 2 yrs ago), //so any patient ID in the original files but not in the rebulk can be treated like this and any data for them can be skipped if (fileType.equals("Admin_Patient")) { //retrieve the Patient and EpisodeOfCare resource for the patient so we can confirm they are deceased or deducted ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID patientUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.Patient, patientGuid); if (patientUuid == null) { throw new Exception("Failed to find patient UUID from GUID [" + patientGuid + "]"); } Patient patientResource = (Patient)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.Patient, patientUuid.toString()); if (patientResource.hasDeceased()) { patientGuidsDeletedOrTooOld.add(patientGuid); continue; } UUID episodeUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.EpisodeOfCare, patientGuid); //we use the patient GUID for the episode too EpisodeOfCare episodeResource = (EpisodeOfCare)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.EpisodeOfCare, episodeUuid.toString()); if (episodeResource.hasPeriod() && !PeriodHelper.isActive(episodeResource.getPeriod())) { patientGuidsDeletedOrTooOld.add(patientGuid); continue; } } //create a new CSV record, carrying over the GUIDs from the original but marking as deleted String[] newRecord = new String[headers.length]; for (int j=0; j<newRecord.length; j++) { String header = headers[j]; if (header.equals("PatientGuid") || header.equals("OrganisationGuid") || (!Strings.isNullOrEmpty(guidColumnName) && header.equals(guidColumnName))) { String val = record.get(header); newRecord[j] = val; } else if (header.equals("Deleted")) { newRecord[j] = "true"; } else { newRecord[j] = ""; } } csvPrinter.printRecord((Object[])newRecord); csvPrinter.flush(); //log out the raw record that's missing from the original StringBuffer sb = new StringBuffer(); sb.append("Record not in re-bulk: "); for (int j=0; j<record.size(); j++) { if (j > 0) { sb.append(","); } sb.append(record.get(j)); } LOG.info(sb.toString()); } } finally { csvParser.close(); } } csvPrinter.flush(); csvPrinter.close(); //also create a version of the CSV file with just the header and nothing else in for (int i=indexDisabled+1; i<indexRebulked; i++) { Exchange ex = exchanges.get(i); List<String> exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex); for (String s: exchangeFiles) { String exchangeFileType = findFileType(s); if (exchangeFileType.equals(fileType)) { String emptyTempFile = FilenameUtils.concat(tempDir, s); File dir = new File(emptyTempFile).getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("Failed to create directory " + dir); } } fileWriter = new FileWriter(emptyTempFile); bufferedWriter = new BufferedWriter(fileWriter); csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers)); csvPrinter.flush(); csvPrinter.close(); tempFilesCreated.add(s); LOG.info("Created empty file " + emptyTempFile); } } } } //we also need to copy the restored sharing agreement file to replace all the period it was disabled String rebulkedSharingAgreementFile = null; for (String s: rebulkFiles) { String fileType = findFileType(s); if (fileType.equals("Agreements_SharingOrganisation")) { rebulkedSharingAgreementFile = s; } } for (int i=indexDisabled; i<indexRebulked; i++) { Exchange ex = exchanges.get(i); List<String> exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex); for (String s: exchangeFiles) { String exchangeFileType = findFileType(s); if (exchangeFileType.equals("Agreements_SharingOrganisation")) { String replacementFile = FilenameUtils.concat(tempDir, s); InputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkedSharingAgreementFile); Files.copy(inputStream, new File(replacementFile).toPath()); inputStream.close(); tempFilesCreated.add(s); } } } //create a script to copy the files into S3 List<String> copyScript = new ArrayList<>(); copyScript.add("#!/bin/bash"); copyScript.add(""); for (String s: tempFilesCreated) { String localFile = FilenameUtils.concat(tempDir, s); copyScript.add("sudo aws s3 cp " + localFile + " s3://discoverysftplanding/endeavour/" + s); } String scriptFile = FilenameUtils.concat(tempDir, "copy.sh"); FileUtils.writeLines(new File(scriptFile), copyScript); /*continueOrQuit(); //back up every file where the service was disabled for (int i=indexDisabled; i<indexRebulked; i++) { Exchange exchange = exchanges.get(i); List<String> files = hmExchangeFiles.get(exchange); for (String file: files) { //first download from S3 to the local temp dir InputStream inputStream = FileHelper.readFileFromSharedStorage(file); String fileName = FilenameUtils.getName(file); String tempPath = FilenameUtils.concat(tempDir, fileName); File downloadDestination = new File(tempPath); Files.copy(inputStream, downloadDestination.toPath()); //then write back to S3 in a sub-dir of the original file String backupPath = FilenameUtils.getPath(file); backupPath = FilenameUtils.concat(backupPath, "Original"); backupPath = FilenameUtils.concat(backupPath, fileName); FileHelper.writeFileToSharedStorage(backupPath, downloadDestination); LOG.info("Backed up " + file + " -> " + backupPath); //delete from temp dir downloadDestination.delete(); } } continueOrQuit(); //copy the new CSV files into the dir where it was disabled List<String> disabledFiles = hmExchangeFiles.get(exchangeDisabled); for (String disabledFile: disabledFiles) { String fileType = findFileType(disabledFile); if (!isPatientFile(fileType)) { continue; } String tempFile = FilenameUtils.concat(tempDirLast.getAbsolutePath(), fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected temp file " + f); } FileHelper.writeFileToSharedStorage(disabledFile, f); LOG.info("Copied " + tempFile + " -> " + disabledFile); } continueOrQuit(); //empty the patient files for any extracts while the service was disabled for (int i=indexDisabled+1; i<indexRebulked; i++) { Exchange otherExchangeDisabled = exchanges.get(i); List<String> otherDisabledFiles = hmExchangeFiles.get(otherExchangeDisabled); for (String otherDisabledFile: otherDisabledFiles) { String fileType = findFileType(otherDisabledFile); if (!isPatientFile(fileType)) { continue; } String tempFile = FilenameUtils.concat(tempDirEmpty.getAbsolutePath(), fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected empty file " + f); } FileHelper.writeFileToSharedStorage(otherDisabledFile, f); LOG.info("Copied " + tempFile + " -> " + otherDisabledFile); } } continueOrQuit(); //copy the content of the sharing agreement file from when it was re-bulked for (String rebulkFile: rebulkFiles) { String fileType = findFileType(rebulkFile); if (fileType.equals("Agreements_SharingOrganisation")) { String tempFile = FilenameUtils.concat(tempDir, fileType + ".csv"); File downloadDestination = new File(tempFile); InputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkFile); Files.copy(inputStream, downloadDestination.toPath()); tempFilesCreated.add(tempFile); } } //replace the sharing agreement file for all disabled extracts with the non-disabled one for (int i=indexDisabled; i<indexRebulked; i++) { Exchange exchange = exchanges.get(i); List<String> files = hmExchangeFiles.get(exchange); for (String file: files) { String fileType = findFileType(file); if (fileType.equals("Agreements_SharingOrganisation")) { String tempFile = FilenameUtils.concat(tempDir, fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected empty file " + f); } FileHelper.writeFileToSharedStorage(file, f); LOG.info("Copied " + tempFile + " -> " + file); } } } LOG.info("Finished Fixing Disabled Emis Extracts Prior to Re-bulk for service " + serviceId); continueOrQuit(); for (String tempFileCreated: tempFilesCreated) { File f = new File(tempFileCreated); if (f.exists()) { f.delete(); } }*/ } catch (Exception ex) { LOG.error("", ex); } } private static String findExtractDate(Exchange exchange, Map<Exchange, List<String>> fileMap) throws Exception { List<String> files = fileMap.get(exchange); String file = findSharingAgreementFile(files); String name = FilenameUtils.getBaseName(file); String[] toks = name.split("_"); return toks[3]; } private static boolean isDisabledInSharingAgreementFile(Exchange exchange, Map<Exchange, List<String>> fileMap) throws Exception { List<String> files = fileMap.get(exchange); String file = findSharingAgreementFile(files); InputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(file); CSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); try { Iterator<CSVRecord> iterator = csvParser.iterator(); CSVRecord record = iterator.next(); String s = record.get("Disabled"); boolean disabled = Boolean.parseBoolean(s); return disabled; } finally { csvParser.close(); } } private static void continueOrQuit() throws Exception { LOG.info("Enter y to continue, anything else to quit"); byte[] bytes = new byte[10]; System.in.read(bytes); char c = (char)bytes[0]; if (c != 'y' && c != 'Y') { System.out.println("Read " + c); System.exit(1); } } private static String getGuidColumnName(String fileType) { if (fileType.equals("Admin_Patient")) { //patient file just has patient GUID, nothing extra return null; } else if (fileType.equals("CareRecord_Consultation")) { return "ConsultationGuid"; } else if (fileType.equals("CareRecord_Diary")) { return "DiaryGuid"; } else if (fileType.equals("CareRecord_Observation")) { return "ObservationGuid"; } else if (fileType.equals("CareRecord_Problem")) { //there is no separate problem GUID, as it's just a modified observation return "ObservationGuid"; } else if (fileType.equals("Prescribing_DrugRecord")) { return "DrugRecordGuid"; } else if (fileType.equals("Prescribing_IssueRecord")) { return "IssueRecordGuid"; } else { throw new IllegalArgumentException(fileType); } } private static String findFileType(String filePath) { String fileName = FilenameUtils.getName(filePath); String[] toks = fileName.split("_"); String domain = toks[1]; String name = toks[2]; return domain + "_" + name; } private static boolean isPatientFile(String fileType) { if (fileType.equals("Admin_Patient") || fileType.equals("CareRecord_Consultation") || fileType.equals("CareRecord_Diary") || fileType.equals("CareRecord_Observation") || fileType.equals("CareRecord_Problem") || fileType.equals("Prescribing_DrugRecord") || fileType.equals("Prescribing_IssueRecord")) { //note the referral file doesn't have a Deleted column, so isn't in this list return true; } else { return false; } } private static String findSharingAgreementFile(List<String> files) throws Exception { for (String file : files) { String fileType = findFileType(file); if (fileType.equals("Agreements_SharingOrganisation")) { return file; } } throw new Exception("Failed to find sharing agreement file in " + files.get(0)); } private static void testSlack() { LOG.info("Testing slack"); try { SlackHelper.sendSlackMessage(SlackHelper.Channel.QueueReaderAlerts, "Test Message from Queue Reader"); LOG.info("Finished testing slack"); } catch (Exception ex) { LOG.error("", ex); } } /*private static void postToInboundFromFile(UUID serviceId, UUID systemId, String filePath) { try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); Service service = serviceDalI.getById(serviceId); LOG.info("Posting to inbound exchange for " + service.getName() + " from file " + filePath); FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); int count = 0; List<UUID> exchangeIdBatch = new ArrayList<>(); while (true) { String line = br.readLine(); if (line == null) { break; } UUID exchangeId = UUID.fromString(line); //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); if (audit != null && !audit.isResubmitted()) { audit.setResubmitted(true); auditRepository.save(audit); } count ++; exchangeIdBatch.add(exchangeId); if (exchangeIdBatch.size() >= 1000) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false); exchangeIdBatch = new ArrayList<>(); LOG.info("Done " + count); } } if (!exchangeIdBatch.isEmpty()) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false); LOG.info("Done " + count); } br.close(); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Posting to inbound for " + serviceId); }*/ /*private static void postToInbound(UUID serviceId, boolean all) { LOG.info("Posting to inbound for " + serviceId); try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); Service service = serviceDalI.getById(serviceId); List<UUID> systemIds = findSystemIds(service); UUID systemId = systemIds.get(0); ExchangeTransformErrorState errorState = auditRepository.getErrorState(serviceId, systemId); for (UUID exchangeId: errorState.getExchangeIdsInError()) { //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); //skip any exchange IDs we've already re-queued up to be processed again if (audit.isResubmitted()) { LOG.debug("Not re-posting " + audit.getExchangeId() + " as it's already been resubmitted"); continue; } LOG.debug("Re-posting " + audit.getExchangeId()); audit.setResubmitted(true); auditRepository.save(audit); //then re-submit the exchange to Rabbit MQ for the queue reader to pick up QueueHelper.postToExchange(exchangeId, "EdsInbound", null, false); if (!all) { LOG.info("Posted first exchange, so stopping"); break; } } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Posting to inbound for " + serviceId); }*/ /*private static void fixPatientSearch(String serviceId) { LOG.info("Fixing patient search for " + serviceId); try { UUID serviceUuid = UUID.fromString(serviceId); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); ParserPool parser = new ParserPool(); Set<UUID> patientsDone = new HashSet<>(); List<UUID> exchanges = exchangeDalI.getExchangeIdsForService(serviceUuid); LOG.info("Found " + exchanges.size() + " exchanges"); for (UUID exchangeId: exchanges) { List<ExchangeBatch> batches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); LOG.info("Found " + batches.size() + " batches in exchange " + exchangeId); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } if (patientsDone.contains(patientId)) { continue; } ResourceWrapper wrapper = resourceDalI.getCurrentVersion(serviceUuid, ResourceType.Patient.toString(), patientId); if (wrapper != null) { String json = wrapper.getResourceData(); if (!Strings.isNullOrEmpty(json)) { Patient fhirPatient = (Patient) parser.parse(json); UUID systemUuid = wrapper.getSystemId(); patientSearchDal.update(serviceUuid, systemUuid, fhirPatient); } } patientsDone.add(patientId); if (patientsDone.size() % 1000 == 0) { LOG.info("Done " + patientsDone.size()); } } } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished fixing patient search for " + serviceId); }*/ private static void runSql(String host, String username, String password, String sqlFile) { LOG.info("Running SQL on " + host + " from " + sqlFile); Connection conn = null; Statement statement = null; try { File f = new File(sqlFile); if (!f.exists()) { LOG.error("" + f + " doesn't exist"); return; } List<String> lines = FileUtils.readLines(f); /*String combined = String.join("\n", lines); LOG.info("Going to run SQL"); LOG.info(combined);*/ //load driver Class.forName("com.mysql.cj.jdbc.Driver"); //create connection Properties props = new Properties(); props.setProperty("user", username); props.setProperty("password", password); conn = DriverManager.getConnection(host, props); LOG.info("Opened connection"); statement = conn.createStatement(); long totalStart = System.currentTimeMillis(); for (String sql: lines) { sql = sql.trim(); if (sql.startsWith("--") || sql.startsWith("/*") || Strings.isNullOrEmpty(sql)) { continue; } LOG.info(""); LOG.info(sql); long start = System.currentTimeMillis(); boolean hasResultSet = statement.execute(sql); long end = System.currentTimeMillis(); LOG.info("SQL took " + (end - start) + "ms"); if (hasResultSet) { while (true) { ResultSet rs = statement.getResultSet(); int cols = rs.getMetaData().getColumnCount(); List<String> colHeaders = new ArrayList<>(); for (int i = 0; i < cols; i++) { String header = rs.getMetaData().getColumnName(i + 1); colHeaders.add(header); } String colHeaderStr = String.join(", ", colHeaders); LOG.info(colHeaderStr); while (rs.next()) { List<String> row = new ArrayList<>(); for (int i = 0; i < cols; i++) { Object o = rs.getObject(i + 1); if (rs.wasNull()) { row.add("<null>"); } else { row.add(o.toString()); } } String rowStr = String.join(", ", row); LOG.info(rowStr); } if (!statement.getMoreResults()) { break; } } } else { int updateCount = statement.getUpdateCount(); LOG.info("Updated " + updateCount + " Row(s)"); } } long totalEnd = System.currentTimeMillis(); LOG.info(""); LOG.info("Total time taken " + (totalEnd - totalStart) + "ms"); } catch (Throwable t) { LOG.error("", t); } finally { if (statement != null) { try { statement.close(); } catch (Exception ex) { } } if (conn != null) { try { conn.close(); } catch (Exception ex) { } } LOG.info("Closed connection"); } LOG.info("Finished Testing DB Size Limit"); } /*private static void fixExchangeBatches() { LOG.info("Starting Fixing Exchange Batches"); try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); List<Service> services = serviceDalI.getAll(); for (Service service: services) { LOG.info("Doing " + service.getName()); List<UUID> exchangeIds = exchangeDalI.getExchangeIdsForService(service.getId()); for (UUID exchangeId: exchangeIds) { LOG.info(" Exchange " + exchangeId); List<ExchangeBatch> exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch: exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null) { continue; } List<ResourceWrapper> resources = resourceDalI.getResourcesForBatch(exchangeBatch.getBatchId()); if (resources.isEmpty()) { continue; } ResourceWrapper first = resources.get(0); UUID patientId = first.getPatientId(); if (patientId != null) { exchangeBatch.setEdsPatientId(patientId); exchangeBatchDalI.save(exchangeBatch); LOG.info("Fixed batch " + exchangeBatch.getBatchId() + " -> " + exchangeBatch.getEdsPatientId()); } } } } LOG.info("Finished Fixing Exchange Batches"); } catch (Exception ex) { LOG.error("", ex); } }*/ /** * exports ADT Encounters for patients based on a CSV file produced using the below SQL --USE EDS DATABASE -- barts b5a08769-cbbe-4093-93d6-b696cd1da483 -- homerton 962d6a9a-5950-47ac-9e16-ebee56f9507a create table adt_patients ( service_id character(36), system_id character(36), nhs_number character varying(10), patient_id character(36) ); -- delete from adt_patients; select * from patient_search limit 10; select * from patient_link limit 10; insert into adt_patients select distinct ps.service_id, ps.system_id, ps.nhs_number, ps.patient_id from patient_search ps join patient_link pl on pl.patient_id = ps.patient_id join patient_link pl2 on pl.person_id = pl2.person_id join patient_search ps2 on ps2.patient_id = pl2.patient_id where ps.service_id IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a') and ps2.service_id NOT IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a'); select count(1) from adt_patients limit 100; select * from adt_patients limit 100; ---MOVE TABLE TO HL7 RECEIVER DB select count(1) from adt_patients; -- top 1000 patients with messages select * from mapping.resource_uuid where resource_type = 'Patient' limit 10; select * from log.message limit 10; create table adt_patient_counts ( nhs_number character varying(100), count int ); insert into adt_patient_counts select pid1, count(1) from log.message where pid1 is not null and pid1 <> '' group by pid1; select * from adt_patient_counts order by count desc limit 100; alter table adt_patients add count int; update adt_patients set count = adt_patient_counts.count from adt_patient_counts where adt_patients.nhs_number = adt_patient_counts.nhs_number; select count(1) from adt_patients where nhs_number is null; select * from adt_patients where nhs_number is not null and count is not null order by count desc limit 1000; */ /*private static void exportHl7Encounters(String sourceCsvPath, String outputPath) { LOG.info("Exporting HL7 Encounters from " + sourceCsvPath + " to " + outputPath); try { File sourceFile = new File(sourceCsvPath); CSVParser csvParser = CSVParser.parse(sourceFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); //"service_id","system_id","nhs_number","patient_id","count" int count = 0; HashMap<UUID, List<UUID>> serviceAndSystemIds = new HashMap<>(); HashMap<UUID, Integer> patientIds = new HashMap<>(); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); count ++; String serviceId = csvRecord.get("service_id"); String systemId = csvRecord.get("system_id"); String patientId = csvRecord.get("patient_id"); UUID serviceUuid = UUID.fromString(serviceId); List<UUID> systemIds = serviceAndSystemIds.get(serviceUuid); if (systemIds == null) { systemIds = new ArrayList<>(); serviceAndSystemIds.put(serviceUuid, systemIds); } systemIds.add(UUID.fromString(systemId)); patientIds.put(UUID.fromString(patientId), new Integer(count)); } csvParser.close(); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ParserPool parser = new ParserPool(); Map<Integer, List<Object[]>> patientRows = new HashMap<>(); SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (UUID serviceId: serviceAndSystemIds.keySet()) { //List<UUID> systemIds = serviceAndSystemIds.get(serviceId); Service service = serviceDalI.getById(serviceId); String serviceName = service.getName(); LOG.info("Doing service " + serviceId + " " + serviceName); List<UUID> exchangeIds = exchangeDalI.getExchangeIdsForService(serviceId); LOG.info("Got " + exchangeIds.size() + " exchange IDs to scan"); int exchangeCount = 0; for (UUID exchangeId: exchangeIds) { exchangeCount ++; if (exchangeCount % 1000 == 0) { LOG.info("Done " + exchangeCount + " exchanges"); } List<ExchangeBatch> exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch: exchangeBatches) { UUID patientId = exchangeBatch.getEdsPatientId(); if (patientId != null && !patientIds.containsKey(patientId)) { continue; } Integer patientIdInt = patientIds.get(patientId); //get encounters for exchange batch UUID batchId = exchangeBatch.getBatchId(); List<ResourceWrapper> resourceWrappers = resourceDalI.getResourcesForBatch(serviceId, batchId); for (ResourceWrapper resourceWrapper: resourceWrappers) { if (resourceWrapper.isDeleted()) { continue; } String resourceType = resourceWrapper.getResourceType(); if (!resourceType.equals(ResourceType.Encounter.toString())) { continue; } LOG.info("Processing " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId()); String json = resourceWrapper.getResourceData(); Encounter fhirEncounter = (Encounter)parser.parse(json); Date date = null; if (fhirEncounter.hasPeriod()) { Period period = fhirEncounter.getPeriod(); if (period.hasStart()) { date = period.getStart(); } } String episodeId = null; if (fhirEncounter.hasEpisodeOfCare()) { Reference episodeReference = fhirEncounter.getEpisodeOfCare().get(0); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(episodeReference); EpisodeOfCare fhirEpisode = (EpisodeOfCare)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirEpisode != null) { if (fhirEpisode.hasIdentifier()) { episodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_BARTS_FIN_EPISODE_ID); if (Strings.isNullOrEmpty(episodeId)) { episodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_HOMERTON_FIN_EPISODE_ID); } } } } String adtType = null; String adtCode = null; Extension extension = ExtensionConverter.findExtension(fhirEncounter, FhirExtensionUri.HL7_MESSAGE_TYPE); if (extension != null) { CodeableConcept codeableConcept = (CodeableConcept) extension.getValue(); Coding hl7MessageTypeCoding = CodeableConceptHelper.findCoding(codeableConcept, FhirUri.CODE_SYSTEM_HL7V2_MESSAGE_TYPE); if (hl7MessageTypeCoding != null) { adtType = hl7MessageTypeCoding.getDisplay(); adtCode = hl7MessageTypeCoding.getCode(); } } else { //for older formats of the transformed resources, the HL7 message type can only be found from the raw original exchange body try { Exchange exchange = exchangeDalI.getExchange(exchangeId); String exchangeBody = exchange.getBody(); Bundle bundle = (Bundle) FhirResourceHelper.deserialiseResouce(exchangeBody); for (Bundle.BundleEntryComponent entry: bundle.getEntry()) { if (entry.getResource() != null && entry.getResource() instanceof MessageHeader) { MessageHeader header = (MessageHeader)entry.getResource(); if (header.hasEvent()) { Coding coding = header.getEvent(); adtType = coding.getDisplay(); adtCode = coding.getCode(); } } } } catch (Exception ex) { //if the exchange body isn't a FHIR bundle, then we'll get an error by treating as such, so just ignore them } } String cls = null; if (fhirEncounter.hasClass_()) { Encounter.EncounterClass encounterClass = fhirEncounter.getClass_(); if (encounterClass == Encounter.EncounterClass.OTHER && fhirEncounter.hasClass_Element() && fhirEncounter.getClass_Element().hasExtension()) { for (Extension classExtension: fhirEncounter.getClass_Element().getExtension()) { if (classExtension.getUrl().equals(FhirExtensionUri.ENCOUNTER_CLASS)) { //not 100% of the type of the value, so just append to a String cls = "" + classExtension.getValue(); } } } if (Strings.isNullOrEmpty(cls)) { cls = encounterClass.toCode(); } } String type = null; if (fhirEncounter.hasType()) { //only seem to ever have one type CodeableConcept codeableConcept = fhirEncounter.getType().get(0); type = codeableConcept.getText(); } String status = null; if (fhirEncounter.hasStatus()) { Encounter.EncounterState encounterState = fhirEncounter.getStatus(); status = encounterState.toCode(); } String location = null; String locationType = null; if (fhirEncounter.hasLocation()) { //first location is always the current location Encounter.EncounterLocationComponent encounterLocation = fhirEncounter.getLocation().get(0); if (encounterLocation.hasLocation()) { Reference locationReference = encounterLocation.getLocation(); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(locationReference); Location fhirLocation = (Location)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirLocation != null) { if (fhirLocation.hasName()) { location = fhirLocation.getName(); } if (fhirLocation.hasType()) { CodeableConcept typeCodeableConcept = fhirLocation.getType(); if (typeCodeableConcept.hasCoding()) { Coding coding = typeCodeableConcept.getCoding().get(0); locationType = coding.getDisplay(); } } } } } String clinician = null; if (fhirEncounter.hasParticipant()) { //first participant seems to be the interesting one Encounter.EncounterParticipantComponent encounterParticipant = fhirEncounter.getParticipant().get(0); if (encounterParticipant.hasIndividual()) { Reference practitionerReference = encounterParticipant.getIndividual(); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(practitionerReference); Practitioner fhirPractitioner = (Practitioner)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirPractitioner != null) { if (fhirPractitioner.hasName()) { HumanName name = fhirPractitioner.getName(); clinician = name.getText(); if (Strings.isNullOrEmpty(clinician)) { clinician = ""; for (StringType s: name.getPrefix()) { clinician += s.getValueNotNull(); clinician += " "; } for (StringType s: name.getGiven()) { clinician += s.getValueNotNull(); clinician += " "; } for (StringType s: name.getFamily()) { clinician += s.getValueNotNull(); clinician += " "; } clinician = clinician.trim(); } } } } } Object[] row = new Object[12]; row[0] = serviceName; row[1] = patientIdInt.toString(); row[2] = sdfOutput.format(date); row[3] = episodeId; row[4] = adtCode; row[5] = adtType; row[6] = cls; row[7] = type; row[8] = status; row[9] = location; row[10] = locationType; row[11] = clinician; List<Object[]> rows = patientRows.get(patientIdInt); if (rows == null) { rows = new ArrayList<>(); patientRows.put(patientIdInt, rows); } rows.add(row); } } } } String[] outputColumnHeaders = new String[] {"Source", "Patient", "Date", "Episode ID", "ADT Message Code", "ADT Message Type", "Class", "Type", "Status", "Location", "Location Type", "Clinician"}; FileWriter fileWriter = new FileWriter(outputPath); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVFormat format = CSVFormat.DEFAULT .withHeader(outputColumnHeaders) .withQuote('"'); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format); for (int i=0; i <= count; i++) { Integer patientIdInt = new Integer(i); List<Object[]> rows = patientRows.get(patientIdInt); if (rows != null) { for (Object[] row: rows) { csvPrinter.printRecord(row); } } } csvPrinter.close(); bufferedWriter.close(); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Exporting Encounters from " + sourceCsvPath + " to " + outputPath); }*/ /*private static void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info(""); try { Thread.sleep(5000); } catch (Throwable ex) { LOG.error("", ex); } LOG.info("Done"); } }); }*/ private static void findEmisStartDates(String path, String outputPath) { LOG.info("Finding EMIS Start Dates in " + path + ", writing to " + outputPath); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH.mm.ss"); Map<String, Date> startDates = new HashMap<>(); Map<String, String> servers = new HashMap<>(); Map<String, String> names = new HashMap<>(); Map<String, String> odsCodes = new HashMap<>(); Map<String, String> cdbNumbers = new HashMap<>(); Map<String, Set<String>> distinctPatients = new HashMap<>(); File root = new File(path); for (File sftpRoot: root.listFiles()) { LOG.info("Checking " + sftpRoot); Map<Date, File> extracts = new HashMap<>(); List<Date> extractDates = new ArrayList<>(); for (File extractRoot: sftpRoot.listFiles()) { Date d = sdf.parse(extractRoot.getName()); //LOG.info("" + extractRoot.getName() + " -> " + d); extracts.put(d, extractRoot); extractDates.add(d); } Collections.sort(extractDates); for (Date extractDate: extractDates) { File extractRoot = extracts.get(extractDate); LOG.info("Checking " + extractRoot); //read the sharing agreements file //e.g. 291_Agreements_SharingOrganisation_20150211164536_45E7CD20-EE37-41AB-90D6-DC9D4B03D102.csv File sharingAgreementsFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("agreements_sharingorganisation") > -1 && name.endsWith(".csv")) { sharingAgreementsFile = f; break; } } if (sharingAgreementsFile == null) { LOG.info("Null agreements file for " + extractRoot); continue; } CSVParser csvParser = CSVParser.parse(sharingAgreementsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String activated = csvRecord.get("IsActivated"); String disabled = csvRecord.get("Disabled"); servers.put(orgGuid, sftpRoot.getName()); if (activated.equalsIgnoreCase("true")) { if (disabled.equalsIgnoreCase("false")) { Date d = sdf.parse(extractRoot.getName()); Date existingDate = startDates.get(orgGuid); if (existingDate == null) { startDates.put(orgGuid, d); } } else { if (startDates.containsKey(orgGuid)) { startDates.put(orgGuid, null); } } } } } finally { csvParser.close(); } //go through orgs file to get name, ods and cdb codes File orgsFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("admin_organisation_") > -1 && name.endsWith(".csv")) { orgsFile = f; break; } } csvParser = CSVParser.parse(orgsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String name = csvRecord.get("OrganisationName"); String odsCode = csvRecord.get("ODSCode"); String cdb = csvRecord.get("CDB"); names.put(orgGuid, name); odsCodes.put(orgGuid, odsCode); cdbNumbers.put(orgGuid, cdb); } } finally { csvParser.close(); } //go through patients file to get count File patientFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("admin_patient_") > -1 && name.endsWith(".csv")) { patientFile = f; break; } } csvParser = CSVParser.parse(patientFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String patientGuid = csvRecord.get("PatientGuid"); String deleted = csvRecord.get("Deleted"); Set<String> distinctPatientSet = distinctPatients.get(orgGuid); if (distinctPatientSet == null) { distinctPatientSet = new HashSet<>(); distinctPatients.put(orgGuid, distinctPatientSet); } if (deleted.equalsIgnoreCase("true")) { distinctPatientSet.remove(patientGuid); } else { distinctPatientSet.add(patientGuid); } } } finally { csvParser.close(); } } } SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd"); StringBuilder sb = new StringBuilder(); sb.append("Name,OdsCode,CDB,OrgGuid,StartDate,Server,Patients"); for (String orgGuid: startDates.keySet()) { Date startDate = startDates.get(orgGuid); String server = servers.get(orgGuid); String name = names.get(orgGuid); String odsCode = odsCodes.get(orgGuid); String cdbNumber = cdbNumbers.get(orgGuid); Set<String> distinctPatientSet = distinctPatients.get(orgGuid); String startDateDesc = null; if (startDate != null) { startDateDesc = sdfOutput.format(startDate); } Long countDistinctPatients = null; if (distinctPatientSet != null) { countDistinctPatients = new Long(distinctPatientSet.size()); } sb.append("\n"); sb.append("\"" + name + "\""); sb.append(","); sb.append("\"" + odsCode + "\""); sb.append(","); sb.append("\"" + cdbNumber + "\""); sb.append(","); sb.append("\"" + orgGuid + "\""); sb.append(","); sb.append(startDateDesc); sb.append(","); sb.append("\"" + server + "\""); sb.append(","); sb.append(countDistinctPatients); } LOG.info(sb.toString()); FileUtils.writeStringToFile(new File(outputPath), sb.toString()); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Finding Start Dates in " + path + ", writing to " + outputPath); } private static void findEncounterTerms(String path, String outputPath) { LOG.info("Finding Encounter Terms from " + path); Map<String, Long> hmResults = new HashMap<>(); //source term, source term snomed ID, source term snomed term - count try { File root = new File(path); File[] files = root.listFiles(); for (File readerRoot: files) { //emis001 LOG.info("Finding terms in " + readerRoot); //first read in all the coding files to build up our map of codes Map<String, String> hmCodes = new HashMap<>(); for (File dateFolder: readerRoot.listFiles()) { LOG.info("Looking for codes in " + dateFolder); File f = findFile(dateFolder, "Coding_ClinicalCode"); if (f == null) { LOG.error("Failed to find coding file in " + dateFolder.getAbsolutePath()); continue; } CSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String codeId = csvRecord.get("CodeId"); String term = csvRecord.get("Term"); String snomed = csvRecord.get("SnomedCTConceptId"); hmCodes.put(codeId, snomed + ",\"" + term + "\""); } csvParser.close(); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date cutoff = dateFormat.parse("2017-01-01"); //now process the consultation files themselves for (File dateFolder: readerRoot.listFiles()) { LOG.info("Looking for consultations in " + dateFolder); File f = findFile(dateFolder, "CareRecord_Consultation"); if (f == null) { LOG.error("Failed to find consultation file in " + dateFolder.getAbsolutePath()); continue; } CSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String term = csvRecord.get("ConsultationSourceTerm"); String codeId = csvRecord.get("ConsultationSourceCodeId"); if (Strings.isNullOrEmpty(term) && Strings.isNullOrEmpty(codeId)) { continue; } String date = csvRecord.get("EffectiveDate"); if (Strings.isNullOrEmpty(date)) { continue; } Date d = dateFormat.parse(date); if (d.before(cutoff)) { continue; } String line = "\"" + term + "\","; if (!Strings.isNullOrEmpty(codeId)) { String codeLookup = hmCodes.get(codeId); if (codeLookup == null) { LOG.error("Failed to find lookup for codeID " + codeId); continue; } line += codeLookup; } else { line += ","; } Long count = hmResults.get(line); if (count == null) { count = new Long(1); } else { count = new Long(count.longValue() + 1); } hmResults.put(line, count); } csvParser.close(); } } //save results to file StringBuilder output = new StringBuilder(); output.append("\"consultation term\",\"snomed concept ID\",\"snomed term\",\"count\""); output.append("\r\n"); for (String line: hmResults.keySet()) { Long count = hmResults.get(line); String combined = line + "," + count; output.append(combined); output.append("\r\n"); } LOG.info("FInished"); LOG.info(output.toString()); FileUtils.writeStringToFile(new File(outputPath), output.toString()); LOG.info("written output to " + outputPath); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished finding Encounter Terms from " + path); } private static File findFile(File root, String token) throws Exception { for (File f: root.listFiles()) { String s = f.getName(); if (s.indexOf(token) > -1) { return f; } } return null; } /*private static void populateProtocolQueue(String serviceIdStr, String startingExchangeId) { LOG.info("Starting Populating Protocol Queue for " + serviceIdStr); ServiceDalI serviceRepository = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); if (serviceIdStr.equalsIgnoreCase("All")) { serviceIdStr = null; } try { List<Service> services = new ArrayList<>(); if (Strings.isNullOrEmpty(serviceIdStr)) { services = serviceRepository.getAll(); } else { UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); services.add(service); } for (Service service: services) { List<UUID> exchangeIds = auditRepository.getExchangeIdsForService(service.getId()); LOG.info("Found " + exchangeIds.size() + " exchangeIds for " + service.getName()); if (startingExchangeId != null) { UUID startingExchangeUuid = UUID.fromString(startingExchangeId); if (exchangeIds.contains(startingExchangeUuid)) { //if in the list, remove everything up to and including the starting exchange int index = exchangeIds.indexOf(startingExchangeUuid); LOG.info("Found starting exchange " + startingExchangeId + " at " + index + " so removing up to this point"); for (int i=index; i>=0; i--) { exchangeIds.remove(i); } startingExchangeId = null; } else { //if not in the list, skip all these exchanges LOG.info("List doesn't contain starting exchange " + startingExchangeId + " so skipping"); continue; } } QueueHelper.postToExchange(exchangeIds, "edsProtocol", null, true); } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Populating Protocol Queue for " + serviceIdStr); }*/ /*private static void findDeletedOrgs() { LOG.info("Starting finding deleted orgs"); ServiceDalI serviceRepository = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); List<Service> services = new ArrayList<>(); try { for (Service service: serviceRepository.getAll()) { services.add(service); } } catch (Exception ex) { LOG.error("", ex); } services.sort((o1, o2) -> { String name1 = o1.getName(); String name2 = o2.getName(); return name1.compareToIgnoreCase(name2); }); for (Service service: services) { try { UUID serviceUuid = service.getId(); List<Exchange> exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 1, new Date(0), new Date()); LOG.info("Service: " + service.getName() + " " + service.getLocalId()); if (exchangeByServices.isEmpty()) { LOG.info(" no exchange found!"); continue; } Exchange exchangeByService = exchangeByServices.get(0); UUID exchangeId = exchangeByService.getId(); Exchange exchange = auditRepository.getExchange(exchangeId); Map<String, String> headers = exchange.getHeaders(); String systemUuidStr = headers.get(HeaderKeys.SenderSystemUuid); UUID systemUuid = UUID.fromString(systemUuidStr); int batches = countBatches(exchangeId, serviceUuid, systemUuid); LOG.info(" Most recent exchange had " + batches + " batches"); if (batches > 1 && batches < 2000) { continue; } //go back until we find the FIRST exchange where it broke exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 250, new Date(0), new Date()); for (int i=0; i<exchangeByServices.size(); i++) { exchangeByService = exchangeByServices.get(i); exchangeId = exchangeByService.getId(); batches = countBatches(exchangeId, serviceUuid, systemUuid); exchange = auditRepository.getExchange(exchangeId); Date timestamp = exchange.getTimestamp(); if (batches < 1 || batches > 2000) { LOG.info(" " + timestamp + " had " + batches); } if (batches > 1 && batches < 2000) { LOG.info(" " + timestamp + " had " + batches); break; } } } catch (Exception ex) { LOG.error("", ex); } } LOG.info("Finished finding deleted orgs"); }*/ private static int countBatches(UUID exchangeId, UUID serviceId, UUID systemId) throws Exception { int batches = 0; ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId); for (ExchangeTransformAudit audit: audits) { if (audit.getNumberBatchesCreated() != null) { batches += audit.getNumberBatchesCreated(); } } return batches; } /*private static void fixExchanges(UUID justThisService) { LOG.info("Fixing exchanges"); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId : exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } boolean changed = false; String body = exchange.getBody(); String[] files = body.split("\n"); if (files.length == 0) { continue; } for (int i=0; i<files.length; i++) { String original = files[i]; //remove /r characters String trimmed = original.trim(); //add the new prefix if (!trimmed.startsWith("sftpreader/EMIS001/")) { trimmed = "sftpreader/EMIS001/" + trimmed; } if (!original.equals(trimmed)) { files[i] = trimmed; changed = true; } } if (changed) { LOG.info("Fixed exchange " + exchangeId); LOG.info(body); body = String.join("\n", files); exchange.setBody(body); AuditWriter.writeExchange(exchange); } } } LOG.info("Fixed exchanges"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void deleteDataForService(UUID serviceId) { Service dbService = new ServiceRepository().getById(serviceId); //the delete will take some time, so do the delete in a separate thread LOG.info("Deleting all data for service " + dbService.getName() + " " + dbService.getId()); FhirDeletionService deletor = new FhirDeletionService(dbService); try { deletor.deleteData(); LOG.info("Completed deleting all data for service " + dbService.getName() + " " + dbService.getId()); } catch (Exception ex) { LOG.error("Error deleting service " + dbService.getName() + " " + dbService.getId(), ex); } }*/ /*private static void fixProblems(UUID serviceId, String sharedStoragePath, boolean testMode) { LOG.info("Fixing problems for service " + serviceId); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); List<ExchangeByService> exchangeByServiceList = auditRepository.getExchangesByService(serviceId, Integer.MAX_VALUE); //go backwards as the most recent is first for (int i=exchangeByServiceList.size()-1; i>=0; i--) { ExchangeByService exchangeByService = exchangeByServiceList.get(i); UUID exchangeId = exchangeByService.getExchangeId(); LOG.info("Doing exchange " + exchangeId); EmisCsvHelper helper = null; try { Exchange exchange = AuditWriter.readExchange(exchangeId); String exchangeBody = exchange.getBody(); String[] files = exchangeBody.split(java.lang.System.lineSeparator()); File orgDirectory = validateAndFindCommonDirectory(sharedStoragePath, files); Map<Class, AbstractCsvParser> allParsers = new HashMap<>(); String properVersion = null; String[] versions = new String[]{EmisCsvToFhirTransformer.VERSION_5_0, EmisCsvToFhirTransformer.VERSION_5_1, EmisCsvToFhirTransformer.VERSION_5_3, EmisCsvToFhirTransformer.VERSION_5_4}; for (String version: versions) { try { List<AbstractCsvParser> parsers = new ArrayList<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(Observation.class, orgDirectory, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(DrugRecord.class, orgDirectory, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(IssueRecord.class, orgDirectory, version, true, parsers); for (AbstractCsvParser parser: parsers) { Class cls = parser.getClass(); allParsers.put(cls, parser); } properVersion = version; } catch (Exception ex) { //ignore } } if (allParsers.isEmpty()) { throw new Exception("Failed to open parsers for exchange " + exchangeId + " in folder " + orgDirectory); } UUID systemId = exchange.getHeaderAsUuid(HeaderKeys.SenderSystemUuid); //FhirResourceFiler dummyFiler = new FhirResourceFiler(exchangeId, serviceId, systemId, null, null, 10); if (helper == null) { helper = new EmisCsvHelper(findDataSharingAgreementGuid(new ArrayList<>(allParsers.values()))); } ObservationPreTransformer.transform(properVersion, allParsers, null, helper); IssueRecordPreTransformer.transform(properVersion, allParsers, null, helper); DrugRecordPreTransformer.transform(properVersion, allParsers, null, helper); Map<String, List<String>> problemChildren = helper.getProblemChildMap(); List<ExchangeBatch> exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (Map.Entry<String, List<String>> entry : problemChildren.entrySet()) { String patientLocallyUniqueId = entry.getKey().split(":")[0]; UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientLocallyUniqueId); if (edsPatientId == null) { throw new Exception("Failed to find edsPatientId for local Patient ID " + patientLocallyUniqueId + " in exchange " + exchangeId); } //find the batch ID for our patient UUID batchId = null; for (ExchangeBatch exchangeBatch: exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null && exchangeBatch.getEdsPatientId().equals(edsPatientId)) { batchId = exchangeBatch.getBatchId(); break; } } if (batchId == null) { throw new Exception("Failed to find batch ID for eds Patient ID " + edsPatientId + " in exchange " + exchangeId); } //find the EDS ID for our problem UUID edsProblemId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Condition, entry.getKey()); if (edsProblemId == null) { LOG.warn("No edsProblemId found for local ID " + entry.getKey() + " - assume bad data referring to non-existing problem?"); //throw new Exception("Failed to find edsProblemId for local Patient ID " + problemLocallyUniqueId + " in exchange " + exchangeId); } //convert our child IDs to EDS references List<Reference> references = new ArrayList<>(); HashSet<String> contentsSet = new HashSet<>(); contentsSet.addAll(entry.getValue()); for (String referenceValue : contentsSet) { Reference reference = ReferenceHelper.createReference(referenceValue); ReferenceComponents components = ReferenceHelper.getReferenceComponents(reference); String locallyUniqueId = components.getId(); ResourceType resourceType = components.getResourceType(); UUID edsResourceId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); Reference globallyUniqueReference = ReferenceHelper.createReference(resourceType, edsResourceId.toString()); references.add(globallyUniqueReference); } //find the resource for the problem itself ResourceByExchangeBatch problemResourceByExchangeBatch = null; List<ResourceByExchangeBatch> resources = resourceRepository.getResourcesForBatch(batchId, ResourceType.Condition.toString()); for (ResourceByExchangeBatch resourceByExchangeBatch: resources) { if (resourceByExchangeBatch.getResourceId().equals(edsProblemId)) { problemResourceByExchangeBatch = resourceByExchangeBatch; break; } } if (problemResourceByExchangeBatch == null) { throw new Exception("Problem not found for edsProblemId " + edsProblemId + " for exchange " + exchangeId); } if (problemResourceByExchangeBatch.getIsDeleted()) { LOG.warn("Problem " + edsProblemId + " is deleted, so not adding to it for exchange " + exchangeId); continue; } String json = problemResourceByExchangeBatch.getResourceData(); Condition fhirProblem = (Condition)PARSER_POOL.parse(json); //update the problems if (fhirProblem.hasContained()) { if (fhirProblem.getContained().size() > 1) { throw new Exception("Problem " + edsProblemId + " is has " + fhirProblem.getContained().size() + " contained resources for exchange " + exchangeId); } fhirProblem.getContained().clear(); } List_ list = new List_(); list.setId("Items"); fhirProblem.getContained().add(list); Extension extension = ExtensionConverter.findExtension(fhirProblem, FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE); if (extension == null) { Reference listReference = ReferenceHelper.createInternalReference("Items"); fhirProblem.addExtension(ExtensionConverter.createExtension(FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE, listReference)); } for (Reference reference : references) { list.addEntry().setItem(reference); } String newJson = FhirSerializationHelper.serializeResource(fhirProblem); if (newJson.equals(json)) { LOG.warn("Skipping edsProblemId " + edsProblemId + " as JSON hasn't changed"); continue; } problemResourceByExchangeBatch.setResourceData(newJson); String resourceType = problemResourceByExchangeBatch.getResourceType(); UUID versionUuid = problemResourceByExchangeBatch.getVersion(); ResourceHistory problemResourceHistory = resourceRepository.getResourceHistoryByKey(edsProblemId, resourceType, versionUuid); problemResourceHistory.setResourceData(newJson); problemResourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); ResourceByService problemResourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType, edsProblemId); if (problemResourceByService.getResourceData() == null) { problemResourceByService = null; LOG.warn("Not updating edsProblemId " + edsProblemId + " for exchange " + exchangeId + " as it's been subsequently delrted"); } else { problemResourceByService.setResourceData(newJson); } //save back to THREE tables if (!testMode) { resourceRepository.save(problemResourceByExchangeBatch); resourceRepository.save(problemResourceHistory); if (problemResourceByService != null) { resourceRepository.save(problemResourceByService); } LOG.info("Fixed edsProblemId " + edsProblemId + " for exchange Id " + exchangeId); } else { LOG.info("Would change edsProblemId " + edsProblemId + " to new JSON"); LOG.info(newJson); } } } catch (Exception ex) { LOG.error("Failed on exchange " + exchangeId, ex); break; } } LOG.info("Finished fixing problems for service " + serviceId); } private static String findDataSharingAgreementGuid(List<AbstractCsvParser> parsers) throws Exception { //we need a file name to work out the data sharing agreement ID, so just the first file we can find File f = parsers .iterator() .next() .getFile(); String name = Files.getNameWithoutExtension(f.getName()); String[] toks = name.split("_"); if (toks.length != 5) { throw new TransformException("Failed to extract data sharing agreement GUID from filename " + f.getName()); } return toks[4]; } private static void closeParsers(Collection<AbstractCsvParser> parsers) { for (AbstractCsvParser parser : parsers) { try { parser.close(); } catch (IOException ex) { //don't worry if this fails, as we're done anyway } } } private static File validateAndFindCommonDirectory(String sharedStoragePath, String[] files) throws Exception { String organisationDir = null; for (String file: files) { File f = new File(sharedStoragePath, file); if (!f.exists()) { LOG.error("Failed to find file {} in shared storage {}", file, sharedStoragePath); throw new FileNotFoundException("" + f + " doesn't exist"); } //LOG.info("Successfully found file {} in shared storage {}", file, sharedStoragePath); try { File orgDir = f.getParentFile(); if (organisationDir == null) { organisationDir = orgDir.getAbsolutePath(); } else { if (!organisationDir.equalsIgnoreCase(orgDir.getAbsolutePath())) { throw new Exception(); } } } catch (Exception ex) { throw new FileNotFoundException("" + f + " isn't in the expected directory structure within " + organisationDir); } } return new File(organisationDir); }*/ /*private static void testLogging() { while (true) { System.out.println("Checking logging at " + System.currentTimeMillis()); try { Thread.sleep(4000); } catch (Exception e) { e.printStackTrace(); } LOG.trace("trace logging"); LOG.debug("debug logging"); LOG.info("info logging"); LOG.warn("warn logging"); LOG.error("error logging"); } } */ /*private static void fixExchangeProtocols() { LOG.info("Fixing exchange protocols"); AuditRepository auditRepository = new AuditRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.Exchange LIMIT 1000;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); LOG.info("Processing exchange " + exchangeId); Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } UUID serviceId = UUID.fromString(serviceIdStr); List<String> newIds = new ArrayList<>(); String protocolJson = headers.get(HeaderKeys.Protocols); if (!headers.containsKey(HeaderKeys.Protocols)) { try { List<LibraryItem> libraryItemList = LibraryRepositoryHelper.getProtocolsByServiceId(serviceIdStr); // Get protocols where service is publisher newIds = libraryItemList.stream() .filter( libraryItem -> libraryItem.getProtocol().getServiceContract().stream() .anyMatch(sc -> sc.getType().equals(ServiceContractType.PUBLISHER) && sc.getService().getUuid().equals(serviceIdStr))) .map(t -> t.getUuid().toString()) .collect(Collectors.toList()); } catch (Exception e) { LOG.error("Failed to find protocols for exchange " + exchange.getExchangeId(), e); continue; } } else { try { JsonNode node = ObjectMapperPool.getInstance().readTree(protocolJson); for (int i = 0; i < node.size(); i++) { JsonNode libraryItemNode = node.get(i); JsonNode idNode = libraryItemNode.get("uuid"); String id = idNode.asText(); newIds.add(id); } } catch (Exception e) { LOG.error("Failed to read Json from " + protocolJson + " for exchange " + exchange.getExchangeId(), e); continue; } } try { if (newIds.isEmpty()) { headers.remove(HeaderKeys.Protocols); } else { String protocolsJson = ObjectMapperPool.getInstance().writeValueAsString(newIds.toArray()); headers.put(HeaderKeys.Protocols, protocolsJson); } } catch (JsonProcessingException e) { LOG.error("Unable to serialize protocols to JSON for exchange " + exchange.getExchangeId(), e); continue; } try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(headerJson); } catch (JsonProcessingException e) { LOG.error("Failed to write exchange headers to Json for exchange " + exchange.getExchangeId(), e); continue; } auditRepository.save(exchange); } LOG.info("Finished fixing exchange protocols"); }*/ /*private static void fixExchangeHeaders() { LOG.info("Fixing exchange headers"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); OrganisationRepository organisationRepository = new OrganisationRepository(); List<Exchange> exchanges = new AuditRepository().getAllExchanges(); for (Exchange exchange: exchanges) { String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } if (headers.containsKey(HeaderKeys.SenderLocalIdentifier) && headers.containsKey(HeaderKeys.SenderOrganisationUuid)) { continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); Map<UUID, String> orgMap = service.getOrganisations(); if (orgMap.size() != 1) { LOG.error("Wrong number of orgs in service " + serviceId + " for exchange " + exchange.getExchangeId()); continue; } UUID orgId = orgMap .keySet() .stream() .collect(StreamExtension.firstOrNullCollector()); Organisation organisation = organisationRepository.getById(orgId); String odsCode = organisation.getNationalId(); headers.put(HeaderKeys.SenderLocalIdentifier, odsCode); headers.put(HeaderKeys.SenderOrganisationUuid, orgId.toString()); try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setHeaders(headerJson); auditRepository.save(exchange); LOG.info("Creating exchange " + exchange.getExchangeId()); } LOG.info("Finished fixing exchange headers"); }*/ /*private static void fixExchangeHeaders() { LOG.info("Fixing exchange headers"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); OrganisationRepository organisationRepository = new OrganisationRepository(); LibraryRepository libraryRepository = new LibraryRepository(); List<Exchange> exchanges = new AuditRepository().getAllExchanges(); for (Exchange exchange: exchanges) { String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } boolean changed = false; UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); try { List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint : endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); String endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString(); ActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId); Item item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId()); LibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent()); System system = libraryItem.getSystem(); for (TechnicalInterface technicalInterface : system.getTechnicalInterface()) { if (endpointInterfaceId.equals(technicalInterface.getUuid())) { if (!headers.containsKey(HeaderKeys.SourceSystem)) { headers.put(HeaderKeys.SourceSystem, technicalInterface.getMessageFormat()); changed = true; } if (!headers.containsKey(HeaderKeys.SystemVersion)) { headers.put(HeaderKeys.SystemVersion, technicalInterface.getMessageFormatVersion()); changed = true; } if (!headers.containsKey(HeaderKeys.SenderSystemUuid)) { headers.put(HeaderKeys.SenderSystemUuid, endpointSystemId.toString()); changed = true; } } } } } catch (Exception e) { LOG.error("Failed to find endpoint details for " + exchange.getExchangeId()); continue; } if (changed) { try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setHeaders(headerJson); auditRepository.save(exchange); LOG.info("Fixed exchange " + exchange.getExchangeId()); } } LOG.info("Finished fixing exchange headers"); }*/ /*private static void testConnection(String configName) { try { JsonNode config = ConfigManager.getConfigurationAsJson(configName, "enterprise"); String driverClass = config.get("driverClass").asText(); String url = config.get("url").asText(); String username = config.get("username").asText(); String password = config.get("password").asText(); //force the driver to be loaded Class.forName(driverClass); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); LOG.info("Connection ok"); conn.close(); } catch (Exception e) { LOG.error("", e); } }*/ /*private static void testConnection() { try { JsonNode config = ConfigManager.getConfigurationAsJson("postgres", "enterprise"); String url = config.get("url").asText(); String username = config.get("username").asText(); String password = config.get("password").asText(); //force the driver to be loaded Class.forName("org.postgresql.Driver"); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); LOG.info("Connection ok"); conn.close(); } catch (Exception e) { LOG.error("", e); } }*/ /*private static void startEnterpriseStream(UUID serviceId, String configName, UUID exchangeIdStartFrom, UUID batchIdStartFrom) throws Exception { LOG.info("Starting Enterprise Streaming for " + serviceId + " using " + configName + " starting from exchange " + exchangeIdStartFrom + " and batch " + batchIdStartFrom); LOG.info("Testing database connection"); testConnection(configName); Service service = new ServiceRepository().getById(serviceId); List<UUID> orgIds = new ArrayList<>(service.getOrganisations().keySet()); UUID orgId = orgIds.get(0); List<ExchangeByService> exchangeByServiceList = new AuditRepository().getExchangesByService(serviceId, Integer.MAX_VALUE); for (int i=exchangeByServiceList.size()-1; i>=0; i--) { ExchangeByService exchangeByService = exchangeByServiceList.get(i); //for (ExchangeByService exchangeByService: exchangeByServiceList) { UUID exchangeId = exchangeByService.getExchangeId(); if (exchangeIdStartFrom != null) { if (!exchangeIdStartFrom.equals(exchangeId)) { continue; } else { //once we have a match, set to null so we don't skip any subsequent ones exchangeIdStartFrom = null; } } Exchange exchange = AuditWriter.readExchange(exchangeId); String senderOrgUuidStr = exchange.getHeader(HeaderKeys.SenderOrganisationUuid); UUID senderOrgUuid = UUID.fromString(senderOrgUuidStr); //this one had 90,000 batches and doesn't need doing again *//*if (exchangeId.equals(UUID.fromString("b9b93be0-afd8-11e6-8c16-c1d5a00342f3"))) { LOG.info("Skipping exchange " + exchangeId); continue; }*//* List<ExchangeBatch> exchangeBatches = new ExchangeBatchRepository().retrieveForExchangeId(exchangeId); LOG.info("Processing exchange " + exchangeId + " with " + exchangeBatches.size() + " batches"); for (int j=0; j<exchangeBatches.size(); j++) { ExchangeBatch exchangeBatch = exchangeBatches.get(j); UUID batchId = exchangeBatch.getBatchId(); if (batchIdStartFrom != null) { if (!batchIdStartFrom.equals(batchId)) { continue; } else { batchIdStartFrom = null; } } LOG.info("Processing exchange " + exchangeId + " and batch " + batchId + " " + (j+1) + "/" + exchangeBatches.size()); try { String outbound = FhirToEnterpriseCsvTransformer.transformFromFhir(senderOrgUuid, batchId, null); if (!Strings.isNullOrEmpty(outbound)) { EnterpriseFiler.file(outbound, configName); } } catch (Exception ex) { throw new PipelineException("Failed to process exchange " + exchangeId + " and batch " + batchId, ex); } } } }*/ /*private static void fixMissingExchanges() { LOG.info("Fixing missing exchanges"); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id, batch_id, inserted_at FROM ehr.exchange_batch LIMIT 600000;"); stmt.setFetchSize(100); Set<UUID> exchangeIdsDone = new HashSet<>(); AuditRepository auditRepository = new AuditRepository(); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); UUID batchId = row.get(1, UUID.class); Date date = row.getTimestamp(2); //LOG.info("Exchange " + exchangeId + " batch " + batchId + " date " + date); if (exchangeIdsDone.contains(exchangeId)) { continue; } if (auditRepository.getExchange(exchangeId) != null) { continue; } UUID serviceId = findServiceId(batchId, session); if (serviceId == null) { continue; } Exchange exchange = new Exchange(); ExchangeByService exchangeByService = new ExchangeByService(); ExchangeEvent exchangeEvent = new ExchangeEvent(); Map<String, String> headers = new HashMap<>(); headers.put(HeaderKeys.SenderServiceUuid, serviceId.toString()); String headersJson = null; try { headersJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setBody("Body not available, as exchange re-created"); exchange.setExchangeId(exchangeId); exchange.setHeaders(headersJson); exchange.setTimestamp(date); exchangeByService.setExchangeId(exchangeId); exchangeByService.setServiceId(serviceId); exchangeByService.setTimestamp(date); exchangeEvent.setEventDesc("Created_By_Conversion"); exchangeEvent.setExchangeId(exchangeId); exchangeEvent.setTimestamp(new Date()); auditRepository.save(exchange); auditRepository.save(exchangeEvent); auditRepository.save(exchangeByService); exchangeIdsDone.add(exchangeId); LOG.info("Creating exchange " + exchangeId); } LOG.info("Finished exchange fix"); } private static UUID findServiceId(UUID batchId, Session session) { Statement stmt = new SimpleStatement("select resource_type, resource_id from ehr.resource_by_exchange_batch where batch_id = " + batchId + " LIMIT 1;"); ResultSet rs = session.execute(stmt); if (rs.isExhausted()) { LOG.error("Failed to find resource_by_exchange_batch for batch_id " + batchId); return null; } Row row = rs.one(); String resourceType = row.getString(0); UUID resourceId = row.get(1, UUID.class); stmt = new SimpleStatement("select service_id from ehr.resource_history where resource_type = '" + resourceType + "' and resource_id = " + resourceId + " LIMIT 1;"); rs = session.execute(stmt); if (rs.isExhausted()) { LOG.error("Failed to find resource_history for resource_type " + resourceType + " and resource_id " + resourceId); return null; } row = rs.one(); UUID serviceId = row.get(0, UUID.class); return serviceId; }*/ /*private static void fixExchangeEvents() { List<ExchangeEvent> events = new AuditRepository().getAllExchangeEvents(); for (ExchangeEvent event: events) { if (event.getEventDesc() != null) { continue; } String eventDesc = ""; int eventType = event.getEvent().intValue(); switch (eventType) { case 1: eventDesc = "Receive"; break; case 2: eventDesc = "Validate"; break; case 3: eventDesc = "Transform_Start"; break; case 4: eventDesc = "Transform_End"; break; case 5: eventDesc = "Send"; break; default: eventDesc = "??? " + eventType; } event.setEventDesc(eventDesc); new AuditRepository().save(null, event); } }*/ /*private static void fixExchanges() { AuditRepository auditRepository = new AuditRepository(); Map<UUID, Set<UUID>> existingOnes = new HashMap(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); List<Exchange> exchanges = auditRepository.getAllExchanges(); for (Exchange exchange: exchanges) { UUID exchangeUuid = exchange.getExchangeId(); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeUuid + " and Json " + headerJson); continue; } *//*String serviceId = headers.get(HeaderKeys.SenderServiceUuid); if (serviceId == null) { LOG.warn("No service ID found for exchange " + exchange.getExchangeId()); continue; } UUID serviceUuid = UUID.fromString(serviceId); Set<UUID> exchangeIdsDone = existingOnes.get(serviceUuid); if (exchangeIdsDone == null) { exchangeIdsDone = new HashSet<>(); List<ExchangeByService> exchangeByServices = auditRepository.getExchangesByService(serviceUuid, Integer.MAX_VALUE); for (ExchangeByService exchangeByService: exchangeByServices) { exchangeIdsDone.add(exchangeByService.getExchangeId()); } existingOnes.put(serviceUuid, exchangeIdsDone); } //create the exchange by service entity if (!exchangeIdsDone.contains(exchangeUuid)) { Date timestamp = exchange.getTimestamp(); ExchangeByService newOne = new ExchangeByService(); newOne.setExchangeId(exchangeUuid); newOne.setServiceId(serviceUuid); newOne.setTimestamp(timestamp); auditRepository.save(newOne); }*//* try { headers.remove(HeaderKeys.BatchIdsJson); String newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(newHeaderJson); auditRepository.save(exchange); } catch (JsonProcessingException e) { LOG.error("Failed to populate batch IDs for exchange " + exchangeUuid, e); } if (!headers.containsKey(HeaderKeys.BatchIdsJson)) { //fix the batch IDs not being in the exchange List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeUuid); if (!batches.isEmpty()) { List<UUID> batchUuids = batches .stream() .map(t -> t.getBatchId()) .collect(Collectors.toList()); try { String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchUuids.toArray()); headers.put(HeaderKeys.BatchIdsJson, batchUuidsStr); String newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(newHeaderJson); auditRepository.save(exchange, null); } catch (JsonProcessingException e) { LOG.error("Failed to populate batch IDs for exchange " + exchangeUuid, e); } } //} } }*/ /*private static UUID findSystemId(Service service, String software, String messageVersion) throws PipelineException { List<JsonServiceInterfaceEndpoint> endpoints = null; try { endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); String endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString(); LibraryRepository libraryRepository = new LibraryRepository(); ActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId); Item item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId()); LibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent()); System system = libraryItem.getSystem(); for (TechnicalInterface technicalInterface: system.getTechnicalInterface()) { if (endpointInterfaceId.equals(technicalInterface.getUuid()) && technicalInterface.getMessageFormat().equalsIgnoreCase(software) && technicalInterface.getMessageFormatVersion().equalsIgnoreCase(messageVersion)) { return endpointSystemId; } } } } catch (Exception e) { throw new PipelineException("Failed to process endpoints from service " + service.getId()); } return null; } */ /*private static void addSystemIdToExchangeHeaders() throws Exception { LOG.info("populateExchangeBatchPatients"); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); ServiceRepository serviceRepository = new ServiceRepository(); //OrganisationRepository organisationRepository = new OrganisationRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.exchange LIMIT 500;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); org.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeId + " and Json " + headerJson); continue; } if (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid))) { LOG.info("Skipping exchange " + exchangeId + " as no service UUID"); continue; } if (!Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) { LOG.info("Skipping exchange " + exchangeId + " as already got system UUID"); continue; } try { //work out service ID String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); UUID serviceId = UUID.fromString(serviceIdStr); String software = headers.get(HeaderKeys.SourceSystem); String version = headers.get(HeaderKeys.SystemVersion); Service service = serviceRepository.getById(serviceId); UUID systemUuid = findSystemId(service, software, version); headers.put(HeaderKeys.SenderSystemUuid, systemUuid.toString()); //work out protocol IDs try { String newProtocolIdsJson = DetermineRelevantProtocolIds.getProtocolIdsForPublisherService(serviceIdStr); headers.put(HeaderKeys.ProtocolIds, newProtocolIdsJson); } catch (Exception ex) { LOG.error("Failed to recalculate protocols for " + exchangeId + ": " + ex.getMessage()); } //save to DB headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(headerJson); auditRepository.save(exchange); } catch (Exception ex) { LOG.error("Error with exchange " + exchangeId, ex); } } LOG.info("Finished populateExchangeBatchPatients"); }*/ /*private static void populateExchangeBatchPatients() throws Exception { LOG.info("populateExchangeBatchPatients"); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); //ServiceRepository serviceRepository = new ServiceRepository(); //OrganisationRepository organisationRepository = new OrganisationRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.exchange LIMIT 500;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); org.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeId + " and Json " + headerJson); continue; } if (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid)) || Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) { LOG.info("Skipping exchange " + exchangeId + " because no service or system in header"); continue; } try { UUID serviceId = UUID.fromString(headers.get(HeaderKeys.SenderServiceUuid)); UUID systemId = UUID.fromString(headers.get(HeaderKeys.SenderSystemUuid)); List<ExchangeBatch> exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch : exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null) { continue; } UUID batchId = exchangeBatch.getBatchId(); List<ResourceByExchangeBatch> resourceWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Patient.toString()); if (resourceWrappers.isEmpty()) { continue; } List<UUID> patientIds = new ArrayList<>(); for (ResourceByExchangeBatch resourceWrapper : resourceWrappers) { UUID patientId = resourceWrapper.getResourceId(); if (resourceWrapper.getIsDeleted()) { deleteEntirePatientRecord(patientId, serviceId, systemId, exchangeId, batchId); } if (!patientIds.contains(patientId)) { patientIds.add(patientId); } } if (patientIds.size() != 1) { LOG.info("Skipping exchange " + exchangeId + " and batch " + batchId + " because found " + patientIds.size() + " patient IDs"); continue; } UUID patientId = patientIds.get(0); exchangeBatch.setEdsPatientId(patientId); exchangeBatchRepository.save(exchangeBatch); } } catch (Exception ex) { LOG.error("Error with exchange " + exchangeId, ex); } } LOG.info("Finished populateExchangeBatchPatients"); } private static void deleteEntirePatientRecord(UUID patientId, UUID serviceId, UUID systemId, UUID exchangeId, UUID batchId) throws Exception { FhirStorageService storageService = new FhirStorageService(serviceId, systemId); ResourceRepository resourceRepository = new ResourceRepository(); List<ResourceByPatient> resourceWrappers = resourceRepository.getResourcesByPatient(serviceId, systemId, patientId); for (ResourceByPatient resourceWrapper: resourceWrappers) { String json = resourceWrapper.getResourceData(); Resource resource = new JsonParser().parse(json); storageService.exchangeBatchDelete(exchangeId, batchId, resource); } }*/ /*private static void convertPatientSearch() { LOG.info("Converting Patient Search"); ResourceRepository resourceRepository = new ResourceRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); LOG.info("Doing service " + service.getName()); for (UUID systemId : findSystemIds(service)) { List<ResourceByService> resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.EpisodeOfCare.toString()); for (ResourceByService resourceWrapper: resourceWrappers) { if (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) { continue; } try { EpisodeOfCare episodeOfCare = (EpisodeOfCare) new JsonParser().parse(resourceWrapper.getResourceData()); String patientId = ReferenceHelper.getReferenceId(episodeOfCare.getPatient()); ResourceHistory patientWrapper = resourceRepository.getCurrentVersion(ResourceType.Patient.toString(), UUID.fromString(patientId)); if (Strings.isNullOrEmpty(patientWrapper.getResourceData())) { continue; } Patient patient = (Patient) new JsonParser().parse(patientWrapper.getResourceData()); PatientSearchHelper.update(serviceId, systemId, patient); PatientSearchHelper.update(serviceId, systemId, episodeOfCare); } catch (Exception ex) { LOG.error("Failed on " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId(), ex); } } } } LOG.info("Converted Patient Search"); } catch (Exception ex) { LOG.error("", ex); } }*/ private static List<UUID> findSystemIds(Service service) throws Exception { List<UUID> ret = new ArrayList<>(); List<JsonServiceInterfaceEndpoint> endpoints = null; try { endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); ret.add(endpointSystemId); } } catch (Exception e) { throw new Exception("Failed to process endpoints from service " + service.getId()); } return ret; } /*private static void convertPatientLink() { LOG.info("Converting Patient Link"); ResourceRepository resourceRepository = new ResourceRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); LOG.info("Doing service " + service.getName()); for (UUID systemId : findSystemIds(service)) { List<ResourceByService> resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.Patient.toString()); for (ResourceByService resourceWrapper: resourceWrappers) { if (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) { continue; } try { Patient patient = (Patient)new JsonParser().parse(resourceWrapper.getResourceData()); PatientLinkHelper.updatePersonId(patient); } catch (Exception ex) { LOG.error("Failed on " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId(), ex); } } } } LOG.info("Converted Patient Link"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixConfidentialPatients(String sharedStoragePath, UUID justThisService) { LOG.info("Fixing Confidential Patients using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); MappingManager mappingManager = CassandraConnector.getInstance().getMappingManager(); Mapper<ResourceHistory> mapperResourceHistory = mappingManager.mapper(ResourceHistory.class); Mapper<ResourceByExchangeBatch> mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); Map<String, ResourceHistory> resourcesFixed = new HashMap<>(); Map<UUID, Set<UUID>> exchangeBatchesToPutInProtocolQueue = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Set<UUID> batchIdsToPutInProtocolQueue = new HashSet<>(); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); String dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f); EmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId); ResourceFiler filer = new ResourceFiler(exchangeId, serviceId, systemId, null, null, 1); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers); ProblemPreTransformer.transform(version, parsers, filer, helper); ObservationPreTransformer.transform(version, parsers, filer, helper); DrugRecordPreTransformer.transform(version, parsers, filer, helper); IssueRecordPreTransformer.transform(version, parsers, filer, helper); DiaryPreTransformer.transform(version, parsers, filer, helper); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient)parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getIsConfidential() && !patientParser.getDeleted()) { PatientTransformer.createResource(patientParser, filer, helper, version); } } patientParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class); while (consultationParser.nextRecord()) { if (consultationParser.getIsConfidential() && !consultationParser.getDeleted()) { ConsultationTransformer.createResource(consultationParser, filer, helper, version); } } consultationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { if (observationParser.getIsConfidential() && !observationParser.getDeleted()) { ObservationTransformer.createResource(observationParser, filer, helper, version); } } observationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class); while (diaryParser.nextRecord()) { if (diaryParser.getIsConfidential() && !diaryParser.getDeleted()) { DiaryTransformer.createResource(diaryParser, filer, helper, version); } } diaryParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class); while (drugRecordParser.nextRecord()) { if (drugRecordParser.getIsConfidential() && !drugRecordParser.getDeleted()) { DrugRecordTransformer.createResource(drugRecordParser, filer, helper, version); } } drugRecordParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class); while (issueRecordParser.nextRecord()) { if (issueRecordParser.getIsConfidential() && !issueRecordParser.getDeleted()) { IssueRecordTransformer.createResource(issueRecordParser, filer, helper, version); } } issueRecordParser.close(); filer.waitToFinish(); //just to close the thread pool, even though it's not been used List<Resource> resources = filer.getNewResources(); for (Resource resource: resources) { String patientId = IdHelper.getPatientId(resource); UUID edsPatientId = UUID.fromString(patientId); ResourceType resourceType = resource.getResourceType(); UUID resourceId = UUID.fromString(resource.getId()); boolean foundResourceInDbBatch = false; List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds != null) { for (UUID batchId : batchIds) { List<ResourceByExchangeBatch> resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), resourceId); if (resourceByExchangeBatches.isEmpty()) { //if we've deleted data, this will be null continue; } foundResourceInDbBatch = true; for (ResourceByExchangeBatch resourceByExchangeBatch : resourceByExchangeBatches) { String json = resourceByExchangeBatch.getResourceData(); if (!Strings.isNullOrEmpty(json)) { LOG.warn("JSON already in resource " + resourceType + " " + resourceId); } else { json = parserPool.composeString(resource); resourceByExchangeBatch.setResourceData(json); resourceByExchangeBatch.setIsDeleted(false); resourceByExchangeBatch.setSchemaVersion("0.1"); LOG.info("Saved resource by batch " + resourceType + " " + resourceId + " in batch " + batchId); UUID versionUuid = resourceByExchangeBatch.getVersion(); ResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(resourceId, resourceType.toString(), versionUuid); if (resourceHistory == null) { throw new Exception("Failed to find resource history for " + resourceType + " " + resourceId + " and version " + versionUuid); } resourceHistory.setIsDeleted(false); resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); resourceHistory.setSchemaVersion("0.1"); resourceRepository.save(resourceByExchangeBatch); resourceRepository.save(resourceHistory); batchIdsToPutInProtocolQueue.add(batchId); String key = resourceType.toString() + ":" + resourceId; resourcesFixed.put(key, resourceHistory); } //if a patient became confidential, we will have deleted all resources for that //patient, so we need to undo that too //to undelete WHOLE patient record //1. if THIS resource is a patient //2. get all other deletes from the same exchange batch //3. delete those from resource_by_exchange_batch (the deleted ones only) //4. delete same ones from resource_history //5. retrieve most recent resource_history //6. if not deleted, add to resources fixed if (resourceType == ResourceType.Patient) { List<ResourceByExchangeBatch> resourcesInSameBatch = resourceRepository.getResourcesForBatch(batchId); LOG.info("Undeleting " + resourcesInSameBatch.size() + " resources for batch " + batchId); for (ResourceByExchangeBatch resourceInSameBatch: resourcesInSameBatch) { if (!resourceInSameBatch.getIsDeleted()) { continue; } //patient and episode resources will be restored by the above stuff, so don't try //to do it again if (resourceInSameBatch.getResourceType().equals(ResourceType.Patient.toString()) || resourceInSameBatch.getResourceType().equals(ResourceType.EpisodeOfCare.toString())) { continue; } ResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(resourceInSameBatch.getResourceId(), resourceInSameBatch.getResourceType(), resourceInSameBatch.getVersion()); mapperResourceByExchangeBatch.delete(resourceInSameBatch); mapperResourceHistory.delete(deletedResourceHistory); batchIdsToPutInProtocolQueue.add(batchId); //check the most recent version of our resource, and if it's not deleted, add to the list to update the resource_by_service table ResourceHistory mostRecentDeletedResourceHistory = resourceRepository.getCurrentVersion(resourceInSameBatch.getResourceType(), resourceInSameBatch.getResourceId()); if (mostRecentDeletedResourceHistory != null && !mostRecentDeletedResourceHistory.getIsDeleted()) { String key2 = mostRecentDeletedResourceHistory.getResourceType().toString() + ":" + mostRecentDeletedResourceHistory.getResourceId(); resourcesFixed.put(key2, mostRecentDeletedResourceHistory); } } } } } } //if we didn't find records in the DB to update, then if (!foundResourceInDbBatch) { //we can't generate a back-dated time UUID, but we need one so the resource_history //table is in order. To get a suitable time UUID, we just pull out the first exchange batch for our exchange, //and the batch ID is actually a time UUID that was allocated around the right time ExchangeBatch firstBatch = exchangeBatchRepository.retrieveFirstForExchangeId(exchangeId); //if there was no batch for the exchange, then the exchange wasn't processed at all. So skip this exchange //and we'll pick up the same patient data in a following exchange if (firstBatch == null) { continue; } UUID versionUuid = firstBatch.getBatchId(); //find suitable batch ID UUID batchId = null; if (batchIds != null && batchIds.size() > 0) { batchId = batchIds.get(batchIds.size()-1); } else { //create new batch ID if not found ExchangeBatch exchangeBatch = new ExchangeBatch(); exchangeBatch.setBatchId(UUIDs.timeBased()); exchangeBatch.setExchangeId(exchangeId); exchangeBatch.setInsertedAt(new Date()); exchangeBatch.setEdsPatientId(edsPatientId); exchangeBatchRepository.save(exchangeBatch); batchId = exchangeBatch.getBatchId(); //add to map for next resource if (batchIds == null) { batchIds = new ArrayList<>(); } batchIds.add(batchId); batchesPerPatient.put(edsPatientId, batchIds); } String json = parserPool.composeString(resource); ResourceHistory resourceHistory = new ResourceHistory(); resourceHistory.setResourceId(resourceId); resourceHistory.setResourceType(resourceType.toString()); resourceHistory.setVersion(versionUuid); resourceHistory.setCreatedAt(new Date()); resourceHistory.setServiceId(serviceId); resourceHistory.setSystemId(systemId); resourceHistory.setIsDeleted(false); resourceHistory.setSchemaVersion("0.1"); resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); ResourceByExchangeBatch resourceByExchangeBatch = new ResourceByExchangeBatch(); resourceByExchangeBatch.setBatchId(batchId); resourceByExchangeBatch.setExchangeId(exchangeId); resourceByExchangeBatch.setResourceType(resourceType.toString()); resourceByExchangeBatch.setResourceId(resourceId); resourceByExchangeBatch.setVersion(versionUuid); resourceByExchangeBatch.setIsDeleted(false); resourceByExchangeBatch.setSchemaVersion("0.1"); resourceByExchangeBatch.setResourceData(json); resourceRepository.save(resourceHistory); resourceRepository.save(resourceByExchangeBatch); batchIdsToPutInProtocolQueue.add(batchId); } } if (!batchIdsToPutInProtocolQueue.isEmpty()) { exchangeBatchesToPutInProtocolQueue.put(exchangeId, batchIdsToPutInProtocolQueue); } } //update the resource_by_service table (and the resource_by_patient view) for (ResourceHistory resourceHistory: resourcesFixed.values()) { UUID latestVersionUpdatedUuid = resourceHistory.getVersion(); ResourceHistory latestVersion = resourceRepository.getCurrentVersion(resourceHistory.getResourceType(), resourceHistory.getResourceId()); UUID latestVersionUuid = latestVersion.getVersion(); //if there have been subsequent updates to the resource, then skip it if (!latestVersionUuid.equals(latestVersionUpdatedUuid)) { continue; } Resource resource = parserPool.parse(resourceHistory.getResourceData()); ResourceMetadata metadata = MetadataFactory.createMetadata(resource); UUID patientId = ((PatientCompartment)metadata).getPatientId(); ResourceByService resourceByService = new ResourceByService(); resourceByService.setServiceId(resourceHistory.getServiceId()); resourceByService.setSystemId(resourceHistory.getSystemId()); resourceByService.setResourceType(resourceHistory.getResourceType()); resourceByService.setResourceId(resourceHistory.getResourceId()); resourceByService.setCurrentVersion(resourceHistory.getVersion()); resourceByService.setUpdatedAt(resourceHistory.getCreatedAt()); resourceByService.setPatientId(patientId); resourceByService.setSchemaVersion(resourceHistory.getSchemaVersion()); resourceByService.setResourceMetadata(JsonSerializer.serialize(metadata)); resourceByService.setResourceData(resourceHistory.getResourceData()); resourceRepository.save(resourceByService); //call out to our patient search and person matching services if (resource instanceof Patient) { PatientLinkHelper.updatePersonId((Patient)resource); PatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (Patient)resource); } else if (resource instanceof EpisodeOfCare) { PatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (EpisodeOfCare)resource); } } if (!exchangeBatchesToPutInProtocolQueue.isEmpty()) { //find the config for our protocol queue String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) { Set<UUID> batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } } LOG.info("Finished Fixing Confidential Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixDeletedAppointments(String sharedStoragePath, boolean saveChanges, UUID justThisService) { LOG.info("Fixing Deleted Appointments using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); MappingManager mappingManager = CassandraConnector.getInstance().getMappingManager(); Mapper<ResourceHistory> mapperResourceHistory = mappingManager.mapper(ResourceHistory.class); Mapper<ResourceByExchangeBatch> mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch : batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class, dir, version, true, parsers); //find any deleted patients List<UUID> deletedPatientUuids = new ArrayList<>(); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getDeleted()) { //find the EDS patient ID for this local guid String patientGuid = patientParser.getPatientGuid(); UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + patientGuid); } deletedPatientUuids.add(edsPatientId); } } patientParser.close(); //go through the appts file to find properly deleted appt GUIDS List<UUID> deletedApptUuids = new ArrayList<>(); org.endeavourhealth.transform.emis.csv.schema.appointment.Slot apptParser = (org.endeavourhealth.transform.emis.csv.schema.appointment.Slot) parsers.get(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class); while (apptParser.nextRecord()) { if (apptParser.getDeleted()) { String patientGuid = apptParser.getPatientGuid(); String slotGuid = apptParser.getSlotGuid(); if (!Strings.isNullOrEmpty(patientGuid)) { String uniqueLocalId = EmisCsvHelper.createUniqueId(patientGuid, slotGuid); UUID edsApptId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Appointment, uniqueLocalId); deletedApptUuids.add(edsApptId); } } } apptParser.close(); for (UUID edsPatientId : deletedPatientUuids) { List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds == null) { //if there are no batches for this patient, we'll be handling this data in another exchange continue; } for (UUID batchId : batchIds) { List<ResourceByExchangeBatch> apptWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Appointment.toString()); for (ResourceByExchangeBatch apptWrapper : apptWrappers) { //ignore non-deleted appts if (!apptWrapper.getIsDeleted()) { continue; } //if the appt was deleted legitamately, then skip it UUID apptId = apptWrapper.getResourceId(); if (deletedApptUuids.contains(apptId)) { continue; } ResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(apptWrapper.getResourceId(), apptWrapper.getResourceType(), apptWrapper.getVersion()); if (saveChanges) { mapperResourceByExchangeBatch.delete(apptWrapper); mapperResourceHistory.delete(deletedResourceHistory); } LOG.info("Un-deleted " + apptWrapper.getResourceType() + " " + apptWrapper.getResourceId() + " in batch " + batchId + " patient " + edsPatientId); //now get the most recent instance of the appointment, and if it's NOT deleted, insert into the resource_by_service table ResourceHistory mostRecentResourceHistory = resourceRepository.getCurrentVersion(apptWrapper.getResourceType(), apptWrapper.getResourceId()); if (mostRecentResourceHistory != null && !mostRecentResourceHistory.getIsDeleted()) { Resource resource = parserPool.parse(mostRecentResourceHistory.getResourceData()); ResourceMetadata metadata = MetadataFactory.createMetadata(resource); UUID patientId = ((PatientCompartment) metadata).getPatientId(); ResourceByService resourceByService = new ResourceByService(); resourceByService.setServiceId(mostRecentResourceHistory.getServiceId()); resourceByService.setSystemId(mostRecentResourceHistory.getSystemId()); resourceByService.setResourceType(mostRecentResourceHistory.getResourceType()); resourceByService.setResourceId(mostRecentResourceHistory.getResourceId()); resourceByService.setCurrentVersion(mostRecentResourceHistory.getVersion()); resourceByService.setUpdatedAt(mostRecentResourceHistory.getCreatedAt()); resourceByService.setPatientId(patientId); resourceByService.setSchemaVersion(mostRecentResourceHistory.getSchemaVersion()); resourceByService.setResourceMetadata(JsonSerializer.serialize(metadata)); resourceByService.setResourceData(mostRecentResourceHistory.getResourceData()); if (saveChanges) { resourceRepository.save(resourceByService); } LOG.info("Restored " + apptWrapper.getResourceType() + " " + apptWrapper.getResourceId() + " to resource_by_service table"); } } } } } } LOG.info("Finished Deleted Appointments Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixReviews(String sharedStoragePath, UUID justThisService) { LOG.info("Fixing Reviews using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); Map<String, Long> problemCodes = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); LOG.info("Doing Emis CSV exchange " + exchangeId + " with " + batches.size() + " batches"); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem problemParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (problemParser.nextRecord()) { String patientGuid = problemParser.getPatientGuid(); String observationGuid = problemParser.getObservationGuid(); String key = patientGuid + ":" + observationGuid; if (!problemCodes.containsKey(key)) { problemCodes.put(key, null); } } problemParser.close(); while (observationParser.nextRecord()) { String patientGuid = observationParser.getPatientGuid(); String observationGuid = observationParser.getObservationGuid(); String key = patientGuid + ":" + observationGuid; if (problemCodes.containsKey(key)) { Long codeId = observationParser.getCodeId(); if (codeId == null) { continue; } problemCodes.put(key, codeId); } } observationParser.close(); LOG.info("Found " + problemCodes.size() + " problem codes so far"); String dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f); EmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId); while (observationParser.nextRecord()) { String problemGuid = observationParser.getProblemGuid(); if (!Strings.isNullOrEmpty(problemGuid)) { String patientGuid = observationParser.getPatientGuid(); Long codeId = observationParser.getCodeId(); if (codeId == null) { continue; } String key = patientGuid + ":" + problemGuid; Long problemCodeId = problemCodes.get(key); if (problemCodeId == null || problemCodeId.longValue() != codeId.longValue()) { continue; } //if here, our code is the same as the problem, so it's a review String locallyUniqueId = patientGuid + ":" + observationParser.getObservationGuid(); ResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, helper); for (UUID systemId: systemIds) { UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + patientGuid); } UUID edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); if (edsObservationId == null) { //try observations as diagnostic reports, because it could be one of those instead if (resourceType == ResourceType.Observation) { resourceType = ResourceType.DiagnosticReport; edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); } if (edsObservationId == null) { throw new Exception("Failed to find observation ID for service " + serviceId + " system " + systemId + " resourceType " + resourceType + " local ID " + locallyUniqueId); } } List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds == null) { //if there are no batches for this patient, we'll be handling this data in another exchange continue; //throw new Exception("Failed to find batch ID for patient " + edsPatientId + " in exchange " + exchangeId + " for resource " + resourceType + " " + edsObservationId); } for (UUID batchId: batchIds) { List<ResourceByExchangeBatch> resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), edsObservationId); if (resourceByExchangeBatches.isEmpty()) { //if we've deleted data, this will be null continue; //throw new Exception("No resources found for batch " + batchId + " resource type " + resourceType + " and resource id " + edsObservationId); } for (ResourceByExchangeBatch resourceByExchangeBatch: resourceByExchangeBatches) { String json = resourceByExchangeBatch.getResourceData(); if (Strings.isNullOrEmpty(json)) { throw new Exception("No JSON in resource " + resourceType + " " + edsObservationId + " in batch " + batchId); } Resource resource = parserPool.parse(json); if (addReviewExtension((DomainResource)resource)) { json = parserPool.composeString(resource); resourceByExchangeBatch.setResourceData(json); LOG.info("Changed " + resourceType + " " + edsObservationId + " to have extension in batch " + batchId); resourceRepository.save(resourceByExchangeBatch); UUID versionUuid = resourceByExchangeBatch.getVersion(); ResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(edsObservationId, resourceType.toString(), versionUuid); if (resourceHistory == null) { throw new Exception("Failed to find resource history for " + resourceType + " " + edsObservationId + " and version " + versionUuid); } resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); resourceRepository.save(resourceHistory); ResourceByService resourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType.toString(), edsObservationId); if (resourceByService != null) { UUID serviceVersionUuid = resourceByService.getCurrentVersion(); if (serviceVersionUuid.equals(versionUuid)) { resourceByService.setResourceData(json); resourceRepository.save(resourceByService); } } } else { LOG.info("" + resourceType + " " + edsObservationId + " already has extension"); } } } } //1. find out resource type originall saved from //2. retrieve from resource_by_exchange_batch //3. update resource in resource_by_exchange_batch //4. retrieve from resource_history //5. update resource_history //6. retrieve record from resource_by_service //7. if resource_by_service version UUID matches the resource_history updated, then update that too } } observationParser.close(); } } LOG.info("Finished Fixing Reviews"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static boolean addReviewExtension(DomainResource resource) { if (ExtensionConverter.hasExtension(resource, FhirExtensionUri.IS_REVIEW)) { return false; } Extension extension = ExtensionConverter.createExtension(FhirExtensionUri.IS_REVIEW, new BooleanType(true)); resource.addExtension(extension); return true; }*/ /*private static void runProtocolsForConfidentialPatients(String sharedStoragePath, UUID justThisService) { LOG.info("Running Protocols for Confidential Patients using path " + sharedStoragePath + " and service " + justThisService); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } //once we match the servce, set this to null to do all other services justThisService = null; LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); List<String> interestingPatientGuids = new ArrayList<>(); Map<UUID, Map<UUID, List<UUID>>> batchesPerPatientPerExchange = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch : batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } batchesPerPatientPerExchange.put(exchangeId, batchesPerPatient); File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getIsConfidential() || patientParser.getDeleted()) { interestingPatientGuids.add(patientParser.getPatientGuid()); } } patientParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class); while (consultationParser.nextRecord()) { if (consultationParser.getIsConfidential() && !consultationParser.getDeleted()) { interestingPatientGuids.add(consultationParser.getPatientGuid()); } } consultationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { if (observationParser.getIsConfidential() && !observationParser.getDeleted()) { interestingPatientGuids.add(observationParser.getPatientGuid()); } } observationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class); while (diaryParser.nextRecord()) { if (diaryParser.getIsConfidential() && !diaryParser.getDeleted()) { interestingPatientGuids.add(diaryParser.getPatientGuid()); } } diaryParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class); while (drugRecordParser.nextRecord()) { if (drugRecordParser.getIsConfidential() && !drugRecordParser.getDeleted()) { interestingPatientGuids.add(drugRecordParser.getPatientGuid()); } } drugRecordParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class); while (issueRecordParser.nextRecord()) { if (issueRecordParser.getIsConfidential() && !issueRecordParser.getDeleted()) { interestingPatientGuids.add(issueRecordParser.getPatientGuid()); } } issueRecordParser.close(); } Map<UUID, Set<UUID>> exchangeBatchesToPutInProtocolQueue = new HashMap<>(); for (String interestingPatientGuid: interestingPatientGuids) { if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, interestingPatientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + interestingPatientGuid); } for (UUID exchangeId: batchesPerPatientPerExchange.keySet()) { Map<UUID, List<UUID>> batchesPerPatient = batchesPerPatientPerExchange.get(exchangeId); List<UUID> batches = batchesPerPatient.get(edsPatientId); if (batches != null) { Set<UUID> batchesForExchange = exchangeBatchesToPutInProtocolQueue.get(exchangeId); if (batchesForExchange == null) { batchesForExchange = new HashSet<>(); exchangeBatchesToPutInProtocolQueue.put(exchangeId, batchesForExchange); } batchesForExchange.addAll(batches); } } } if (!exchangeBatchesToPutInProtocolQueue.isEmpty()) { //find the config for our protocol queue String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) { Set<UUID> batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); LOG.info("Posting exchange " + exchangeId + " batch " + batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } } LOG.info("Finished Running Protocols for Confidential Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixOrgs() { LOG.info("Posting orgs to protocol queue"); String[] orgIds = new String[]{ "332f31a2-7b28-47cb-af6f-18f65440d43d", "c893d66b-eb89-4657-9f53-94c5867e7ed9"}; ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); Map<UUID, Set<UUID>> exchangeBatches = new HashMap<>(); for (String orgId: orgIds) { LOG.info("Doing org ID " + orgId); UUID orgUuid = UUID.fromString(orgId); try { //select batch_id from ehr.resource_by_exchange_batch where resource_type = 'Organization' and resource_id = 8f465517-729b-4ad9-b405-92b487047f19 LIMIT 1 ALLOW FILTERING; ResourceByExchangeBatch resourceByExchangeBatch = resourceRepository.getFirstResourceByExchangeBatch(ResourceType.Organization.toString(), orgUuid); UUID batchId = resourceByExchangeBatch.getBatchId(); //select exchange_id from ehr.exchange_batch where batch_id = 1a940e10-1535-11e7-a29d-a90b99186399 LIMIT 1 ALLOW FILTERING; ExchangeBatch exchangeBatch = exchangeBatchRepository.retrieveFirstForBatchId(batchId); UUID exchangeId = exchangeBatch.getExchangeId(); Set<UUID> list = exchangeBatches.get(exchangeId); if (list == null) { list = new HashSet<>(); exchangeBatches.put(exchangeId, list); } list.add(batchId); } catch (Exception ex) { LOG.error("", ex); break; } } try { //find the config for our protocol queue (which is in the inbound config) String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatches.keySet()) { Set<UUID> batchIds = exchangeBatches.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); LOG.info("Posting exchange " + exchangeId + " batch " + batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } catch (Exception ex) { LOG.error("", ex); return; } LOG.info("Finished posting orgs to protocol queue"); }*/ /*private static void findCodes() { LOG.info("Finding missing codes"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT service_id, system_id, exchange_id, version FROM audit.exchange_transform_audit ALLOW FILTERING;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID serviceId = row.get(0, UUID.class); UUID systemId = row.get(1, UUID.class); UUID exchangeId = row.get(2, UUID.class); UUID version = row.get(3, UUID.class); ExchangeTransformAudit audit = auditRepository.getExchangeTransformAudit(serviceId, systemId, exchangeId, version); String xml = audit.getErrorXml(); if (xml == null) { continue; } String codePrefix = "Failed to find clinical code CodeableConcept for codeId "; int codeIndex = xml.indexOf(codePrefix); if (codeIndex > -1) { int startIndex = codeIndex + codePrefix.length(); int tagEndIndex = xml.indexOf("<", startIndex); String code = xml.substring(startIndex, tagEndIndex); Service service = serviceRepository.getById(serviceId); String name = service.getName(); LOG.info(name + " clinical code " + code + " from " + audit.getStarted()); continue; } codePrefix = "Failed to find medication CodeableConcept for codeId "; codeIndex = xml.indexOf(codePrefix); if (codeIndex > -1) { int startIndex = codeIndex + codePrefix.length(); int tagEndIndex = xml.indexOf("<", startIndex); String code = xml.substring(startIndex, tagEndIndex); Service service = serviceRepository.getById(serviceId); String name = service.getName(); LOG.info(name + " drug code " + code + " from " + audit.getStarted()); continue; } } LOG.info("Finished finding missing codes"); }*/ private static void createTppSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating TPP Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createTppSubsetForFile(sourceDir, destDir, personIds); LOG.info("Finished Creating TPP Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createTppSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } //LOG.info("Doing dir " + sourceFile); createTppSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } Charset encoding = Charset.forName("CP1252"); InputStreamReader reader = new InputStreamReader( new BufferedInputStream( new FileInputStream(sourceFile)), encoding); CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL).withHeader(); CSVParser parser = new CSVParser(reader, format); String filterColumn = null; Map<String, Integer> headerMap = parser.getHeaderMap(); if (headerMap.containsKey("IDPatient")) { filterColumn = "IDPatient"; } else if (name.equalsIgnoreCase("SRPatient.csv")) { filterColumn = "RowIdentifier"; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } String[] columnHeaders = new String[headerMap.size()]; Iterator<String> headerIterator = headerMap.keySet().iterator(); while (headerIterator.hasNext()) { String headerName = headerIterator.next(); int headerIndex = headerMap.get(headerName); columnHeaders[headerIndex] = headerName; } BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(destFile), encoding)); CSVPrinter printer = new CSVPrinter(bw, format.withHeader(columnHeaders)); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); /*} else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); copyFile(sourceFile, destFile); }*/ } } } private static void createVisionSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Vision Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createVisionSubsetForFile(sourceDir, destDir, personIds); LOG.info("Finished Creating Vision Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createVisionSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createVisionSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; if (name.contains("encounter_data") || name.contains("journal_data") || name.contains("patient_data") || name.contains("referral_data")) { filterColumn = 0; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } private static void createHomertonSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Homerton Subset"); try { Set<String> PersonIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } PersonIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createHomertonSubsetForFile(sourceDir, destDir, PersonIds); LOG.info("Finished Creating Homerton Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createHomertonSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createHomertonSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); //fully quote destination file to fix CRLF in columns CSVFormat format = CSVFormat.DEFAULT.withHeader(); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; //PersonId column at 1 if (name.contains("ENCOUNTER") || name.contains("PATIENT")) { filterColumn = 1; } else if (name.contains("DIAGNOSIS")) { //PersonId column at 13 filterColumn = 13; } else if (name.contains("ALLERGY")) { //PersonId column at 2 filterColumn = 2; } else if (name.contains("PROBLEM")) { //PersonId column at 4 filterColumn = 4; } else { //if no patient column, just copy the file (i.e. PROCEDURE) parser.close(); LOG.info("Copying file without PatientId " + sourceFile); copyFile(sourceFile, destFile); continue; } Map<String, Integer> headerMap = parser.getHeaderMap(); String[] columnHeaders = new String[headerMap.size()]; Iterator<String> headerIterator = headerMap.keySet().iterator(); while (headerIterator.hasNext()) { String headerName = headerIterator.next(); int headerIndex = headerMap.get(headerName); columnHeaders[headerIndex] = headerName; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format.withHeader(columnHeaders)); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } private static void createAdastraSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Adastra Subset"); try { Set<String> caseIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } //adastra extract files are all keyed on caseId caseIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createAdastraSubsetForFile(sourceDir, destDir, caseIds); LOG.info("Finished Creating Adastra Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createAdastraSubsetForFile(File sourceDir, File destDir, Set<String> caseIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createAdastraSubsetForFile(sourceFile, destFile, caseIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); //fully quote destination file to fix CRLF in columns CSVFormat format = CSVFormat.DEFAULT.withDelimiter('|'); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; //CaseRef column at 0 if (name.contains("NOTES") || name.contains("CASEQUESTIONS") || name.contains("OUTCOMES") || name.contains("CONSULTATION") || name.contains("CLINICALCODES") || name.contains("PRESCRIPTIONS") || name.contains("PATIENT")) { filterColumn = 0; } else if (name.contains("CASE")) { //CaseRef column at 2 filterColumn = 2; } else if (name.contains("PROVIDER")) { //CaseRef column at 7 filterColumn = 7; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String caseId = csvRecord.get(filterColumn); if (caseIds.contains(caseId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } private static void exportFhirToCsv(UUID serviceId, String destinationPath) { try { File dir = new File(destinationPath); if (dir.exists()) { dir.mkdirs(); } Map<String, CSVPrinter> hmPrinters = new HashMap<>(); EntityManager entityManager = ConnectionManager.getEhrEntityManager(serviceId); SessionImpl session = (SessionImpl) entityManager.getDelegate(); Connection connection = session.connection(); PreparedStatement ps = connection.prepareStatement("SELECT resource_id, resource_type, resource_data FROM resource_current"); LOG.debug("Running query"); ResultSet rs = ps.executeQuery(); LOG.debug("Got result set"); while (rs.next()) { String id = rs.getString(1); String type = rs.getString(2); String json = rs.getString(3); CSVPrinter printer = hmPrinters.get(type); if (printer == null) { String path = FilenameUtils.concat(dir.getAbsolutePath(), type + ".tsv"); FileWriter fileWriter = new FileWriter(new File(path)); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVFormat format = CSVFormat.DEFAULT .withHeader("resource_id", "resource_json") .withDelimiter('\t') .withEscape((Character) null) .withQuote((Character) null) .withQuoteMode(QuoteMode.MINIMAL); printer = new CSVPrinter(bufferedWriter, format); hmPrinters.put(type, printer); } printer.printRecord(id, json); } for (String type : hmPrinters.keySet()) { CSVPrinter printer = hmPrinters.get(type); printer.flush(); printer.close(); } ps.close(); entityManager.close(); } catch (Throwable t) { LOG.error("", t); } } } /*class ResourceFiler extends FhirResourceFiler { public ResourceFiler(UUID exchangeId, UUID serviceId, UUID systemId, TransformError transformError, List<UUID> batchIdsCreated, int maxFilingThreads) { super(exchangeId, serviceId, systemId, transformError, batchIdsCreated, maxFilingThreads); } private List<Resource> newResources = new ArrayList<>(); public List<Resource> getNewResources() { return newResources; } @Override public void saveAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception { throw new Exception("shouldn't be calling saveAdminResource"); } @Override public void deleteAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception { throw new Exception("shouldn't be calling deleteAdminResource"); } @Override public void savePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception { for (Resource resource: resources) { if (mapIds) { IdHelper.mapIds(getServiceId(), getSystemId(), resource); } newResources.add(resource); } } @Override public void deletePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception { throw new Exception("shouldn't be calling deletePatientResource"); } }*/
src/eds-queuereader/src/main/java/org/endeavourhealth/queuereader/Main.java
package org.endeavourhealth.queuereader; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.apache.commons.csv.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.endeavourhealth.common.cache.ObjectMapperPool; import org.endeavourhealth.common.config.ConfigManager; import org.endeavourhealth.common.fhir.*; import org.endeavourhealth.common.utility.FileHelper; import org.endeavourhealth.common.utility.SlackHelper; import org.endeavourhealth.core.configuration.ConfigDeserialiser; import org.endeavourhealth.core.configuration.PostMessageToExchangeConfig; import org.endeavourhealth.core.configuration.QueueReaderConfiguration; import org.endeavourhealth.core.csv.CsvHelper; import org.endeavourhealth.core.database.dal.DalProvider; import org.endeavourhealth.core.database.dal.admin.ServiceDalI; import org.endeavourhealth.core.database.dal.admin.models.Service; import org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI; import org.endeavourhealth.core.database.dal.audit.ExchangeDalI; import org.endeavourhealth.core.database.dal.audit.models.*; import org.endeavourhealth.core.database.dal.ehr.ResourceDalI; import org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper; import org.endeavourhealth.core.database.dal.subscriberTransform.EnterpriseIdDalI; import org.endeavourhealth.core.database.rdbms.ConnectionManager; import org.endeavourhealth.core.exceptions.TransformException; import org.endeavourhealth.core.fhirStorage.FhirSerializationHelper; import org.endeavourhealth.core.fhirStorage.FhirStorageService; import org.endeavourhealth.core.fhirStorage.JsonServiceInterfaceEndpoint; import org.endeavourhealth.core.messaging.pipeline.components.PostMessageToExchange; import org.endeavourhealth.core.queueing.QueueHelper; import org.endeavourhealth.core.xml.TransformErrorSerializer; import org.endeavourhealth.core.xml.transformError.TransformError; import org.endeavourhealth.transform.common.*; import org.endeavourhealth.transform.emis.EmisCsvToFhirTransformer; import org.endeavourhealth.transform.emis.csv.helpers.EmisCsvHelper; import org.hibernate.internal.SessionImpl; import org.hl7.fhir.instance.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.sql.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; public class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { String configId = args[0]; LOG.info("Initialising config manager"); ConfigManager.initialize("queuereader", configId); /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixEncounters")) { String table = args[1]; fixEncounters(table); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("CreateHomertonSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createHomertonSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateAdastraSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createAdastraSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateVisionSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createVisionSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateTppSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createTppSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateBartsSubset")) { String sourceDirPath = args[1]; UUID serviceUuid = UUID.fromString(args[2]); UUID systemUuid = UUID.fromString(args[3]); String samplePatientsFile = args[4]; createBartsSubset(sourceDirPath, serviceUuid, systemUuid, samplePatientsFile); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixBartsOrgs")) { String serviceId = args[1]; fixBartsOrgs(serviceId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("TestPreparedStatements")) { String url = args[1]; String user = args[2]; String pass = args[3]; String serviceId = args[4]; testPreparedStatements(url, user, pass, serviceId); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("ExportFhirToCsv")) { UUID serviceId = UUID.fromString(args[1]); String path = args[2]; exportFhirToCsv(serviceId, path); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("TestBatchInserts")) { String url = args[1]; String user = args[2]; String pass = args[3]; String num = args[4]; String batchSize = args[5]; testBatchInserts(url, user, pass, num, batchSize); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("ApplyEmisAdminCaches")) { applyEmisAdminCaches(); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixSubscribers")) { fixSubscriberDbs(); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixEmisProblems")) { String serviceId = args[1]; String systemId = args[2]; fixEmisProblems(UUID.fromString(serviceId), UUID.fromString(systemId)); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("FixEmisProblems3ForPublisher")) { String publisherId = args[1]; String systemId = args[2]; fixEmisProblems3ForPublisher(publisherId, UUID.fromString(systemId)); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixEmisProblems3")) { String serviceId = args[1]; String systemId = args[2]; fixEmisProblems3(UUID.fromString(serviceId), UUID.fromString(systemId)); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CheckDeletedObs")) { String serviceId = args[1]; String systemId = args[2]; checkDeletedObs(UUID.fromString(serviceId), UUID.fromString(systemId)); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("ConvertExchangeBody")) { String systemId = args[1]; convertExchangeBody(UUID.fromString(systemId)); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixReferrals")) { fixReferralRequests(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PopulateNewSearchTable")) { String table = args[1]; populateNewSearchTable(table); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixBartsEscapes")) { String filePath = args[1]; fixBartsEscapedFiles(filePath); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("PostToInbound")) { String serviceId = args[1]; String systemId = args[2]; String filePath = args[3]; postToInboundFromFile(UUID.fromString(serviceId), UUID.fromString(systemId), filePath); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixDisabledExtract")) { String serviceId = args[1]; String systemId = args[2]; String sharedStoragePath = args[3]; String tempDir = args[4]; fixDisabledEmisExtract(serviceId, systemId, sharedStoragePath, tempDir); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("TestSlack")) { testSlack(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PostToInbound")) { String serviceId = args[1]; boolean all = Boolean.parseBoolean(args[2]); postToInbound(UUID.fromString(serviceId), all); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixPatientSearch")) { String serviceId = args[1]; fixPatientSearch(serviceId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("Exit")) { String exitCode = args[1]; LOG.info("Exiting with error code " + exitCode); int exitCodeInt = Integer.parseInt(exitCode); System.exit(exitCodeInt); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("RunSql")) { String host = args[1]; String username = args[2]; String password = args[3]; String sqlFile = args[4]; runSql(host, username, password, sqlFile); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PopulateProtocolQueue")) { String serviceId = null; if (args.length > 1) { serviceId = args[1]; } String startingExchangeId = null; if (args.length > 2) { startingExchangeId = args[2]; } populateProtocolQueue(serviceId, startingExchangeId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FindEncounterTerms")) { String path = args[1]; String outputPath = args[2]; findEncounterTerms(path, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FindEmisStartDates")) { String path = args[1]; String outputPath = args[2]; findEmisStartDates(path, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("ExportHl7Encounters")) { String sourceCsvPpath = args[1]; String outputPath = args[2]; exportHl7Encounters(sourceCsvPpath, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixExchangeBatches")) { fixExchangeBatches(); System.exit(0); }*/ /*if (args.length >= 0 && args[0].equalsIgnoreCase("FindCodes")) { findCodes(); System.exit(0); }*/ /*if (args.length >= 0 && args[0].equalsIgnoreCase("FindDeletedOrgs")) { findDeletedOrgs(); System.exit(0); }*/ if (args.length != 1) { LOG.error("Usage: queuereader config_id"); return; } LOG.info("--------------------------------------------------"); LOG.info("EDS Queue Reader " + configId); LOG.info("--------------------------------------------------"); LOG.info("Fetching queuereader configuration"); String configXml = ConfigManager.getConfiguration(configId); QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); /*LOG.info("Registering shutdown hook"); registerShutdownHook();*/ // Instantiate rabbit handler LOG.info("Creating EDS queue reader"); RabbitHandler rabbitHandler = new RabbitHandler(configuration, configId); // Begin consume rabbitHandler.start(); LOG.info("EDS Queue reader running (kill file location " + TransformConfig.instance().getKillFileLocation() + ")"); } private static void checkDeletedObs(UUID serviceId, UUID systemId) { LOG.info("Checking Observations for " + serviceId); try { ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); List<ResourceType> potentialResourceTypes = new ArrayList<>(); potentialResourceTypes.add(ResourceType.Procedure); potentialResourceTypes.add(ResourceType.AllergyIntolerance); potentialResourceTypes.add(ResourceType.FamilyMemberHistory); potentialResourceTypes.add(ResourceType.Immunization); potentialResourceTypes.add(ResourceType.DiagnosticOrder); potentialResourceTypes.add(ResourceType.Specimen); potentialResourceTypes.add(ResourceType.DiagnosticReport); potentialResourceTypes.add(ResourceType.ReferralRequest); potentialResourceTypes.add(ResourceType.Condition); potentialResourceTypes.add(ResourceType.Observation); List<String> subscriberConfigs = new ArrayList<>(); subscriberConfigs.add("ceg_data_checking"); subscriberConfigs.add("ceg_enterprise"); subscriberConfigs.add("hurley_data_checking"); subscriberConfigs.add("hurley_deidentified"); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceId, systemId, Integer.MAX_VALUE); for (Exchange exchange : exchanges) { List<ExchangePayloadFile> payload = ExchangeHelper.parseExchangeBody(exchange.getBody()); //String version = EmisCsvToFhirTransformer.determineVersion(payload); //if we've reached the point before we process data for this practice, break out if (!EmisCsvToFhirTransformer.shouldProcessPatientData(payload)) { break; } ExchangePayloadFile firstItem = payload.get(0); String name = FilenameUtils.getBaseName(firstItem.getPath()); String[] toks = name.split("_"); String agreementId = toks[4]; LOG.info("Doing exchange containing " + firstItem.getPath()); EmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchange.getId(), agreementId, true); Map<UUID, ExchangeBatch> hmBatchesByPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchange.getId()); for (ExchangeBatch batch : batches) { if (batch.getEdsPatientId() != null) { hmBatchesByPatient.put(batch.getEdsPatientId(), batch); } } for (ExchangePayloadFile item : payload) { String type = item.getType(); if (type.equals("CareRecord_Observation")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String deleted = record.get("Deleted"); if (deleted.equalsIgnoreCase("true")) { String patientId = record.get("PatientGuid"); String observationId = record.get("ObservationGuid"); //find observation UUID UUID uuid = IdHelper.getEdsResourceId(serviceId, ResourceType.Observation, patientId + ":" + observationId); if (uuid == null) { continue; } //find TRUE resource type Reference edsReference = ReferenceHelper.createReference(ResourceType.Observation, uuid.toString()); if (fixReference(serviceId, csvHelper, edsReference, potentialResourceTypes)) { ReferenceComponents comps = ReferenceHelper.getReferenceComponents(edsReference); ResourceType newType = comps.getResourceType(); String newId = comps.getId(); //delete resource if not already done ResourceWrapper resourceWrapper = resourceDal.getCurrentVersion(serviceId, newType.toString(), UUID.fromString(newId)); if (resourceWrapper.isDeleted()) { continue; } LOG.debug("Fixing " + edsReference.getReference()); //create file of IDs to delete for each subscriber DB for (String subscriberConfig : subscriberConfigs) { EnterpriseIdDalI subscriberDal = DalProvider.factoryEnterpriseIdDal(subscriberConfig); Long enterpriseId = subscriberDal.findEnterpriseId(newType.toString(), newId); if (enterpriseId == null) { continue; } String sql = null; if (newType == ResourceType.AllergyIntolerance) { sql = "DELETE FROM allergy_intolerance WHERE id = " + enterpriseId; } else if (newType == ResourceType.ReferralRequest) { sql = "DELETE FROM referral_request WHERE id = " + enterpriseId; } else { sql = "DELETE FROM observation WHERE id = " + enterpriseId; } sql += "\n"; File f = new File(subscriberConfig + ".sql"); Files.write(f.toPath(), sql.getBytes(), StandardOpenOption.APPEND); } ExchangeBatch batch = hmBatchesByPatient.get(resourceWrapper.getPatientId()); resourceWrapper.setDeleted(true); resourceWrapper.setResourceData(null); resourceWrapper.setExchangeBatchId(batch.getBatchId()); resourceWrapper.setVersion(UUID.randomUUID()); resourceWrapper.setCreatedAt(new Date()); resourceWrapper.setExchangeId(exchange.getId()); resourceDal.delete(resourceWrapper); } } } parser.close(); } else { //no problem link } } } LOG.info("Finished Checking Observations for " + serviceId); } catch (Exception ex) { LOG.error("", ex); } } private static void testBatchInserts(String url, String user, String pass, String num, String batchSizeStr) { LOG.info("Testing Batch Inserts"); try { int inserts = Integer.parseInt(num); int batchSize = Integer.parseInt(batchSizeStr); LOG.info("Openning Connection"); Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", pass); Connection conn = DriverManager.getConnection(url, props); //String sql = "INSERT INTO drewtest.insert_test VALUES (?, ?, ?);"; String sql = "INSERT INTO drewtest.insert_test VALUES (?, ?, ?)"; PreparedStatement ps = conn.prepareStatement(sql); if (batchSize == 1) { LOG.info("Testing non-batched inserts"); long start = System.currentTimeMillis(); for (int i = 0; i < inserts; i++) { int col = 1; ps.setString(col++, UUID.randomUUID().toString()); ps.setString(col++, UUID.randomUUID().toString()); ps.setString(col++, randomStr()); ps.execute(); } long end = System.currentTimeMillis(); LOG.info("Done " + inserts + " in " + (end - start) + " ms"); } else { LOG.info("Testing batched inserts with batch size " + batchSize); long start = System.currentTimeMillis(); for (int i = 0; i < inserts; i++) { int col = 1; ps.setString(col++, UUID.randomUUID().toString()); ps.setString(col++, UUID.randomUUID().toString()); ps.setString(col++, randomStr()); ps.addBatch(); if ((i + 1) % batchSize == 0 || i + 1 >= inserts) { ps.executeBatch(); } } long end = System.currentTimeMillis(); LOG.info("Done " + inserts + " in " + (end - start) + " ms"); } ps.close(); conn.close(); LOG.info("Finished Testing Batch Inserts"); } catch (Exception ex) { LOG.error("", ex); } } private static String randomStr() { StringBuffer sb = new StringBuffer(); Random r = new Random(System.currentTimeMillis()); while (sb.length() < 1100) { sb.append(r.nextLong()); } return sb.toString(); } /*private static void fixEmisProblems(UUID serviceId, UUID systemId) { LOG.info("Fixing Emis Problems for " + serviceId); try { Map<String, List<String>> hmReferences = new HashMap<>(); Set<String> patientIds = new HashSet<>(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); FhirResourceFiler filer = new FhirResourceFiler(null, serviceId, systemId, null, null); LOG.info("Caching problem links"); //Go through all files to work out problem children for every problem ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceId, systemId, Integer.MAX_VALUE); for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); List<ExchangePayloadFile> payload = ExchangeHelper.parseExchangeBody(exchange.getBody()); //String version = EmisCsvToFhirTransformer.determineVersion(payload); ExchangePayloadFile firstItem = payload.get(0); String name = FilenameUtils.getBaseName(firstItem.getPath()); String[] toks = name.split("_"); String agreementId = toks[4]; LOG.info("Doing exchange containing " + firstItem.getPath()); EmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchange.getId(), agreementId, true); for (ExchangePayloadFile item: payload) { String type = item.getType(); if (type.equals("CareRecord_Observation")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String parentProblemId = record.get("ProblemGuid"); String patientId = record.get("PatientGuid"); patientIds.add(patientId); if (!Strings.isNullOrEmpty(parentProblemId)) { String observationId = record.get("ObservationGuid"); String localId = patientId + ":" + observationId; ResourceType resourceType = ObservationTransformer.findOriginalTargetResourceType(filer, CsvCell.factoryDummyWrapper(patientId), CsvCell.factoryDummyWrapper(observationId)); Reference localReference = ReferenceHelper.createReference(resourceType, localId); Reference globalReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localReference, csvHelper); String localProblemId = patientId + ":" + parentProblemId; Reference localProblemReference = ReferenceHelper.createReference(ResourceType.Condition, localProblemId); Reference globalProblemReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localProblemReference, csvHelper); String globalProblemId = ReferenceHelper.getReferenceId(globalProblemReference); List<String> problemChildren = hmReferences.get(globalProblemId); if (problemChildren == null) { problemChildren = new ArrayList<>(); hmReferences.put(globalProblemId, problemChildren); } problemChildren.add(globalReference.getReference()); } } parser.close(); } else if (type.equals("Prescribing_DrugRecord")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String parentProblemId = record.get("ProblemObservationGuid"); String patientId = record.get("PatientGuid"); patientIds.add(patientId); if (!Strings.isNullOrEmpty(parentProblemId)) { String observationId = record.get("DrugRecordGuid"); String localId = patientId + ":" + observationId; Reference localReference = ReferenceHelper.createReference(ResourceType.MedicationStatement, localId); Reference globalReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localReference, csvHelper); String localProblemId = patientId + ":" + parentProblemId; Reference localProblemReference = ReferenceHelper.createReference(ResourceType.Condition, localProblemId); Reference globalProblemReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localProblemReference, csvHelper); String globalProblemId = ReferenceHelper.getReferenceId(globalProblemReference); List<String> problemChildren = hmReferences.get(globalProblemId); if (problemChildren == null) { problemChildren = new ArrayList<>(); hmReferences.put(globalProblemId, problemChildren); } problemChildren.add(globalReference.getReference()); } } parser.close(); } else if (type.equals("Prescribing_IssueRecord")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String parentProblemId = record.get("ProblemObservationGuid"); String patientId = record.get("PatientGuid"); patientIds.add(patientId); if (!Strings.isNullOrEmpty(parentProblemId)) { String observationId = record.get("IssueRecordGuid"); String localId = patientId + ":" + observationId; Reference localReference = ReferenceHelper.createReference(ResourceType.MedicationOrder, localId); String localProblemId = patientId + ":" + parentProblemId; Reference localProblemReference = ReferenceHelper.createReference(ResourceType.Condition, localProblemId); Reference globalProblemReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localProblemReference, csvHelper); Reference globalReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localReference, csvHelper); String globalProblemId = ReferenceHelper.getReferenceId(globalProblemReference); List<String> problemChildren = hmReferences.get(globalProblemId); if (problemChildren == null) { problemChildren = new ArrayList<>(); hmReferences.put(globalProblemId, problemChildren); } problemChildren.add(globalReference.getReference()); } } parser.close(); } else { //no problem link } } } LOG.info("Finished caching problem links, finding " + patientIds.size() + " patients"); int done = 0; int fixed = 0; for (String localPatientId: patientIds) { Reference localPatientReference = ReferenceHelper.createReference(ResourceType.Patient, localPatientId); Reference globalPatientReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localPatientReference, filer); String patientUuid = ReferenceHelper.getReferenceId(globalPatientReference); List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(serviceId, UUID.fromString(patientUuid), ResourceType.Condition.toString()); for (ResourceWrapper wrapper: wrappers) { if (wrapper.isDeleted()) { continue; } String originalJson = wrapper.getResourceData(); Condition condition = (Condition)FhirSerializationHelper.deserializeResource(originalJson); ConditionBuilder conditionBuilder = new ConditionBuilder(condition); //sort out the nested extension references Extension outerExtension = ExtensionConverter.findExtension(condition, FhirExtensionUri.PROBLEM_LAST_REVIEWED); if (outerExtension != null) { Extension innerExtension = ExtensionConverter.findExtension(outerExtension, FhirExtensionUri._PROBLEM_LAST_REVIEWED__PERFORMER); if (innerExtension != null) { Reference performerReference = (Reference)innerExtension.getValue(); String value = performerReference.getReference(); if (value.endsWith("}")) { Reference globalPerformerReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(performerReference, filer); innerExtension.setValue(globalPerformerReference); } } } //sort out the contained list of children ContainedListBuilder listBuilder = new ContainedListBuilder(conditionBuilder); //remove any existing children listBuilder.removeContainedList(); //add all the new ones we've found List<String> localChildReferences = hmReferences.get(wrapper.getResourceId().toString()); if (localChildReferences != null) { for (String localChildReference: localChildReferences) { Reference reference = ReferenceHelper.createReference(localChildReference); listBuilder.addContainedListItem(reference); } } //save the updated condition String newJson = FhirSerializationHelper.serializeResource(condition); if (!newJson.equals(originalJson)) { wrapper.setResourceData(newJson); saveResourceWrapper(serviceId, wrapper); fixed ++; } } done ++; if (done % 1000 == 0) { LOG.info("Done " + done + " patients and fixed " + fixed + " problems"); } } LOG.info("Done " + done + " patients and fixed " + fixed + " problems"); LOG.info("Finished Emis Problems for " + serviceId); } catch (Exception ex) { LOG.error("", ex); } }*/ private static void fixEmisProblems3ForPublisher(String publisher, UUID systemId) { try { LOG.info("Doing fix for " + publisher); ServiceDalI dal = DalProvider.factoryServiceDal(); List<Service> all = dal.getAll(); for (Service service: all) { if (service.getPublisherConfigName() != null && service.getPublisherConfigName().equals(publisher)) { fixEmisProblems3(service.getId(), systemId); } } LOG.info("Done fix for " + publisher); } catch (Throwable t) { LOG.error("", t); } } private static void fixEmisProblems3(UUID serviceId, UUID systemId) { LOG.info("Fixing Emis Problems 3 for " + serviceId); try { Set<String> patientIds = new HashSet<>(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); FhirResourceFiler filer = new FhirResourceFiler(null, serviceId, systemId, null, null); LOG.info("Finding patients"); //Go through all files to work out problem children for every problem ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceId, systemId, Integer.MAX_VALUE); for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); List<ExchangePayloadFile> payload = ExchangeHelper.parseExchangeBody(exchange.getBody()); for (ExchangePayloadFile item: payload) { String type = item.getType(); if (type.equals("Admin_Patient")) { InputStreamReader isr = FileHelper.readFileReaderFromSharedStorage(item.getPath()); CSVParser parser = new CSVParser(isr, EmisCsvToFhirTransformer.CSV_FORMAT); Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String patientId = record.get("PatientGuid"); patientIds.add(patientId); } parser.close(); } } } LOG.info("Finished checking files, finding " + patientIds.size() + " patients"); int done = 0; int fixed = 0; for (String localPatientId: patientIds) { Reference localPatientReference = ReferenceHelper.createReference(ResourceType.Patient, localPatientId); Reference globalPatientReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(localPatientReference, filer); String patientUuid = ReferenceHelper.getReferenceId(globalPatientReference); List<ResourceType> potentialResourceTypes = new ArrayList<>(); potentialResourceTypes.add(ResourceType.Procedure); potentialResourceTypes.add(ResourceType.AllergyIntolerance); potentialResourceTypes.add(ResourceType.FamilyMemberHistory); potentialResourceTypes.add(ResourceType.Immunization); potentialResourceTypes.add(ResourceType.DiagnosticOrder); potentialResourceTypes.add(ResourceType.Specimen); potentialResourceTypes.add(ResourceType.DiagnosticReport); potentialResourceTypes.add(ResourceType.ReferralRequest); potentialResourceTypes.add(ResourceType.Condition); potentialResourceTypes.add(ResourceType.Observation); for (ResourceType resourceType: potentialResourceTypes) { List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(serviceId, UUID.fromString(patientUuid), resourceType.toString()); for (ResourceWrapper wrapper : wrappers) { if (wrapper.isDeleted()) { continue; } String originalJson = wrapper.getResourceData(); DomainResource resource = (DomainResource)FhirSerializationHelper.deserializeResource(originalJson); //Also go through all observation records and any that have parent observations - these need fixing too??? Extension extension = ExtensionConverter.findExtension(resource, FhirExtensionUri.PARENT_RESOURCE); if (extension != null) { Reference reference = (Reference)extension.getValue(); fixReference(serviceId, filer, reference, potentialResourceTypes); } if (resource instanceof Observation) { Observation obs = (Observation)resource; if (obs.hasRelated()) { for (Observation.ObservationRelatedComponent related: obs.getRelated()) { if (related.hasTarget()) { Reference reference = related.getTarget(); fixReference(serviceId, filer, reference, potentialResourceTypes); } } } } if (resource instanceof DiagnosticReport) { DiagnosticReport diag = (DiagnosticReport)resource; if (diag.hasResult()) { for (Reference reference: diag.getResult()) { fixReference(serviceId, filer, reference, potentialResourceTypes); } } } //Go through all patients, go through all problems, for any child that's Observation, find the true resource type then update and save if (resource instanceof Condition) { if (resource.hasContained()) { for (Resource contained: resource.getContained()) { if (contained.getId().equals("Items")) { List_ containedList = (List_)contained; if (containedList.hasEntry()) { for (List_.ListEntryComponent entry: containedList.getEntry()) { Reference reference = entry.getItem(); fixReference(serviceId, filer, reference, potentialResourceTypes); } } } } } //sort out the nested extension references Extension outerExtension = ExtensionConverter.findExtension(resource, FhirExtensionUri.PROBLEM_RELATED); if (outerExtension != null) { Extension innerExtension = ExtensionConverter.findExtension(outerExtension, FhirExtensionUri._PROBLEM_RELATED__TARGET); if (innerExtension != null) { Reference performerReference = (Reference)innerExtension.getValue(); String value = performerReference.getReference(); if (value.endsWith("}")) { Reference globalPerformerReference = IdHelper.convertLocallyUniqueReferenceToEdsReference(performerReference, filer); innerExtension.setValue(globalPerformerReference); } } } } //save the updated condition String newJson = FhirSerializationHelper.serializeResource(resource); if (!newJson.equals(originalJson)) { wrapper.setResourceData(newJson); saveResourceWrapper(serviceId, wrapper); fixed++; } } } done ++; if (done % 1000 == 0) { LOG.info("Done " + done + " patients and fixed " + fixed + " problems"); } } LOG.info("Done " + done + " patients and fixed " + fixed + " problems"); LOG.info("Finished Emis Problems 3 for " + serviceId); } catch (Exception ex) { LOG.error("", ex); } } private static boolean fixReference(UUID serviceId, HasServiceSystemAndExchangeIdI csvHelper, Reference reference, List<ResourceType> potentialResourceTypes) throws Exception { //if it's already something other than observation, we're OK ReferenceComponents comps = ReferenceHelper.getReferenceComponents(reference); if (comps.getResourceType() != ResourceType.Observation) { return false; } Reference sourceReference = IdHelper.convertEdsReferenceToLocallyUniqueReference(csvHelper, reference); String sourceId = ReferenceHelper.getReferenceId(sourceReference); String newReferenceValue = findTrueResourceType(serviceId, potentialResourceTypes, sourceId); if (newReferenceValue == null) { return false; } reference.setReference(newReferenceValue); return true; } private static String findTrueResourceType(UUID serviceId, List<ResourceType> potentials, String sourceId) throws Exception { ResourceDalI dal = DalProvider.factoryResourceDal(); for (ResourceType resourceType: potentials) { UUID uuid = IdHelper.getEdsResourceId(serviceId, resourceType, sourceId); if (uuid == null) { continue; } ResourceWrapper wrapper = dal.getCurrentVersion(serviceId, resourceType.toString(), uuid); if (wrapper != null) { return ReferenceHelper.createResourceReference(resourceType, uuid.toString()); } } return null; } /*private static void convertExchangeBody(UUID systemUuid) { try { LOG.info("Converting exchange bodies for system " + systemUuid); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemUuid, Integer.MAX_VALUE); if (exchanges.isEmpty()) { continue; } LOG.debug("doing " + service.getName() + " with " + exchanges.size() + " exchanges"); for (Exchange exchange: exchanges) { String exchangeBody = exchange.getBody(); try { //already done ExchangePayloadFile[] files = JsonSerializer.deserialize(exchangeBody, ExchangePayloadFile[].class); continue; } catch (JsonSyntaxException ex) { //if the JSON can't be parsed, then it'll be the old format of body that isn't JSON } List<ExchangePayloadFile> newFiles = new ArrayList<>(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); for (String file: files) { ExchangePayloadFile fileObj = new ExchangePayloadFile(); String fileWithoutSharedStorage = file.substring(TransformConfig.instance().getSharedStoragePath().length()+1); fileObj.setPath(fileWithoutSharedStorage); //size List<FileInfo> fileInfos = FileHelper.listFilesInSharedStorageWithInfo(file); for (FileInfo info: fileInfos) { if (info.getFilePath().equals(file)) { long size = info.getSize(); fileObj.setSize(new Long(size)); } } //type if (systemUuid.toString().equalsIgnoreCase("991a9068-01d3-4ff2-86ed-249bd0541fb3") //live || systemUuid.toString().equalsIgnoreCase("55c08fa5-ef1e-4e94-aadc-e3d6adc80774")) { //dev //emis String name = FilenameUtils.getName(file); String[] toks = name.split("_"); String first = toks[1]; String second = toks[2]; fileObj.setType(first + "_" + second); *//* } else if (systemUuid.toString().equalsIgnoreCase("e517fa69-348a-45e9-a113-d9b59ad13095") || systemUuid.toString().equalsIgnoreCase("b0277098-0b6c-4d9d-86ef-5f399fb25f34")) { //dev //cerner String name = FilenameUtils.getName(file); if (Strings.isNullOrEmpty(name)) { continue; } try { String type = BartsCsvToFhirTransformer.identifyFileType(name); fileObj.setType(type); } catch (Exception ex2) { throw new Exception("Failed to parse file name " + name + " on exchange " + exchange.getId()); }*//* } else { throw new Exception("Unknown system ID " + systemUuid); } newFiles.add(fileObj); } String json = JsonSerializer.serialize(newFiles); exchange.setBody(json); exchangeDal.save(exchange); } } LOG.info("Finished Converting exchange bodies for system " + systemUuid); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixBartsOrgs(String serviceId) { try { LOG.info("Fixing Barts orgs"); ResourceDalI dal = DalProvider.factoryResourceDal(); List<ResourceWrapper> wrappers = dal.getResourcesByService(UUID.fromString(serviceId), ResourceType.Organization.toString()); LOG.debug("Found " + wrappers.size() + " resources"); int done = 0; int fixed = 0; for (ResourceWrapper wrapper: wrappers) { if (!wrapper.isDeleted()) { List<ResourceWrapper> history = dal.getResourceHistory(UUID.fromString(serviceId), wrapper.getResourceType(), wrapper.getResourceId()); ResourceWrapper mostRecent = history.get(0); String json = mostRecent.getResourceData(); Organization org = (Organization)FhirSerializationHelper.deserializeResource(json); String odsCode = IdentifierHelper.findOdsCode(org); if (Strings.isNullOrEmpty(odsCode) && org.hasIdentifier()) { boolean hasBeenFixed = false; for (Identifier identifier: org.getIdentifier()) { if (identifier.getSystem().equals(FhirIdentifierUri.IDENTIFIER_SYSTEM_ODS_CODE) && identifier.hasId()) { odsCode = identifier.getId(); identifier.setValue(odsCode); identifier.setId(null); hasBeenFixed = true; } } if (hasBeenFixed) { String newJson = FhirSerializationHelper.serializeResource(org); mostRecent.setResourceData(newJson); LOG.debug("Fixed Organization " + org.getId()); *//*LOG.debug(json); LOG.debug(newJson);*//* saveResourceWrapper(UUID.fromString(serviceId), mostRecent); fixed ++; } } } done ++; if (done % 100 == 0) { LOG.debug("Done " + done + ", Fixed " + fixed); } } LOG.debug("Done " + done + ", Fixed " + fixed); LOG.info("Finished Barts orgs"); } catch (Throwable t) { LOG.error("", t); } }*/ /*private static void testPreparedStatements(String url, String user, String pass, String serviceId) { try { LOG.info("Testing Prepared Statements"); LOG.info("Url: " + url); LOG.info("user: " + user); LOG.info("pass: " + pass); //open connection Class.forName("com.mysql.cj.jdbc.Driver"); //create connection Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", pass); Connection conn = DriverManager.getConnection(url, props); String sql = "SELECT * FROM internal_id_map WHERE service_id = ? AND id_type = ? AND source_id = ?"; long start = System.currentTimeMillis(); for (int i=0; i<10000; i++) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setString(1, serviceId); ps.setString(2, "MILLPERSIDtoMRN"); ps.setString(3, UUID.randomUUID().toString()); ResultSet rs = ps.executeQuery(); while (rs.next()) { //do nothing } } finally { if (ps != null) { ps.close(); } } } long end = System.currentTimeMillis(); LOG.info("Took " + (end-start) + " ms"); //close connection conn.close(); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixEncounters(String table) { LOG.info("Fixing encounters from " + table); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date cutoff = sdf.parse("2018-03-14 11:42"); EntityManager entityManager = ConnectionManager.getAdminEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); List<UUID> serviceIds = new ArrayList<>(); Map<UUID, UUID> hmSystems = new HashMap<>(); String sql = "SELECT service_id, system_id FROM " + table + " WHERE done = 0"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { UUID serviceId = UUID.fromString(rs.getString(1)); UUID systemId = UUID.fromString(rs.getString(2)); serviceIds.add(serviceId); hmSystems.put(serviceId, systemId); } rs.close(); statement.close(); entityManager.close(); for (UUID serviceId: serviceIds) { UUID systemId = hmSystems.get(serviceId); LOG.info("Doing service " + serviceId + " and system " + systemId); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, systemId); List<UUID> exchangeIdsToProcess = new ArrayList<>(); for (UUID exchangeId: exchangeIds) { List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId); for (ExchangeTransformAudit audit: audits) { Date d = audit.getStarted(); if (d.after(cutoff)) { exchangeIdsToProcess.add(exchangeId); break; } } } Map<String, ReferenceList> consultationNewChildMap = new HashMap<>(); Map<String, ReferenceList> observationChildMap = new HashMap<>(); Map<String, ReferenceList> newProblemChildren = new HashMap<>(); for (UUID exchangeId: exchangeIdsToProcess) { Exchange exchange = exchangeDal.getExchange(exchangeId); String[] files = ExchangeHelper.parseExchangeBodyIntoFileList(exchange.getBody()); String version = EmisCsvToFhirTransformer.determineVersion(files); List<String> interestingFiles = new ArrayList<>(); for (String file: files) { if (file.indexOf("CareRecord_Consultation") > -1 || file.indexOf("CareRecord_Observation") > -1 || file.indexOf("CareRecord_Diary") > -1 || file.indexOf("Prescribing_DrugRecord") > -1 || file.indexOf("Prescribing_IssueRecord") > -1 || file.indexOf("CareRecord_Problem") > -1) { interestingFiles.add(file); } } files = interestingFiles.toArray(new String[0]); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.createParsers(serviceId, systemId, exchangeId, files, version, parsers); String dataSharingAgreementGuid = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(parsers); EmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchangeId, dataSharingAgreementGuid, true); Consultation consultationParser = (Consultation)parsers.get(Consultation.class); while (consultationParser.nextRecord()) { CsvCell consultationGuid = consultationParser.getConsultationGuid(); CsvCell patientGuid = consultationParser.getPatientGuid(); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); consultationNewChildMap.put(sourceId, new ReferenceList()); } Problem problemParser = (Problem)parsers.get(Problem.class); while (problemParser.nextRecord()) { CsvCell problemGuid = problemParser.getObservationGuid(); CsvCell patientGuid = problemParser.getPatientGuid(); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); newProblemChildren.put(sourceId, new ReferenceList()); } //run this pre-transformer to pre-cache some stuff in the csv helper, which //is needed when working out the resource type that each observation would be saved as ObservationPreTransformer.transform(version, parsers, null, csvHelper); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { CsvCell observationGuid = observationParser.getObservationGuid(); CsvCell patientGuid = observationParser.getPatientGuid(); String obSourceId = EmisCsvHelper.createUniqueId(patientGuid, observationGuid); CsvCell codeId = observationParser.getCodeId(); if (codeId.isEmpty()) { continue; } ResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper); UUID obUuid = IdHelper.getEdsResourceId(serviceId, resourceType, obSourceId); if (obUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + resourceType + " and source ID " + obSourceId); //resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper); } Reference obReference = ReferenceHelper.createReference(resourceType, obUuid.toString()); CsvCell consultationGuid = observationParser.getConsultationGuid(); if (!consultationGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); ReferenceList referenceList = consultationNewChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); consultationNewChildMap.put(sourceId, referenceList); } referenceList.add(obReference); } CsvCell problemGuid = observationParser.getProblemGuid(); if (!problemGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(obReference); } CsvCell parentObGuid = observationParser.getParentObservationGuid(); if (!parentObGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, parentObGuid); ReferenceList referenceList = observationChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); observationChildMap.put(sourceId, referenceList); } referenceList.add(obReference); } } Diary diaryParser = (Diary)parsers.get(Diary.class); while (diaryParser.nextRecord()) { CsvCell consultationGuid = diaryParser.getConsultationGuid(); if (!consultationGuid.isEmpty()) { CsvCell diaryGuid = diaryParser.getDiaryGuid(); CsvCell patientGuid = diaryParser.getPatientGuid(); String diarySourceId = EmisCsvHelper.createUniqueId(patientGuid, diaryGuid); UUID diaryUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.ProcedureRequest, diarySourceId); if (diaryUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.ProcedureRequest + " and source ID " + diarySourceId); } Reference diaryReference = ReferenceHelper.createReference(ResourceType.ProcedureRequest, diaryUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); ReferenceList referenceList = consultationNewChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); consultationNewChildMap.put(sourceId, referenceList); } referenceList.add(diaryReference); } } IssueRecord issueRecordParser = (IssueRecord)parsers.get(IssueRecord.class); while (issueRecordParser.nextRecord()) { CsvCell problemGuid = issueRecordParser.getProblemObservationGuid(); if (!problemGuid.isEmpty()) { CsvCell issueRecordGuid = issueRecordParser.getIssueRecordGuid(); CsvCell patientGuid = issueRecordParser.getPatientGuid(); String issueRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, issueRecordGuid); UUID issueRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationOrder, issueRecordSourceId); if (issueRecordUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.MedicationOrder + " and source ID " + issueRecordSourceId); } Reference issueRecordReference = ReferenceHelper.createReference(ResourceType.MedicationOrder, issueRecordUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(issueRecordReference); } } DrugRecord drugRecordParser = (DrugRecord)parsers.get(DrugRecord.class); while (drugRecordParser.nextRecord()) { CsvCell problemGuid = drugRecordParser.getProblemObservationGuid(); if (!problemGuid.isEmpty()) { CsvCell drugRecordGuid = drugRecordParser.getDrugRecordGuid(); CsvCell patientGuid = drugRecordParser.getPatientGuid(); String drugRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, drugRecordGuid); UUID drugRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationStatement, drugRecordSourceId); if (drugRecordUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.MedicationStatement + " and source ID " + drugRecordSourceId); } Reference drugRecordReference = ReferenceHelper.createReference(ResourceType.MedicationStatement, drugRecordUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(drugRecordReference); } } for (AbstractCsvParser parser : parsers.values()) { try { parser.close(); } catch (IOException ex) { //don't worry if this fails, as we're done anyway } } } ResourceDalI resourceDal = DalProvider.factoryResourceDal(); LOG.info("Found " + consultationNewChildMap.size() + " Encounters to fix"); for (String encounterSourceId: consultationNewChildMap.keySet()) { ReferenceList childReferences = consultationNewChildMap.get(encounterSourceId); //map to UUID UUID encounterId = IdHelper.getEdsResourceId(serviceId, ResourceType.Encounter, encounterSourceId); if (encounterId == null) { continue; } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, ResourceType.Encounter.toString(), encounterId); if (history.isEmpty()) { continue; //throw new Exception("Empty history for Encounter " + encounterId); } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (wrapper.getResourceData() != null) { Encounter encounter = (Encounter) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); EncounterBuilder encounterBuilder = new EncounterBuilder(encounter); ContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder); List<Reference> previousChildren = containedListBuilder.getContainedListItems(); childReferences.add(previousChildren); } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Encounter encounter = (Encounter)FhirSerializationHelper.deserializeResource(currentState.getResourceData()); EncounterBuilder encounterBuilder = new EncounterBuilder(encounter); ContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder); containedListBuilder.addReferences(childReferences); String newJson = FhirSerializationHelper.serializeResource(encounter); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState);*//* } LOG.info("Found " + observationChildMap.size() + " Parent Observations to fix"); for (String sourceId: observationChildMap.keySet()) { ReferenceList childReferences = observationChildMap.get(sourceId); //map to UUID ResourceType resourceType = null; UUID resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.Observation, sourceId); if (resourceId != null) { resourceType = ResourceType.Observation; } else { resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.DiagnosticReport, sourceId); if (resourceId != null) { resourceType = ResourceType.DiagnosticReport; } else { continue; } } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, resourceType.toString(), resourceId); if (history.isEmpty()) { //throw new Exception("Empty history for " + resourceType + " " + resourceId); continue; } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (resourceType == ResourceType.Observation) { if (wrapper.getResourceData() != null) { Observation observation = (Observation) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); if (observation.hasRelated()) { for (Observation.ObservationRelatedComponent related : observation.getRelated()) { Reference reference = related.getTarget(); childReferences.add(reference); } } } } else { if (wrapper.getResourceData() != null) { DiagnosticReport report = (DiagnosticReport) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); if (report.hasResult()) { for (Reference reference : report.getResult()) { childReferences.add(reference); } } } } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Resource resource = FhirSerializationHelper.deserializeResource(currentState.getResourceData()); boolean changed = false; if (resourceType == ResourceType.Observation) { ObservationBuilder resourceBuilder = new ObservationBuilder((Observation)resource); for (int i=0; i<childReferences.size(); i++) { Reference reference = childReferences.getReference(i); if (resourceBuilder.addChildObservation(reference)) { changed = true; } } } else { DiagnosticReportBuilder resourceBuilder = new DiagnosticReportBuilder((DiagnosticReport)resource); for (int i=0; i<childReferences.size(); i++) { Reference reference = childReferences.getReference(i); if (resourceBuilder.addResult(reference)) { changed = true; } } } if (changed) { String newJson = FhirSerializationHelper.serializeResource(resource); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); }*//* } LOG.info("Found " + newProblemChildren.size() + " Problems to fix"); for (String sourceId: newProblemChildren.keySet()) { ReferenceList childReferences = newProblemChildren.get(sourceId); //map to UUID UUID conditionId = IdHelper.getEdsResourceId(serviceId, ResourceType.Condition, sourceId); if (conditionId == null) { continue; } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, ResourceType.Condition.toString(), conditionId); if (history.isEmpty()) { continue; //throw new Exception("Empty history for Condition " + conditionId); } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (wrapper.getResourceData() != null) { Condition previousVersion = (Condition) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); ConditionBuilder conditionBuilder = new ConditionBuilder(previousVersion); ContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder); List<Reference> previousChildren = containedListBuilder.getContainedListItems(); childReferences.add(previousChildren); } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Condition condition = (Condition)FhirSerializationHelper.deserializeResource(currentState.getResourceData()); ConditionBuilder conditionBuilder = new ConditionBuilder(condition); ContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder); containedListBuilder.addReferences(childReferences); String newJson = FhirSerializationHelper.serializeResource(condition); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState);*//* } //mark as done String updateSql = "UPDATE " + table + " SET done = 1 WHERE service_id = '" + serviceId + "';"; entityManager = ConnectionManager.getAdminEntityManager(); session = (SessionImpl)entityManager.getDelegate(); connection = session.connection(); statement = connection.createStatement(); entityManager.getTransaction().begin(); statement.executeUpdate(updateSql); entityManager.getTransaction().commit(); } *//** * For each practice: Go through all files processed since 14 March Cache all links as above Cache all Encounters saved too For each Encounter referenced at all: Retrieve latest version from resource current Retrieve version prior to 14 March Update current version with old references plus new ones For each parent observation: Retrieve latest version (could be observation or diagnostic report) For each problem: Retrieve latest version from resource current Check if still a problem: Retrieve version prior to 14 March Update current version with old references plus new ones *//* LOG.info("Finished Fixing encounters from " + table); } catch (Throwable t) { LOG.error("", t); } }*/ private static void saveResourceWrapper(UUID serviceId, ResourceWrapper wrapper) throws Exception { if (wrapper.getResourceData() != null) { long checksum = FhirStorageService.generateChecksum(wrapper.getResourceData()); wrapper.setResourceChecksum(new Long(checksum)); } EntityManager entityManager = ConnectionManager.getEhrEntityManager(serviceId); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); entityManager.getTransaction().begin(); String json = wrapper.getResourceData(); json = json.replace("'", "''"); json = json.replace("\\", "\\\\"); String patientId = ""; if (wrapper.getPatientId() != null) { patientId = wrapper.getPatientId().toString(); } String updateSql = "UPDATE resource_current" + " SET resource_data = '" + json + "'," + " resource_checksum = " + wrapper.getResourceChecksum() + " WHERE service_id = '" + wrapper.getServiceId() + "'" + " AND patient_id = '" + patientId + "'" + " AND resource_type = '" + wrapper.getResourceType() + "'" + " AND resource_id = '" + wrapper.getResourceId() + "'"; statement.executeUpdate(updateSql); //LOG.debug(updateSql); //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS"); //String createdAtStr = sdf.format(wrapper.getCreatedAt()); updateSql = "UPDATE resource_history" + " SET resource_data = '" + json + "'," + " resource_checksum = " + wrapper.getResourceChecksum() + " WHERE resource_id = '" + wrapper.getResourceId() + "'" + " AND resource_type = '" + wrapper.getResourceType() + "'" //+ " AND created_at = '" + createdAtStr + "'" + " AND version = '" + wrapper.getVersion() + "'"; statement.executeUpdate(updateSql); //LOG.debug(updateSql); entityManager.getTransaction().commit(); } /*private static void populateNewSearchTable(String table) { LOG.info("Populating New Search Table"); try { EntityManager entityManager = ConnectionManager.getEdsEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); List<String> patientIds = new ArrayList<>(); Map<String, String> serviceIds = new HashMap<>(); String sql = "SELECT patient_id, service_id FROM " + table + " WHERE done = 0"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String patientId = rs.getString(1); String serviceId = rs.getString(2); patientIds.add(patientId); serviceIds.put(patientId, serviceId); } rs.close(); statement.close(); entityManager.close(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearch2Dal(); LOG.info("Found " + patientIds.size() + " to do"); for (int i=0; i<patientIds.size(); i++) { String patientIdStr = patientIds.get(i); UUID patientId = UUID.fromString(patientIdStr); String serviceIdStr = serviceIds.get(patientIdStr); UUID serviceId = UUID.fromString(serviceIdStr); Patient patient = (Patient)resourceDal.getCurrentVersionAsResource(serviceId, ResourceType.Patient, patientIdStr); if (patient != null) { patientSearchDal.update(serviceId, patient); //find episode of care List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(serviceId, null, patientId, ResourceType.EpisodeOfCare.toString()); for (ResourceWrapper wrapper: wrappers) { if (!wrapper.isDeleted()) { EpisodeOfCare episodeOfCare = (EpisodeOfCare)FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); patientSearchDal.update(serviceId, episodeOfCare); } } } String updateSql = "UPDATE " + table + " SET done = 1 WHERE patient_id = '" + patientIdStr + "' AND service_id = '" + serviceIdStr + "';"; entityManager = ConnectionManager.getEdsEntityManager(); session = (SessionImpl)entityManager.getDelegate(); connection = session.connection(); statement = connection.createStatement(); entityManager.getTransaction().begin(); statement.executeUpdate(updateSql); entityManager.getTransaction().commit(); if (i % 5000 == 0) { LOG.info("Done " + (i+1) + " of " + patientIds.size()); } } entityManager.close(); LOG.info("Finished Populating New Search Table"); } catch (Exception ex) { LOG.error("", ex); } }*/ private static void createBartsSubset(String sourceDir, UUID serviceUuid, UUID systemUuid, String samplePatientsFile) { LOG.info("Creating Barts Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } createBartsSubsetForFile(sourceDir, serviceUuid, systemUuid, personIds); LOG.info("Finished Creating Barts Subset"); } catch (Throwable t) { LOG.error("", t); } } /*private static void createBartsSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { for (File sourceFile: sourceDir.listFiles()) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } LOG.info("Doing dir " + sourceFile); createBartsSubsetForFile(sourceFile, destFile, personIds); } else { //we have some bad partial files in, so ignore them String ext = FilenameUtils.getExtension(name); if (ext.equalsIgnoreCase("filepart")) { continue; } //if the file is empty, we still need the empty file in the filtered directory, so just copy it if (sourceFile.length() == 0) { LOG.info("Copying empty file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } continue; } String baseName = FilenameUtils.getBaseName(name); String fileType = BartsCsvToFhirTransformer.identifyFileType(baseName); if (isCerner22File(fileType)) { LOG.info("Checking 2.2 file " + sourceFile); if (destFile.exists()) { destFile.delete(); } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); int lineIndex = -1; PrintWriter pw = null; int personIdColIndex = -1; int expectedCols = -1; while (true) { String line = br.readLine(); if (line == null) { break; } lineIndex ++; if (lineIndex == 0) { if (fileType.equalsIgnoreCase("FAMILYHISTORY")) { //this file has no headers, so needs hard-coding personIdColIndex = 5; } else { //check headings for PersonID col String[] toks = line.split("\\|", -1); expectedCols = toks.length; for (int i=0; i<expectedCols; i++) { String col = toks[i]; if (col.equalsIgnoreCase("PERSON_ID") || col.equalsIgnoreCase("#PERSON_ID")) { personIdColIndex = i; break; } } //if no person ID, then just copy the entire file if (personIdColIndex == -1) { br.close(); br = null; LOG.info(" Copying 2.2 file to " + destFile); copyFile(sourceFile, destFile); break; } else { LOG.info(" Filtering 2.2 file to " + destFile + ", person ID col at " + personIdColIndex); } } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } else { //filter on personID String[] toks = line.split("\\|", -1); if (expectedCols != -1 && toks.length != expectedCols) { throw new Exception("Line " + (lineIndex+1) + " has " + toks.length + " cols but expecting " + expectedCols); } else { String personId = toks[personIdColIndex]; if (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes && !personIds.contains(personId)) { continue; } } } pw.println(line); } if (br != null) { br.close(); } if (pw != null) { pw.flush(); pw.close(); } } else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } } } } }*/ private static void createBartsSubsetForFile(String sourceDir, UUID serviceUuid, UUID systemUuid, Set<String> personIds) throws Exception { ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE); for (Exchange exchange: exchanges) { List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(exchange.getBody()); for (ExchangePayloadFile fileObj : files) { String filePathWithoutSharedStorage = fileObj.getPath().substring(TransformConfig.instance().getSharedStoragePath().length()+1); String sourceFilePath = FilenameUtils.concat(sourceDir, filePathWithoutSharedStorage); File sourceFile = new File(sourceFilePath); String destFilePath = fileObj.getPath(); File destFile = new File(destFilePath); File destDir = destFile.getParentFile(); if (!destDir.exists()) { destDir.mkdirs(); } //if the file is empty, we still need the empty file in the filtered directory, so just copy it if (sourceFile.length() == 0) { LOG.info("Copying empty file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } continue; } String fileType = fileObj.getType(); if (isCerner22File(fileType)) { LOG.info("Checking 2.2 file " + sourceFile); if (destFile.exists()) { destFile.delete(); } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); int lineIndex = -1; PrintWriter pw = null; int personIdColIndex = -1; int expectedCols = -1; while (true) { String line = br.readLine(); if (line == null) { break; } lineIndex++; if (lineIndex == 0) { if (fileType.equalsIgnoreCase("FAMILYHISTORY")) { //this file has no headers, so needs hard-coding personIdColIndex = 5; } else { //check headings for PersonID col String[] toks = line.split("\\|", -1); expectedCols = toks.length; for (int i = 0; i < expectedCols; i++) { String col = toks[i]; if (col.equalsIgnoreCase("PERSON_ID") || col.equalsIgnoreCase("#PERSON_ID")) { personIdColIndex = i; break; } } //if no person ID, then just copy the entire file if (personIdColIndex == -1) { br.close(); br = null; LOG.info(" Copying 2.2 file to " + destFile); copyFile(sourceFile, destFile); break; } else { LOG.info(" Filtering 2.2 file to " + destFile + ", person ID col at " + personIdColIndex); } } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } else { //filter on personID String[] toks = line.split("\\|", -1); if (expectedCols != -1 && toks.length != expectedCols) { throw new Exception("Line " + (lineIndex + 1) + " has " + toks.length + " cols but expecting " + expectedCols); } else { String personId = toks[personIdColIndex]; if (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes && !personIds.contains(personId)) { continue; } } } pw.println(line); } if (br != null) { br.close(); } if (pw != null) { pw.flush(); pw.close(); } } else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } } } } } private static void copyFile(File src, File dst) throws Exception { FileInputStream fis = new FileInputStream(src); BufferedInputStream bis = new BufferedInputStream(fis); Files.copy(bis, dst.toPath()); bis.close(); } private static boolean isCerner22File(String fileType) throws Exception { if (fileType.equalsIgnoreCase("PPATI") || fileType.equalsIgnoreCase("PPREL") || fileType.equalsIgnoreCase("CDSEV") || fileType.equalsIgnoreCase("PPATH") || fileType.equalsIgnoreCase("RTTPE") || fileType.equalsIgnoreCase("AEATT") || fileType.equalsIgnoreCase("AEINV") || fileType.equalsIgnoreCase("AETRE") || fileType.equalsIgnoreCase("OPREF") || fileType.equalsIgnoreCase("OPATT") || fileType.equalsIgnoreCase("EALEN") || fileType.equalsIgnoreCase("EALSU") || fileType.equalsIgnoreCase("EALOF") || fileType.equalsIgnoreCase("HPSSP") || fileType.equalsIgnoreCase("IPEPI") || fileType.equalsIgnoreCase("IPWDS") || fileType.equalsIgnoreCase("DELIV") || fileType.equalsIgnoreCase("BIRTH") || fileType.equalsIgnoreCase("SCHAC") || fileType.equalsIgnoreCase("APPSL") || fileType.equalsIgnoreCase("DIAGN") || fileType.equalsIgnoreCase("PROCE") || fileType.equalsIgnoreCase("ORDER") || fileType.equalsIgnoreCase("DOCRP") || fileType.equalsIgnoreCase("DOCREF") || fileType.equalsIgnoreCase("CNTRQ") || fileType.equalsIgnoreCase("LETRS") || fileType.equalsIgnoreCase("LOREF") || fileType.equalsIgnoreCase("ORGREF") || fileType.equalsIgnoreCase("PRSNLREF") || fileType.equalsIgnoreCase("CVREF") || fileType.equalsIgnoreCase("NOMREF") || fileType.equalsIgnoreCase("EALIP") || fileType.equalsIgnoreCase("CLEVE") || fileType.equalsIgnoreCase("ENCNT") || fileType.equalsIgnoreCase("RESREF") || fileType.equalsIgnoreCase("PPNAM") || fileType.equalsIgnoreCase("PPADD") || fileType.equalsIgnoreCase("PPPHO") || fileType.equalsIgnoreCase("PPALI") || fileType.equalsIgnoreCase("PPINF") || fileType.equalsIgnoreCase("PPAGP") || fileType.equalsIgnoreCase("SURCC") || fileType.equalsIgnoreCase("SURCP") || fileType.equalsIgnoreCase("SURCA") || fileType.equalsIgnoreCase("SURCD") || fileType.equalsIgnoreCase("PDRES") || fileType.equalsIgnoreCase("PDREF") || fileType.equalsIgnoreCase("ABREF") || fileType.equalsIgnoreCase("CEPRS") || fileType.equalsIgnoreCase("ORDDT") || fileType.equalsIgnoreCase("STATREF") || fileType.equalsIgnoreCase("STATA") || fileType.equalsIgnoreCase("ENCINF") || fileType.equalsIgnoreCase("SCHDETAIL") || fileType.equalsIgnoreCase("SCHOFFER") || fileType.equalsIgnoreCase("PPGPORG") || fileType.equalsIgnoreCase("FAMILYHISTORY")) { return true; } else { return false; } } private static void fixSubscriberDbs() { LOG.info("Fixing Subscriber DBs"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); Date dateError = new SimpleDateFormat("yyyy-MM-dd").parse("2018-05-11"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); boolean needsFixing = false; for (UUID exchangeId: exchangeIds) { if (!needsFixing) { List<ExchangeTransformAudit> transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId); for (ExchangeTransformAudit audit: transformAudits) { Date transfromStart = audit.getStarted(); if (!transfromStart.before(dateError)) { needsFixing = true; break; } } } if (!needsFixing) { continue; } List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); LOG.info(" Posting exchange " + exchangeId + " with " + batches.size() + " batches"); List<UUID> batchIds = new ArrayList<>(); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } UUID batchId = batch.getBatchId(); batchIds.add(batchId); } String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } LOG.info("Finished Fixing Subscriber DBs"); } catch (Throwable t) { LOG.error("", t); } } /*private static void fixReferralRequests() { LOG.info("Fixing Referral Requests"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); Date dateError = new SimpleDateFormat("yyyy-MM-dd").parse("2018-04-24"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); boolean needsFixing = false; Set<UUID> patientIdsToPost = new HashSet<>(); for (UUID exchangeId: exchangeIds) { if (!needsFixing) { List<ExchangeTransformAudit> transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId); for (ExchangeTransformAudit audit: transformAudits) { Date transfromStart = audit.getStarted(); if (!transfromStart.before(dateError)) { needsFixing = true; break; } } } if (!needsFixing) { continue; } List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); LOG.info("Checking exchange " + exchangeId + " with " + batches.size() + " batches"); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } UUID batchId = batch.getBatchId(); List<ResourceWrapper> wrappers = resourceDal.getResourcesForBatch(serviceId, batchId); for (ResourceWrapper wrapper: wrappers) { String resourceType = wrapper.getResourceType(); if (!resourceType.equals(ResourceType.ReferralRequest.toString()) || wrapper.isDeleted()) { continue; } String json = wrapper.getResourceData(); ReferralRequest referral = (ReferralRequest)FhirSerializationHelper.deserializeResource(json); *//*if (!referral.hasServiceRequested()) { continue; } CodeableConcept reason = referral.getServiceRequested().get(0); referral.setReason(reason); referral.getServiceRequested().clear();*//* if (!referral.hasReason()) { continue; } CodeableConcept reason = referral.getReason(); referral.setReason(null); referral.addServiceRequested(reason); json = FhirSerializationHelper.serializeResource(referral); wrapper.setResourceData(json); saveResourceWrapper(serviceId, wrapper); //add to the set of patients we know need sending on to the protocol queue patientIdsToPost.add(patientId); LOG.info("Fixed " + resourceType + " " + wrapper.getResourceId() + " in batch " + batchId); } //if our patient has just been fixed or was fixed before, post onto the protocol queue if (patientIdsToPost.contains(patientId)) { List<UUID> batchIds = new ArrayList<>(); batchIds.add(batchId); String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } } } LOG.info("Finished Fixing Referral Requests"); } catch (Throwable t) { LOG.error("", t); } }*/ private static void applyEmisAdminCaches() { LOG.info("Applying Emis Admin Caches"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } if (!exchangeDal.isServiceStarted(serviceId, endpointSystemId)) { LOG.info(" Service not started, so skipping"); continue; } //get exchanges List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); if (exchangeIds.isEmpty()) { LOG.info(" No exchanges found, so skipping"); continue; } UUID firstExchangeId = exchangeIds.get(0); List<ExchangeEvent> events = exchangeDal.getExchangeEvents(firstExchangeId); boolean appliedAdminCache = false; for (ExchangeEvent event: events) { if (event.getEventDesc().equals("Applied Emis Admin Resource Cache")) { appliedAdminCache = true; } } if (appliedAdminCache) { LOG.info(" Have already applied admin cache, so skipping"); continue; } Exchange exchange = exchangeDal.getExchange(firstExchangeId); String body = exchange.getBody(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(body); if (files.length == 0) { LOG.info(" No files in exchange " + firstExchangeId + " so skipping"); continue; } String firstFilePath = files[0]; String name = FilenameUtils.getBaseName(firstFilePath); //file name without extension String[] toks = name.split("_"); if (toks.length != 5) { throw new TransformException("Failed to extract data sharing agreement GUID from filename " + firstFilePath); } String sharingAgreementGuid = toks[4]; List<UUID> batchIds = new ArrayList<>(); TransformError transformError = new TransformError(); FhirResourceFiler fhirResourceFiler = new FhirResourceFiler(firstExchangeId, serviceId, endpointSystemId, transformError, batchIds); EmisCsvHelper csvHelper = new EmisCsvHelper(fhirResourceFiler.getServiceId(), fhirResourceFiler.getSystemId(), fhirResourceFiler.getExchangeId(), sharingAgreementGuid, true); ExchangeTransformAudit transformAudit = new ExchangeTransformAudit(); transformAudit.setServiceId(serviceId); transformAudit.setSystemId(endpointSystemId); transformAudit.setExchangeId(firstExchangeId); transformAudit.setId(UUID.randomUUID()); transformAudit.setStarted(new Date()); LOG.info(" Going to apply admin resource cache"); csvHelper.applyAdminResourceCache(fhirResourceFiler); fhirResourceFiler.waitToFinish(); for (UUID batchId: batchIds) { LOG.info(" Created batch ID " + batchId + " for exchange " + firstExchangeId); } transformAudit.setEnded(new Date()); transformAudit.setNumberBatchesCreated(new Integer(batchIds.size())); boolean hadError = false; if (transformError.getError().size() > 0) { transformAudit.setErrorXml(TransformErrorSerializer.writeToXml(transformError)); hadError = true; } exchangeDal.save(transformAudit); //clear down the cache of reference mappings since they won't be of much use for the next Exchange IdHelper.clearCache(); if (hadError) { LOG.error(" <<<<<<Error applying resource cache!"); continue; } //add the event to say we've applied the cache AuditWriter.writeExchangeEvent(firstExchangeId, "Applied Emis Admin Resource Cache"); //post that ONE new batch ID onto the protocol queue String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } LOG.info("Finished Applying Emis Admin Caches"); } catch (Throwable t) { LOG.error("", t); } } /*private static void fixBartsEscapedFiles(String filePath) { LOG.info("Fixing Barts Escaped Files in " + filePath); try { fixBartsEscapedFilesInDir(new File(filePath)); LOG.info("Finished fixing Barts Escaped Files in " + filePath); } catch (Throwable t) { LOG.error("", t); } } /** * fixes Emis extract(s) when a practice was disabled then subsequently re-bulked, by * replacing the "delete" extracts with newly generated deltas that can be processed * before the re-bulk is done */ private static void fixDisabledEmisExtract(String serviceId, String systemId, String sharedStoragePath, String tempDir) { LOG.info("Fixing Disabled Emis Extracts Prior to Re-bulk for service " + serviceId); try { /*File tempDirLast = new File(tempDir, "last"); if (!tempDirLast.exists()) { if (!tempDirLast.mkdirs()) { throw new Exception("Failed to create temp dir " + tempDirLast); } tempDirLast.mkdirs(); } File tempDirEmpty = new File(tempDir, "empty"); if (!tempDirEmpty.exists()) { if (!tempDirEmpty.mkdirs()) { throw new Exception("Failed to create temp dir " + tempDirEmpty); } tempDirEmpty.mkdirs(); }*/ UUID serviceUuid = UUID.fromString(serviceId); UUID systemUuid = UUID.fromString(systemId); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); //get all the exchanges, which are returned in reverse order, so reverse for simplicity List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE); //sorting by timestamp seems unreliable when exchanges were posted close together? List<Exchange> tmp = new ArrayList<>(); for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); tmp.add(exchange); } exchanges = tmp; /*exchanges.sort((o1, o2) -> { Date d1 = o1.getTimestamp(); Date d2 = o2.getTimestamp(); return d1.compareTo(d2); });*/ LOG.info("Found " + exchanges.size() + " exchanges"); //continueOrQuit(); //find the files for each exchange Map<Exchange, List<String>> hmExchangeFiles = new HashMap<>(); Map<Exchange, List<String>> hmExchangeFilesWithoutStoragePrefix = new HashMap<>(); for (Exchange exchange: exchanges) { //populate a map of the files with the shared storage prefix String exchangeBody = exchange.getBody(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); List<String> fileList = Lists.newArrayList(files); hmExchangeFiles.put(exchange, fileList); //populate a map of the same files without the prefix files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); for (int i=0; i<files.length; i++) { String file = files[i].substring(sharedStoragePath.length() + 1); files[i] = file; } fileList = Lists.newArrayList(files); hmExchangeFilesWithoutStoragePrefix.put(exchange, fileList); } LOG.info("Cached files for each exchange"); int indexDisabled = -1; int indexRebulked = -1; int indexOriginallyBulked = -1; //go back through them to find the extract where the re-bulk is and when it was disabled for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); boolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles); if (disabled) { indexDisabled = i; } else { if (indexDisabled == -1) { indexRebulked = i; } else { //if we've found a non-disabled extract older than the disabled ones, //then we've gone far enough back break; } } } //go back from when disabled to find the previous bulk load (i.e. the first one or one after it was previously not disabled) for (int i=indexDisabled-1; i>=0; i--) { Exchange exchange = exchanges.get(i); boolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles); if (disabled) { break; } indexOriginallyBulked = i; } if (indexDisabled == -1 || indexRebulked == -1 || indexOriginallyBulked == -1) { throw new Exception("Failed to find exchanges for disabling (" + indexDisabled + "), re-bulking (" + indexRebulked + ") or original bulk (" + indexOriginallyBulked + ")"); } Exchange exchangeDisabled = exchanges.get(indexDisabled); LOG.info("Disabled on " + findExtractDate(exchangeDisabled, hmExchangeFiles) + " " + exchangeDisabled.getId()); Exchange exchangeRebulked = exchanges.get(indexRebulked); LOG.info("Rebulked on " + findExtractDate(exchangeRebulked, hmExchangeFiles) + " " + exchangeRebulked.getId()); Exchange exchangeOriginallyBulked = exchanges.get(indexOriginallyBulked); LOG.info("Originally bulked on " + findExtractDate(exchangeOriginallyBulked, hmExchangeFiles) + " " + exchangeOriginallyBulked.getId()); //continueOrQuit(); List<String> rebulkFiles = hmExchangeFiles.get(exchangeRebulked); List<String> tempFilesCreated = new ArrayList<>(); Set<String> patientGuidsDeletedOrTooOld = new HashSet<>(); for (String rebulkFile: rebulkFiles) { String fileType = findFileType(rebulkFile); if (!isPatientFile(fileType)) { continue; } LOG.info("Doing " + fileType); String guidColumnName = getGuidColumnName(fileType); //find all the guids in the re-bulk Set<String> idsInRebulk = new HashSet<>(); InputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(rebulkFile); CSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); String[] headers = null; try { headers = CsvHelper.getHeaderMapAsArray(csvParser); Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); //get the patient and row guid out of the file and cache in our set String id = record.get("PatientGuid"); if (!Strings.isNullOrEmpty(guidColumnName)) { id += "//" + record.get(guidColumnName); } idsInRebulk.add(id); } } finally { csvParser.close(); } LOG.info("Found " + idsInRebulk.size() + " IDs in re-bulk file: " + rebulkFile); //create a replacement file for the exchange the service was disabled String replacementDisabledFile = null; List<String> disabledFiles = hmExchangeFilesWithoutStoragePrefix.get(exchangeDisabled); for (String s: disabledFiles) { String disabledFileType = findFileType(s); if (disabledFileType.equals(fileType)) { replacementDisabledFile = FilenameUtils.concat(tempDir, s); File dir = new File(replacementDisabledFile).getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("Failed to create directory " + dir); } } tempFilesCreated.add(s); LOG.info("Created replacement file " + replacementDisabledFile); } } FileWriter fileWriter = new FileWriter(replacementDisabledFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers)); csvPrinter.flush(); Set<String> pastIdsProcessed = new HashSet<>(); //now go through all files of the same type PRIOR to the service was disabled //to find any rows that we'll need to explicitly delete because they were deleted while //the extract was disabled for (int i=indexDisabled-1; i>=indexOriginallyBulked; i--) { Exchange exchange = exchanges.get(i); String originalFile = null; List<String> files = hmExchangeFiles.get(exchange); for (String s: files) { String originalFileType = findFileType(s); if (originalFileType.equals(fileType)) { originalFile = s; break; } } if (originalFile == null) { continue; } LOG.info(" Reading " + originalFile); reader = FileHelper.readFileReaderFromSharedStorage(originalFile); csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); try { Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String patientGuid = record.get("PatientGuid"); //get the patient and row guid out of the file and cache in our set String uniqueId = patientGuid; if (!Strings.isNullOrEmpty(guidColumnName)) { uniqueId += "//" + record.get(guidColumnName); } //if we're already handled this record in a more recent extract, then skip it if (pastIdsProcessed.contains(uniqueId)) { continue; } pastIdsProcessed.add(uniqueId); //if this ID isn't deleted and isn't in the re-bulk then it means //it WAS deleted in Emis Web but we didn't receive the delete, because it was deleted //from Emis Web while the extract feed was disabled //if the record is deleted, then we won't expect it in the re-bulk boolean deleted = Boolean.parseBoolean(record.get("Deleted")); if (deleted) { //if it's the Patient file, stick the patient GUID in a set so we know full patient record deletes if (fileType.equals("Admin_Patient")) { patientGuidsDeletedOrTooOld.add(patientGuid); } continue; } //if it's not the patient file and we refer to a patient that we know //has been deleted, then skip this row, since we know we're deleting the entire patient record if (patientGuidsDeletedOrTooOld.contains(patientGuid)) { continue; } //if the re-bulk contains a record matching this one, then it's OK if (idsInRebulk.contains(uniqueId)) { continue; } //the rebulk won't contain any data for patients that are now too old (i.e. deducted or deceased > 2 yrs ago), //so any patient ID in the original files but not in the rebulk can be treated like this and any data for them can be skipped if (fileType.equals("Admin_Patient")) { //retrieve the Patient and EpisodeOfCare resource for the patient so we can confirm they are deceased or deducted ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID patientUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.Patient, patientGuid); if (patientUuid == null) { throw new Exception("Failed to find patient UUID from GUID [" + patientGuid + "]"); } Patient patientResource = (Patient)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.Patient, patientUuid.toString()); if (patientResource.hasDeceased()) { patientGuidsDeletedOrTooOld.add(patientGuid); continue; } UUID episodeUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.EpisodeOfCare, patientGuid); //we use the patient GUID for the episode too EpisodeOfCare episodeResource = (EpisodeOfCare)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.EpisodeOfCare, episodeUuid.toString()); if (episodeResource.hasPeriod() && !PeriodHelper.isActive(episodeResource.getPeriod())) { patientGuidsDeletedOrTooOld.add(patientGuid); continue; } } //create a new CSV record, carrying over the GUIDs from the original but marking as deleted String[] newRecord = new String[headers.length]; for (int j=0; j<newRecord.length; j++) { String header = headers[j]; if (header.equals("PatientGuid") || header.equals("OrganisationGuid") || (!Strings.isNullOrEmpty(guidColumnName) && header.equals(guidColumnName))) { String val = record.get(header); newRecord[j] = val; } else if (header.equals("Deleted")) { newRecord[j] = "true"; } else { newRecord[j] = ""; } } csvPrinter.printRecord((Object[])newRecord); csvPrinter.flush(); //log out the raw record that's missing from the original StringBuffer sb = new StringBuffer(); sb.append("Record not in re-bulk: "); for (int j=0; j<record.size(); j++) { if (j > 0) { sb.append(","); } sb.append(record.get(j)); } LOG.info(sb.toString()); } } finally { csvParser.close(); } } csvPrinter.flush(); csvPrinter.close(); //also create a version of the CSV file with just the header and nothing else in for (int i=indexDisabled+1; i<indexRebulked; i++) { Exchange ex = exchanges.get(i); List<String> exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex); for (String s: exchangeFiles) { String exchangeFileType = findFileType(s); if (exchangeFileType.equals(fileType)) { String emptyTempFile = FilenameUtils.concat(tempDir, s); File dir = new File(emptyTempFile).getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("Failed to create directory " + dir); } } fileWriter = new FileWriter(emptyTempFile); bufferedWriter = new BufferedWriter(fileWriter); csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers)); csvPrinter.flush(); csvPrinter.close(); tempFilesCreated.add(s); LOG.info("Created empty file " + emptyTempFile); } } } } //we also need to copy the restored sharing agreement file to replace all the period it was disabled String rebulkedSharingAgreementFile = null; for (String s: rebulkFiles) { String fileType = findFileType(s); if (fileType.equals("Agreements_SharingOrganisation")) { rebulkedSharingAgreementFile = s; } } for (int i=indexDisabled; i<indexRebulked; i++) { Exchange ex = exchanges.get(i); List<String> exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex); for (String s: exchangeFiles) { String exchangeFileType = findFileType(s); if (exchangeFileType.equals("Agreements_SharingOrganisation")) { String replacementFile = FilenameUtils.concat(tempDir, s); InputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkedSharingAgreementFile); Files.copy(inputStream, new File(replacementFile).toPath()); inputStream.close(); tempFilesCreated.add(s); } } } //create a script to copy the files into S3 List<String> copyScript = new ArrayList<>(); copyScript.add("#!/bin/bash"); copyScript.add(""); for (String s: tempFilesCreated) { String localFile = FilenameUtils.concat(tempDir, s); copyScript.add("sudo aws s3 cp " + localFile + " s3://discoverysftplanding/endeavour/" + s); } String scriptFile = FilenameUtils.concat(tempDir, "copy.sh"); FileUtils.writeLines(new File(scriptFile), copyScript); /*continueOrQuit(); //back up every file where the service was disabled for (int i=indexDisabled; i<indexRebulked; i++) { Exchange exchange = exchanges.get(i); List<String> files = hmExchangeFiles.get(exchange); for (String file: files) { //first download from S3 to the local temp dir InputStream inputStream = FileHelper.readFileFromSharedStorage(file); String fileName = FilenameUtils.getName(file); String tempPath = FilenameUtils.concat(tempDir, fileName); File downloadDestination = new File(tempPath); Files.copy(inputStream, downloadDestination.toPath()); //then write back to S3 in a sub-dir of the original file String backupPath = FilenameUtils.getPath(file); backupPath = FilenameUtils.concat(backupPath, "Original"); backupPath = FilenameUtils.concat(backupPath, fileName); FileHelper.writeFileToSharedStorage(backupPath, downloadDestination); LOG.info("Backed up " + file + " -> " + backupPath); //delete from temp dir downloadDestination.delete(); } } continueOrQuit(); //copy the new CSV files into the dir where it was disabled List<String> disabledFiles = hmExchangeFiles.get(exchangeDisabled); for (String disabledFile: disabledFiles) { String fileType = findFileType(disabledFile); if (!isPatientFile(fileType)) { continue; } String tempFile = FilenameUtils.concat(tempDirLast.getAbsolutePath(), fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected temp file " + f); } FileHelper.writeFileToSharedStorage(disabledFile, f); LOG.info("Copied " + tempFile + " -> " + disabledFile); } continueOrQuit(); //empty the patient files for any extracts while the service was disabled for (int i=indexDisabled+1; i<indexRebulked; i++) { Exchange otherExchangeDisabled = exchanges.get(i); List<String> otherDisabledFiles = hmExchangeFiles.get(otherExchangeDisabled); for (String otherDisabledFile: otherDisabledFiles) { String fileType = findFileType(otherDisabledFile); if (!isPatientFile(fileType)) { continue; } String tempFile = FilenameUtils.concat(tempDirEmpty.getAbsolutePath(), fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected empty file " + f); } FileHelper.writeFileToSharedStorage(otherDisabledFile, f); LOG.info("Copied " + tempFile + " -> " + otherDisabledFile); } } continueOrQuit(); //copy the content of the sharing agreement file from when it was re-bulked for (String rebulkFile: rebulkFiles) { String fileType = findFileType(rebulkFile); if (fileType.equals("Agreements_SharingOrganisation")) { String tempFile = FilenameUtils.concat(tempDir, fileType + ".csv"); File downloadDestination = new File(tempFile); InputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkFile); Files.copy(inputStream, downloadDestination.toPath()); tempFilesCreated.add(tempFile); } } //replace the sharing agreement file for all disabled extracts with the non-disabled one for (int i=indexDisabled; i<indexRebulked; i++) { Exchange exchange = exchanges.get(i); List<String> files = hmExchangeFiles.get(exchange); for (String file: files) { String fileType = findFileType(file); if (fileType.equals("Agreements_SharingOrganisation")) { String tempFile = FilenameUtils.concat(tempDir, fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected empty file " + f); } FileHelper.writeFileToSharedStorage(file, f); LOG.info("Copied " + tempFile + " -> " + file); } } } LOG.info("Finished Fixing Disabled Emis Extracts Prior to Re-bulk for service " + serviceId); continueOrQuit(); for (String tempFileCreated: tempFilesCreated) { File f = new File(tempFileCreated); if (f.exists()) { f.delete(); } }*/ } catch (Exception ex) { LOG.error("", ex); } } private static String findExtractDate(Exchange exchange, Map<Exchange, List<String>> fileMap) throws Exception { List<String> files = fileMap.get(exchange); String file = findSharingAgreementFile(files); String name = FilenameUtils.getBaseName(file); String[] toks = name.split("_"); return toks[3]; } private static boolean isDisabledInSharingAgreementFile(Exchange exchange, Map<Exchange, List<String>> fileMap) throws Exception { List<String> files = fileMap.get(exchange); String file = findSharingAgreementFile(files); InputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(file); CSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); try { Iterator<CSVRecord> iterator = csvParser.iterator(); CSVRecord record = iterator.next(); String s = record.get("Disabled"); boolean disabled = Boolean.parseBoolean(s); return disabled; } finally { csvParser.close(); } } private static void continueOrQuit() throws Exception { LOG.info("Enter y to continue, anything else to quit"); byte[] bytes = new byte[10]; System.in.read(bytes); char c = (char)bytes[0]; if (c != 'y' && c != 'Y') { System.out.println("Read " + c); System.exit(1); } } private static String getGuidColumnName(String fileType) { if (fileType.equals("Admin_Patient")) { //patient file just has patient GUID, nothing extra return null; } else if (fileType.equals("CareRecord_Consultation")) { return "ConsultationGuid"; } else if (fileType.equals("CareRecord_Diary")) { return "DiaryGuid"; } else if (fileType.equals("CareRecord_Observation")) { return "ObservationGuid"; } else if (fileType.equals("CareRecord_Problem")) { //there is no separate problem GUID, as it's just a modified observation return "ObservationGuid"; } else if (fileType.equals("Prescribing_DrugRecord")) { return "DrugRecordGuid"; } else if (fileType.equals("Prescribing_IssueRecord")) { return "IssueRecordGuid"; } else { throw new IllegalArgumentException(fileType); } } private static String findFileType(String filePath) { String fileName = FilenameUtils.getName(filePath); String[] toks = fileName.split("_"); String domain = toks[1]; String name = toks[2]; return domain + "_" + name; } private static boolean isPatientFile(String fileType) { if (fileType.equals("Admin_Patient") || fileType.equals("CareRecord_Consultation") || fileType.equals("CareRecord_Diary") || fileType.equals("CareRecord_Observation") || fileType.equals("CareRecord_Problem") || fileType.equals("Prescribing_DrugRecord") || fileType.equals("Prescribing_IssueRecord")) { //note the referral file doesn't have a Deleted column, so isn't in this list return true; } else { return false; } } private static String findSharingAgreementFile(List<String> files) throws Exception { for (String file : files) { String fileType = findFileType(file); if (fileType.equals("Agreements_SharingOrganisation")) { return file; } } throw new Exception("Failed to find sharing agreement file in " + files.get(0)); } private static void testSlack() { LOG.info("Testing slack"); try { SlackHelper.sendSlackMessage(SlackHelper.Channel.QueueReaderAlerts, "Test Message from Queue Reader"); LOG.info("Finished testing slack"); } catch (Exception ex) { LOG.error("", ex); } } private static void postToInboundFromFile(UUID serviceId, UUID systemId, String filePath) { try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); Service service = serviceDalI.getById(serviceId); LOG.info("Posting to inbound exchange for " + service.getName() + " from file " + filePath); FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); int count = 0; List<UUID> exchangeIdBatch = new ArrayList<>(); while (true) { String line = br.readLine(); if (line == null) { break; } UUID exchangeId = UUID.fromString(line); //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); if (audit != null && !audit.isResubmitted()) { audit.setResubmitted(true); auditRepository.save(audit); } count ++; exchangeIdBatch.add(exchangeId); if (exchangeIdBatch.size() >= 1000) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false); exchangeIdBatch = new ArrayList<>(); LOG.info("Done " + count); } } if (!exchangeIdBatch.isEmpty()) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false); LOG.info("Done " + count); } br.close(); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Posting to inbound for " + serviceId); } /*private static void postToInbound(UUID serviceId, boolean all) { LOG.info("Posting to inbound for " + serviceId); try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); Service service = serviceDalI.getById(serviceId); List<UUID> systemIds = findSystemIds(service); UUID systemId = systemIds.get(0); ExchangeTransformErrorState errorState = auditRepository.getErrorState(serviceId, systemId); for (UUID exchangeId: errorState.getExchangeIdsInError()) { //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); //skip any exchange IDs we've already re-queued up to be processed again if (audit.isResubmitted()) { LOG.debug("Not re-posting " + audit.getExchangeId() + " as it's already been resubmitted"); continue; } LOG.debug("Re-posting " + audit.getExchangeId()); audit.setResubmitted(true); auditRepository.save(audit); //then re-submit the exchange to Rabbit MQ for the queue reader to pick up QueueHelper.postToExchange(exchangeId, "EdsInbound", null, false); if (!all) { LOG.info("Posted first exchange, so stopping"); break; } } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Posting to inbound for " + serviceId); }*/ /*private static void fixPatientSearch(String serviceId) { LOG.info("Fixing patient search for " + serviceId); try { UUID serviceUuid = UUID.fromString(serviceId); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); ParserPool parser = new ParserPool(); Set<UUID> patientsDone = new HashSet<>(); List<UUID> exchanges = exchangeDalI.getExchangeIdsForService(serviceUuid); LOG.info("Found " + exchanges.size() + " exchanges"); for (UUID exchangeId: exchanges) { List<ExchangeBatch> batches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); LOG.info("Found " + batches.size() + " batches in exchange " + exchangeId); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } if (patientsDone.contains(patientId)) { continue; } ResourceWrapper wrapper = resourceDalI.getCurrentVersion(serviceUuid, ResourceType.Patient.toString(), patientId); if (wrapper != null) { String json = wrapper.getResourceData(); if (!Strings.isNullOrEmpty(json)) { Patient fhirPatient = (Patient) parser.parse(json); UUID systemUuid = wrapper.getSystemId(); patientSearchDal.update(serviceUuid, systemUuid, fhirPatient); } } patientsDone.add(patientId); if (patientsDone.size() % 1000 == 0) { LOG.info("Done " + patientsDone.size()); } } } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished fixing patient search for " + serviceId); }*/ private static void runSql(String host, String username, String password, String sqlFile) { LOG.info("Running SQL on " + host + " from " + sqlFile); Connection conn = null; Statement statement = null; try { File f = new File(sqlFile); if (!f.exists()) { LOG.error("" + f + " doesn't exist"); return; } List<String> lines = FileUtils.readLines(f); /*String combined = String.join("\n", lines); LOG.info("Going to run SQL"); LOG.info(combined);*/ //load driver Class.forName("com.mysql.cj.jdbc.Driver"); //create connection Properties props = new Properties(); props.setProperty("user", username); props.setProperty("password", password); conn = DriverManager.getConnection(host, props); LOG.info("Opened connection"); statement = conn.createStatement(); long totalStart = System.currentTimeMillis(); for (String sql: lines) { sql = sql.trim(); if (sql.startsWith("--") || sql.startsWith("/*") || Strings.isNullOrEmpty(sql)) { continue; } LOG.info(""); LOG.info(sql); long start = System.currentTimeMillis(); boolean hasResultSet = statement.execute(sql); long end = System.currentTimeMillis(); LOG.info("SQL took " + (end - start) + "ms"); if (hasResultSet) { while (true) { ResultSet rs = statement.getResultSet(); int cols = rs.getMetaData().getColumnCount(); List<String> colHeaders = new ArrayList<>(); for (int i = 0; i < cols; i++) { String header = rs.getMetaData().getColumnName(i + 1); colHeaders.add(header); } String colHeaderStr = String.join(", ", colHeaders); LOG.info(colHeaderStr); while (rs.next()) { List<String> row = new ArrayList<>(); for (int i = 0; i < cols; i++) { Object o = rs.getObject(i + 1); if (rs.wasNull()) { row.add("<null>"); } else { row.add(o.toString()); } } String rowStr = String.join(", ", row); LOG.info(rowStr); } if (!statement.getMoreResults()) { break; } } } else { int updateCount = statement.getUpdateCount(); LOG.info("Updated " + updateCount + " Row(s)"); } } long totalEnd = System.currentTimeMillis(); LOG.info(""); LOG.info("Total time taken " + (totalEnd - totalStart) + "ms"); } catch (Throwable t) { LOG.error("", t); } finally { if (statement != null) { try { statement.close(); } catch (Exception ex) { } } if (conn != null) { try { conn.close(); } catch (Exception ex) { } } LOG.info("Closed connection"); } LOG.info("Finished Testing DB Size Limit"); } /*private static void fixExchangeBatches() { LOG.info("Starting Fixing Exchange Batches"); try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); List<Service> services = serviceDalI.getAll(); for (Service service: services) { LOG.info("Doing " + service.getName()); List<UUID> exchangeIds = exchangeDalI.getExchangeIdsForService(service.getId()); for (UUID exchangeId: exchangeIds) { LOG.info(" Exchange " + exchangeId); List<ExchangeBatch> exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch: exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null) { continue; } List<ResourceWrapper> resources = resourceDalI.getResourcesForBatch(exchangeBatch.getBatchId()); if (resources.isEmpty()) { continue; } ResourceWrapper first = resources.get(0); UUID patientId = first.getPatientId(); if (patientId != null) { exchangeBatch.setEdsPatientId(patientId); exchangeBatchDalI.save(exchangeBatch); LOG.info("Fixed batch " + exchangeBatch.getBatchId() + " -> " + exchangeBatch.getEdsPatientId()); } } } } LOG.info("Finished Fixing Exchange Batches"); } catch (Exception ex) { LOG.error("", ex); } }*/ /** * exports ADT Encounters for patients based on a CSV file produced using the below SQL --USE EDS DATABASE -- barts b5a08769-cbbe-4093-93d6-b696cd1da483 -- homerton 962d6a9a-5950-47ac-9e16-ebee56f9507a create table adt_patients ( service_id character(36), system_id character(36), nhs_number character varying(10), patient_id character(36) ); -- delete from adt_patients; select * from patient_search limit 10; select * from patient_link limit 10; insert into adt_patients select distinct ps.service_id, ps.system_id, ps.nhs_number, ps.patient_id from patient_search ps join patient_link pl on pl.patient_id = ps.patient_id join patient_link pl2 on pl.person_id = pl2.person_id join patient_search ps2 on ps2.patient_id = pl2.patient_id where ps.service_id IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a') and ps2.service_id NOT IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a'); select count(1) from adt_patients limit 100; select * from adt_patients limit 100; ---MOVE TABLE TO HL7 RECEIVER DB select count(1) from adt_patients; -- top 1000 patients with messages select * from mapping.resource_uuid where resource_type = 'Patient' limit 10; select * from log.message limit 10; create table adt_patient_counts ( nhs_number character varying(100), count int ); insert into adt_patient_counts select pid1, count(1) from log.message where pid1 is not null and pid1 <> '' group by pid1; select * from adt_patient_counts order by count desc limit 100; alter table adt_patients add count int; update adt_patients set count = adt_patient_counts.count from adt_patient_counts where adt_patients.nhs_number = adt_patient_counts.nhs_number; select count(1) from adt_patients where nhs_number is null; select * from adt_patients where nhs_number is not null and count is not null order by count desc limit 1000; */ /*private static void exportHl7Encounters(String sourceCsvPath, String outputPath) { LOG.info("Exporting HL7 Encounters from " + sourceCsvPath + " to " + outputPath); try { File sourceFile = new File(sourceCsvPath); CSVParser csvParser = CSVParser.parse(sourceFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); //"service_id","system_id","nhs_number","patient_id","count" int count = 0; HashMap<UUID, List<UUID>> serviceAndSystemIds = new HashMap<>(); HashMap<UUID, Integer> patientIds = new HashMap<>(); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); count ++; String serviceId = csvRecord.get("service_id"); String systemId = csvRecord.get("system_id"); String patientId = csvRecord.get("patient_id"); UUID serviceUuid = UUID.fromString(serviceId); List<UUID> systemIds = serviceAndSystemIds.get(serviceUuid); if (systemIds == null) { systemIds = new ArrayList<>(); serviceAndSystemIds.put(serviceUuid, systemIds); } systemIds.add(UUID.fromString(systemId)); patientIds.put(UUID.fromString(patientId), new Integer(count)); } csvParser.close(); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ParserPool parser = new ParserPool(); Map<Integer, List<Object[]>> patientRows = new HashMap<>(); SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (UUID serviceId: serviceAndSystemIds.keySet()) { //List<UUID> systemIds = serviceAndSystemIds.get(serviceId); Service service = serviceDalI.getById(serviceId); String serviceName = service.getName(); LOG.info("Doing service " + serviceId + " " + serviceName); List<UUID> exchangeIds = exchangeDalI.getExchangeIdsForService(serviceId); LOG.info("Got " + exchangeIds.size() + " exchange IDs to scan"); int exchangeCount = 0; for (UUID exchangeId: exchangeIds) { exchangeCount ++; if (exchangeCount % 1000 == 0) { LOG.info("Done " + exchangeCount + " exchanges"); } List<ExchangeBatch> exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch: exchangeBatches) { UUID patientId = exchangeBatch.getEdsPatientId(); if (patientId != null && !patientIds.containsKey(patientId)) { continue; } Integer patientIdInt = patientIds.get(patientId); //get encounters for exchange batch UUID batchId = exchangeBatch.getBatchId(); List<ResourceWrapper> resourceWrappers = resourceDalI.getResourcesForBatch(serviceId, batchId); for (ResourceWrapper resourceWrapper: resourceWrappers) { if (resourceWrapper.isDeleted()) { continue; } String resourceType = resourceWrapper.getResourceType(); if (!resourceType.equals(ResourceType.Encounter.toString())) { continue; } LOG.info("Processing " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId()); String json = resourceWrapper.getResourceData(); Encounter fhirEncounter = (Encounter)parser.parse(json); Date date = null; if (fhirEncounter.hasPeriod()) { Period period = fhirEncounter.getPeriod(); if (period.hasStart()) { date = period.getStart(); } } String episodeId = null; if (fhirEncounter.hasEpisodeOfCare()) { Reference episodeReference = fhirEncounter.getEpisodeOfCare().get(0); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(episodeReference); EpisodeOfCare fhirEpisode = (EpisodeOfCare)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirEpisode != null) { if (fhirEpisode.hasIdentifier()) { episodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_BARTS_FIN_EPISODE_ID); if (Strings.isNullOrEmpty(episodeId)) { episodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_HOMERTON_FIN_EPISODE_ID); } } } } String adtType = null; String adtCode = null; Extension extension = ExtensionConverter.findExtension(fhirEncounter, FhirExtensionUri.HL7_MESSAGE_TYPE); if (extension != null) { CodeableConcept codeableConcept = (CodeableConcept) extension.getValue(); Coding hl7MessageTypeCoding = CodeableConceptHelper.findCoding(codeableConcept, FhirUri.CODE_SYSTEM_HL7V2_MESSAGE_TYPE); if (hl7MessageTypeCoding != null) { adtType = hl7MessageTypeCoding.getDisplay(); adtCode = hl7MessageTypeCoding.getCode(); } } else { //for older formats of the transformed resources, the HL7 message type can only be found from the raw original exchange body try { Exchange exchange = exchangeDalI.getExchange(exchangeId); String exchangeBody = exchange.getBody(); Bundle bundle = (Bundle) FhirResourceHelper.deserialiseResouce(exchangeBody); for (Bundle.BundleEntryComponent entry: bundle.getEntry()) { if (entry.getResource() != null && entry.getResource() instanceof MessageHeader) { MessageHeader header = (MessageHeader)entry.getResource(); if (header.hasEvent()) { Coding coding = header.getEvent(); adtType = coding.getDisplay(); adtCode = coding.getCode(); } } } } catch (Exception ex) { //if the exchange body isn't a FHIR bundle, then we'll get an error by treating as such, so just ignore them } } String cls = null; if (fhirEncounter.hasClass_()) { Encounter.EncounterClass encounterClass = fhirEncounter.getClass_(); if (encounterClass == Encounter.EncounterClass.OTHER && fhirEncounter.hasClass_Element() && fhirEncounter.getClass_Element().hasExtension()) { for (Extension classExtension: fhirEncounter.getClass_Element().getExtension()) { if (classExtension.getUrl().equals(FhirExtensionUri.ENCOUNTER_CLASS)) { //not 100% of the type of the value, so just append to a String cls = "" + classExtension.getValue(); } } } if (Strings.isNullOrEmpty(cls)) { cls = encounterClass.toCode(); } } String type = null; if (fhirEncounter.hasType()) { //only seem to ever have one type CodeableConcept codeableConcept = fhirEncounter.getType().get(0); type = codeableConcept.getText(); } String status = null; if (fhirEncounter.hasStatus()) { Encounter.EncounterState encounterState = fhirEncounter.getStatus(); status = encounterState.toCode(); } String location = null; String locationType = null; if (fhirEncounter.hasLocation()) { //first location is always the current location Encounter.EncounterLocationComponent encounterLocation = fhirEncounter.getLocation().get(0); if (encounterLocation.hasLocation()) { Reference locationReference = encounterLocation.getLocation(); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(locationReference); Location fhirLocation = (Location)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirLocation != null) { if (fhirLocation.hasName()) { location = fhirLocation.getName(); } if (fhirLocation.hasType()) { CodeableConcept typeCodeableConcept = fhirLocation.getType(); if (typeCodeableConcept.hasCoding()) { Coding coding = typeCodeableConcept.getCoding().get(0); locationType = coding.getDisplay(); } } } } } String clinician = null; if (fhirEncounter.hasParticipant()) { //first participant seems to be the interesting one Encounter.EncounterParticipantComponent encounterParticipant = fhirEncounter.getParticipant().get(0); if (encounterParticipant.hasIndividual()) { Reference practitionerReference = encounterParticipant.getIndividual(); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(practitionerReference); Practitioner fhirPractitioner = (Practitioner)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirPractitioner != null) { if (fhirPractitioner.hasName()) { HumanName name = fhirPractitioner.getName(); clinician = name.getText(); if (Strings.isNullOrEmpty(clinician)) { clinician = ""; for (StringType s: name.getPrefix()) { clinician += s.getValueNotNull(); clinician += " "; } for (StringType s: name.getGiven()) { clinician += s.getValueNotNull(); clinician += " "; } for (StringType s: name.getFamily()) { clinician += s.getValueNotNull(); clinician += " "; } clinician = clinician.trim(); } } } } } Object[] row = new Object[12]; row[0] = serviceName; row[1] = patientIdInt.toString(); row[2] = sdfOutput.format(date); row[3] = episodeId; row[4] = adtCode; row[5] = adtType; row[6] = cls; row[7] = type; row[8] = status; row[9] = location; row[10] = locationType; row[11] = clinician; List<Object[]> rows = patientRows.get(patientIdInt); if (rows == null) { rows = new ArrayList<>(); patientRows.put(patientIdInt, rows); } rows.add(row); } } } } String[] outputColumnHeaders = new String[] {"Source", "Patient", "Date", "Episode ID", "ADT Message Code", "ADT Message Type", "Class", "Type", "Status", "Location", "Location Type", "Clinician"}; FileWriter fileWriter = new FileWriter(outputPath); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVFormat format = CSVFormat.DEFAULT .withHeader(outputColumnHeaders) .withQuote('"'); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format); for (int i=0; i <= count; i++) { Integer patientIdInt = new Integer(i); List<Object[]> rows = patientRows.get(patientIdInt); if (rows != null) { for (Object[] row: rows) { csvPrinter.printRecord(row); } } } csvPrinter.close(); bufferedWriter.close(); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Exporting Encounters from " + sourceCsvPath + " to " + outputPath); }*/ /*private static void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info(""); try { Thread.sleep(5000); } catch (Throwable ex) { LOG.error("", ex); } LOG.info("Done"); } }); }*/ private static void findEmisStartDates(String path, String outputPath) { LOG.info("Finding EMIS Start Dates in " + path + ", writing to " + outputPath); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH.mm.ss"); Map<String, Date> startDates = new HashMap<>(); Map<String, String> servers = new HashMap<>(); Map<String, String> names = new HashMap<>(); Map<String, String> odsCodes = new HashMap<>(); Map<String, String> cdbNumbers = new HashMap<>(); Map<String, Set<String>> distinctPatients = new HashMap<>(); File root = new File(path); for (File sftpRoot: root.listFiles()) { LOG.info("Checking " + sftpRoot); Map<Date, File> extracts = new HashMap<>(); List<Date> extractDates = new ArrayList<>(); for (File extractRoot: sftpRoot.listFiles()) { Date d = sdf.parse(extractRoot.getName()); //LOG.info("" + extractRoot.getName() + " -> " + d); extracts.put(d, extractRoot); extractDates.add(d); } Collections.sort(extractDates); for (Date extractDate: extractDates) { File extractRoot = extracts.get(extractDate); LOG.info("Checking " + extractRoot); //read the sharing agreements file //e.g. 291_Agreements_SharingOrganisation_20150211164536_45E7CD20-EE37-41AB-90D6-DC9D4B03D102.csv File sharingAgreementsFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("agreements_sharingorganisation") > -1 && name.endsWith(".csv")) { sharingAgreementsFile = f; break; } } if (sharingAgreementsFile == null) { LOG.info("Null agreements file for " + extractRoot); continue; } CSVParser csvParser = CSVParser.parse(sharingAgreementsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String activated = csvRecord.get("IsActivated"); String disabled = csvRecord.get("Disabled"); servers.put(orgGuid, sftpRoot.getName()); if (activated.equalsIgnoreCase("true")) { if (disabled.equalsIgnoreCase("false")) { Date d = sdf.parse(extractRoot.getName()); Date existingDate = startDates.get(orgGuid); if (existingDate == null) { startDates.put(orgGuid, d); } } else { if (startDates.containsKey(orgGuid)) { startDates.put(orgGuid, null); } } } } } finally { csvParser.close(); } //go through orgs file to get name, ods and cdb codes File orgsFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("admin_organisation_") > -1 && name.endsWith(".csv")) { orgsFile = f; break; } } csvParser = CSVParser.parse(orgsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String name = csvRecord.get("OrganisationName"); String odsCode = csvRecord.get("ODSCode"); String cdb = csvRecord.get("CDB"); names.put(orgGuid, name); odsCodes.put(orgGuid, odsCode); cdbNumbers.put(orgGuid, cdb); } } finally { csvParser.close(); } //go through patients file to get count File patientFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("admin_patient_") > -1 && name.endsWith(".csv")) { patientFile = f; break; } } csvParser = CSVParser.parse(patientFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String patientGuid = csvRecord.get("PatientGuid"); String deleted = csvRecord.get("Deleted"); Set<String> distinctPatientSet = distinctPatients.get(orgGuid); if (distinctPatientSet == null) { distinctPatientSet = new HashSet<>(); distinctPatients.put(orgGuid, distinctPatientSet); } if (deleted.equalsIgnoreCase("true")) { distinctPatientSet.remove(patientGuid); } else { distinctPatientSet.add(patientGuid); } } } finally { csvParser.close(); } } } SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd"); StringBuilder sb = new StringBuilder(); sb.append("Name,OdsCode,CDB,OrgGuid,StartDate,Server,Patients"); for (String orgGuid: startDates.keySet()) { Date startDate = startDates.get(orgGuid); String server = servers.get(orgGuid); String name = names.get(orgGuid); String odsCode = odsCodes.get(orgGuid); String cdbNumber = cdbNumbers.get(orgGuid); Set<String> distinctPatientSet = distinctPatients.get(orgGuid); String startDateDesc = null; if (startDate != null) { startDateDesc = sdfOutput.format(startDate); } Long countDistinctPatients = null; if (distinctPatientSet != null) { countDistinctPatients = new Long(distinctPatientSet.size()); } sb.append("\n"); sb.append("\"" + name + "\""); sb.append(","); sb.append("\"" + odsCode + "\""); sb.append(","); sb.append("\"" + cdbNumber + "\""); sb.append(","); sb.append("\"" + orgGuid + "\""); sb.append(","); sb.append(startDateDesc); sb.append(","); sb.append("\"" + server + "\""); sb.append(","); sb.append(countDistinctPatients); } LOG.info(sb.toString()); FileUtils.writeStringToFile(new File(outputPath), sb.toString()); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Finding Start Dates in " + path + ", writing to " + outputPath); } private static void findEncounterTerms(String path, String outputPath) { LOG.info("Finding Encounter Terms from " + path); Map<String, Long> hmResults = new HashMap<>(); //source term, source term snomed ID, source term snomed term - count try { File root = new File(path); File[] files = root.listFiles(); for (File readerRoot: files) { //emis001 LOG.info("Finding terms in " + readerRoot); //first read in all the coding files to build up our map of codes Map<String, String> hmCodes = new HashMap<>(); for (File dateFolder: readerRoot.listFiles()) { LOG.info("Looking for codes in " + dateFolder); File f = findFile(dateFolder, "Coding_ClinicalCode"); if (f == null) { LOG.error("Failed to find coding file in " + dateFolder.getAbsolutePath()); continue; } CSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String codeId = csvRecord.get("CodeId"); String term = csvRecord.get("Term"); String snomed = csvRecord.get("SnomedCTConceptId"); hmCodes.put(codeId, snomed + ",\"" + term + "\""); } csvParser.close(); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date cutoff = dateFormat.parse("2017-01-01"); //now process the consultation files themselves for (File dateFolder: readerRoot.listFiles()) { LOG.info("Looking for consultations in " + dateFolder); File f = findFile(dateFolder, "CareRecord_Consultation"); if (f == null) { LOG.error("Failed to find consultation file in " + dateFolder.getAbsolutePath()); continue; } CSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String term = csvRecord.get("ConsultationSourceTerm"); String codeId = csvRecord.get("ConsultationSourceCodeId"); if (Strings.isNullOrEmpty(term) && Strings.isNullOrEmpty(codeId)) { continue; } String date = csvRecord.get("EffectiveDate"); if (Strings.isNullOrEmpty(date)) { continue; } Date d = dateFormat.parse(date); if (d.before(cutoff)) { continue; } String line = "\"" + term + "\","; if (!Strings.isNullOrEmpty(codeId)) { String codeLookup = hmCodes.get(codeId); if (codeLookup == null) { LOG.error("Failed to find lookup for codeID " + codeId); continue; } line += codeLookup; } else { line += ","; } Long count = hmResults.get(line); if (count == null) { count = new Long(1); } else { count = new Long(count.longValue() + 1); } hmResults.put(line, count); } csvParser.close(); } } //save results to file StringBuilder output = new StringBuilder(); output.append("\"consultation term\",\"snomed concept ID\",\"snomed term\",\"count\""); output.append("\r\n"); for (String line: hmResults.keySet()) { Long count = hmResults.get(line); String combined = line + "," + count; output.append(combined); output.append("\r\n"); } LOG.info("FInished"); LOG.info(output.toString()); FileUtils.writeStringToFile(new File(outputPath), output.toString()); LOG.info("written output to " + outputPath); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished finding Encounter Terms from " + path); } private static File findFile(File root, String token) throws Exception { for (File f: root.listFiles()) { String s = f.getName(); if (s.indexOf(token) > -1) { return f; } } return null; } /*private static void populateProtocolQueue(String serviceIdStr, String startingExchangeId) { LOG.info("Starting Populating Protocol Queue for " + serviceIdStr); ServiceDalI serviceRepository = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); if (serviceIdStr.equalsIgnoreCase("All")) { serviceIdStr = null; } try { List<Service> services = new ArrayList<>(); if (Strings.isNullOrEmpty(serviceIdStr)) { services = serviceRepository.getAll(); } else { UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); services.add(service); } for (Service service: services) { List<UUID> exchangeIds = auditRepository.getExchangeIdsForService(service.getId()); LOG.info("Found " + exchangeIds.size() + " exchangeIds for " + service.getName()); if (startingExchangeId != null) { UUID startingExchangeUuid = UUID.fromString(startingExchangeId); if (exchangeIds.contains(startingExchangeUuid)) { //if in the list, remove everything up to and including the starting exchange int index = exchangeIds.indexOf(startingExchangeUuid); LOG.info("Found starting exchange " + startingExchangeId + " at " + index + " so removing up to this point"); for (int i=index; i>=0; i--) { exchangeIds.remove(i); } startingExchangeId = null; } else { //if not in the list, skip all these exchanges LOG.info("List doesn't contain starting exchange " + startingExchangeId + " so skipping"); continue; } } QueueHelper.postToExchange(exchangeIds, "edsProtocol", null, true); } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Populating Protocol Queue for " + serviceIdStr); }*/ /*private static void findDeletedOrgs() { LOG.info("Starting finding deleted orgs"); ServiceDalI serviceRepository = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); List<Service> services = new ArrayList<>(); try { for (Service service: serviceRepository.getAll()) { services.add(service); } } catch (Exception ex) { LOG.error("", ex); } services.sort((o1, o2) -> { String name1 = o1.getName(); String name2 = o2.getName(); return name1.compareToIgnoreCase(name2); }); for (Service service: services) { try { UUID serviceUuid = service.getId(); List<Exchange> exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 1, new Date(0), new Date()); LOG.info("Service: " + service.getName() + " " + service.getLocalId()); if (exchangeByServices.isEmpty()) { LOG.info(" no exchange found!"); continue; } Exchange exchangeByService = exchangeByServices.get(0); UUID exchangeId = exchangeByService.getId(); Exchange exchange = auditRepository.getExchange(exchangeId); Map<String, String> headers = exchange.getHeaders(); String systemUuidStr = headers.get(HeaderKeys.SenderSystemUuid); UUID systemUuid = UUID.fromString(systemUuidStr); int batches = countBatches(exchangeId, serviceUuid, systemUuid); LOG.info(" Most recent exchange had " + batches + " batches"); if (batches > 1 && batches < 2000) { continue; } //go back until we find the FIRST exchange where it broke exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 250, new Date(0), new Date()); for (int i=0; i<exchangeByServices.size(); i++) { exchangeByService = exchangeByServices.get(i); exchangeId = exchangeByService.getId(); batches = countBatches(exchangeId, serviceUuid, systemUuid); exchange = auditRepository.getExchange(exchangeId); Date timestamp = exchange.getTimestamp(); if (batches < 1 || batches > 2000) { LOG.info(" " + timestamp + " had " + batches); } if (batches > 1 && batches < 2000) { LOG.info(" " + timestamp + " had " + batches); break; } } } catch (Exception ex) { LOG.error("", ex); } } LOG.info("Finished finding deleted orgs"); }*/ private static int countBatches(UUID exchangeId, UUID serviceId, UUID systemId) throws Exception { int batches = 0; ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId); for (ExchangeTransformAudit audit: audits) { if (audit.getNumberBatchesCreated() != null) { batches += audit.getNumberBatchesCreated(); } } return batches; } /*private static void fixExchanges(UUID justThisService) { LOG.info("Fixing exchanges"); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId : exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } boolean changed = false; String body = exchange.getBody(); String[] files = body.split("\n"); if (files.length == 0) { continue; } for (int i=0; i<files.length; i++) { String original = files[i]; //remove /r characters String trimmed = original.trim(); //add the new prefix if (!trimmed.startsWith("sftpreader/EMIS001/")) { trimmed = "sftpreader/EMIS001/" + trimmed; } if (!original.equals(trimmed)) { files[i] = trimmed; changed = true; } } if (changed) { LOG.info("Fixed exchange " + exchangeId); LOG.info(body); body = String.join("\n", files); exchange.setBody(body); AuditWriter.writeExchange(exchange); } } } LOG.info("Fixed exchanges"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void deleteDataForService(UUID serviceId) { Service dbService = new ServiceRepository().getById(serviceId); //the delete will take some time, so do the delete in a separate thread LOG.info("Deleting all data for service " + dbService.getName() + " " + dbService.getId()); FhirDeletionService deletor = new FhirDeletionService(dbService); try { deletor.deleteData(); LOG.info("Completed deleting all data for service " + dbService.getName() + " " + dbService.getId()); } catch (Exception ex) { LOG.error("Error deleting service " + dbService.getName() + " " + dbService.getId(), ex); } }*/ /*private static void fixProblems(UUID serviceId, String sharedStoragePath, boolean testMode) { LOG.info("Fixing problems for service " + serviceId); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); List<ExchangeByService> exchangeByServiceList = auditRepository.getExchangesByService(serviceId, Integer.MAX_VALUE); //go backwards as the most recent is first for (int i=exchangeByServiceList.size()-1; i>=0; i--) { ExchangeByService exchangeByService = exchangeByServiceList.get(i); UUID exchangeId = exchangeByService.getExchangeId(); LOG.info("Doing exchange " + exchangeId); EmisCsvHelper helper = null; try { Exchange exchange = AuditWriter.readExchange(exchangeId); String exchangeBody = exchange.getBody(); String[] files = exchangeBody.split(java.lang.System.lineSeparator()); File orgDirectory = validateAndFindCommonDirectory(sharedStoragePath, files); Map<Class, AbstractCsvParser> allParsers = new HashMap<>(); String properVersion = null; String[] versions = new String[]{EmisCsvToFhirTransformer.VERSION_5_0, EmisCsvToFhirTransformer.VERSION_5_1, EmisCsvToFhirTransformer.VERSION_5_3, EmisCsvToFhirTransformer.VERSION_5_4}; for (String version: versions) { try { List<AbstractCsvParser> parsers = new ArrayList<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(Observation.class, orgDirectory, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(DrugRecord.class, orgDirectory, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(IssueRecord.class, orgDirectory, version, true, parsers); for (AbstractCsvParser parser: parsers) { Class cls = parser.getClass(); allParsers.put(cls, parser); } properVersion = version; } catch (Exception ex) { //ignore } } if (allParsers.isEmpty()) { throw new Exception("Failed to open parsers for exchange " + exchangeId + " in folder " + orgDirectory); } UUID systemId = exchange.getHeaderAsUuid(HeaderKeys.SenderSystemUuid); //FhirResourceFiler dummyFiler = new FhirResourceFiler(exchangeId, serviceId, systemId, null, null, 10); if (helper == null) { helper = new EmisCsvHelper(findDataSharingAgreementGuid(new ArrayList<>(allParsers.values()))); } ObservationPreTransformer.transform(properVersion, allParsers, null, helper); IssueRecordPreTransformer.transform(properVersion, allParsers, null, helper); DrugRecordPreTransformer.transform(properVersion, allParsers, null, helper); Map<String, List<String>> problemChildren = helper.getProblemChildMap(); List<ExchangeBatch> exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (Map.Entry<String, List<String>> entry : problemChildren.entrySet()) { String patientLocallyUniqueId = entry.getKey().split(":")[0]; UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientLocallyUniqueId); if (edsPatientId == null) { throw new Exception("Failed to find edsPatientId for local Patient ID " + patientLocallyUniqueId + " in exchange " + exchangeId); } //find the batch ID for our patient UUID batchId = null; for (ExchangeBatch exchangeBatch: exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null && exchangeBatch.getEdsPatientId().equals(edsPatientId)) { batchId = exchangeBatch.getBatchId(); break; } } if (batchId == null) { throw new Exception("Failed to find batch ID for eds Patient ID " + edsPatientId + " in exchange " + exchangeId); } //find the EDS ID for our problem UUID edsProblemId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Condition, entry.getKey()); if (edsProblemId == null) { LOG.warn("No edsProblemId found for local ID " + entry.getKey() + " - assume bad data referring to non-existing problem?"); //throw new Exception("Failed to find edsProblemId for local Patient ID " + problemLocallyUniqueId + " in exchange " + exchangeId); } //convert our child IDs to EDS references List<Reference> references = new ArrayList<>(); HashSet<String> contentsSet = new HashSet<>(); contentsSet.addAll(entry.getValue()); for (String referenceValue : contentsSet) { Reference reference = ReferenceHelper.createReference(referenceValue); ReferenceComponents components = ReferenceHelper.getReferenceComponents(reference); String locallyUniqueId = components.getId(); ResourceType resourceType = components.getResourceType(); UUID edsResourceId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); Reference globallyUniqueReference = ReferenceHelper.createReference(resourceType, edsResourceId.toString()); references.add(globallyUniqueReference); } //find the resource for the problem itself ResourceByExchangeBatch problemResourceByExchangeBatch = null; List<ResourceByExchangeBatch> resources = resourceRepository.getResourcesForBatch(batchId, ResourceType.Condition.toString()); for (ResourceByExchangeBatch resourceByExchangeBatch: resources) { if (resourceByExchangeBatch.getResourceId().equals(edsProblemId)) { problemResourceByExchangeBatch = resourceByExchangeBatch; break; } } if (problemResourceByExchangeBatch == null) { throw new Exception("Problem not found for edsProblemId " + edsProblemId + " for exchange " + exchangeId); } if (problemResourceByExchangeBatch.getIsDeleted()) { LOG.warn("Problem " + edsProblemId + " is deleted, so not adding to it for exchange " + exchangeId); continue; } String json = problemResourceByExchangeBatch.getResourceData(); Condition fhirProblem = (Condition)PARSER_POOL.parse(json); //update the problems if (fhirProblem.hasContained()) { if (fhirProblem.getContained().size() > 1) { throw new Exception("Problem " + edsProblemId + " is has " + fhirProblem.getContained().size() + " contained resources for exchange " + exchangeId); } fhirProblem.getContained().clear(); } List_ list = new List_(); list.setId("Items"); fhirProblem.getContained().add(list); Extension extension = ExtensionConverter.findExtension(fhirProblem, FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE); if (extension == null) { Reference listReference = ReferenceHelper.createInternalReference("Items"); fhirProblem.addExtension(ExtensionConverter.createExtension(FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE, listReference)); } for (Reference reference : references) { list.addEntry().setItem(reference); } String newJson = FhirSerializationHelper.serializeResource(fhirProblem); if (newJson.equals(json)) { LOG.warn("Skipping edsProblemId " + edsProblemId + " as JSON hasn't changed"); continue; } problemResourceByExchangeBatch.setResourceData(newJson); String resourceType = problemResourceByExchangeBatch.getResourceType(); UUID versionUuid = problemResourceByExchangeBatch.getVersion(); ResourceHistory problemResourceHistory = resourceRepository.getResourceHistoryByKey(edsProblemId, resourceType, versionUuid); problemResourceHistory.setResourceData(newJson); problemResourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); ResourceByService problemResourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType, edsProblemId); if (problemResourceByService.getResourceData() == null) { problemResourceByService = null; LOG.warn("Not updating edsProblemId " + edsProblemId + " for exchange " + exchangeId + " as it's been subsequently delrted"); } else { problemResourceByService.setResourceData(newJson); } //save back to THREE tables if (!testMode) { resourceRepository.save(problemResourceByExchangeBatch); resourceRepository.save(problemResourceHistory); if (problemResourceByService != null) { resourceRepository.save(problemResourceByService); } LOG.info("Fixed edsProblemId " + edsProblemId + " for exchange Id " + exchangeId); } else { LOG.info("Would change edsProblemId " + edsProblemId + " to new JSON"); LOG.info(newJson); } } } catch (Exception ex) { LOG.error("Failed on exchange " + exchangeId, ex); break; } } LOG.info("Finished fixing problems for service " + serviceId); } private static String findDataSharingAgreementGuid(List<AbstractCsvParser> parsers) throws Exception { //we need a file name to work out the data sharing agreement ID, so just the first file we can find File f = parsers .iterator() .next() .getFile(); String name = Files.getNameWithoutExtension(f.getName()); String[] toks = name.split("_"); if (toks.length != 5) { throw new TransformException("Failed to extract data sharing agreement GUID from filename " + f.getName()); } return toks[4]; } private static void closeParsers(Collection<AbstractCsvParser> parsers) { for (AbstractCsvParser parser : parsers) { try { parser.close(); } catch (IOException ex) { //don't worry if this fails, as we're done anyway } } } private static File validateAndFindCommonDirectory(String sharedStoragePath, String[] files) throws Exception { String organisationDir = null; for (String file: files) { File f = new File(sharedStoragePath, file); if (!f.exists()) { LOG.error("Failed to find file {} in shared storage {}", file, sharedStoragePath); throw new FileNotFoundException("" + f + " doesn't exist"); } //LOG.info("Successfully found file {} in shared storage {}", file, sharedStoragePath); try { File orgDir = f.getParentFile(); if (organisationDir == null) { organisationDir = orgDir.getAbsolutePath(); } else { if (!organisationDir.equalsIgnoreCase(orgDir.getAbsolutePath())) { throw new Exception(); } } } catch (Exception ex) { throw new FileNotFoundException("" + f + " isn't in the expected directory structure within " + organisationDir); } } return new File(organisationDir); }*/ /*private static void testLogging() { while (true) { System.out.println("Checking logging at " + System.currentTimeMillis()); try { Thread.sleep(4000); } catch (Exception e) { e.printStackTrace(); } LOG.trace("trace logging"); LOG.debug("debug logging"); LOG.info("info logging"); LOG.warn("warn logging"); LOG.error("error logging"); } } */ /*private static void fixExchangeProtocols() { LOG.info("Fixing exchange protocols"); AuditRepository auditRepository = new AuditRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.Exchange LIMIT 1000;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); LOG.info("Processing exchange " + exchangeId); Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } UUID serviceId = UUID.fromString(serviceIdStr); List<String> newIds = new ArrayList<>(); String protocolJson = headers.get(HeaderKeys.Protocols); if (!headers.containsKey(HeaderKeys.Protocols)) { try { List<LibraryItem> libraryItemList = LibraryRepositoryHelper.getProtocolsByServiceId(serviceIdStr); // Get protocols where service is publisher newIds = libraryItemList.stream() .filter( libraryItem -> libraryItem.getProtocol().getServiceContract().stream() .anyMatch(sc -> sc.getType().equals(ServiceContractType.PUBLISHER) && sc.getService().getUuid().equals(serviceIdStr))) .map(t -> t.getUuid().toString()) .collect(Collectors.toList()); } catch (Exception e) { LOG.error("Failed to find protocols for exchange " + exchange.getExchangeId(), e); continue; } } else { try { JsonNode node = ObjectMapperPool.getInstance().readTree(protocolJson); for (int i = 0; i < node.size(); i++) { JsonNode libraryItemNode = node.get(i); JsonNode idNode = libraryItemNode.get("uuid"); String id = idNode.asText(); newIds.add(id); } } catch (Exception e) { LOG.error("Failed to read Json from " + protocolJson + " for exchange " + exchange.getExchangeId(), e); continue; } } try { if (newIds.isEmpty()) { headers.remove(HeaderKeys.Protocols); } else { String protocolsJson = ObjectMapperPool.getInstance().writeValueAsString(newIds.toArray()); headers.put(HeaderKeys.Protocols, protocolsJson); } } catch (JsonProcessingException e) { LOG.error("Unable to serialize protocols to JSON for exchange " + exchange.getExchangeId(), e); continue; } try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(headerJson); } catch (JsonProcessingException e) { LOG.error("Failed to write exchange headers to Json for exchange " + exchange.getExchangeId(), e); continue; } auditRepository.save(exchange); } LOG.info("Finished fixing exchange protocols"); }*/ /*private static void fixExchangeHeaders() { LOG.info("Fixing exchange headers"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); OrganisationRepository organisationRepository = new OrganisationRepository(); List<Exchange> exchanges = new AuditRepository().getAllExchanges(); for (Exchange exchange: exchanges) { String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } if (headers.containsKey(HeaderKeys.SenderLocalIdentifier) && headers.containsKey(HeaderKeys.SenderOrganisationUuid)) { continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); Map<UUID, String> orgMap = service.getOrganisations(); if (orgMap.size() != 1) { LOG.error("Wrong number of orgs in service " + serviceId + " for exchange " + exchange.getExchangeId()); continue; } UUID orgId = orgMap .keySet() .stream() .collect(StreamExtension.firstOrNullCollector()); Organisation organisation = organisationRepository.getById(orgId); String odsCode = organisation.getNationalId(); headers.put(HeaderKeys.SenderLocalIdentifier, odsCode); headers.put(HeaderKeys.SenderOrganisationUuid, orgId.toString()); try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setHeaders(headerJson); auditRepository.save(exchange); LOG.info("Creating exchange " + exchange.getExchangeId()); } LOG.info("Finished fixing exchange headers"); }*/ /*private static void fixExchangeHeaders() { LOG.info("Fixing exchange headers"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); OrganisationRepository organisationRepository = new OrganisationRepository(); LibraryRepository libraryRepository = new LibraryRepository(); List<Exchange> exchanges = new AuditRepository().getAllExchanges(); for (Exchange exchange: exchanges) { String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } boolean changed = false; UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); try { List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint : endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); String endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString(); ActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId); Item item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId()); LibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent()); System system = libraryItem.getSystem(); for (TechnicalInterface technicalInterface : system.getTechnicalInterface()) { if (endpointInterfaceId.equals(technicalInterface.getUuid())) { if (!headers.containsKey(HeaderKeys.SourceSystem)) { headers.put(HeaderKeys.SourceSystem, technicalInterface.getMessageFormat()); changed = true; } if (!headers.containsKey(HeaderKeys.SystemVersion)) { headers.put(HeaderKeys.SystemVersion, technicalInterface.getMessageFormatVersion()); changed = true; } if (!headers.containsKey(HeaderKeys.SenderSystemUuid)) { headers.put(HeaderKeys.SenderSystemUuid, endpointSystemId.toString()); changed = true; } } } } } catch (Exception e) { LOG.error("Failed to find endpoint details for " + exchange.getExchangeId()); continue; } if (changed) { try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setHeaders(headerJson); auditRepository.save(exchange); LOG.info("Fixed exchange " + exchange.getExchangeId()); } } LOG.info("Finished fixing exchange headers"); }*/ /*private static void testConnection(String configName) { try { JsonNode config = ConfigManager.getConfigurationAsJson(configName, "enterprise"); String driverClass = config.get("driverClass").asText(); String url = config.get("url").asText(); String username = config.get("username").asText(); String password = config.get("password").asText(); //force the driver to be loaded Class.forName(driverClass); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); LOG.info("Connection ok"); conn.close(); } catch (Exception e) { LOG.error("", e); } }*/ /*private static void testConnection() { try { JsonNode config = ConfigManager.getConfigurationAsJson("postgres", "enterprise"); String url = config.get("url").asText(); String username = config.get("username").asText(); String password = config.get("password").asText(); //force the driver to be loaded Class.forName("org.postgresql.Driver"); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); LOG.info("Connection ok"); conn.close(); } catch (Exception e) { LOG.error("", e); } }*/ /*private static void startEnterpriseStream(UUID serviceId, String configName, UUID exchangeIdStartFrom, UUID batchIdStartFrom) throws Exception { LOG.info("Starting Enterprise Streaming for " + serviceId + " using " + configName + " starting from exchange " + exchangeIdStartFrom + " and batch " + batchIdStartFrom); LOG.info("Testing database connection"); testConnection(configName); Service service = new ServiceRepository().getById(serviceId); List<UUID> orgIds = new ArrayList<>(service.getOrganisations().keySet()); UUID orgId = orgIds.get(0); List<ExchangeByService> exchangeByServiceList = new AuditRepository().getExchangesByService(serviceId, Integer.MAX_VALUE); for (int i=exchangeByServiceList.size()-1; i>=0; i--) { ExchangeByService exchangeByService = exchangeByServiceList.get(i); //for (ExchangeByService exchangeByService: exchangeByServiceList) { UUID exchangeId = exchangeByService.getExchangeId(); if (exchangeIdStartFrom != null) { if (!exchangeIdStartFrom.equals(exchangeId)) { continue; } else { //once we have a match, set to null so we don't skip any subsequent ones exchangeIdStartFrom = null; } } Exchange exchange = AuditWriter.readExchange(exchangeId); String senderOrgUuidStr = exchange.getHeader(HeaderKeys.SenderOrganisationUuid); UUID senderOrgUuid = UUID.fromString(senderOrgUuidStr); //this one had 90,000 batches and doesn't need doing again *//*if (exchangeId.equals(UUID.fromString("b9b93be0-afd8-11e6-8c16-c1d5a00342f3"))) { LOG.info("Skipping exchange " + exchangeId); continue; }*//* List<ExchangeBatch> exchangeBatches = new ExchangeBatchRepository().retrieveForExchangeId(exchangeId); LOG.info("Processing exchange " + exchangeId + " with " + exchangeBatches.size() + " batches"); for (int j=0; j<exchangeBatches.size(); j++) { ExchangeBatch exchangeBatch = exchangeBatches.get(j); UUID batchId = exchangeBatch.getBatchId(); if (batchIdStartFrom != null) { if (!batchIdStartFrom.equals(batchId)) { continue; } else { batchIdStartFrom = null; } } LOG.info("Processing exchange " + exchangeId + " and batch " + batchId + " " + (j+1) + "/" + exchangeBatches.size()); try { String outbound = FhirToEnterpriseCsvTransformer.transformFromFhir(senderOrgUuid, batchId, null); if (!Strings.isNullOrEmpty(outbound)) { EnterpriseFiler.file(outbound, configName); } } catch (Exception ex) { throw new PipelineException("Failed to process exchange " + exchangeId + " and batch " + batchId, ex); } } } }*/ /*private static void fixMissingExchanges() { LOG.info("Fixing missing exchanges"); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id, batch_id, inserted_at FROM ehr.exchange_batch LIMIT 600000;"); stmt.setFetchSize(100); Set<UUID> exchangeIdsDone = new HashSet<>(); AuditRepository auditRepository = new AuditRepository(); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); UUID batchId = row.get(1, UUID.class); Date date = row.getTimestamp(2); //LOG.info("Exchange " + exchangeId + " batch " + batchId + " date " + date); if (exchangeIdsDone.contains(exchangeId)) { continue; } if (auditRepository.getExchange(exchangeId) != null) { continue; } UUID serviceId = findServiceId(batchId, session); if (serviceId == null) { continue; } Exchange exchange = new Exchange(); ExchangeByService exchangeByService = new ExchangeByService(); ExchangeEvent exchangeEvent = new ExchangeEvent(); Map<String, String> headers = new HashMap<>(); headers.put(HeaderKeys.SenderServiceUuid, serviceId.toString()); String headersJson = null; try { headersJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setBody("Body not available, as exchange re-created"); exchange.setExchangeId(exchangeId); exchange.setHeaders(headersJson); exchange.setTimestamp(date); exchangeByService.setExchangeId(exchangeId); exchangeByService.setServiceId(serviceId); exchangeByService.setTimestamp(date); exchangeEvent.setEventDesc("Created_By_Conversion"); exchangeEvent.setExchangeId(exchangeId); exchangeEvent.setTimestamp(new Date()); auditRepository.save(exchange); auditRepository.save(exchangeEvent); auditRepository.save(exchangeByService); exchangeIdsDone.add(exchangeId); LOG.info("Creating exchange " + exchangeId); } LOG.info("Finished exchange fix"); } private static UUID findServiceId(UUID batchId, Session session) { Statement stmt = new SimpleStatement("select resource_type, resource_id from ehr.resource_by_exchange_batch where batch_id = " + batchId + " LIMIT 1;"); ResultSet rs = session.execute(stmt); if (rs.isExhausted()) { LOG.error("Failed to find resource_by_exchange_batch for batch_id " + batchId); return null; } Row row = rs.one(); String resourceType = row.getString(0); UUID resourceId = row.get(1, UUID.class); stmt = new SimpleStatement("select service_id from ehr.resource_history where resource_type = '" + resourceType + "' and resource_id = " + resourceId + " LIMIT 1;"); rs = session.execute(stmt); if (rs.isExhausted()) { LOG.error("Failed to find resource_history for resource_type " + resourceType + " and resource_id " + resourceId); return null; } row = rs.one(); UUID serviceId = row.get(0, UUID.class); return serviceId; }*/ /*private static void fixExchangeEvents() { List<ExchangeEvent> events = new AuditRepository().getAllExchangeEvents(); for (ExchangeEvent event: events) { if (event.getEventDesc() != null) { continue; } String eventDesc = ""; int eventType = event.getEvent().intValue(); switch (eventType) { case 1: eventDesc = "Receive"; break; case 2: eventDesc = "Validate"; break; case 3: eventDesc = "Transform_Start"; break; case 4: eventDesc = "Transform_End"; break; case 5: eventDesc = "Send"; break; default: eventDesc = "??? " + eventType; } event.setEventDesc(eventDesc); new AuditRepository().save(null, event); } }*/ /*private static void fixExchanges() { AuditRepository auditRepository = new AuditRepository(); Map<UUID, Set<UUID>> existingOnes = new HashMap(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); List<Exchange> exchanges = auditRepository.getAllExchanges(); for (Exchange exchange: exchanges) { UUID exchangeUuid = exchange.getExchangeId(); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeUuid + " and Json " + headerJson); continue; } *//*String serviceId = headers.get(HeaderKeys.SenderServiceUuid); if (serviceId == null) { LOG.warn("No service ID found for exchange " + exchange.getExchangeId()); continue; } UUID serviceUuid = UUID.fromString(serviceId); Set<UUID> exchangeIdsDone = existingOnes.get(serviceUuid); if (exchangeIdsDone == null) { exchangeIdsDone = new HashSet<>(); List<ExchangeByService> exchangeByServices = auditRepository.getExchangesByService(serviceUuid, Integer.MAX_VALUE); for (ExchangeByService exchangeByService: exchangeByServices) { exchangeIdsDone.add(exchangeByService.getExchangeId()); } existingOnes.put(serviceUuid, exchangeIdsDone); } //create the exchange by service entity if (!exchangeIdsDone.contains(exchangeUuid)) { Date timestamp = exchange.getTimestamp(); ExchangeByService newOne = new ExchangeByService(); newOne.setExchangeId(exchangeUuid); newOne.setServiceId(serviceUuid); newOne.setTimestamp(timestamp); auditRepository.save(newOne); }*//* try { headers.remove(HeaderKeys.BatchIdsJson); String newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(newHeaderJson); auditRepository.save(exchange); } catch (JsonProcessingException e) { LOG.error("Failed to populate batch IDs for exchange " + exchangeUuid, e); } if (!headers.containsKey(HeaderKeys.BatchIdsJson)) { //fix the batch IDs not being in the exchange List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeUuid); if (!batches.isEmpty()) { List<UUID> batchUuids = batches .stream() .map(t -> t.getBatchId()) .collect(Collectors.toList()); try { String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchUuids.toArray()); headers.put(HeaderKeys.BatchIdsJson, batchUuidsStr); String newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(newHeaderJson); auditRepository.save(exchange, null); } catch (JsonProcessingException e) { LOG.error("Failed to populate batch IDs for exchange " + exchangeUuid, e); } } //} } }*/ /*private static UUID findSystemId(Service service, String software, String messageVersion) throws PipelineException { List<JsonServiceInterfaceEndpoint> endpoints = null; try { endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); String endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString(); LibraryRepository libraryRepository = new LibraryRepository(); ActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId); Item item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId()); LibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent()); System system = libraryItem.getSystem(); for (TechnicalInterface technicalInterface: system.getTechnicalInterface()) { if (endpointInterfaceId.equals(technicalInterface.getUuid()) && technicalInterface.getMessageFormat().equalsIgnoreCase(software) && technicalInterface.getMessageFormatVersion().equalsIgnoreCase(messageVersion)) { return endpointSystemId; } } } } catch (Exception e) { throw new PipelineException("Failed to process endpoints from service " + service.getId()); } return null; } */ /*private static void addSystemIdToExchangeHeaders() throws Exception { LOG.info("populateExchangeBatchPatients"); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); ServiceRepository serviceRepository = new ServiceRepository(); //OrganisationRepository organisationRepository = new OrganisationRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.exchange LIMIT 500;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); org.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeId + " and Json " + headerJson); continue; } if (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid))) { LOG.info("Skipping exchange " + exchangeId + " as no service UUID"); continue; } if (!Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) { LOG.info("Skipping exchange " + exchangeId + " as already got system UUID"); continue; } try { //work out service ID String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); UUID serviceId = UUID.fromString(serviceIdStr); String software = headers.get(HeaderKeys.SourceSystem); String version = headers.get(HeaderKeys.SystemVersion); Service service = serviceRepository.getById(serviceId); UUID systemUuid = findSystemId(service, software, version); headers.put(HeaderKeys.SenderSystemUuid, systemUuid.toString()); //work out protocol IDs try { String newProtocolIdsJson = DetermineRelevantProtocolIds.getProtocolIdsForPublisherService(serviceIdStr); headers.put(HeaderKeys.ProtocolIds, newProtocolIdsJson); } catch (Exception ex) { LOG.error("Failed to recalculate protocols for " + exchangeId + ": " + ex.getMessage()); } //save to DB headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(headerJson); auditRepository.save(exchange); } catch (Exception ex) { LOG.error("Error with exchange " + exchangeId, ex); } } LOG.info("Finished populateExchangeBatchPatients"); }*/ /*private static void populateExchangeBatchPatients() throws Exception { LOG.info("populateExchangeBatchPatients"); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); //ServiceRepository serviceRepository = new ServiceRepository(); //OrganisationRepository organisationRepository = new OrganisationRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.exchange LIMIT 500;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); org.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeId + " and Json " + headerJson); continue; } if (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid)) || Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) { LOG.info("Skipping exchange " + exchangeId + " because no service or system in header"); continue; } try { UUID serviceId = UUID.fromString(headers.get(HeaderKeys.SenderServiceUuid)); UUID systemId = UUID.fromString(headers.get(HeaderKeys.SenderSystemUuid)); List<ExchangeBatch> exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch : exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null) { continue; } UUID batchId = exchangeBatch.getBatchId(); List<ResourceByExchangeBatch> resourceWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Patient.toString()); if (resourceWrappers.isEmpty()) { continue; } List<UUID> patientIds = new ArrayList<>(); for (ResourceByExchangeBatch resourceWrapper : resourceWrappers) { UUID patientId = resourceWrapper.getResourceId(); if (resourceWrapper.getIsDeleted()) { deleteEntirePatientRecord(patientId, serviceId, systemId, exchangeId, batchId); } if (!patientIds.contains(patientId)) { patientIds.add(patientId); } } if (patientIds.size() != 1) { LOG.info("Skipping exchange " + exchangeId + " and batch " + batchId + " because found " + patientIds.size() + " patient IDs"); continue; } UUID patientId = patientIds.get(0); exchangeBatch.setEdsPatientId(patientId); exchangeBatchRepository.save(exchangeBatch); } } catch (Exception ex) { LOG.error("Error with exchange " + exchangeId, ex); } } LOG.info("Finished populateExchangeBatchPatients"); } private static void deleteEntirePatientRecord(UUID patientId, UUID serviceId, UUID systemId, UUID exchangeId, UUID batchId) throws Exception { FhirStorageService storageService = new FhirStorageService(serviceId, systemId); ResourceRepository resourceRepository = new ResourceRepository(); List<ResourceByPatient> resourceWrappers = resourceRepository.getResourcesByPatient(serviceId, systemId, patientId); for (ResourceByPatient resourceWrapper: resourceWrappers) { String json = resourceWrapper.getResourceData(); Resource resource = new JsonParser().parse(json); storageService.exchangeBatchDelete(exchangeId, batchId, resource); } }*/ /*private static void convertPatientSearch() { LOG.info("Converting Patient Search"); ResourceRepository resourceRepository = new ResourceRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); LOG.info("Doing service " + service.getName()); for (UUID systemId : findSystemIds(service)) { List<ResourceByService> resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.EpisodeOfCare.toString()); for (ResourceByService resourceWrapper: resourceWrappers) { if (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) { continue; } try { EpisodeOfCare episodeOfCare = (EpisodeOfCare) new JsonParser().parse(resourceWrapper.getResourceData()); String patientId = ReferenceHelper.getReferenceId(episodeOfCare.getPatient()); ResourceHistory patientWrapper = resourceRepository.getCurrentVersion(ResourceType.Patient.toString(), UUID.fromString(patientId)); if (Strings.isNullOrEmpty(patientWrapper.getResourceData())) { continue; } Patient patient = (Patient) new JsonParser().parse(patientWrapper.getResourceData()); PatientSearchHelper.update(serviceId, systemId, patient); PatientSearchHelper.update(serviceId, systemId, episodeOfCare); } catch (Exception ex) { LOG.error("Failed on " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId(), ex); } } } } LOG.info("Converted Patient Search"); } catch (Exception ex) { LOG.error("", ex); } }*/ private static List<UUID> findSystemIds(Service service) throws Exception { List<UUID> ret = new ArrayList<>(); List<JsonServiceInterfaceEndpoint> endpoints = null; try { endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); ret.add(endpointSystemId); } } catch (Exception e) { throw new Exception("Failed to process endpoints from service " + service.getId()); } return ret; } /*private static void convertPatientLink() { LOG.info("Converting Patient Link"); ResourceRepository resourceRepository = new ResourceRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); LOG.info("Doing service " + service.getName()); for (UUID systemId : findSystemIds(service)) { List<ResourceByService> resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.Patient.toString()); for (ResourceByService resourceWrapper: resourceWrappers) { if (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) { continue; } try { Patient patient = (Patient)new JsonParser().parse(resourceWrapper.getResourceData()); PatientLinkHelper.updatePersonId(patient); } catch (Exception ex) { LOG.error("Failed on " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId(), ex); } } } } LOG.info("Converted Patient Link"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixConfidentialPatients(String sharedStoragePath, UUID justThisService) { LOG.info("Fixing Confidential Patients using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); MappingManager mappingManager = CassandraConnector.getInstance().getMappingManager(); Mapper<ResourceHistory> mapperResourceHistory = mappingManager.mapper(ResourceHistory.class); Mapper<ResourceByExchangeBatch> mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); Map<String, ResourceHistory> resourcesFixed = new HashMap<>(); Map<UUID, Set<UUID>> exchangeBatchesToPutInProtocolQueue = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Set<UUID> batchIdsToPutInProtocolQueue = new HashSet<>(); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); String dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f); EmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId); ResourceFiler filer = new ResourceFiler(exchangeId, serviceId, systemId, null, null, 1); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers); ProblemPreTransformer.transform(version, parsers, filer, helper); ObservationPreTransformer.transform(version, parsers, filer, helper); DrugRecordPreTransformer.transform(version, parsers, filer, helper); IssueRecordPreTransformer.transform(version, parsers, filer, helper); DiaryPreTransformer.transform(version, parsers, filer, helper); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient)parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getIsConfidential() && !patientParser.getDeleted()) { PatientTransformer.createResource(patientParser, filer, helper, version); } } patientParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class); while (consultationParser.nextRecord()) { if (consultationParser.getIsConfidential() && !consultationParser.getDeleted()) { ConsultationTransformer.createResource(consultationParser, filer, helper, version); } } consultationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { if (observationParser.getIsConfidential() && !observationParser.getDeleted()) { ObservationTransformer.createResource(observationParser, filer, helper, version); } } observationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class); while (diaryParser.nextRecord()) { if (diaryParser.getIsConfidential() && !diaryParser.getDeleted()) { DiaryTransformer.createResource(diaryParser, filer, helper, version); } } diaryParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class); while (drugRecordParser.nextRecord()) { if (drugRecordParser.getIsConfidential() && !drugRecordParser.getDeleted()) { DrugRecordTransformer.createResource(drugRecordParser, filer, helper, version); } } drugRecordParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class); while (issueRecordParser.nextRecord()) { if (issueRecordParser.getIsConfidential() && !issueRecordParser.getDeleted()) { IssueRecordTransformer.createResource(issueRecordParser, filer, helper, version); } } issueRecordParser.close(); filer.waitToFinish(); //just to close the thread pool, even though it's not been used List<Resource> resources = filer.getNewResources(); for (Resource resource: resources) { String patientId = IdHelper.getPatientId(resource); UUID edsPatientId = UUID.fromString(patientId); ResourceType resourceType = resource.getResourceType(); UUID resourceId = UUID.fromString(resource.getId()); boolean foundResourceInDbBatch = false; List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds != null) { for (UUID batchId : batchIds) { List<ResourceByExchangeBatch> resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), resourceId); if (resourceByExchangeBatches.isEmpty()) { //if we've deleted data, this will be null continue; } foundResourceInDbBatch = true; for (ResourceByExchangeBatch resourceByExchangeBatch : resourceByExchangeBatches) { String json = resourceByExchangeBatch.getResourceData(); if (!Strings.isNullOrEmpty(json)) { LOG.warn("JSON already in resource " + resourceType + " " + resourceId); } else { json = parserPool.composeString(resource); resourceByExchangeBatch.setResourceData(json); resourceByExchangeBatch.setIsDeleted(false); resourceByExchangeBatch.setSchemaVersion("0.1"); LOG.info("Saved resource by batch " + resourceType + " " + resourceId + " in batch " + batchId); UUID versionUuid = resourceByExchangeBatch.getVersion(); ResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(resourceId, resourceType.toString(), versionUuid); if (resourceHistory == null) { throw new Exception("Failed to find resource history for " + resourceType + " " + resourceId + " and version " + versionUuid); } resourceHistory.setIsDeleted(false); resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); resourceHistory.setSchemaVersion("0.1"); resourceRepository.save(resourceByExchangeBatch); resourceRepository.save(resourceHistory); batchIdsToPutInProtocolQueue.add(batchId); String key = resourceType.toString() + ":" + resourceId; resourcesFixed.put(key, resourceHistory); } //if a patient became confidential, we will have deleted all resources for that //patient, so we need to undo that too //to undelete WHOLE patient record //1. if THIS resource is a patient //2. get all other deletes from the same exchange batch //3. delete those from resource_by_exchange_batch (the deleted ones only) //4. delete same ones from resource_history //5. retrieve most recent resource_history //6. if not deleted, add to resources fixed if (resourceType == ResourceType.Patient) { List<ResourceByExchangeBatch> resourcesInSameBatch = resourceRepository.getResourcesForBatch(batchId); LOG.info("Undeleting " + resourcesInSameBatch.size() + " resources for batch " + batchId); for (ResourceByExchangeBatch resourceInSameBatch: resourcesInSameBatch) { if (!resourceInSameBatch.getIsDeleted()) { continue; } //patient and episode resources will be restored by the above stuff, so don't try //to do it again if (resourceInSameBatch.getResourceType().equals(ResourceType.Patient.toString()) || resourceInSameBatch.getResourceType().equals(ResourceType.EpisodeOfCare.toString())) { continue; } ResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(resourceInSameBatch.getResourceId(), resourceInSameBatch.getResourceType(), resourceInSameBatch.getVersion()); mapperResourceByExchangeBatch.delete(resourceInSameBatch); mapperResourceHistory.delete(deletedResourceHistory); batchIdsToPutInProtocolQueue.add(batchId); //check the most recent version of our resource, and if it's not deleted, add to the list to update the resource_by_service table ResourceHistory mostRecentDeletedResourceHistory = resourceRepository.getCurrentVersion(resourceInSameBatch.getResourceType(), resourceInSameBatch.getResourceId()); if (mostRecentDeletedResourceHistory != null && !mostRecentDeletedResourceHistory.getIsDeleted()) { String key2 = mostRecentDeletedResourceHistory.getResourceType().toString() + ":" + mostRecentDeletedResourceHistory.getResourceId(); resourcesFixed.put(key2, mostRecentDeletedResourceHistory); } } } } } } //if we didn't find records in the DB to update, then if (!foundResourceInDbBatch) { //we can't generate a back-dated time UUID, but we need one so the resource_history //table is in order. To get a suitable time UUID, we just pull out the first exchange batch for our exchange, //and the batch ID is actually a time UUID that was allocated around the right time ExchangeBatch firstBatch = exchangeBatchRepository.retrieveFirstForExchangeId(exchangeId); //if there was no batch for the exchange, then the exchange wasn't processed at all. So skip this exchange //and we'll pick up the same patient data in a following exchange if (firstBatch == null) { continue; } UUID versionUuid = firstBatch.getBatchId(); //find suitable batch ID UUID batchId = null; if (batchIds != null && batchIds.size() > 0) { batchId = batchIds.get(batchIds.size()-1); } else { //create new batch ID if not found ExchangeBatch exchangeBatch = new ExchangeBatch(); exchangeBatch.setBatchId(UUIDs.timeBased()); exchangeBatch.setExchangeId(exchangeId); exchangeBatch.setInsertedAt(new Date()); exchangeBatch.setEdsPatientId(edsPatientId); exchangeBatchRepository.save(exchangeBatch); batchId = exchangeBatch.getBatchId(); //add to map for next resource if (batchIds == null) { batchIds = new ArrayList<>(); } batchIds.add(batchId); batchesPerPatient.put(edsPatientId, batchIds); } String json = parserPool.composeString(resource); ResourceHistory resourceHistory = new ResourceHistory(); resourceHistory.setResourceId(resourceId); resourceHistory.setResourceType(resourceType.toString()); resourceHistory.setVersion(versionUuid); resourceHistory.setCreatedAt(new Date()); resourceHistory.setServiceId(serviceId); resourceHistory.setSystemId(systemId); resourceHistory.setIsDeleted(false); resourceHistory.setSchemaVersion("0.1"); resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); ResourceByExchangeBatch resourceByExchangeBatch = new ResourceByExchangeBatch(); resourceByExchangeBatch.setBatchId(batchId); resourceByExchangeBatch.setExchangeId(exchangeId); resourceByExchangeBatch.setResourceType(resourceType.toString()); resourceByExchangeBatch.setResourceId(resourceId); resourceByExchangeBatch.setVersion(versionUuid); resourceByExchangeBatch.setIsDeleted(false); resourceByExchangeBatch.setSchemaVersion("0.1"); resourceByExchangeBatch.setResourceData(json); resourceRepository.save(resourceHistory); resourceRepository.save(resourceByExchangeBatch); batchIdsToPutInProtocolQueue.add(batchId); } } if (!batchIdsToPutInProtocolQueue.isEmpty()) { exchangeBatchesToPutInProtocolQueue.put(exchangeId, batchIdsToPutInProtocolQueue); } } //update the resource_by_service table (and the resource_by_patient view) for (ResourceHistory resourceHistory: resourcesFixed.values()) { UUID latestVersionUpdatedUuid = resourceHistory.getVersion(); ResourceHistory latestVersion = resourceRepository.getCurrentVersion(resourceHistory.getResourceType(), resourceHistory.getResourceId()); UUID latestVersionUuid = latestVersion.getVersion(); //if there have been subsequent updates to the resource, then skip it if (!latestVersionUuid.equals(latestVersionUpdatedUuid)) { continue; } Resource resource = parserPool.parse(resourceHistory.getResourceData()); ResourceMetadata metadata = MetadataFactory.createMetadata(resource); UUID patientId = ((PatientCompartment)metadata).getPatientId(); ResourceByService resourceByService = new ResourceByService(); resourceByService.setServiceId(resourceHistory.getServiceId()); resourceByService.setSystemId(resourceHistory.getSystemId()); resourceByService.setResourceType(resourceHistory.getResourceType()); resourceByService.setResourceId(resourceHistory.getResourceId()); resourceByService.setCurrentVersion(resourceHistory.getVersion()); resourceByService.setUpdatedAt(resourceHistory.getCreatedAt()); resourceByService.setPatientId(patientId); resourceByService.setSchemaVersion(resourceHistory.getSchemaVersion()); resourceByService.setResourceMetadata(JsonSerializer.serialize(metadata)); resourceByService.setResourceData(resourceHistory.getResourceData()); resourceRepository.save(resourceByService); //call out to our patient search and person matching services if (resource instanceof Patient) { PatientLinkHelper.updatePersonId((Patient)resource); PatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (Patient)resource); } else if (resource instanceof EpisodeOfCare) { PatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (EpisodeOfCare)resource); } } if (!exchangeBatchesToPutInProtocolQueue.isEmpty()) { //find the config for our protocol queue String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) { Set<UUID> batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } } LOG.info("Finished Fixing Confidential Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixDeletedAppointments(String sharedStoragePath, boolean saveChanges, UUID justThisService) { LOG.info("Fixing Deleted Appointments using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); MappingManager mappingManager = CassandraConnector.getInstance().getMappingManager(); Mapper<ResourceHistory> mapperResourceHistory = mappingManager.mapper(ResourceHistory.class); Mapper<ResourceByExchangeBatch> mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch : batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class, dir, version, true, parsers); //find any deleted patients List<UUID> deletedPatientUuids = new ArrayList<>(); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getDeleted()) { //find the EDS patient ID for this local guid String patientGuid = patientParser.getPatientGuid(); UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + patientGuid); } deletedPatientUuids.add(edsPatientId); } } patientParser.close(); //go through the appts file to find properly deleted appt GUIDS List<UUID> deletedApptUuids = new ArrayList<>(); org.endeavourhealth.transform.emis.csv.schema.appointment.Slot apptParser = (org.endeavourhealth.transform.emis.csv.schema.appointment.Slot) parsers.get(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class); while (apptParser.nextRecord()) { if (apptParser.getDeleted()) { String patientGuid = apptParser.getPatientGuid(); String slotGuid = apptParser.getSlotGuid(); if (!Strings.isNullOrEmpty(patientGuid)) { String uniqueLocalId = EmisCsvHelper.createUniqueId(patientGuid, slotGuid); UUID edsApptId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Appointment, uniqueLocalId); deletedApptUuids.add(edsApptId); } } } apptParser.close(); for (UUID edsPatientId : deletedPatientUuids) { List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds == null) { //if there are no batches for this patient, we'll be handling this data in another exchange continue; } for (UUID batchId : batchIds) { List<ResourceByExchangeBatch> apptWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Appointment.toString()); for (ResourceByExchangeBatch apptWrapper : apptWrappers) { //ignore non-deleted appts if (!apptWrapper.getIsDeleted()) { continue; } //if the appt was deleted legitamately, then skip it UUID apptId = apptWrapper.getResourceId(); if (deletedApptUuids.contains(apptId)) { continue; } ResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(apptWrapper.getResourceId(), apptWrapper.getResourceType(), apptWrapper.getVersion()); if (saveChanges) { mapperResourceByExchangeBatch.delete(apptWrapper); mapperResourceHistory.delete(deletedResourceHistory); } LOG.info("Un-deleted " + apptWrapper.getResourceType() + " " + apptWrapper.getResourceId() + " in batch " + batchId + " patient " + edsPatientId); //now get the most recent instance of the appointment, and if it's NOT deleted, insert into the resource_by_service table ResourceHistory mostRecentResourceHistory = resourceRepository.getCurrentVersion(apptWrapper.getResourceType(), apptWrapper.getResourceId()); if (mostRecentResourceHistory != null && !mostRecentResourceHistory.getIsDeleted()) { Resource resource = parserPool.parse(mostRecentResourceHistory.getResourceData()); ResourceMetadata metadata = MetadataFactory.createMetadata(resource); UUID patientId = ((PatientCompartment) metadata).getPatientId(); ResourceByService resourceByService = new ResourceByService(); resourceByService.setServiceId(mostRecentResourceHistory.getServiceId()); resourceByService.setSystemId(mostRecentResourceHistory.getSystemId()); resourceByService.setResourceType(mostRecentResourceHistory.getResourceType()); resourceByService.setResourceId(mostRecentResourceHistory.getResourceId()); resourceByService.setCurrentVersion(mostRecentResourceHistory.getVersion()); resourceByService.setUpdatedAt(mostRecentResourceHistory.getCreatedAt()); resourceByService.setPatientId(patientId); resourceByService.setSchemaVersion(mostRecentResourceHistory.getSchemaVersion()); resourceByService.setResourceMetadata(JsonSerializer.serialize(metadata)); resourceByService.setResourceData(mostRecentResourceHistory.getResourceData()); if (saveChanges) { resourceRepository.save(resourceByService); } LOG.info("Restored " + apptWrapper.getResourceType() + " " + apptWrapper.getResourceId() + " to resource_by_service table"); } } } } } } LOG.info("Finished Deleted Appointments Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixReviews(String sharedStoragePath, UUID justThisService) { LOG.info("Fixing Reviews using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); Map<String, Long> problemCodes = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); LOG.info("Doing Emis CSV exchange " + exchangeId + " with " + batches.size() + " batches"); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem problemParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (problemParser.nextRecord()) { String patientGuid = problemParser.getPatientGuid(); String observationGuid = problemParser.getObservationGuid(); String key = patientGuid + ":" + observationGuid; if (!problemCodes.containsKey(key)) { problemCodes.put(key, null); } } problemParser.close(); while (observationParser.nextRecord()) { String patientGuid = observationParser.getPatientGuid(); String observationGuid = observationParser.getObservationGuid(); String key = patientGuid + ":" + observationGuid; if (problemCodes.containsKey(key)) { Long codeId = observationParser.getCodeId(); if (codeId == null) { continue; } problemCodes.put(key, codeId); } } observationParser.close(); LOG.info("Found " + problemCodes.size() + " problem codes so far"); String dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f); EmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId); while (observationParser.nextRecord()) { String problemGuid = observationParser.getProblemGuid(); if (!Strings.isNullOrEmpty(problemGuid)) { String patientGuid = observationParser.getPatientGuid(); Long codeId = observationParser.getCodeId(); if (codeId == null) { continue; } String key = patientGuid + ":" + problemGuid; Long problemCodeId = problemCodes.get(key); if (problemCodeId == null || problemCodeId.longValue() != codeId.longValue()) { continue; } //if here, our code is the same as the problem, so it's a review String locallyUniqueId = patientGuid + ":" + observationParser.getObservationGuid(); ResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, helper); for (UUID systemId: systemIds) { UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + patientGuid); } UUID edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); if (edsObservationId == null) { //try observations as diagnostic reports, because it could be one of those instead if (resourceType == ResourceType.Observation) { resourceType = ResourceType.DiagnosticReport; edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); } if (edsObservationId == null) { throw new Exception("Failed to find observation ID for service " + serviceId + " system " + systemId + " resourceType " + resourceType + " local ID " + locallyUniqueId); } } List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds == null) { //if there are no batches for this patient, we'll be handling this data in another exchange continue; //throw new Exception("Failed to find batch ID for patient " + edsPatientId + " in exchange " + exchangeId + " for resource " + resourceType + " " + edsObservationId); } for (UUID batchId: batchIds) { List<ResourceByExchangeBatch> resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), edsObservationId); if (resourceByExchangeBatches.isEmpty()) { //if we've deleted data, this will be null continue; //throw new Exception("No resources found for batch " + batchId + " resource type " + resourceType + " and resource id " + edsObservationId); } for (ResourceByExchangeBatch resourceByExchangeBatch: resourceByExchangeBatches) { String json = resourceByExchangeBatch.getResourceData(); if (Strings.isNullOrEmpty(json)) { throw new Exception("No JSON in resource " + resourceType + " " + edsObservationId + " in batch " + batchId); } Resource resource = parserPool.parse(json); if (addReviewExtension((DomainResource)resource)) { json = parserPool.composeString(resource); resourceByExchangeBatch.setResourceData(json); LOG.info("Changed " + resourceType + " " + edsObservationId + " to have extension in batch " + batchId); resourceRepository.save(resourceByExchangeBatch); UUID versionUuid = resourceByExchangeBatch.getVersion(); ResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(edsObservationId, resourceType.toString(), versionUuid); if (resourceHistory == null) { throw new Exception("Failed to find resource history for " + resourceType + " " + edsObservationId + " and version " + versionUuid); } resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); resourceRepository.save(resourceHistory); ResourceByService resourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType.toString(), edsObservationId); if (resourceByService != null) { UUID serviceVersionUuid = resourceByService.getCurrentVersion(); if (serviceVersionUuid.equals(versionUuid)) { resourceByService.setResourceData(json); resourceRepository.save(resourceByService); } } } else { LOG.info("" + resourceType + " " + edsObservationId + " already has extension"); } } } } //1. find out resource type originall saved from //2. retrieve from resource_by_exchange_batch //3. update resource in resource_by_exchange_batch //4. retrieve from resource_history //5. update resource_history //6. retrieve record from resource_by_service //7. if resource_by_service version UUID matches the resource_history updated, then update that too } } observationParser.close(); } } LOG.info("Finished Fixing Reviews"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static boolean addReviewExtension(DomainResource resource) { if (ExtensionConverter.hasExtension(resource, FhirExtensionUri.IS_REVIEW)) { return false; } Extension extension = ExtensionConverter.createExtension(FhirExtensionUri.IS_REVIEW, new BooleanType(true)); resource.addExtension(extension); return true; }*/ /*private static void runProtocolsForConfidentialPatients(String sharedStoragePath, UUID justThisService) { LOG.info("Running Protocols for Confidential Patients using path " + sharedStoragePath + " and service " + justThisService); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } //once we match the servce, set this to null to do all other services justThisService = null; LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); List<String> interestingPatientGuids = new ArrayList<>(); Map<UUID, Map<UUID, List<UUID>>> batchesPerPatientPerExchange = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch : batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } batchesPerPatientPerExchange.put(exchangeId, batchesPerPatient); File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getIsConfidential() || patientParser.getDeleted()) { interestingPatientGuids.add(patientParser.getPatientGuid()); } } patientParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class); while (consultationParser.nextRecord()) { if (consultationParser.getIsConfidential() && !consultationParser.getDeleted()) { interestingPatientGuids.add(consultationParser.getPatientGuid()); } } consultationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { if (observationParser.getIsConfidential() && !observationParser.getDeleted()) { interestingPatientGuids.add(observationParser.getPatientGuid()); } } observationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class); while (diaryParser.nextRecord()) { if (diaryParser.getIsConfidential() && !diaryParser.getDeleted()) { interestingPatientGuids.add(diaryParser.getPatientGuid()); } } diaryParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class); while (drugRecordParser.nextRecord()) { if (drugRecordParser.getIsConfidential() && !drugRecordParser.getDeleted()) { interestingPatientGuids.add(drugRecordParser.getPatientGuid()); } } drugRecordParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class); while (issueRecordParser.nextRecord()) { if (issueRecordParser.getIsConfidential() && !issueRecordParser.getDeleted()) { interestingPatientGuids.add(issueRecordParser.getPatientGuid()); } } issueRecordParser.close(); } Map<UUID, Set<UUID>> exchangeBatchesToPutInProtocolQueue = new HashMap<>(); for (String interestingPatientGuid: interestingPatientGuids) { if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, interestingPatientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + interestingPatientGuid); } for (UUID exchangeId: batchesPerPatientPerExchange.keySet()) { Map<UUID, List<UUID>> batchesPerPatient = batchesPerPatientPerExchange.get(exchangeId); List<UUID> batches = batchesPerPatient.get(edsPatientId); if (batches != null) { Set<UUID> batchesForExchange = exchangeBatchesToPutInProtocolQueue.get(exchangeId); if (batchesForExchange == null) { batchesForExchange = new HashSet<>(); exchangeBatchesToPutInProtocolQueue.put(exchangeId, batchesForExchange); } batchesForExchange.addAll(batches); } } } if (!exchangeBatchesToPutInProtocolQueue.isEmpty()) { //find the config for our protocol queue String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) { Set<UUID> batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); LOG.info("Posting exchange " + exchangeId + " batch " + batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } } LOG.info("Finished Running Protocols for Confidential Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixOrgs() { LOG.info("Posting orgs to protocol queue"); String[] orgIds = new String[]{ "332f31a2-7b28-47cb-af6f-18f65440d43d", "c893d66b-eb89-4657-9f53-94c5867e7ed9"}; ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); Map<UUID, Set<UUID>> exchangeBatches = new HashMap<>(); for (String orgId: orgIds) { LOG.info("Doing org ID " + orgId); UUID orgUuid = UUID.fromString(orgId); try { //select batch_id from ehr.resource_by_exchange_batch where resource_type = 'Organization' and resource_id = 8f465517-729b-4ad9-b405-92b487047f19 LIMIT 1 ALLOW FILTERING; ResourceByExchangeBatch resourceByExchangeBatch = resourceRepository.getFirstResourceByExchangeBatch(ResourceType.Organization.toString(), orgUuid); UUID batchId = resourceByExchangeBatch.getBatchId(); //select exchange_id from ehr.exchange_batch where batch_id = 1a940e10-1535-11e7-a29d-a90b99186399 LIMIT 1 ALLOW FILTERING; ExchangeBatch exchangeBatch = exchangeBatchRepository.retrieveFirstForBatchId(batchId); UUID exchangeId = exchangeBatch.getExchangeId(); Set<UUID> list = exchangeBatches.get(exchangeId); if (list == null) { list = new HashSet<>(); exchangeBatches.put(exchangeId, list); } list.add(batchId); } catch (Exception ex) { LOG.error("", ex); break; } } try { //find the config for our protocol queue (which is in the inbound config) String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatches.keySet()) { Set<UUID> batchIds = exchangeBatches.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); LOG.info("Posting exchange " + exchangeId + " batch " + batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } catch (Exception ex) { LOG.error("", ex); return; } LOG.info("Finished posting orgs to protocol queue"); }*/ /*private static void findCodes() { LOG.info("Finding missing codes"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT service_id, system_id, exchange_id, version FROM audit.exchange_transform_audit ALLOW FILTERING;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID serviceId = row.get(0, UUID.class); UUID systemId = row.get(1, UUID.class); UUID exchangeId = row.get(2, UUID.class); UUID version = row.get(3, UUID.class); ExchangeTransformAudit audit = auditRepository.getExchangeTransformAudit(serviceId, systemId, exchangeId, version); String xml = audit.getErrorXml(); if (xml == null) { continue; } String codePrefix = "Failed to find clinical code CodeableConcept for codeId "; int codeIndex = xml.indexOf(codePrefix); if (codeIndex > -1) { int startIndex = codeIndex + codePrefix.length(); int tagEndIndex = xml.indexOf("<", startIndex); String code = xml.substring(startIndex, tagEndIndex); Service service = serviceRepository.getById(serviceId); String name = service.getName(); LOG.info(name + " clinical code " + code + " from " + audit.getStarted()); continue; } codePrefix = "Failed to find medication CodeableConcept for codeId "; codeIndex = xml.indexOf(codePrefix); if (codeIndex > -1) { int startIndex = codeIndex + codePrefix.length(); int tagEndIndex = xml.indexOf("<", startIndex); String code = xml.substring(startIndex, tagEndIndex); Service service = serviceRepository.getById(serviceId); String name = service.getName(); LOG.info(name + " drug code " + code + " from " + audit.getStarted()); continue; } } LOG.info("Finished finding missing codes"); }*/ private static void createTppSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating TPP Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createTppSubsetForFile(sourceDir, destDir, personIds); LOG.info("Finished Creating TPP Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createTppSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } //LOG.info("Doing dir " + sourceFile); createTppSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } Charset encoding = Charset.forName("CP1252"); InputStreamReader reader = new InputStreamReader( new BufferedInputStream( new FileInputStream(sourceFile)), encoding); CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL).withHeader(); CSVParser parser = new CSVParser(reader, format); String filterColumn = null; Map<String, Integer> headerMap = parser.getHeaderMap(); if (headerMap.containsKey("IDPatient")) { filterColumn = "IDPatient"; } else if (name.equalsIgnoreCase("SRPatient.csv")) { filterColumn = "RowIdentifier"; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } String[] columnHeaders = new String[headerMap.size()]; Iterator<String> headerIterator = headerMap.keySet().iterator(); while (headerIterator.hasNext()) { String headerName = headerIterator.next(); int headerIndex = headerMap.get(headerName); columnHeaders[headerIndex] = headerName; } BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(destFile), encoding)); CSVPrinter printer = new CSVPrinter(bw, format.withHeader(columnHeaders)); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); /*} else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); copyFile(sourceFile, destFile); }*/ } } } private static void createVisionSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Vision Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createVisionSubsetForFile(sourceDir, destDir, personIds); LOG.info("Finished Creating Vision Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createVisionSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createVisionSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; if (name.contains("encounter_data") || name.contains("journal_data") || name.contains("patient_data") || name.contains("referral_data")) { filterColumn = 0; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } private static void createHomertonSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Homerton Subset"); try { Set<String> PersonIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } PersonIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createHomertonSubsetForFile(sourceDir, destDir, PersonIds); LOG.info("Finished Creating Homerton Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createHomertonSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createHomertonSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); //fully quote destination file to fix CRLF in columns CSVFormat format = CSVFormat.DEFAULT.withHeader(); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; //PersonId column at 1 if (name.contains("ENCOUNTER") || name.contains("PATIENT")) { filterColumn = 1; } else if (name.contains("DIAGNOSIS")) { //PersonId column at 13 filterColumn = 13; } else if (name.contains("ALLERGY")) { //PersonId column at 2 filterColumn = 2; } else if (name.contains("PROBLEM")) { //PersonId column at 4 filterColumn = 4; } else { //if no patient column, just copy the file (i.e. PROCEDURE) parser.close(); LOG.info("Copying file without PatientId " + sourceFile); copyFile(sourceFile, destFile); continue; } Map<String, Integer> headerMap = parser.getHeaderMap(); String[] columnHeaders = new String[headerMap.size()]; Iterator<String> headerIterator = headerMap.keySet().iterator(); while (headerIterator.hasNext()) { String headerName = headerIterator.next(); int headerIndex = headerMap.get(headerName); columnHeaders[headerIndex] = headerName; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format.withHeader(columnHeaders)); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } private static void createAdastraSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Adastra Subset"); try { Set<String> caseIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } //adastra extract files are all keyed on caseId caseIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createAdastraSubsetForFile(sourceDir, destDir, caseIds); LOG.info("Finished Creating Adastra Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createAdastraSubsetForFile(File sourceDir, File destDir, Set<String> caseIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createAdastraSubsetForFile(sourceFile, destFile, caseIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); //fully quote destination file to fix CRLF in columns CSVFormat format = CSVFormat.DEFAULT.withDelimiter('|'); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; //CaseRef column at 0 if (name.contains("NOTES") || name.contains("CASEQUESTIONS") || name.contains("OUTCOMES") || name.contains("CONSULTATION") || name.contains("CLINICALCODES") || name.contains("PRESCRIPTIONS") || name.contains("PATIENT")) { filterColumn = 0; } else if (name.contains("CASE")) { //CaseRef column at 2 filterColumn = 2; } else if (name.contains("PROVIDER")) { //CaseRef column at 7 filterColumn = 7; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String caseId = csvRecord.get(filterColumn); if (caseIds.contains(caseId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } private static void exportFhirToCsv(UUID serviceId, String destinationPath) { try { File dir = new File(destinationPath); if (dir.exists()) { dir.mkdirs(); } Map<String, CSVPrinter> hmPrinters = new HashMap<>(); EntityManager entityManager = ConnectionManager.getEhrEntityManager(serviceId); SessionImpl session = (SessionImpl) entityManager.getDelegate(); Connection connection = session.connection(); PreparedStatement ps = connection.prepareStatement("SELECT resource_id, resource_type, resource_data FROM resource_current"); LOG.debug("Running query"); ResultSet rs = ps.executeQuery(); LOG.debug("Got result set"); while (rs.next()) { String id = rs.getString(1); String type = rs.getString(2); String json = rs.getString(3); CSVPrinter printer = hmPrinters.get(type); if (printer == null) { String path = FilenameUtils.concat(dir.getAbsolutePath(), type + ".tsv"); FileWriter fileWriter = new FileWriter(new File(path)); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVFormat format = CSVFormat.DEFAULT .withHeader("resource_id", "resource_json") .withDelimiter('\t') .withEscape((Character) null) .withQuote((Character) null) .withQuoteMode(QuoteMode.MINIMAL); printer = new CSVPrinter(bufferedWriter, format); hmPrinters.put(type, printer); } printer.printRecord(id, json); } for (String type : hmPrinters.keySet()) { CSVPrinter printer = hmPrinters.get(type); printer.flush(); printer.close(); } ps.close(); entityManager.close(); } catch (Throwable t) { LOG.error("", t); } } } /*class ResourceFiler extends FhirResourceFiler { public ResourceFiler(UUID exchangeId, UUID serviceId, UUID systemId, TransformError transformError, List<UUID> batchIdsCreated, int maxFilingThreads) { super(exchangeId, serviceId, systemId, transformError, batchIdsCreated, maxFilingThreads); } private List<Resource> newResources = new ArrayList<>(); public List<Resource> getNewResources() { return newResources; } @Override public void saveAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception { throw new Exception("shouldn't be calling saveAdminResource"); } @Override public void deleteAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception { throw new Exception("shouldn't be calling deleteAdminResource"); } @Override public void savePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception { for (Resource resource: resources) { if (mapIds) { IdHelper.mapIds(getServiceId(), getSystemId(), resource); } newResources.add(resource); } } @Override public void deletePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception { throw new Exception("shouldn't be calling deletePatientResource"); } }*/
Adding routine to fix patients mapped to the same person using invalid NHS numbers
src/eds-queuereader/src/main/java/org/endeavourhealth/queuereader/Main.java
Adding routine to fix patients mapped to the same person using invalid NHS numbers
<ide><path>rc/eds-queuereader/src/main/java/org/endeavourhealth/queuereader/Main.java <ide> import org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI; <ide> import org.endeavourhealth.core.database.dal.audit.ExchangeDalI; <ide> import org.endeavourhealth.core.database.dal.audit.models.*; <add>import org.endeavourhealth.core.database.dal.eds.PatientSearchDalI; <ide> import org.endeavourhealth.core.database.dal.ehr.ResourceDalI; <ide> import org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper; <ide> import org.endeavourhealth.core.database.dal.subscriberTransform.EnterpriseIdDalI; <ide> System.exit(0); <ide> } <ide> <del> if (args.length >= 1 <add> /*if (args.length >= 1 <ide> && args[0].equalsIgnoreCase("FixSubscribers")) { <ide> fixSubscriberDbs(); <ide> System.exit(0); <del> } <add> }*/ <ide> <ide> /*if (args.length >= 1 <ide> && args[0].equalsIgnoreCase("FixEmisProblems")) { <ide> System.exit(0); <ide> } <ide> <add> if (args.length >= 1 <add> && args[0].equalsIgnoreCase("FixPersonsNoNhsNumber")) { <add> fixPersonsNoNhsNumber(); <add> System.exit(0); <add> } <add> <ide> <ide> /*if (args.length >= 1 <ide> && args[0].equalsIgnoreCase("ConvertExchangeBody")) { <ide> System.exit(0); <ide> }*/ <ide> <del> if (args.length >= 1 <add> /*if (args.length >= 1 <ide> && args[0].equalsIgnoreCase("PostToInbound")) { <ide> String serviceId = args[1]; <ide> String systemId = args[2]; <ide> String filePath = args[3]; <ide> postToInboundFromFile(UUID.fromString(serviceId), UUID.fromString(systemId), filePath); <ide> System.exit(0); <del> } <add> }*/ <ide> <ide> if (args.length >= 1 <ide> && args[0].equalsIgnoreCase("FixDisabledExtract")) { <ide> // Begin consume <ide> rabbitHandler.start(); <ide> LOG.info("EDS Queue reader running (kill file location " + TransformConfig.instance().getKillFileLocation() + ")"); <add> } <add> <add> private static void fixPersonsNoNhsNumber() { <add> LOG.info("Fixing persons with no NHS number"); <add> try { <add> <add> ServiceDalI serviceDal = DalProvider.factoryServiceDal(); <add> List<Service> services = serviceDal.getAll(); <add> <add> EntityManager entityManager = ConnectionManager.getEdsEntityManager(); <add> SessionImpl session = (SessionImpl)entityManager.getDelegate(); <add> Connection patientSearchConnection = session.connection(); <add> Statement patientSearchStatement = patientSearchConnection.createStatement(); <add> <add> for (Service service: services) { <add> LOG.info("Doing " + service.getName() + " " + service.getId()); <add> <add> int checked = 0; <add> int fixedPersons = 0; <add> int fixedSearches = 0; <add> <add> String sql = "SELECT patient_id, nhs_number FROM patient_search WHERE service_id = '" + service.getId() + "' AND (nhs_number IS NULL or CHAR_LENGTH(nhs_number) != 10)"; <add> ResultSet rs = patientSearchStatement.executeQuery(sql); <add> <add> while (rs.next()) { <add> String patientId = rs.getString(1); <add> String nhsNumber = rs.getString(2); <add> <add> //find matched person ID <add> String personIdSql = "SELECT person_id FROM patient_link WHERE patient_id = '" + patientId + "'"; <add> Statement s = patientSearchConnection.createStatement(); <add> ResultSet rsPersonId = s.executeQuery(personIdSql); <add> String personId = null; <add> if (rsPersonId.next()) { <add> personId = rsPersonId.getString(1); <add> } <add> rsPersonId.close(); <add> s.close(); <add> if (Strings.isNullOrEmpty(personId)) { <add> LOG.error("Patient " + patientId + " has no person ID"); <add> continue; <add> } <add> <add> //see whether person ID used NHS number to match <add> String patientLinkSql = "SELECT nhs_number FROM patient_link_person WHERE person_id = '" + personId + "'"; <add> s = patientSearchConnection.createStatement(); <add> ResultSet rsPatientLink = s.executeQuery(patientLinkSql); <add> String matchingNhsNumber = null; <add> if (rsPatientLink.next()) { <add> matchingNhsNumber = rsPatientLink.getString(1); <add> } <add> rsPatientLink.close(); <add> s.close(); <add> <add> //if patient link person has a record for this nhs number, update the person link <add> if (!Strings.isNullOrEmpty(matchingNhsNumber)) { <add> String newPersonId = UUID.randomUUID().toString(); <add> <add> SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); <add> String createdAtStr = sdf.format(new Date()); <add> <add> <add> s = patientSearchConnection.createStatement(); <add> <add> //new record in patient link history <add> String patientHistorySql = "INSERT INTO patient_link_history VALUES ('" + patientId + "', '" + service.getId() + "', '" + createdAtStr + "', '" + newPersonId + "', '" + personId + "')"; <add> //LOG.debug(patientHistorySql); <add> s.execute(patientHistorySql); <add> <add> //update patient link <add> String patientLinkUpdateSql = "UPDATE patient_link SET person_id = '" + newPersonId + "' WHERE patient_id = '" + patientId + "'"; <add> s.execute(patientLinkUpdateSql); <add> <add> patientSearchConnection.commit(); <add> s.close(); <add> <add> fixedPersons ++; <add> } <add> <add> //if patient search has an invalid NHS number, update it <add> if (!Strings.isNullOrEmpty(nhsNumber)) { <add> ResourceDalI resourceDal = DalProvider.factoryResourceDal(); <add> Patient patient = (Patient)resourceDal.getCurrentVersionAsResource(service.getId(), ResourceType.Patient, patientId); <add> <add> PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); <add> patientSearchDal.update(service.getId(), patient); <add> <add> fixedSearches ++; <add> } <add> <add> checked ++; <add> if (checked % 50 == 0) { <add> LOG.info("Checked " + checked + ", FixedPersons = " + fixedPersons + ", FixedSearches = " + fixedSearches); <add> } <add> } <add> <add> LOG.info("Checked " + checked + ", FixedPersons = " + fixedPersons + ", FixedSearches = " + fixedSearches); <add> <add> rs.close(); <add> } <add> <add> patientSearchStatement.close(); <add> entityManager.close(); <add> <add> LOG.info("Finished fixing persons with no NHS number"); <add> } catch (Throwable t) { <add> LOG.error("", t); <add> } <ide> } <ide> <ide> private static void checkDeletedObs(UUID serviceId, UUID systemId) { <ide> } <ide> } <ide> <del> private static void fixSubscriberDbs() { <add> /*private static void fixSubscriberDbs() { <ide> LOG.info("Fixing Subscriber DBs"); <ide> <ide> try { <ide> } catch (Throwable t) { <ide> LOG.error("", t); <ide> } <del> } <add> }*/ <ide> <ide> /*private static void fixReferralRequests() { <ide> LOG.info("Fixing Referral Requests"); <ide> } <ide> } <ide> <del> private static void postToInboundFromFile(UUID serviceId, UUID systemId, String filePath) { <add> /*private static void postToInboundFromFile(UUID serviceId, UUID systemId, String filePath) { <ide> <ide> try { <ide> <ide> } <ide> <ide> LOG.info("Finished Posting to inbound for " + serviceId); <del> } <add> }*/ <ide> <ide> /*private static void postToInbound(UUID serviceId, boolean all) { <ide> LOG.info("Posting to inbound for " + serviceId);
Java
apache-2.0
3287672c23e5f7ae45d2f8d034b4c17d69f9e56e
0
sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.solvers.cvc5; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import io.github.cvc5.api.CVC5ApiException; import io.github.cvc5.api.Kind; import io.github.cvc5.api.Solver; import io.github.cvc5.api.Sort; import io.github.cvc5.api.Term; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.ArrayFormula; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.FloatingPointFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType; import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType; import org.sosy_lab.java_smt.api.FunctionDeclarationKind; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; import org.sosy_lab.java_smt.api.RegexFormula; import org.sosy_lab.java_smt.api.StringFormula; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; import org.sosy_lab.java_smt.basicimpl.FormulaCreator; import org.sosy_lab.java_smt.basicimpl.FunctionDeclarationImpl; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5ArrayFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5BitvectorFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5BooleanFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5FloatingPointFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5FloatingPointRoundingModeFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5IntegerFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5RationalFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5RegexFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5StringFormula; public class CVC5FormulaCreator extends FormulaCreator<Term, Sort, Solver, Term> { private static final Pattern FLOATING_POINT_PATTERN = Pattern.compile("^\\(fp #b(?<sign>\\d) #b(?<exp>\\d+) #b(?<mant>\\d+)$"); private final Map<String, Term> variablesCache = new HashMap<>(); private final Map<String, Term> functionsCache = new HashMap<>(); private final Solver solver; protected CVC5FormulaCreator(Solver pSolver) { super( pSolver, pSolver.getBooleanSort(), pSolver.getIntegerSort(), pSolver.getRealSort(), pSolver.getStringSort(), pSolver.getRegExpSort()); solver = pSolver; } @Override public Term makeVariable(Sort sort, String name) { Term exp = variablesCache.computeIfAbsent(name, n -> solver.mkConst(sort, name)); Preconditions.checkArgument( sort.equals(exp.getSort()), "symbol name already in use for different Type %s", exp.getSort()); return exp; } /** * Makes a bound copy of a variable for use in quantifier. Note that all occurrences of the free * var have to be substituted by the bound once it exists. * * @param var Variable you want a bound copy of. * @return Bound Variable */ public Term makeBoundCopy(Term var) { Sort sort = var.getSort(); String name = getName(var); Term boundCopy = solver.mkVar(sort, name); return boundCopy; } @Override public Sort getBitvectorType(int pBitwidth) { try { return solver.mkBitVectorSort(pBitwidth); } catch (CVC5ApiException e) { throw new IllegalArgumentException( "You tried creating a invalid bitvector sort with size " + pBitwidth + ".", e); } } @Override public Sort getFloatingPointType(FloatingPointType pType) { try { // plus sign bit return solver.mkFloatingPointSort(pType.getExponentSize(), pType.getMantissaSize() + 1); } catch (CVC5ApiException e) { throw new IllegalArgumentException( "You tried creating a invalid floatingpoint sort with exponent size " + pType.getExponentSize() + " and mantissa " + pType.getMantissaSize() + ".", e); } } @Override public Sort getArrayType(Sort pIndexType, Sort pElementType) { return solver.mkArraySort(pIndexType, pElementType); } @Override public Term extractInfo(Formula pT) { return CVC5FormulaManager.getCVC5Term(pT); } @Override @SuppressWarnings("MethodTypeParameterName") protected <TD extends Formula, TR extends Formula> FormulaType<TR> getArrayFormulaElementType( ArrayFormula<TD, TR> pArray) { return ((CVC5ArrayFormula<TD, TR>) pArray).getElementType(); } @Override @SuppressWarnings("MethodTypeParameterName") protected <TD extends Formula, TR extends Formula> FormulaType<TD> getArrayFormulaIndexType( ArrayFormula<TD, TR> pArray) { return ((CVC5ArrayFormula<TD, TR>) pArray).getIndexType(); } @SuppressWarnings("unchecked") @Override public <T extends Formula> FormulaType<T> getFormulaType(T pFormula) { Sort cvc5sort = extractInfo(pFormula).getSort(); if (pFormula instanceof BitvectorFormula) { checkArgument( cvc5sort.isBitVector(), "BitvectorFormula with actual Type %s: %s", cvc5sort, pFormula); return (FormulaType<T>) getFormulaType(extractInfo(pFormula)); } else if (pFormula instanceof FloatingPointFormula) { checkArgument( cvc5sort.isFloatingPoint(), "FloatingPointFormula with actual Type %s: %s", cvc5sort, pFormula); return (FormulaType<T>) FormulaType.getFloatingPointType( cvc5sort.getFloatingPointExponentSize(), cvc5sort.getFloatingPointSignificandSize() - 1); // TODO: check for sign bit } else if (pFormula instanceof ArrayFormula<?, ?>) { FormulaType<T> arrayIndexType = getArrayFormulaIndexType((ArrayFormula<T, T>) pFormula); FormulaType<T> arrayElementType = getArrayFormulaElementType((ArrayFormula<T, T>) pFormula); return (FormulaType<T>) FormulaType.getArrayType(arrayIndexType, arrayElementType); } return super.getFormulaType(pFormula); } @Override public FormulaType<?> getFormulaType(Term pFormula) { return getFormulaTypeFromTermType(pFormula.getSort()); } private FormulaType<?> getFormulaTypeFromTermType(Sort sort) { if (sort.isBoolean()) { return FormulaType.BooleanType; } else if (sort.isInteger()) { return FormulaType.IntegerType; } else if (sort.isBitVector()) { return FormulaType.getBitvectorTypeWithSize(sort.getBitVectorSize()); } else if (sort.isFloatingPoint()) { return FormulaType.getFloatingPointType( sort.getFloatingPointExponentSize(), sort.getFloatingPointSignificandSize() - 1); // TODO: check for sign bit } else if (sort.isRoundingMode()) { return FormulaType.FloatingPointRoundingModeType; } else if (sort.isReal()) { // The theory REAL in CVC5 is the theory of (infinite precision!) real numbers. // As such, the theory RATIONAL is contained in REAL. TODO: find a better solution. return FormulaType.RationalType; } else if (sort.isArray()) { FormulaType<?> indexType = getFormulaTypeFromTermType(sort.getArrayIndexSort()); FormulaType<?> elementType = getFormulaTypeFromTermType(sort.getArrayElementSort()); return FormulaType.getArrayType(indexType, elementType); } else if (sort.isString()) { return FormulaType.StringType; } else if (sort.isRegExp()) { return FormulaType.RegexType; } else { throw new AssertionError(String.format("Encountered unhandled Type '%s'.", sort)); } } @SuppressWarnings("unchecked") @Override public <T extends Formula> T encapsulate(FormulaType<T> pType, Term pTerm) { assert pType.equals(getFormulaType(pTerm)) || (pType.equals(FormulaType.RationalType) && getFormulaType(pTerm).equals(FormulaType.IntegerType)) : String.format( "Trying to encapsulate formula %s of Type %s as %s", pTerm, getFormulaType(pTerm), pType); if (pType.isBooleanType()) { return (T) new CVC5BooleanFormula(pTerm); } else if (pType.isIntegerType()) { return (T) new CVC5IntegerFormula(pTerm); } else if (pType.isRationalType()) { return (T) new CVC5RationalFormula(pTerm); } else if (pType.isArrayType()) { ArrayFormulaType<?, ?> arrFt = (ArrayFormulaType<?, ?>) pType; return (T) new CVC5ArrayFormula<>(pTerm, arrFt.getIndexType(), arrFt.getElementType()); } else if (pType.isBitvectorType()) { return (T) new CVC5BitvectorFormula(pTerm); } else if (pType.isFloatingPointType()) { return (T) new CVC5FloatingPointFormula(pTerm); } else if (pType.isFloatingPointRoundingModeType()) { return (T) new CVC5FloatingPointRoundingModeFormula(pTerm); } else if (pType.isStringType()) { return (T) new CVC5StringFormula(pTerm); } else if (pType.isRegexType()) { return (T) new CVC5RegexFormula(pTerm); } throw new IllegalArgumentException("Cannot create formulas of Type " + pType + " in CVC5"); } private Formula encapsulate(Term pTerm) { return encapsulate(getFormulaType(pTerm), pTerm); } @Override public BooleanFormula encapsulateBoolean(Term pTerm) { assert getFormulaType(pTerm).isBooleanType() : String.format( "%s is not boolean, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5BooleanFormula(pTerm); } @Override public BitvectorFormula encapsulateBitvector(Term pTerm) { assert getFormulaType(pTerm).isBitvectorType() : String.format("%s is no BV, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5BitvectorFormula(pTerm); } @Override protected FloatingPointFormula encapsulateFloatingPoint(Term pTerm) { assert getFormulaType(pTerm).isFloatingPointType() : String.format("%s is no FP, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5FloatingPointFormula(pTerm); } @Override @SuppressWarnings("MethodTypeParameterName") protected <TI extends Formula, TE extends Formula> ArrayFormula<TI, TE> encapsulateArray( Term pTerm, FormulaType<TI> pIndexType, FormulaType<TE> pElementType) { assert getFormulaType(pTerm).equals(FormulaType.getArrayType(pIndexType, pElementType)) : String.format( "%s is no array, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5ArrayFormula<>(pTerm, pIndexType, pElementType); } @Override protected StringFormula encapsulateString(Term pTerm) { assert getFormulaType(pTerm).isStringType() : String.format( "%s is no String, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5StringFormula(pTerm); } @Override protected RegexFormula encapsulateRegex(Term pTerm) { assert getFormulaType(pTerm).isRegexType(); return new CVC5RegexFormula(pTerm); } private static String getName(Term e) { checkState(!e.isNull()); /* TODO: this will fail most likely if (!e.isConst() && !e.isVariable()) { e = e.getOperator(); }*/ return dequote(e.toString()); } /** Variable names can be wrapped with "|". This function removes those chars. */ private static String dequote(String s) { int l = s.length(); if (s.charAt(0) == '|' && s.charAt(l - 1) == '|') { return s.substring(1, l - 1); } return s; } @Override public <R> R visit(FormulaVisitor<R> visitor, Formula formula, final Term f) { checkState(!f.isNull()); Sort sort = f.getSort(); try { if (f.getKind() == Kind.CONSTANT) { if (sort.isBoolean()) { return visitor.visitConstant(formula, solver.getValue(f)); } else if (sort.isReal()) { return visitor.visitConstant(formula, solver.getValue(f)); } else if (sort.isInteger()) { return visitor.visitConstant(formula, solver.getValue(f)); } else if (sort.isBitVector()) { return visitor.visitConstant(formula, solver.getValue(f)); } else if (sort.isFloatingPoint()) { return visitor.visitConstant(formula, solver.getValue(f)); } else if (sort.isString()) { return visitor.visitConstant(formula, solver.getValue(f)); } else { throw new UnsupportedOperationException("Unhandled constant " + f + " with Type " + sort); } } else if (f.getKind() == Kind.VARIABLE) { // Bound and unbound vars are the same in CVC5! // BOUND vars are used for all vars that are bound to a quantifier in CVC5. // We resubstitute them back to the original free. // CVC5 doesn't give you the de-brujin index Term originalVar = variablesCache.get(formula.toString()); return visitor.visitBoundVariable(encapsulate(originalVar), 0); } else if (f.getKind() == Kind.FORALL || f.getKind() == Kind.EXISTS) { // QUANTIFIER: replace bound variable with free variable for visitation assert f.getNumChildren() == 2; Term body = f.getChild(1); List<Formula> freeVars = new ArrayList<>(); for (Term boundVar : f.getChild(0)) { // unpack grand-children of f. String name = getName(boundVar); Term freeVar = Preconditions.checkNotNull(variablesCache.get(name)); body = body.substitute(boundVar, freeVar); freeVars.add(encapsulate(freeVar)); } BooleanFormula fBody = encapsulateBoolean(body); Quantifier quant = f.getKind() == Kind.EXISTS ? Quantifier.EXISTS : Quantifier.FORALL; return visitor.visitQuantifier((BooleanFormula) formula, quant, freeVars, fBody); } else if (f.getKind() == Kind.VARIABLE) { // TODO: This is kinda pointless, rework return visitor.visitFreeVariable(formula, getName(f)); } else { // Termessions like uninterpreted function calls (Kind.APPLY_UF) or operators (e.g. // Kind.AND). // These are all treated like operators, so we can get the declaration by f.getOperator()! List<Formula> args = ImmutableList.copyOf(Iterables.transform(f, this::encapsulate)); List<FormulaType<?>> argsTypes = new ArrayList<>(); // Term operator = normalize(f.getSort()); Kind kind = f.getKind(); if (sort.isFunction() || kind == Kind.APPLY_UF) { // The arguments are all children except the first one for (int i = 1; i < f.getNumChildren() - 1; i++) { argsTypes.add(getFormulaTypeFromTermType(f.getChild(i).getSort())); } } else { for (Term arg : f) { argsTypes.add(getFormulaType(arg)); } } checkState(args.size() == argsTypes.size()); // TODO some operations (BV_SIGN_EXTEND, BV_ZERO_EXTEND, maybe more) encode information as // part of the operator itself, thus the arity is one too small and there might be no // possibility to access the information from user side. Should we encode such information // as additional parameters? We do so for some methods of Princess. return visitor.visitFunction( formula, args, FunctionDeclarationImpl.of( getName(f), getDeclarationKind(f), argsTypes, getFormulaType(f), f.getChild(0))); } } catch (CVC5ApiException e) { throw new IllegalArgumentException("Failure visiting the Term " + f + ".", e); } } /** CVC5 returns new objects when querying operators for UFs. */ @SuppressWarnings("unused") private Term normalize(Term operator) { Term function = functionsCache.get(getName(operator)); if (function != null) { checkState( Long.compare(function.getId(), operator.getId()) == 0, "operator '%s' with ID %s differs from existing function '%s' with ID '%s'.", operator, operator.getId(), function, function.getId()); return function; } return operator; } // see src/theory/*/kinds in CVC5 sources for description of the different CVC5 kinds ;) private static final ImmutableMap<Kind, FunctionDeclarationKind> KIND_MAPPING = ImmutableMap.<Kind, FunctionDeclarationKind>builder() .put(Kind.EQUAL, FunctionDeclarationKind.EQ) .put(Kind.DISTINCT, FunctionDeclarationKind.DISTINCT) .put(Kind.NOT, FunctionDeclarationKind.NOT) .put(Kind.AND, FunctionDeclarationKind.AND) .put(Kind.IMPLIES, FunctionDeclarationKind.IMPLIES) .put(Kind.OR, FunctionDeclarationKind.OR) .put(Kind.XOR, FunctionDeclarationKind.XOR) .put(Kind.ITE, FunctionDeclarationKind.ITE) .put(Kind.APPLY_UF, FunctionDeclarationKind.UF) .put(Kind.PLUS, FunctionDeclarationKind.ADD) .put(Kind.MULT, FunctionDeclarationKind.MUL) .put(Kind.MINUS, FunctionDeclarationKind.SUB) .put(Kind.DIVISION, FunctionDeclarationKind.DIV) .put(Kind.LT, FunctionDeclarationKind.LT) .put(Kind.LEQ, FunctionDeclarationKind.LTE) .put(Kind.GT, FunctionDeclarationKind.GT) .put(Kind.GEQ, FunctionDeclarationKind.GTE) // Bitvector theory .put(Kind.BITVECTOR_ADD, FunctionDeclarationKind.BV_ADD) .put(Kind.BITVECTOR_SUB, FunctionDeclarationKind.BV_SUB) .put(Kind.BITVECTOR_MULT, FunctionDeclarationKind.BV_MUL) .put(Kind.BITVECTOR_AND, FunctionDeclarationKind.BV_AND) .put(Kind.BITVECTOR_OR, FunctionDeclarationKind.BV_OR) .put(Kind.BITVECTOR_XOR, FunctionDeclarationKind.BV_XOR) .put(Kind.BITVECTOR_SLT, FunctionDeclarationKind.BV_SLT) .put(Kind.BITVECTOR_ULT, FunctionDeclarationKind.BV_ULT) .put(Kind.BITVECTOR_SLE, FunctionDeclarationKind.BV_SLE) .put(Kind.BITVECTOR_ULE, FunctionDeclarationKind.BV_ULE) .put(Kind.BITVECTOR_SGT, FunctionDeclarationKind.BV_SGT) .put(Kind.BITVECTOR_UGT, FunctionDeclarationKind.BV_UGT) .put(Kind.BITVECTOR_SGE, FunctionDeclarationKind.BV_SGE) .put(Kind.BITVECTOR_UGE, FunctionDeclarationKind.BV_UGE) .put(Kind.BITVECTOR_SDIV, FunctionDeclarationKind.BV_SDIV) .put(Kind.BITVECTOR_UDIV, FunctionDeclarationKind.BV_UDIV) .put(Kind.BITVECTOR_SREM, FunctionDeclarationKind.BV_SREM) // TODO: find out where Kind.BITVECTOR_SMOD fits in here .put(Kind.BITVECTOR_UREM, FunctionDeclarationKind.BV_UREM) .put(Kind.BITVECTOR_NOT, FunctionDeclarationKind.BV_NOT) .put(Kind.BITVECTOR_NEG, FunctionDeclarationKind.BV_NEG) .put(Kind.BITVECTOR_EXTRACT, FunctionDeclarationKind.BV_EXTRACT) .put(Kind.BITVECTOR_CONCAT, FunctionDeclarationKind.BV_CONCAT) .put(Kind.BITVECTOR_SIGN_EXTEND, FunctionDeclarationKind.BV_SIGN_EXTENSION) .put(Kind.BITVECTOR_ZERO_EXTEND, FunctionDeclarationKind.BV_ZERO_EXTENSION) // Floating-point theory .put(Kind.TO_INTEGER, FunctionDeclarationKind.FLOOR) .put(Kind.FLOATINGPOINT_TO_SBV, FunctionDeclarationKind.FP_CASTTO_SBV) .put(Kind.FLOATINGPOINT_TO_UBV, FunctionDeclarationKind.FP_CASTTO_UBV) .put(Kind.FLOATINGPOINT_TO_FP_FLOATINGPOINT, FunctionDeclarationKind.FP_CASTTO_FP) .put(Kind.FLOATINGPOINT_TO_FP_SIGNED_BITVECTOR, FunctionDeclarationKind.BV_SCASTTO_FP) .put(Kind.FLOATINGPOINT_TO_FP_UNSIGNED_BITVECTOR, FunctionDeclarationKind.BV_UCASTTO_FP) .put(Kind.FLOATINGPOINT_ISNAN, FunctionDeclarationKind.FP_IS_NAN) .put(Kind.FLOATINGPOINT_ISNEG, FunctionDeclarationKind.FP_IS_NEGATIVE) .put(Kind.FLOATINGPOINT_ISINF, FunctionDeclarationKind.FP_IS_INF) .put(Kind.FLOATINGPOINT_ISN, FunctionDeclarationKind.FP_IS_NORMAL) .put(Kind.FLOATINGPOINT_ISSN, FunctionDeclarationKind.FP_IS_SUBNORMAL) .put(Kind.FLOATINGPOINT_ISZ, FunctionDeclarationKind.FP_IS_ZERO) .put(Kind.FLOATINGPOINT_EQ, FunctionDeclarationKind.FP_EQ) .put(Kind.FLOATINGPOINT_ABS, FunctionDeclarationKind.FP_ABS) .put(Kind.FLOATINGPOINT_MAX, FunctionDeclarationKind.FP_MAX) .put(Kind.FLOATINGPOINT_MIN, FunctionDeclarationKind.FP_MIN) .put(Kind.FLOATINGPOINT_SQRT, FunctionDeclarationKind.FP_SQRT) .put(Kind.FLOATINGPOINT_ADD, FunctionDeclarationKind.FP_ADD) .put(Kind.FLOATINGPOINT_SUB, FunctionDeclarationKind.FP_SUB) .put(Kind.FLOATINGPOINT_MULT, FunctionDeclarationKind.FP_MUL) .put(Kind.FLOATINGPOINT_DIV, FunctionDeclarationKind.FP_DIV) .put(Kind.FLOATINGPOINT_LT, FunctionDeclarationKind.FP_LT) .put(Kind.FLOATINGPOINT_LEQ, FunctionDeclarationKind.FP_LE) .put(Kind.FLOATINGPOINT_GT, FunctionDeclarationKind.FP_GT) .put(Kind.FLOATINGPOINT_GEQ, FunctionDeclarationKind.FP_GE) .put(Kind.FLOATINGPOINT_RTI, FunctionDeclarationKind.FP_ROUND_TO_INTEGRAL) .put(Kind.FLOATINGPOINT_TO_FP_IEEE_BITVECTOR, FunctionDeclarationKind.FP_AS_IEEEBV) // String and Regex theory .put(Kind.STRING_CONCAT, FunctionDeclarationKind.STR_CONCAT) .put(Kind.STRING_PREFIX, FunctionDeclarationKind.STR_PREFIX) .put(Kind.STRING_SUFFIX, FunctionDeclarationKind.STR_SUFFIX) .put(Kind.STRING_CONTAINS, FunctionDeclarationKind.STR_CONTAINS) .put(Kind.STRING_SUBSTR, FunctionDeclarationKind.STR_SUBSTRING) .put(Kind.STRING_REPLACE, FunctionDeclarationKind.STR_REPLACE) .put(Kind.STRING_REPLACE_ALL, FunctionDeclarationKind.STR_REPLACE_ALL) .put(Kind.STRING_CHARAT, FunctionDeclarationKind.STR_CHAR_AT) .put(Kind.STRING_LENGTH, FunctionDeclarationKind.STR_LENGTH) .put(Kind.STRING_INDEXOF, FunctionDeclarationKind.STR_INDEX_OF) .put(Kind.STRING_TO_REGEXP, FunctionDeclarationKind.STR_TO_RE) .put(Kind.STRING_IN_REGEXP, FunctionDeclarationKind.STR_IN_RE) .put(Kind.STRING_FROM_INT, FunctionDeclarationKind.INT_TO_STR) .put(Kind.STRING_TO_INT, FunctionDeclarationKind.STR_TO_INT) .put(Kind.STRING_LT, FunctionDeclarationKind.STR_LT) .put(Kind.STRING_LEQ, FunctionDeclarationKind.STR_LE) .put(Kind.REGEXP_PLUS, FunctionDeclarationKind.RE_PLUS) .put(Kind.REGEXP_STAR, FunctionDeclarationKind.RE_STAR) .put(Kind.REGEXP_OPT, FunctionDeclarationKind.RE_OPTIONAL) .put(Kind.REGEXP_CONCAT, FunctionDeclarationKind.RE_CONCAT) .put(Kind.REGEXP_UNION, FunctionDeclarationKind.RE_UNION) .put(Kind.REGEXP_RANGE, FunctionDeclarationKind.RE_RANGE) .put(Kind.REGEXP_INTER, FunctionDeclarationKind.RE_INTERSECT) .put(Kind.REGEXP_COMPLEMENT, FunctionDeclarationKind.RE_COMPLEMENT) .put(Kind.REGEXP_DIFF, FunctionDeclarationKind.RE_DIFFERENCE) .build(); @SuppressWarnings("unused") private FunctionDeclarationKind getDeclarationKind(Term f) { try { Kind kind = f.getKind(); // special case: IFF for Boolean, EQ for all other Types if (kind == Kind.EQUAL && Iterables.all(f, child -> child.getSort().isBoolean())) { return FunctionDeclarationKind.IFF; } return KIND_MAPPING.getOrDefault(kind, FunctionDeclarationKind.OTHER); } catch (CVC5ApiException e) { throw new IllegalArgumentException("Failure trying to get the KIND of Term " + f + ".", e); } } @Override protected Term getBooleanVarDeclarationImpl(Term pTFormulaInfo) { try { Kind kind = pTFormulaInfo.getKind(); assert kind == Kind.APPLY_UF || kind == Kind.VARIABLE : pTFormulaInfo.getKind(); if (kind == Kind.APPLY_UF) { // TODO: Test this, this is the old internal implementation return pTFormulaInfo.getChild(0); // old // return pTFormulaInfo.getOperator(); } else { return pTFormulaInfo; } } catch (CVC5ApiException e) { throw new IllegalArgumentException( "You tried reading a bool variable potentially in a UF application that failed. Checked term: " + pTFormulaInfo + ".", e); } } @Override public Term callFunctionImpl(Term pDeclaration, List<Term> pArgs) { if (pArgs.isEmpty()) { // CVC5 does not allow argumentless functions! throw new IllegalArgumentException( "You tried calling a UF with no arguments. CVC5 does not allow this."); } else { // Applying UFs in CVC5 works with an array of Terms with the UF being the first argument // If you pull the children out of it the order will be the same! Term[] args = Stream.of(new Term[] {pDeclaration}, (Term[]) pArgs.toArray()) .flatMap(Stream::of) .toArray(Term[]::new); return solver.mkTerm(Kind.APPLY_UF, args); } } @Override public Term declareUFImpl(String pName, Sort pReturnType, List<Sort> pArgTypes) { if (pArgTypes.isEmpty()) { // Ufs in CVC5 can't have 0 arity. I tried an empty array and nullsort. throw new IllegalArgumentException( "You tried creating a UF with no arguments. CVC5 does not allow this."); } Term exp = functionsCache.get(pName); if (exp == null) { Sort[] argSorts = pArgTypes.toArray(new Sort[0]); // array of argument types and the return type Sort ufToReturnType = solver.mkFunctionSort(argSorts, pReturnType); exp = solver.mkConst(ufToReturnType, pName); functionsCache.put(pName, exp); } return exp; } @Override public Object convertValue(Term expForType, Term value) { // Make sure that final Sort type = expForType.getSort(); final Sort valueType = value.getSort(); // Variables are Kind.CONSTANT and can't be check with isIntegerValue() or getIntegerValue() // etc. but only with solver.getValue() and its String serialization try { if (value.getKind() == Kind.VARIABLE) { // CVC5 does not allow model values for bound vars; just return the name return value.toString(); } else if (valueType.isInteger() && type.isInteger()) { return new BigInteger(solver.getValue(value).toString()); } else if (valueType.isReal() && type.isReal()) { Rational rat = Rational.ofString(solver.getValue(value).toString()); return org.sosy_lab.common.rationals.Rational.of( new BigInteger(rat.getNum().toString()), new BigInteger(rat.getDen().toString())); } else if (valueType.isBitVector()) { return new BigInteger(solver.getValue(value).toString()); } else if (valueType.isFloatingPoint()) { return parseFloatingPoint(value); } else { // String serialization for Strings, booleans and unknown terms. return solver.getValue(value).toString(); } } catch (CVC5ApiException e) { throw new IllegalArgumentException( "Failure trying to convert CVC5 " + valueType + " variable into a " + type + " value.", e); } } @SuppressWarnings("unused") private Object parseFloatingPoint(Term fpTerm) { Matcher matcher = FLOATING_POINT_PATTERN.matcher(fpTerm.toString()); if (!matcher.matches()) { throw new NumberFormatException("Unknown floating-point format: " + fpTerm); } /* // First is exponent, second is mantissa, third if bitvec value of the fp Triplet<Long, Long, Term> fpTriplet = fpTerm.getFloatingPointValue(); long expWidth = fpTriplet.first; long mantWidth = fpTriplet.second - 1; // without sign bit assert matcher.group("sign").length() == 1; assert matcher.group("exp").length() == expWidth; assert matcher.group("mant").length() == mantWidth; String str = matcher.group("sign") + matcher.group("exp") + matcher.group("mant"); if (expWidth == 11 && mantWidth == 52) { return Double.longBitsToDouble(UnsignedLong.valueOf(str, 2).longValue()); } else if (expWidth == 8 && mantWidth == 23) { return Float.intBitsToFloat(UnsignedInteger.valueOf(str, 2).intValue()); } */ // TODO to be fully correct, we would need to interpret this string // it may be interpreted with i.e. FLOATINGPOINT_TO_REAL return solver.getValue(fpTerm).toString(); } }
src/org/sosy_lab/java_smt/solvers/cvc5/CVC5FormulaCreator.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.solvers.cvc5; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import io.github.cvc5.api.CVC5ApiException; import io.github.cvc5.api.Kind; import io.github.cvc5.api.Solver; import io.github.cvc5.api.Sort; import io.github.cvc5.api.Term; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.ArrayFormula; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.FloatingPointFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType; import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType; import org.sosy_lab.java_smt.api.FunctionDeclarationKind; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; import org.sosy_lab.java_smt.api.RegexFormula; import org.sosy_lab.java_smt.api.StringFormula; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; import org.sosy_lab.java_smt.basicimpl.FormulaCreator; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5ArrayFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5BitvectorFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5BooleanFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5FloatingPointFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5FloatingPointRoundingModeFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5IntegerFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5RationalFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5RegexFormula; import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5StringFormula; public class CVC5FormulaCreator extends FormulaCreator<Term, Sort, Solver, Term> { private static final Pattern FLOATING_POINT_PATTERN = Pattern.compile("^\\(fp #b(?<sign>\\d) #b(?<exp>\\d+) #b(?<mant>\\d+)$"); private final Map<String, Term> variablesCache = new HashMap<>(); private final Map<String, Term> functionsCache = new HashMap<>(); private final Solver solver; protected CVC5FormulaCreator(Solver pSolver) { super( pSolver, pSolver.getBooleanSort(), pSolver.getIntegerSort(), pSolver.getRealSort(), pSolver.getStringSort(), pSolver.getRegExpSort()); solver = pSolver; } @Override public Term makeVariable(Sort sort, String name) { Term exp = variablesCache.computeIfAbsent(name, n -> solver.mkConst(sort, name)); Preconditions.checkArgument( sort.equals(exp.getSort()), "symbol name already in use for different Type %s", exp.getSort()); return exp; } /** * Makes a bound copy of a variable for use in quantifier. Note that all occurrences of the free * var have to be substituted by the bound once it exists. * * @param var Variable you want a bound copy of. * @return Bound Variable */ public Term makeBoundCopy(Term var) { Sort sort = var.getSort(); String name = getName(var); Term boundCopy = solver.mkVar(sort, name); return boundCopy; } @Override public Sort getBitvectorType(int pBitwidth) { try { return solver.mkBitVectorSort(pBitwidth); } catch (CVC5ApiException e) { throw new IllegalArgumentException( "You tried creating a invalid bitvector sort with size " + pBitwidth + ".", e); } } @Override public Sort getFloatingPointType(FloatingPointType pType) { try { // plus sign bit return solver.mkFloatingPointSort(pType.getExponentSize(), pType.getMantissaSize() + 1); } catch (CVC5ApiException e) { throw new IllegalArgumentException( "You tried creating a invalid floatingpoint sort with exponent size " + pType.getExponentSize() + " and mantissa " + pType.getMantissaSize() + ".", e); } } @Override public Sort getArrayType(Sort pIndexType, Sort pElementType) { return solver.mkArraySort(pIndexType, pElementType); } @Override public Term extractInfo(Formula pT) { return CVC5FormulaManager.getCVC5Term(pT); } @Override @SuppressWarnings("MethodTypeParameterName") protected <TD extends Formula, TR extends Formula> FormulaType<TR> getArrayFormulaElementType( ArrayFormula<TD, TR> pArray) { return ((CVC5ArrayFormula<TD, TR>) pArray).getElementType(); } @Override @SuppressWarnings("MethodTypeParameterName") protected <TD extends Formula, TR extends Formula> FormulaType<TD> getArrayFormulaIndexType( ArrayFormula<TD, TR> pArray) { return ((CVC5ArrayFormula<TD, TR>) pArray).getIndexType(); } @SuppressWarnings("unchecked") @Override public <T extends Formula> FormulaType<T> getFormulaType(T pFormula) { Sort cvc5sort = extractInfo(pFormula).getSort(); if (pFormula instanceof BitvectorFormula) { checkArgument( cvc5sort.isBitVector(), "BitvectorFormula with actual Type %s: %s", cvc5sort, pFormula); return (FormulaType<T>) getFormulaType(extractInfo(pFormula)); } else if (pFormula instanceof FloatingPointFormula) { checkArgument( cvc5sort.isFloatingPoint(), "FloatingPointFormula with actual Type %s: %s", cvc5sort, pFormula); return (FormulaType<T>) FormulaType.getFloatingPointType( cvc5sort.getFloatingPointExponentSize(), cvc5sort.getFloatingPointSignificandSize() - 1); // TODO: check for sign bit } else if (pFormula instanceof ArrayFormula<?, ?>) { FormulaType<T> arrayIndexType = getArrayFormulaIndexType((ArrayFormula<T, T>) pFormula); FormulaType<T> arrayElementType = getArrayFormulaElementType((ArrayFormula<T, T>) pFormula); return (FormulaType<T>) FormulaType.getArrayType(arrayIndexType, arrayElementType); } return super.getFormulaType(pFormula); } @Override public FormulaType<?> getFormulaType(Term pFormula) { return getFormulaTypeFromTermType(pFormula.getSort()); } private FormulaType<?> getFormulaTypeFromTermType(Sort sort) { if (sort.isBoolean()) { return FormulaType.BooleanType; } else if (sort.isInteger()) { return FormulaType.IntegerType; } else if (sort.isBitVector()) { return FormulaType.getBitvectorTypeWithSize(sort.getBitVectorSize()); } else if (sort.isFloatingPoint()) { return FormulaType.getFloatingPointType( sort.getFloatingPointExponentSize(), sort.getFloatingPointSignificandSize() - 1); // TODO: check for sign bit } else if (sort.isRoundingMode()) { return FormulaType.FloatingPointRoundingModeType; } else if (sort.isReal()) { // The theory REAL in CVC5 is the theory of (infinite precision!) real numbers. // As such, the theory RATIONAL is contained in REAL. TODO: find a better solution. return FormulaType.RationalType; } else if (sort.isArray()) { FormulaType<?> indexType = getFormulaTypeFromTermType(sort.getArrayIndexSort()); FormulaType<?> elementType = getFormulaTypeFromTermType(sort.getArrayElementSort()); return FormulaType.getArrayType(indexType, elementType); } else if (sort.isString()) { return FormulaType.StringType; } else if (sort.isRegExp()) { return FormulaType.RegexType; } else { throw new AssertionError(String.format("Encountered unhandled Type '%s'.", sort)); } } @SuppressWarnings("unchecked") @Override public <T extends Formula> T encapsulate(FormulaType<T> pType, Term pTerm) { assert pType.equals(getFormulaType(pTerm)) || (pType.equals(FormulaType.RationalType) && getFormulaType(pTerm).equals(FormulaType.IntegerType)) : String.format( "Trying to encapsulate formula %s of Type %s as %s", pTerm, getFormulaType(pTerm), pType); if (pType.isBooleanType()) { return (T) new CVC5BooleanFormula(pTerm); } else if (pType.isIntegerType()) { return (T) new CVC5IntegerFormula(pTerm); } else if (pType.isRationalType()) { return (T) new CVC5RationalFormula(pTerm); } else if (pType.isArrayType()) { ArrayFormulaType<?, ?> arrFt = (ArrayFormulaType<?, ?>) pType; return (T) new CVC5ArrayFormula<>(pTerm, arrFt.getIndexType(), arrFt.getElementType()); } else if (pType.isBitvectorType()) { return (T) new CVC5BitvectorFormula(pTerm); } else if (pType.isFloatingPointType()) { return (T) new CVC5FloatingPointFormula(pTerm); } else if (pType.isFloatingPointRoundingModeType()) { return (T) new CVC5FloatingPointRoundingModeFormula(pTerm); } else if (pType.isStringType()) { return (T) new CVC5StringFormula(pTerm); } else if (pType.isRegexType()) { return (T) new CVC5RegexFormula(pTerm); } throw new IllegalArgumentException("Cannot create formulas of Type " + pType + " in CVC5"); } private Formula encapsulate(Term pTerm) { return encapsulate(getFormulaType(pTerm), pTerm); } @Override public BooleanFormula encapsulateBoolean(Term pTerm) { assert getFormulaType(pTerm).isBooleanType() : String.format( "%s is not boolean, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5BooleanFormula(pTerm); } @Override public BitvectorFormula encapsulateBitvector(Term pTerm) { assert getFormulaType(pTerm).isBitvectorType() : String.format("%s is no BV, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5BitvectorFormula(pTerm); } @Override protected FloatingPointFormula encapsulateFloatingPoint(Term pTerm) { assert getFormulaType(pTerm).isFloatingPointType() : String.format("%s is no FP, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5FloatingPointFormula(pTerm); } @Override @SuppressWarnings("MethodTypeParameterName") protected <TI extends Formula, TE extends Formula> ArrayFormula<TI, TE> encapsulateArray( Term pTerm, FormulaType<TI> pIndexType, FormulaType<TE> pElementType) { assert getFormulaType(pTerm).equals(FormulaType.getArrayType(pIndexType, pElementType)) : String.format( "%s is no array, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5ArrayFormula<>(pTerm, pIndexType, pElementType); } @Override protected StringFormula encapsulateString(Term pTerm) { assert getFormulaType(pTerm).isStringType() : String.format( "%s is no String, but %s (%s)", pTerm, pTerm.getSort(), getFormulaType(pTerm)); return new CVC5StringFormula(pTerm); } @Override protected RegexFormula encapsulateRegex(Term pTerm) { assert getFormulaType(pTerm).isRegexType(); return new CVC5RegexFormula(pTerm); } private static String getName(Term e) { checkState(!e.isNull()); /* TODO: this will fail most likely if (!e.isConst() && !e.isVariable()) { e = e.getOperator(); }*/ return dequote(e.toString()); } /** Variable names can be wrapped with "|". This function removes those chars. */ private static String dequote(String s) { int l = s.length(); if (s.charAt(0) == '|' && s.charAt(l - 1) == '|') { return s.substring(1, l - 1); } return s; } @Override public <R> R visit(FormulaVisitor<R> visitor, Formula formula, final Term f) { checkState(!f.isNull()); Sort sort = f.getSort(); try { if (f.getKind() == Kind.CONSTANT) { if (sort.isBoolean()) { return visitor.visitConstant(formula, f.getBooleanValue()); } else if (sort.isReal()) { return visitor.visitConstant(formula, f.getRealValue()); } else if (sort.isInteger()) { return visitor.visitConstant(formula, f.getIntegerValue()); } else if (sort.isBitVector()) { return visitor.visitConstant(formula, f.getBitVectorValue()); } else if (sort.isFloatingPoint()) { return visitor.visitConstant(formula, f.getFloatingPointValue()); } else if (sort.isRoundingMode()) { // TODO: this is most likely bullshit and WILL fail! return visitor.visitConstant(formula, solver.getRoundingModeSort()); } else if (sort.isString()) { return visitor.visitConstant(formula, f.getStringValue()); } else { throw new UnsupportedOperationException("Unhandled constant " + f + " with Type " + sort); } } else if (f.getKind() == Kind.VARIABLE) { // Bound and unbound vars are the same in CVC5! // BOUND vars are used for all vars that are bound to a quantifier in CVC5. // We resubstitute them back to the original free. // CVC5 doesn't give you the de-brujin index Term originalVar = variablesCache.get(formula.toString()); return visitor.visitBoundVariable(encapsulate(originalVar), 0); } else if (f.getKind() == Kind.FORALL || f.getKind() == Kind.EXISTS) { // QUANTIFIER: replace bound variable with free variable for visitation assert f.getNumChildren() == 2; Term body = f.getChild(1); List<Formula> freeVars = new ArrayList<>(); for (Term boundVar : f.getChild(0)) { // unpack grand-children of f. String name = getName(boundVar); Term freeVar = Preconditions.checkNotNull(variablesCache.get(name)); body = body.substitute(boundVar, freeVar); freeVars.add(encapsulate(freeVar)); } BooleanFormula fBody = encapsulateBoolean(body); Quantifier quant = f.getKind() == Kind.EXISTS ? Quantifier.EXISTS : Quantifier.FORALL; return visitor.visitQuantifier((BooleanFormula) formula, quant, freeVars, fBody); } else if (f.getKind() == Kind.VARIABLE) { // assert f.getKind() != Kind.BOUND_VARIABLE; return visitor.visitFreeVariable(formula, getName(f)); } else { // Termessions like uninterpreted function calls (Kind.APPLY_UF) or operators (e.g. // Kind.AND). // These are all treated like operators, so we can get the declaration by f.getOperator()! /* List<Formula> args = ImmutableList.copyOf(Iterables.transform(f, this::encapsulate)); List<FormulaType<?>> argsTypes = new ArrayList<>(); Term operator = normalize(f.getOperator()); if (operator.getSort().isFunction()) { vectorType argTypes = new FunctionType(operator.getSort()).getArgTypes(); for (int i = 0; i < argTypes.size(); i++) { argsTypes.add(getFormulaTypeFromTermType(argTypes.get(i))); } } else { for (Term arg : f) { argsTypes.add(getFormulaType(arg)); } } checkState(args.size() == argsTypes.size()); */ // TODO some operations (BV_SIGN_EXTEND, BV_ZERO_EXTEND, maybe more) encode information as // part of the operator itself, thus the arity is one too small and there might be no // possibility to access the information from user side. Should we encode such information // as // additional parameters? We do so for some methods of Princess. /* return visitor.visitFunction( formula, args, FunctionDeclarationImpl.of( getName(f), getDeclarationKind(f), argsTypes, getFormulaType(f), operator)); */ return null; } } catch (CVC5ApiException e) { throw new IllegalArgumentException("Failure visiting the Term " + f + ".", e); } } /** CVC5 returns new objects when querying operators for UFs. */ @SuppressWarnings("unused") private Term normalize(Term operator) { Term function = functionsCache.get(getName(operator)); if (function != null) { checkState( Long.compare(function.getId(), operator.getId()) == 0, "operator '%s' with ID %s differs from existing function '%s' with ID '%s'.", operator, operator.getId(), function, function.getId()); return function; } return operator; } // see src/theory/*/kinds in CVC5 sources for description of the different CVC5 kinds ;) private static final ImmutableMap<Kind, FunctionDeclarationKind> KIND_MAPPING = ImmutableMap.<Kind, FunctionDeclarationKind>builder() .put(Kind.EQUAL, FunctionDeclarationKind.EQ) .put(Kind.DISTINCT, FunctionDeclarationKind.DISTINCT) .put(Kind.NOT, FunctionDeclarationKind.NOT) .put(Kind.AND, FunctionDeclarationKind.AND) .put(Kind.IMPLIES, FunctionDeclarationKind.IMPLIES) .put(Kind.OR, FunctionDeclarationKind.OR) .put(Kind.XOR, FunctionDeclarationKind.XOR) .put(Kind.ITE, FunctionDeclarationKind.ITE) .put(Kind.APPLY_UF, FunctionDeclarationKind.UF) .put(Kind.PLUS, FunctionDeclarationKind.ADD) .put(Kind.MULT, FunctionDeclarationKind.MUL) .put(Kind.MINUS, FunctionDeclarationKind.SUB) .put(Kind.DIVISION, FunctionDeclarationKind.DIV) .put(Kind.LT, FunctionDeclarationKind.LT) .put(Kind.LEQ, FunctionDeclarationKind.LTE) .put(Kind.GT, FunctionDeclarationKind.GT) .put(Kind.GEQ, FunctionDeclarationKind.GTE) // Bitvector theory .put(Kind.PLUS, FunctionDeclarationKind.BV_ADD) .put(Kind.BITVECTOR_SUB, FunctionDeclarationKind.BV_SUB) .put(Kind.BITVECTOR_MULT, FunctionDeclarationKind.BV_MUL) .put(Kind.BITVECTOR_AND, FunctionDeclarationKind.BV_AND) .put(Kind.BITVECTOR_OR, FunctionDeclarationKind.BV_OR) .put(Kind.BITVECTOR_XOR, FunctionDeclarationKind.BV_XOR) .put(Kind.BITVECTOR_SLT, FunctionDeclarationKind.BV_SLT) .put(Kind.BITVECTOR_ULT, FunctionDeclarationKind.BV_ULT) .put(Kind.BITVECTOR_SLE, FunctionDeclarationKind.BV_SLE) .put(Kind.BITVECTOR_ULE, FunctionDeclarationKind.BV_ULE) .put(Kind.BITVECTOR_SGT, FunctionDeclarationKind.BV_SGT) .put(Kind.BITVECTOR_UGT, FunctionDeclarationKind.BV_UGT) .put(Kind.BITVECTOR_SGE, FunctionDeclarationKind.BV_SGE) .put(Kind.BITVECTOR_UGE, FunctionDeclarationKind.BV_UGE) .put(Kind.BITVECTOR_SDIV, FunctionDeclarationKind.BV_SDIV) .put(Kind.BITVECTOR_UDIV, FunctionDeclarationKind.BV_UDIV) .put(Kind.BITVECTOR_SREM, FunctionDeclarationKind.BV_SREM) // TODO: find out where Kind.BITVECTOR_SMOD fits in here .put(Kind.BITVECTOR_UREM, FunctionDeclarationKind.BV_UREM) .put(Kind.BITVECTOR_NOT, FunctionDeclarationKind.BV_NOT) .put(Kind.BITVECTOR_NEG, FunctionDeclarationKind.BV_NEG) .put(Kind.BITVECTOR_EXTRACT, FunctionDeclarationKind.BV_EXTRACT) .put(Kind.BITVECTOR_CONCAT, FunctionDeclarationKind.BV_CONCAT) .put(Kind.BITVECTOR_SIGN_EXTEND, FunctionDeclarationKind.BV_SIGN_EXTENSION) .put(Kind.BITVECTOR_ZERO_EXTEND, FunctionDeclarationKind.BV_ZERO_EXTENSION) // Floating-point theory .put(Kind.TO_INTEGER, FunctionDeclarationKind.FLOOR) .put(Kind.FLOATINGPOINT_TO_SBV, FunctionDeclarationKind.FP_CASTTO_SBV) .put(Kind.FLOATINGPOINT_TO_UBV, FunctionDeclarationKind.FP_CASTTO_UBV) .put(Kind.FLOATINGPOINT_TO_FP_FLOATINGPOINT, FunctionDeclarationKind.FP_CASTTO_FP) .put(Kind.FLOATINGPOINT_TO_FP_SIGNED_BITVECTOR, FunctionDeclarationKind.BV_SCASTTO_FP) .put(Kind.FLOATINGPOINT_TO_FP_UNSIGNED_BITVECTOR, FunctionDeclarationKind.BV_UCASTTO_FP) .put(Kind.FLOATINGPOINT_ISNAN, FunctionDeclarationKind.FP_IS_NAN) .put(Kind.FLOATINGPOINT_ISNEG, FunctionDeclarationKind.FP_IS_NEGATIVE) .put(Kind.FLOATINGPOINT_ISINF, FunctionDeclarationKind.FP_IS_INF) .put(Kind.FLOATINGPOINT_ISN, FunctionDeclarationKind.FP_IS_NORMAL) .put(Kind.FLOATINGPOINT_ISSN, FunctionDeclarationKind.FP_IS_SUBNORMAL) .put(Kind.FLOATINGPOINT_ISZ, FunctionDeclarationKind.FP_IS_ZERO) .put(Kind.FLOATINGPOINT_EQ, FunctionDeclarationKind.FP_EQ) .put(Kind.FLOATINGPOINT_ABS, FunctionDeclarationKind.FP_ABS) .put(Kind.FLOATINGPOINT_MAX, FunctionDeclarationKind.FP_MAX) .put(Kind.FLOATINGPOINT_MIN, FunctionDeclarationKind.FP_MIN) .put(Kind.FLOATINGPOINT_SQRT, FunctionDeclarationKind.FP_SQRT) .put(Kind.PLUS, FunctionDeclarationKind.FP_ADD) .put(Kind.FLOATINGPOINT_SUB, FunctionDeclarationKind.FP_SUB) .put(Kind.FLOATINGPOINT_MULT, FunctionDeclarationKind.FP_MUL) .put(Kind.FLOATINGPOINT_DIV, FunctionDeclarationKind.FP_DIV) .put(Kind.FLOATINGPOINT_LT, FunctionDeclarationKind.FP_LT) .put(Kind.FLOATINGPOINT_LEQ, FunctionDeclarationKind.FP_LE) .put(Kind.FLOATINGPOINT_GT, FunctionDeclarationKind.FP_GT) .put(Kind.FLOATINGPOINT_GEQ, FunctionDeclarationKind.FP_GE) .put(Kind.FLOATINGPOINT_RTI, FunctionDeclarationKind.FP_ROUND_TO_INTEGRAL) .put(Kind.FLOATINGPOINT_TO_FP_IEEE_BITVECTOR, FunctionDeclarationKind.FP_AS_IEEEBV) // String and Regex theory .put(Kind.STRING_CONCAT, FunctionDeclarationKind.STR_CONCAT) .put(Kind.STRING_PREFIX, FunctionDeclarationKind.STR_PREFIX) .put(Kind.STRING_SUFFIX, FunctionDeclarationKind.STR_SUFFIX) .put(Kind.STRING_CONTAINS, FunctionDeclarationKind.STR_CONTAINS) .put(Kind.STRING_SUBSTR, FunctionDeclarationKind.STR_SUBSTRING) .put(Kind.STRING_REPLACE, FunctionDeclarationKind.STR_REPLACE) .put(Kind.STRING_REPLACE_ALL, FunctionDeclarationKind.STR_REPLACE_ALL) .put(Kind.STRING_CHARAT, FunctionDeclarationKind.STR_CHAR_AT) .put(Kind.STRING_LENGTH, FunctionDeclarationKind.STR_LENGTH) .put(Kind.STRING_INDEXOF, FunctionDeclarationKind.STR_INDEX_OF) .put(Kind.STRING_TO_REGEXP, FunctionDeclarationKind.STR_TO_RE) .put(Kind.STRING_IN_REGEXP, FunctionDeclarationKind.STR_IN_RE) .put(Kind.STRING_FROM_INT, FunctionDeclarationKind.INT_TO_STR) .put(Kind.STRING_TO_INT, FunctionDeclarationKind.STR_TO_INT) .put(Kind.STRING_LT, FunctionDeclarationKind.STR_LT) .put(Kind.STRING_LEQ, FunctionDeclarationKind.STR_LE) .put(Kind.REGEXP_PLUS, FunctionDeclarationKind.RE_PLUS) .put(Kind.REGEXP_STAR, FunctionDeclarationKind.RE_STAR) .put(Kind.REGEXP_OPT, FunctionDeclarationKind.RE_OPTIONAL) .put(Kind.REGEXP_CONCAT, FunctionDeclarationKind.RE_CONCAT) .put(Kind.REGEXP_UNION, FunctionDeclarationKind.RE_UNION) .put(Kind.REGEXP_RANGE, FunctionDeclarationKind.RE_RANGE) .put(Kind.REGEXP_INTER, FunctionDeclarationKind.RE_INTERSECT) .put(Kind.REGEXP_COMPLEMENT, FunctionDeclarationKind.RE_COMPLEMENT) .put(Kind.REGEXP_DIFF, FunctionDeclarationKind.RE_DIFFERENCE) .build(); @SuppressWarnings("unused") private FunctionDeclarationKind getDeclarationKind(Term f) { try { Kind kind = f.getKind(); // special case: IFF for Boolean, EQ for all other Types if (kind == Kind.EQUAL && Iterables.all(f, child -> child.getSort().isBoolean())) { return FunctionDeclarationKind.IFF; } return KIND_MAPPING.getOrDefault(kind, FunctionDeclarationKind.OTHER); } catch (CVC5ApiException e) { throw new IllegalArgumentException("Failure trying to get the KIND of Term " + f + ".", e); } } @Override protected Term getBooleanVarDeclarationImpl(Term pTFormulaInfo) { try { Kind kind = pTFormulaInfo.getKind(); assert kind == Kind.APPLY_UF || kind == Kind.VARIABLE : pTFormulaInfo.getKind(); if (kind == Kind.APPLY_UF) { // TODO: Test this, this is the old internal implementation return pTFormulaInfo.getChild(0); // old // return pTFormulaInfo.getOperator(); } else { return pTFormulaInfo; } } catch (CVC5ApiException e) { throw new IllegalArgumentException( "You tried reading a bool variable potentially in a UF application that failed. Checked term: " + pTFormulaInfo + ".", e); } } @Override public Term callFunctionImpl(Term pDeclaration, List<Term> pArgs) { if (pArgs.isEmpty()) { // CVC5 does not allow argumentless functions! throw new IllegalArgumentException( "You tried calling a UF with no arguments. CVC5 does not allow this."); } else { // Applying UFs in CVC5 works with an array of Terms with the UF being the first argument // If you pull the children out of it the order will be the same! Term[] args = Stream.of(new Term[] {pDeclaration}, (Term[]) pArgs.toArray()) .flatMap(Stream::of) .toArray(Term[]::new); return solver.mkTerm(Kind.APPLY_UF, args); } } @Override public Term declareUFImpl(String pName, Sort pReturnType, List<Sort> pArgTypes) { if (pArgTypes.isEmpty()) { // Ufs in CVC5 can't have 0 arity. I tried an empty array and nullsort. throw new IllegalArgumentException( "You tried creating a UF with no arguments. CVC5 does not allow this."); } Term exp = functionsCache.get(pName); if (exp == null) { // array of argument types and the return type Sort ufToReturnType = solver.mkFunctionSort((Sort[]) pArgTypes.toArray(), pReturnType); exp = solver.mkConst(ufToReturnType, pName); functionsCache.put(pName, exp); } return exp; } @Override public Object convertValue(Term expForType, Term value) { // Make sure that final Sort type = expForType.getSort(); final Sort valueType = value.getSort(); // Variables are Kind.CONSTANT and can't be check with isIntegerValue() or getIntegerValue() // etc. but only with solver.getValue() and its String serialization try { if (value.getKind() == Kind.VARIABLE) { // CVC5 does not allow model values for bound vars; just return the name return value.toString(); } else if (valueType.isInteger() && type.isInteger()) { return new BigInteger(solver.getValue(value).toString()); } else if (valueType.isReal() && type.isReal()) { Rational rat = Rational.ofString(solver.getValue(value).toString()); return org.sosy_lab.common.rationals.Rational.of( new BigInteger(rat.getNum().toString()), new BigInteger(rat.getDen().toString())); } else if (valueType.isBitVector()) { return new BigInteger(solver.getValue(value).toString()); } else if (valueType.isFloatingPoint()) { return parseFloatingPoint(value); } else { // String serialization for Strings, booleans and unknown terms. return solver.getValue(value).toString(); } } catch (CVC5ApiException e) { throw new IllegalArgumentException( "Failure trying to convert CVC5 " + valueType + " variable into a " + type + " value.", e); } } @SuppressWarnings("unused") private Object parseFloatingPoint(Term fpTerm) { Matcher matcher = FLOATING_POINT_PATTERN.matcher(fpTerm.toString()); if (!matcher.matches()) { throw new NumberFormatException("Unknown floating-point format: " + fpTerm); } /* // First is exponent, second is mantissa, third if bitvec value of the fp Triplet<Long, Long, Term> fpTriplet = fpTerm.getFloatingPointValue(); long expWidth = fpTriplet.first; long mantWidth = fpTriplet.second - 1; // without sign bit assert matcher.group("sign").length() == 1; assert matcher.group("exp").length() == expWidth; assert matcher.group("mant").length() == mantWidth; String str = matcher.group("sign") + matcher.group("exp") + matcher.group("mant"); if (expWidth == 11 && mantWidth == 52) { return Double.longBitsToDouble(UnsignedLong.valueOf(str, 2).longValue()); } else if (expWidth == 8 && mantWidth == 23) { return Float.intBitsToFloat(UnsignedInteger.valueOf(str, 2).intValue()); } */ // TODO to be fully correct, we would need to interpret this string // it may be interpreted with i.e. FLOATINGPOINT_TO_REAL return solver.getValue(fpTerm).toString(); } }
Fix preliminary visitor for CVC5 and remove duplicates in function declr to kind map
src/org/sosy_lab/java_smt/solvers/cvc5/CVC5FormulaCreator.java
Fix preliminary visitor for CVC5 and remove duplicates in function declr to kind map
<ide><path>rc/org/sosy_lab/java_smt/solvers/cvc5/CVC5FormulaCreator.java <ide> import static com.google.common.base.Preconditions.checkState; <ide> <ide> import com.google.common.base.Preconditions; <add>import com.google.common.collect.ImmutableList; <ide> import com.google.common.collect.ImmutableMap; <ide> import com.google.common.collect.Iterables; <ide> import io.github.cvc5.api.CVC5ApiException; <ide> import org.sosy_lab.java_smt.api.StringFormula; <ide> import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; <ide> import org.sosy_lab.java_smt.basicimpl.FormulaCreator; <add>import org.sosy_lab.java_smt.basicimpl.FunctionDeclarationImpl; <ide> import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5ArrayFormula; <ide> import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5BitvectorFormula; <ide> import org.sosy_lab.java_smt.solvers.cvc5.CVC5Formula.CVC5BooleanFormula; <ide> try { <ide> if (f.getKind() == Kind.CONSTANT) { <ide> if (sort.isBoolean()) { <del> return visitor.visitConstant(formula, f.getBooleanValue()); <add> return visitor.visitConstant(formula, solver.getValue(f)); <ide> } else if (sort.isReal()) { <del> return visitor.visitConstant(formula, f.getRealValue()); <add> return visitor.visitConstant(formula, solver.getValue(f)); <ide> } else if (sort.isInteger()) { <del> return visitor.visitConstant(formula, f.getIntegerValue()); <add> return visitor.visitConstant(formula, solver.getValue(f)); <ide> } else if (sort.isBitVector()) { <del> return visitor.visitConstant(formula, f.getBitVectorValue()); <add> return visitor.visitConstant(formula, solver.getValue(f)); <ide> } else if (sort.isFloatingPoint()) { <del> return visitor.visitConstant(formula, f.getFloatingPointValue()); <del> } else if (sort.isRoundingMode()) { <del> // TODO: this is most likely bullshit and WILL fail! <del> return visitor.visitConstant(formula, solver.getRoundingModeSort()); <add> return visitor.visitConstant(formula, solver.getValue(f)); <ide> } else if (sort.isString()) { <del> return visitor.visitConstant(formula, f.getStringValue()); <add> return visitor.visitConstant(formula, solver.getValue(f)); <ide> } else { <ide> throw new UnsupportedOperationException("Unhandled constant " + f + " with Type " + sort); <ide> } <ide> return visitor.visitQuantifier((BooleanFormula) formula, quant, freeVars, fBody); <ide> <ide> } else if (f.getKind() == Kind.VARIABLE) { <del> // assert f.getKind() != Kind.BOUND_VARIABLE; <add> // TODO: This is kinda pointless, rework <ide> return visitor.visitFreeVariable(formula, getName(f)); <ide> <ide> } else { <ide> // Termessions like uninterpreted function calls (Kind.APPLY_UF) or operators (e.g. <ide> // Kind.AND). <ide> // These are all treated like operators, so we can get the declaration by f.getOperator()! <del> /* <del> List<Formula> args = ImmutableList.copyOf(Iterables.transform(f, this::encapsulate)); <del> List<FormulaType<?>> argsTypes = new ArrayList<>(); <del> <del> Term operator = normalize(f.getOperator()); <del> if (operator.getSort().isFunction()) { <del> vectorType argTypes = new FunctionType(operator.getSort()).getArgTypes(); <del> for (int i = 0; i < argTypes.size(); i++) { <del> argsTypes.add(getFormulaTypeFromTermType(argTypes.get(i))); <del> } <del> } else { <del> for (Term arg : f) { <del> argsTypes.add(getFormulaType(arg)); <del> } <del> } <del> <del> <del> checkState(args.size() == argsTypes.size()); <del> */ <add> <add> List<Formula> args = ImmutableList.copyOf(Iterables.transform(f, this::encapsulate)); <add> List<FormulaType<?>> argsTypes = new ArrayList<>(); <add> <add> // Term operator = normalize(f.getSort()); <add> Kind kind = f.getKind(); <add> if (sort.isFunction() || kind == Kind.APPLY_UF) { <add> // The arguments are all children except the first one <add> for (int i = 1; i < f.getNumChildren() - 1; i++) { <add> argsTypes.add(getFormulaTypeFromTermType(f.getChild(i).getSort())); <add> } <add> } else { <add> for (Term arg : f) { <add> argsTypes.add(getFormulaType(arg)); <add> } <add> } <add> <add> checkState(args.size() == argsTypes.size()); <add> <ide> // TODO some operations (BV_SIGN_EXTEND, BV_ZERO_EXTEND, maybe more) encode information as <ide> // part of the operator itself, thus the arity is one too small and there might be no <ide> // possibility to access the information from user side. Should we encode such information <del> // as <del> // additional parameters? We do so for some methods of Princess. <del> /* <add> // as additional parameters? We do so for some methods of Princess. <add> <ide> return visitor.visitFunction( <ide> formula, <ide> args, <ide> FunctionDeclarationImpl.of( <del> getName(f), getDeclarationKind(f), argsTypes, getFormulaType(f), operator)); <del> */ <del> return null; <add> getName(f), getDeclarationKind(f), argsTypes, getFormulaType(f), f.getChild(0))); <ide> } <ide> } catch (CVC5ApiException e) { <ide> throw new IllegalArgumentException("Failure visiting the Term " + f + ".", e); <ide> .put(Kind.GT, FunctionDeclarationKind.GT) <ide> .put(Kind.GEQ, FunctionDeclarationKind.GTE) <ide> // Bitvector theory <del> .put(Kind.PLUS, FunctionDeclarationKind.BV_ADD) <add> .put(Kind.BITVECTOR_ADD, FunctionDeclarationKind.BV_ADD) <ide> .put(Kind.BITVECTOR_SUB, FunctionDeclarationKind.BV_SUB) <ide> .put(Kind.BITVECTOR_MULT, FunctionDeclarationKind.BV_MUL) <ide> .put(Kind.BITVECTOR_AND, FunctionDeclarationKind.BV_AND) <ide> .put(Kind.FLOATINGPOINT_MAX, FunctionDeclarationKind.FP_MAX) <ide> .put(Kind.FLOATINGPOINT_MIN, FunctionDeclarationKind.FP_MIN) <ide> .put(Kind.FLOATINGPOINT_SQRT, FunctionDeclarationKind.FP_SQRT) <del> .put(Kind.PLUS, FunctionDeclarationKind.FP_ADD) <add> .put(Kind.FLOATINGPOINT_ADD, FunctionDeclarationKind.FP_ADD) <ide> .put(Kind.FLOATINGPOINT_SUB, FunctionDeclarationKind.FP_SUB) <ide> .put(Kind.FLOATINGPOINT_MULT, FunctionDeclarationKind.FP_MUL) <ide> .put(Kind.FLOATINGPOINT_DIV, FunctionDeclarationKind.FP_DIV) <ide> } <ide> Term exp = functionsCache.get(pName); <ide> if (exp == null) { <add> Sort[] argSorts = pArgTypes.toArray(new Sort[0]); <ide> // array of argument types and the return type <del> Sort ufToReturnType = solver.mkFunctionSort((Sort[]) pArgTypes.toArray(), pReturnType); <add> Sort ufToReturnType = solver.mkFunctionSort(argSorts, pReturnType); <ide> exp = solver.mkConst(ufToReturnType, pName); <ide> functionsCache.put(pName, exp); <ide> }
Java
mit
2673347489a7e6ea83437a311ec94da8422f484f
0
IanEdington/ud405,IanEdington/ud405,IanEdington/ud405
package com.udacity.gamedev.viewportsexercise; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.utils.viewport.FitViewport; /** * In this exercise, you'll use a fit viewport to make sure the entire game world is onscreen and * at the right aspect ratio. * * One new concept is the fact that a viewport will happily create its own camera if you don't * provide it with one. To get the camera (to set a ShapeRenderer's projection matrix, for * instance), you can just call getCamera() on the viewport. * * When you're done, change up the WORLD_WIDTH and WORLD_HEIGHT, and see how the world still fits on * screen */ public class ViewportsExercise extends ApplicationAdapter { private static final float WORLD_WIDTH = 100.0f; private static final float WORLD_HEIGHT = 100.0f; private static final int RECURSIONS = 3; ShapeRenderer renderer; // Declare a FitViewport FitViewport viewport; @Override public void create() { renderer = new ShapeRenderer(); // Initialize the viewport with the world width and height viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT); } @Override public void dispose() { renderer.dispose(); } @Override public void resize(int width, int height) { // update the viewport and center the camera by passing true as the third argument viewport.update(width, height, true); } @Override public void render() { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Apply the viewport viewport.apply(); // Set the projection matrix of the ShapeRenderer to the combined matrix of the viewport's camera renderer.setProjectionMatrix(viewport.getCamera().combined); renderer.begin(ShapeType.Filled); renderer.setColor(Color.WHITE); renderer.rect(0, 0, WORLD_WIDTH, WORLD_HEIGHT); renderer.setColor(Color.BLACK); punchCantorGasket(0, 0, WORLD_WIDTH, WORLD_HEIGHT, RECURSIONS); renderer.setColor(Color.WHITE); renderer.circle(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, Math.min(WORLD_WIDTH, WORLD_HEIGHT) / 6.5f, 20); renderer.end(); } private void punchCantorGasket(float x, float y, float width, float height, int recursions) { if (recursions == 0) { return; } float newWidth = width / 3; float newHeight = height / 3; renderer.rect(x + newWidth, y + newHeight, newWidth, newHeight); punchCantorGasket(x, y, newWidth, newHeight, recursions - 1); punchCantorGasket(x + newWidth, y, newWidth, newHeight, recursions - 1); punchCantorGasket(x + 2 * newWidth, y, newWidth, newHeight, recursions - 1); punchCantorGasket(x, y + newHeight, newWidth, newHeight, recursions - 1); punchCantorGasket(x + 2 * newWidth, y + newHeight, newWidth, newHeight, recursions - 1); punchCantorGasket(x, y + 2 * newHeight, newWidth, newHeight, recursions - 1); punchCantorGasket(x + newWidth, y + 2 * newHeight, newWidth, newHeight, recursions - 1); punchCantorGasket(x + 2 * newWidth, y + 2 * newHeight, newWidth, newHeight, recursions - 1); } }
1.4.07-Exercise-Viewports/core/src/com/udacity/gamedev/viewportsexercise/ViewportsExercise.java
package com.udacity.gamedev.viewportsexercise; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; /** * TODO: Start here * * In this exercise, you'll use a fit viewport to make sure the entire game world is onscreen and * at the right aspect ratio. * * One new concept is the fact that a viewport will happily create its own camera if you don't * provide it with one. To get the camera (to set a ShapeRenderer's projection matrix, for * instance), you can just call getCamera() on the viewport. * * When you're done, change up the WORLD_WIDTH and WORLD_HEIGHT, and see how the world still fits on * screen */ public class ViewportsExercise extends ApplicationAdapter { private static final float WORLD_WIDTH = 100.0f; private static final float WORLD_HEIGHT = 100.0f; private static final int RECURSIONS = 3; ShapeRenderer renderer; // TODO: Declare a FitViewport @Override public void create() { renderer = new ShapeRenderer(); // TODO: Initialize the viewport with the world width and height } @Override public void dispose() { renderer.dispose(); } @Override public void resize(int width, int height) { // TODO: update the viewport and center the camera by passing true as the third argument } @Override public void render() { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // TODO: Apply the viewport // TODO: Set the projection matrix of the ShapeRenderer to the combined matrix of the viewport's camera renderer.begin(ShapeType.Filled); renderer.setColor(Color.WHITE); renderer.rect(0, 0, WORLD_WIDTH, WORLD_HEIGHT); renderer.setColor(Color.BLACK); punchCantorGasket(0, 0, WORLD_WIDTH, WORLD_HEIGHT, RECURSIONS); renderer.setColor(Color.WHITE); renderer.circle(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, Math.min(WORLD_WIDTH, WORLD_HEIGHT) / 6.5f, 20); renderer.end(); } private void punchCantorGasket(float x, float y, float width, float height, int recursions) { if (recursions == 0) { return; } float newWidth = width / 3; float newHeight = height / 3; renderer.rect(x + newWidth, y + newHeight, newWidth, newHeight); punchCantorGasket(x, y, newWidth, newHeight, recursions - 1); punchCantorGasket(x + newWidth, y, newWidth, newHeight, recursions - 1); punchCantorGasket(x + 2 * newWidth, y, newWidth, newHeight, recursions - 1); punchCantorGasket(x, y + newHeight, newWidth, newHeight, recursions - 1); punchCantorGasket(x + 2 * newWidth, y + newHeight, newWidth, newHeight, recursions - 1); punchCantorGasket(x, y + 2 * newHeight, newWidth, newHeight, recursions - 1); punchCantorGasket(x + newWidth, y + 2 * newHeight, newWidth, newHeight, recursions - 1); punchCantorGasket(x + 2 * newWidth, y + 2 * newHeight, newWidth, newHeight, recursions - 1); } }
Useing viewport instead of camera to manage views
1.4.07-Exercise-Viewports/core/src/com/udacity/gamedev/viewportsexercise/ViewportsExercise.java
Useing viewport instead of camera to manage views
<ide><path>.4.07-Exercise-Viewports/core/src/com/udacity/gamedev/viewportsexercise/ViewportsExercise.java <ide> import com.badlogic.gdx.graphics.GL20; <ide> import com.badlogic.gdx.graphics.glutils.ShapeRenderer; <ide> import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; <add>import com.badlogic.gdx.utils.viewport.FitViewport; <ide> <ide> /** <del> * TODO: Start here <del> * <ide> * In this exercise, you'll use a fit viewport to make sure the entire game world is onscreen and <ide> * at the right aspect ratio. <ide> * <ide> private static final int RECURSIONS = 3; <ide> <ide> ShapeRenderer renderer; <del> // TODO: Declare a FitViewport <add> // Declare a FitViewport <add> FitViewport viewport; <ide> <ide> <ide> @Override <ide> public void create() { <ide> renderer = new ShapeRenderer(); <del> // TODO: Initialize the viewport with the world width and height <add> // Initialize the viewport with the world width and height <add> viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT); <ide> <ide> } <ide> <ide> <ide> @Override <ide> public void resize(int width, int height) { <del> // TODO: update the viewport and center the camera by passing true as the third argument <add> // update the viewport and center the camera by passing true as the third argument <add> viewport.update(width, height, true); <ide> <ide> } <ide> <ide> Gdx.gl.glClearColor(0, 0, 0, 1); <ide> Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); <ide> <del> // TODO: Apply the viewport <add> // Apply the viewport <add> viewport.apply(); <ide> <ide> <del> // TODO: Set the projection matrix of the ShapeRenderer to the combined matrix of the viewport's camera <add> // Set the projection matrix of the ShapeRenderer to the combined matrix of the viewport's camera <add> renderer.setProjectionMatrix(viewport.getCamera().combined); <ide> <ide> <ide> renderer.begin(ShapeType.Filled);
Java
lgpl-2.1
49da2ba60110333a582049a68ded00f26d4f6ded
0
levants/lightmare
package org.lightmare.cache; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceUnit; import org.lightmare.utils.ObjectUtils; /** * Container class to save bean {@link Field} with annotation * {@link PersistenceContext} and bean class * * @author Levan * */ public class MetaData { private Class<?> beanClass; private Class<?>[] interfaceClasses; private Class<?>[] localInterfaces; private Class<?>[] remoteInterfaces; private Field transactionField; private Collection<ConnectionData> connections; private ClassLoader loader; private AtomicBoolean inProgress = new AtomicBoolean(); private boolean transactional; private TransactionAttributeType transactionAttrType; private TransactionManagementType transactionManType; private List<InjectionData> injects; private Collection<Field> unitFields; private Queue<InterceptorData> interceptors; public Class<?> getBeanClass() { return beanClass; } public void setBeanClass(Class<?> beanClass) { this.beanClass = beanClass; } public Class<?>[] getInterfaceClasses() { return interfaceClasses; } public void setInterfaceClasses(Class<?>[] interfaceClasses) { this.interfaceClasses = interfaceClasses; } public Class<?>[] getLocalInterfaces() { return localInterfaces; } public void setLocalInterfaces(Class<?>[] localInterfaces) { this.localInterfaces = localInterfaces; } public Class<?>[] getRemoteInterfaces() { return remoteInterfaces; } public void setRemoteInterfaces(Class<?>[] remoteInterfaces) { this.remoteInterfaces = remoteInterfaces; } public Field getTransactionField() { return transactionField; } public void setTransactionField(Field transactionField) { this.transactionField = transactionField; } public Collection<ConnectionData> getConnections() { return connections; } public void setConnections(Collection<ConnectionData> connections) { this.connections = connections; } public void addConnection(ConnectionData connection) { if (connections == null) { connections = new ArrayList<ConnectionData>(); } connections.add(connection); } private void addUnitField(String unitName, Field unitField) { for (ConnectionData connection : connections) { if (unitName.equals(connection.getUnitName())) { connection.setUnitField(unitField); } } } /** * Adds {@link javax.ejb.PersistenceUnit} annotated field to * {@link MetaData} for cache * * @param unitFields */ public void addUnitFields(Collection<Field> unitFields) { if (ObjectUtils.availableAll(connections, unitFields)) { String unitName; for (Field unitField : unitFields) { unitName = unitField.getAnnotation(PersistenceUnit.class) .unitName(); addUnitField(unitName, unitField); } this.unitFields = unitFields; } } public ClassLoader getLoader() { return loader; } public void setLoader(ClassLoader loader) { this.loader = loader; } public boolean isInProgress() { return inProgress.get(); } public void setInProgress(boolean inProgress) { this.inProgress.getAndSet(inProgress); } public boolean isTransactional() { return transactional; } public void setTransactional(boolean transactional) { this.transactional = transactional; } public TransactionAttributeType getTransactionAttrType() { return transactionAttrType; } public void setTransactionAttrType( TransactionAttributeType transactionAttrType) { this.transactionAttrType = transactionAttrType; } public TransactionManagementType getTransactionManType() { return transactionManType; } public void setTransactionManType( TransactionManagementType transactionManType) { this.transactionManType = transactionManType; } public List<InjectionData> getInjects() { return injects; } public void addInject(InjectionData inject) { if (injects == null) { injects = new ArrayList<InjectionData>(); } injects.add(inject); } public Collection<Field> getUnitFields() { return this.unitFields; } public void addInterceptor(InterceptorData interceptor) { if (interceptors == null) { interceptors = new LinkedList<InterceptorData>(); } interceptors.offer(interceptor); } public Collection<InterceptorData> getInterceptors() { return interceptors; } }
src/main/java/org/lightmare/cache/MetaData.java
package org.lightmare.cache; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceUnit; import org.lightmare.utils.ObjectUtils; /** * Container class to save bean {@link Field} with annotation * {@link PersistenceContext} and bean class * * @author Levan * */ public class MetaData { private Class<?> beanClass; private Class<?>[] interfaceClasses; private Class<?>[] localInterfaces; private Class<?>[] remoteInterfaces; private Field transactionField; private Collection<ConnectionData> connections; private ClassLoader loader; private AtomicBoolean inProgress = new AtomicBoolean(); private boolean transactional; private TransactionAttributeType transactionAttrType; private TransactionManagementType transactionManType; private List<InjectionData> injects; private Collection<Field> unitFields; private Queue<InterceptorData> interceptors; public Class<?> getBeanClass() { return beanClass; } public void setBeanClass(Class<?> beanClass) { this.beanClass = beanClass; } public Class<?>[] getInterfaceClasses() { return interfaceClasses; } public void setInterfaceClasses(Class<?>[] interfaceClasses) { this.interfaceClasses = interfaceClasses; } public Class<?>[] getLocalInterfaces() { return localInterfaces; } public void setLocalInterfaces(Class<?>[] localInterfaces) { this.localInterfaces = localInterfaces; } public Class<?>[] getRemoteInterfaces() { return remoteInterfaces; } public void setRemoteInterfaces(Class<?>[] remoteInterfaces) { this.remoteInterfaces = remoteInterfaces; } public Field getTransactionField() { return transactionField; } public void setTransactionField(Field transactionField) { this.transactionField = transactionField; } public Collection<ConnectionData> getConnections() { return connections; } public void setConnections(Collection<ConnectionData> connections) { this.connections = connections; } public void addConnection(ConnectionData connection) { if (connections == null) { connections = new ArrayList<ConnectionData>(); } connections.add(connection); } private void addUnitField(String unitName, Field unitField) { for (ConnectionData connection : connections) { if (unitName.equals(connection.getUnitName())) { connection.setUnitField(unitField); } } } /** * Adds {@link javax.ejb.PersistenceUnit} annotated field to * {@link MetaData} for cache * * @param unitFields */ public void addUnitFields(Collection<Field> unitFields) { if (ObjectUtils.availableAll(connections, unitFields)) { String unitName; for (Field unitField : unitFields) { unitName = unitField.getAnnotation(PersistenceUnit.class) .unitName(); addUnitField(unitName, unitField); } this.unitFields = unitFields; } } public ClassLoader getLoader() { return loader; } public void setLoader(ClassLoader loader) { this.loader = loader; } public boolean isInProgress() { return inProgress.get(); } public void setInProgress(boolean inProgress) { this.inProgress.getAndSet(inProgress); } public boolean isTransactional() { return transactional; } public void setTransactional(boolean transactional) { this.transactional = transactional; } public TransactionAttributeType getTransactionAttrType() { return transactionAttrType; } public void setTransactionAttrType( TransactionAttributeType transactionAttrType) { this.transactionAttrType = transactionAttrType; } public TransactionManagementType getTransactionManType() { return transactionManType; } public void setTransactionManType( TransactionManagementType transactionManType) { this.transactionManType = transactionManType; } public List<InjectionData> getInjects() { return injects; } public void addInject(InjectionData inject) { if (injects == null) { injects = new ArrayList<InjectionData>(); } injects.add(inject); } public Collection<Field> getUnitFields() { return this.unitFields; } public void addInterceptor(InterceptorData interceptor) { if (interceptors == null) { interceptors = new LinkedList<InterceptorData>(); } interceptors.offer(interceptor); } }
implemented cache for Interceptors data
src/main/java/org/lightmare/cache/MetaData.java
implemented cache for Interceptors data
<ide><path>rc/main/java/org/lightmare/cache/MetaData.java <ide> } <ide> interceptors.offer(interceptor); <ide> } <add> <add> public Collection<InterceptorData> getInterceptors() { <add> <add> return interceptors; <add> } <ide> }
Java
mit
cedb805d218d8873c22ce7475069b2317c74eb79
0
YOTOV-LIMITED/validator,takenspc/validator,tripu/validator,validator/validator,tripu/validator,YOTOV-LIMITED/validator,sammuelyee/validator,sammuelyee/validator,validator/validator,takenspc/validator,YOTOV-LIMITED/validator,YOTOV-LIMITED/validator,tripu/validator,takenspc/validator,sammuelyee/validator,takenspc/validator,validator/validator,validator/validator,validator/validator,sammuelyee/validator,takenspc/validator,sammuelyee/validator,tripu/validator,YOTOV-LIMITED/validator,tripu/validator
/* * This file is part of the RELAX NG schemas far (X)HTML5. * Please see the file named LICENSE in the relaxng directory for * license details. */ package org.whattf.syntax; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.MalformedURLException; import nu.validator.gnu.xml.aelfred2.SAXDriver; import nu.validator.htmlparser.sax.HtmlParser; import nu.validator.xml.IdFilter; import nu.validator.xml.SystemErrErrorHandler; import org.whattf.checker.NormalizationChecker; import org.whattf.checker.TextContentChecker; import org.whattf.checker.jing.CheckerSchema; import org.whattf.checker.jing.CheckerValidator; import org.whattf.checker.table.TableChecker; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import com.thaiopensource.relaxng.impl.CombineValidator; import com.thaiopensource.util.PropertyMap; import com.thaiopensource.util.PropertyMapBuilder; import com.thaiopensource.validate.Schema; import com.thaiopensource.validate.SchemaReader; import com.thaiopensource.validate.ValidateProperty; import com.thaiopensource.validate.Validator; import com.thaiopensource.validate.auto.AutoSchemaReader; import com.thaiopensource.validate.prop.rng.RngProperty; import com.thaiopensource.validate.rng.CompactSchemaReader; import com.thaiopensource.xml.sax.CountingErrorHandler; import com.thaiopensource.xml.sax.Jaxp11XMLReaderCreator; /** * * @version $Id$ * @author hsivonen */ public class Driver { private static final String PATH = "syntax/relaxng/tests/"; private PrintWriter err; private PrintWriter out; private Schema mainSchema; private Schema assertionSchema; private Validator validator; private SystemErrErrorHandler errorHandler = new SystemErrErrorHandler(); private CountingErrorHandler countingErrorHandler = new CountingErrorHandler(); private HtmlParser htmlParser = new HtmlParser(); private XMLReader xmlParser; private boolean failed = false; private boolean verbose; /** * @param basePath */ public Driver(boolean verbose) { this.verbose = verbose; try { this.err = new PrintWriter(new OutputStreamWriter(System.err, "UTF-8")); this.out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); /* * SAXParserFactory factory = SAXParserFactory.newInstance(); * factory.setNamespaceAware(true); factory.setValidating(false); * XMLReader parser = factory.newSAXParser().getXMLReader(); */ this.xmlParser = new IdFilter(new SAXDriver()); } catch (Exception e) { // If this happens, the JDK is too broken anyway throw new RuntimeException(e); } } private Schema schemaByFilename(File name) throws Exception { PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, errorHandler); pmb.put(ValidateProperty.XML_READER_CREATOR, new Jaxp11XMLReaderCreator()); RngProperty.CHECK_ID_IDREF.add(pmb); PropertyMap jingPropertyMap = pmb.toPropertyMap(); InputSource schemaInput; try { schemaInput = new InputSource(name.toURL().toString()); } catch (MalformedURLException e1) { System.err.println(); e1.printStackTrace(err); failed = true; return null; } SchemaReader sr; if (name.getName().endsWith(".rnc")) { sr = CompactSchemaReader.getInstance(); } else { sr = new AutoSchemaReader(); } return sr.createSchema(schemaInput, jingPropertyMap); } private void checkFile(File file) throws IOException, SAXException { validator.reset(); InputSource is = new InputSource(new FileInputStream(file)); is.setSystemId(file.toURL().toString()); String name = file.getName(); if (name.endsWith(".html") || name.endsWith(".htm")) { is.setEncoding("UTF-8"); if (verbose) { out.println(file); out.flush(); } htmlParser.parse(is); } else if (name.endsWith(".xhtml") || name.endsWith(".xht")) { if (verbose) { out.println(file); out.flush(); } xmlParser.parse(is); } } private boolean isCheckableFile(File file) { String name = file.getName(); return file.isFile() && (name.endsWith(".html") || name.endsWith(".htm") || name.endsWith(".xhtml") || name.endsWith(".xht")); } private void checkValidFiles(File directory) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (isCheckableFile(file)) { errorHandler.reset(); try { checkFile(file); } catch (IOException e) { } catch (SAXException e) { } if (errorHandler.isInError()) { failed = true; } } else if (file.isDirectory()) { checkValidFiles(file); } } } private void checkInvalidFiles(File directory) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (isCheckableFile(file)) { countingErrorHandler.reset(); try { checkFile(file); } catch (IOException e) { } catch (SAXException e) { } if (!countingErrorHandler.getHadErrorOrFatalError()) { failed = true; try { err.println(file.toURL().toString() + " was supposed to be invalid but was not."); err.flush(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } else if (file.isDirectory()) { checkInvalidFiles(file); } } } private void checkDirectory(File directory, File schema) throws SAXException { try { mainSchema = schemaByFilename(schema); } catch (Exception e) { err.println("Reading schema failed. Skipping test directory."); e.printStackTrace(); err.flush(); return; } File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if ("valid".equals(file.getName())) { setup(errorHandler); checkValidFiles(file); } else if ("invalid".equals(file.getName())) { setup(countingErrorHandler); checkInvalidFiles(file); } } } /** * @throws SAXNotSupportedException * @throws SAXdException * */ private void setup(ErrorHandler eh) throws SAXException { PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, eh); pmb.put(ValidateProperty.XML_READER_CREATOR, new Jaxp11XMLReaderCreator()); RngProperty.CHECK_ID_IDREF.add(pmb); PropertyMap jingPropertyMap = pmb.toPropertyMap(); validator = mainSchema.createValidator(jingPropertyMap); Validator assertionValidator = assertionSchema.createValidator(jingPropertyMap); validator = new CombineValidator(validator, assertionValidator); validator = new CombineValidator(validator, new CheckerValidator( new TableChecker(), jingPropertyMap)); validator = new CombineValidator(validator, new CheckerValidator( new NormalizationChecker(), jingPropertyMap)); validator = new CombineValidator(validator, new CheckerValidator( new TextContentChecker(), jingPropertyMap)); htmlParser.setContentHandler(validator.getContentHandler()); htmlParser.setErrorHandler(eh); htmlParser.setFeature("http://xml.org/sax/features/unicode-normalization-checking", true); xmlParser.setContentHandler(validator.getContentHandler()); xmlParser.setErrorHandler(eh); xmlParser.setFeature("http://xml.org/sax/features/unicode-normalization-checking", true); htmlParser.setMappingLangToXmlLang(true); } public boolean check() throws SAXException { try { assertionSchema = CheckerSchema.ASSERTION_SCH; } catch (Exception e) { err.println("Reading schema failed. Terminating."); e.printStackTrace(); err.flush(); return false; } checkDirectory(new File(PATH + "html5core/"), new File(PATH + "../xhtml5core.rnc")); checkDirectory(new File(PATH + "html5core-plus-web-forms2/"), new File( PATH + "../xhtml5core-plus-web-forms2.rnc")); checkDirectory(new File(PATH + "html5full-html/"), new File( PATH + "../html5full.rnc")); checkDirectory(new File(PATH + "html5full-xhtml/"), new File( PATH + "../xhtml5full-xhtml.rnc")); checkDirectory(new File(PATH + "assertions/"), new File( PATH + "../xhtml5full-xhtml.rnc")); checkDirectory(new File(PATH + "tables/"), new File(PATH + "../xhtml5full-xhtml.rnc")); checkDirectory(new File(PATH + "media-queries/"), new File(PATH + "../html5full.rnc")); checkDirectory(new File(PATH + "mime-types/"), new File(PATH + "../html5full.rnc")); if (verbose) { if (failed) { out.println("Failure!"); } else { out.println("Success!"); } } err.flush(); out.flush(); return !failed; } /** * @param args * @throws SAXException */ public static void main(String[] args) throws SAXException { boolean verbose = ((args.length == 1) && "-v".equals(args[0])); Driver d = new Driver(verbose); if (d.check()) { System.exit(0); } else { System.exit(-1); } } }
relaxng/tests/jdriver/src/org/whattf/syntax/Driver.java
/* * This file is part of the RELAX NG schemas far (X)HTML5. * Please see the file named LICENSE in the relaxng directory for * license details. */ package org.whattf.syntax; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.MalformedURLException; import nu.validator.gnu.xml.aelfred2.SAXDriver; import nu.validator.htmlparser.sax.HtmlParser; import nu.validator.xml.IdFilter; import nu.validator.xml.SystemErrErrorHandler; import org.whattf.checker.NormalizationChecker; import org.whattf.checker.TextContentChecker; import org.whattf.checker.jing.CheckerSchema; import org.whattf.checker.jing.CheckerValidator; import org.whattf.checker.table.TableChecker; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import com.thaiopensource.relaxng.impl.CombineValidator; import com.thaiopensource.util.PropertyMap; import com.thaiopensource.util.PropertyMapBuilder; import com.thaiopensource.validate.Schema; import com.thaiopensource.validate.SchemaReader; import com.thaiopensource.validate.ValidateProperty; import com.thaiopensource.validate.Validator; import com.thaiopensource.validate.auto.AutoSchemaReader; import com.thaiopensource.validate.prop.rng.RngProperty; import com.thaiopensource.validate.rng.CompactSchemaReader; import com.thaiopensource.xml.sax.CountingErrorHandler; import com.thaiopensource.xml.sax.Jaxp11XMLReaderCreator; /** * * @version $Id$ * @author hsivonen */ public class Driver { private static final String PATH = "syntax/relaxng/tests/"; private PrintWriter err; private PrintWriter out; private Schema mainSchema; private Schema assertionSchema; private Validator validator; private SystemErrErrorHandler errorHandler = new SystemErrErrorHandler(); private CountingErrorHandler countingErrorHandler = new CountingErrorHandler(); private HtmlParser htmlParser = new HtmlParser(); private XMLReader xmlParser; private boolean failed = false; private boolean verbose; /** * @param basePath */ public Driver(boolean verbose) { this.verbose = verbose; try { this.err = new PrintWriter(new OutputStreamWriter(System.err, "UTF-8")); this.out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); /* * SAXParserFactory factory = SAXParserFactory.newInstance(); * factory.setNamespaceAware(true); factory.setValidating(false); * XMLReader parser = factory.newSAXParser().getXMLReader(); */ this.xmlParser = new IdFilter(new SAXDriver()); } catch (Exception e) { // If this happens, the JDK is too broken anyway throw new RuntimeException(e); } } private Schema schemaByFilename(File name) throws Exception { PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, errorHandler); pmb.put(ValidateProperty.XML_READER_CREATOR, new Jaxp11XMLReaderCreator()); RngProperty.CHECK_ID_IDREF.add(pmb); PropertyMap jingPropertyMap = pmb.toPropertyMap(); InputSource schemaInput; try { schemaInput = new InputSource(name.toURL().toString()); } catch (MalformedURLException e1) { System.err.println(); e1.printStackTrace(err); failed = true; return null; } SchemaReader sr; if (name.getName().endsWith(".rnc")) { sr = CompactSchemaReader.getInstance(); } else { sr = new AutoSchemaReader(); } return sr.createSchema(schemaInput, jingPropertyMap); } private void checkFile(File file) throws IOException, SAXException { validator.reset(); InputSource is = new InputSource(new FileInputStream(file)); is.setSystemId(file.toURL().toString()); String name = file.getName(); if (name.endsWith(".html") || name.endsWith(".htm")) { is.setEncoding("UTF-8"); if (verbose) { out.println(file); out.flush(); } htmlParser.parse(is); } else if (name.endsWith(".xhtml") || name.endsWith(".xht")) { if (verbose) { out.println(file); out.flush(); } xmlParser.parse(is); } } private boolean isCheckableFile(File file) { String name = file.getName(); return file.isFile() && (name.endsWith(".html") || name.endsWith(".htm") || name.endsWith(".xhtml") || name.endsWith(".xht")); } private void checkValidFiles(File directory) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (isCheckableFile(file)) { errorHandler.reset(); try { checkFile(file); } catch (IOException e) { } catch (SAXException e) { } if (errorHandler.isInError()) { failed = true; } } else if (file.isDirectory()) { checkValidFiles(file); } } } private void checkInvalidFiles(File directory) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (isCheckableFile(file)) { countingErrorHandler.reset(); try { checkFile(file); } catch (IOException e) { } catch (SAXException e) { } if (!countingErrorHandler.getHadErrorOrFatalError()) { failed = true; try { err.println(file.toURL().toString() + "was supposed to be invalid but was not."); err.flush(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } else if (file.isDirectory()) { checkInvalidFiles(file); } } } private void checkDirectory(File directory, File schema) throws SAXException { try { mainSchema = schemaByFilename(schema); } catch (Exception e) { err.println("Reading schema failed. Skipping test directory."); e.printStackTrace(); err.flush(); return; } File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if ("valid".equals(file.getName())) { setup(errorHandler); checkValidFiles(file); } else if ("invalid".equals(file.getName())) { setup(countingErrorHandler); checkInvalidFiles(file); } } } /** * @throws SAXNotSupportedException * @throws SAXdException * */ private void setup(ErrorHandler eh) throws SAXException { PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, eh); pmb.put(ValidateProperty.XML_READER_CREATOR, new Jaxp11XMLReaderCreator()); RngProperty.CHECK_ID_IDREF.add(pmb); PropertyMap jingPropertyMap = pmb.toPropertyMap(); validator = mainSchema.createValidator(jingPropertyMap); Validator assertionValidator = assertionSchema.createValidator(jingPropertyMap); validator = new CombineValidator(validator, assertionValidator); validator = new CombineValidator(validator, new CheckerValidator( new TableChecker(), jingPropertyMap)); validator = new CombineValidator(validator, new CheckerValidator( new NormalizationChecker(), jingPropertyMap)); validator = new CombineValidator(validator, new CheckerValidator( new TextContentChecker(), jingPropertyMap)); htmlParser.setContentHandler(validator.getContentHandler()); htmlParser.setErrorHandler(eh); htmlParser.setFeature("http://xml.org/sax/features/unicode-normalization-checking", true); xmlParser.setContentHandler(validator.getContentHandler()); xmlParser.setErrorHandler(eh); xmlParser.setFeature("http://xml.org/sax/features/unicode-normalization-checking", true); htmlParser.setMappingLangToXmlLang(true); } public boolean check() throws SAXException { try { assertionSchema = CheckerSchema.ASSERTION_SCH; } catch (Exception e) { err.println("Reading schema failed. Terminating."); e.printStackTrace(); err.flush(); return false; } checkDirectory(new File(PATH + "html5core/"), new File(PATH + "../xhtml5core.rnc")); checkDirectory(new File(PATH + "html5core-plus-web-forms2/"), new File( PATH + "../xhtml5core-plus-web-forms2.rnc")); checkDirectory(new File(PATH + "html5full-html/"), new File( PATH + "../html5full.rnc")); checkDirectory(new File(PATH + "html5full-xhtml/"), new File( PATH + "../xhtml5full-xhtml.rnc")); checkDirectory(new File(PATH + "assertions/"), new File( PATH + "../xhtml5full-xhtml.rnc")); checkDirectory(new File(PATH + "tables/"), new File(PATH + "../xhtml5full-xhtml.rnc")); checkDirectory(new File(PATH + "media-queries/"), new File(PATH + "../html5full.rnc")); checkDirectory(new File(PATH + "mime-types/"), new File(PATH + "../html5full.rnc")); if (verbose) { if (failed) { out.println("Failure!"); } else { out.println("Success!"); } } err.flush(); out.flush(); return !failed; } /** * @param args * @throws SAXException */ public static void main(String[] args) throws SAXException { boolean verbose = ((args.length == 1) && "-v".equals(args[0])); Driver d = new Driver(verbose); if (d.check()) { System.exit(0); } else { System.exit(-1); } } }
added necessary space in test-output message before word "was", so that error message does not appear as "file:foo.xhtmlwas supposed to be invalid but was not." --HG-- extra : convert_revision : svn%3Ae7398766-c432-0410-9565-638d39ca0058/trunk%40404
relaxng/tests/jdriver/src/org/whattf/syntax/Driver.java
added necessary space in test-output message before word "was", so that error message does not appear as "file:foo.xhtmlwas supposed to be invalid but was not."
<ide><path>elaxng/tests/jdriver/src/org/whattf/syntax/Driver.java <ide> failed = true; <ide> try { <ide> err.println(file.toURL().toString() <del> + "was supposed to be invalid but was not."); <add> + " was supposed to be invalid but was not."); <ide> err.flush(); <ide> } catch (MalformedURLException e) { <ide> throw new RuntimeException(e);
JavaScript
mit
864b4d3dbc187ce8d8af3ccb466dd9a6b1f67416
0
mobyan/thc-platform,mobyan/thc-platform,mobyan/thc-platform,mobyan/thc-platform
export default [{ "name": "SOILMTYXR1_H", "desc": "土壤传感器,采集的数据为湿度H", "unit": "%", "type": "humility" }, { "name": "SOILMTYXR1_T", "desc": "土壤传感器,采集的数据为温度T", "unit": "℃", "type": "temperature" }, { "name": "CWS1806A1AG_H", "desc": "环境传感器, 采集的数据为湿度H", "unit": "%", "type": "humility" }, { "name": "CWS1806A1AG_T", "desc": "环境传感器, 采集的数据为温度T", "unit": "℃", "type": "temperature" }, { "name": "NHZD1CI_S", "desc": "光照传感器, 采集的数据为光照S(lux)", "unit": "lux", "type": "solar-radiation" }, { "name": "NHFS45B1_WS", "desc": "风速传感器,采集的数据为风速WS", "unit": "m/s", "type": "wind-velocity" }, { "name": "NHFX46A1_WD", "desc": " 风向传感器, 采集的数据为风向WD", "unit": "°", "type": "wind-direction" }, { "name": "KAVT2_V", "desc": "电压传感器,采集的数据为电压V", "unit": "V", "type": "voltage" }, { "name": "DAVIS785_R", "desc": "雨量传感器,采集的数据为降雨量R", "unit": "mm", "type": "rainfall" }, { "name": "HIKVISION_CAM_I", "desc": "图像传感器,采集数据为图像I", "unit": "", "type": "image" }]
src/resources/assets/js/configs/sensors.js
export default [{ "name": "SOILMTYXR1_H", "desc": "土壤传感器,采集的数据为湿度H", "unit": "%", "type": "humility" }, { "name": "SOILMTYXR1_T", "desc": "土壤传感器,采集的数据为温度T", "unit": "℃", "type": "temperature" }, { "name": "CWS1806A1AG_H", "desc": "环境传感器, 采集的数据为湿度H", "unit": "%", "type": "humility" }, { "name": "CWS1806A1AG_T", "desc": "环境传感器, 采集的数据为温度T", "unit": "℃", "type": "temperature" }, { "name": "NHZD1CI_S", "desc": "光照传感器, 采集的数据为光照S(lux)", "unit": "lux", "type": "solar-radiation" }, { "name": "NHFS45B1_WS", "desc": "风速传感器,采集的数据为风速WS", "unit": "m/s", "type": "wind-velocity" }, { "name": "NHFX46A1_WD", "desc": " 风向传感器, 采集的数据为风向WD", "unit": "°", "type": "wind-direction" }, { "name": "KAVT2_V", "desc": "电压传感器,采集的数据为电压V", "unit": "V", "type": "voltage" }, { "name": "DAVIS785_R", "desc": "雨量传感器,采集的数据为降雨量R", "unit": "mm", "type": "rainfall" }]
add image sensor
src/resources/assets/js/configs/sensors.js
add image sensor
<ide><path>rc/resources/assets/js/configs/sensors.js <ide> "desc": "雨量传感器,采集的数据为降雨量R", <ide> "unit": "mm", <ide> "type": "rainfall" <add>}, { <add> "name": "HIKVISION_CAM_I", <add> "desc": "图像传感器,采集数据为图像I", <add> "unit": "", <add> "type": "image" <ide> }]
Java
apache-2.0
dd3f1e4a681e5c8e58ba3a1ebbf75ba0861ff456
0
apache/helix,apache/helix,lei-xia/helix,dasahcc/helix,lei-xia/helix,lei-xia/helix,lei-xia/helix,apache/helix,dasahcc/helix,dasahcc/helix,apache/helix,lei-xia/helix,dasahcc/helix,apache/helix,apache/helix,dasahcc/helix,lei-xia/helix,dasahcc/helix
package org.apache.helix; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.I0Itec.zkclient.IZkStateListener; import org.I0Itec.zkclient.ZkConnection; import org.I0Itec.zkclient.ZkServer; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.controller.pipeline.Pipeline; import org.apache.helix.controller.pipeline.Stage; import org.apache.helix.controller.pipeline.StageContext; import org.apache.helix.controller.stages.ClusterEvent; import org.apache.helix.manager.zk.ZKHelixAdmin; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZNRecordSerializer; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.manager.zk.ZkClient; import org.apache.helix.model.CurrentState; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.IdealState.RebalanceMode; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.LiveInstance; import org.apache.helix.model.Message; import org.apache.helix.model.Message.Attributes; import org.apache.helix.model.Message.MessageType; import org.apache.helix.model.StateModelDefinition; import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier; import org.apache.helix.tools.StateModelConfigGenerator; import org.apache.helix.util.ZKClientPool; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; // TODO merge code with ZkIntegrationTestBase public class ZkUnitTestBase { private static Logger LOG = LoggerFactory.getLogger(ZkUnitTestBase.class); protected static ZkServer _zkServer = null; protected static ZkClient _gZkClient; public static final String ZK_ADDR = "localhost:2185"; protected static final String CLUSTER_PREFIX = "CLUSTER"; protected static final String CONTROLLER_CLUSTER_PREFIX = "CONTROLLER_CLUSTER"; @BeforeSuite(alwaysRun = true) public void beforeSuite() throws Exception { // Due to ZOOKEEPER-2693 fix, we need to specify whitelist for execute zk commends System.setProperty("zookeeper.4lw.commands.whitelist", "*"); _zkServer = TestHelper.startZkServer(ZK_ADDR); AssertJUnit.assertTrue(_zkServer != null); ZKClientPool.reset(); // System.out.println("Number of open zkClient before ZkUnitTests: " // + ZkClient.getNumberOfConnections()); _gZkClient = new ZkClient(ZK_ADDR); _gZkClient.setZkSerializer(new ZNRecordSerializer()); } @AfterSuite(alwaysRun = true) public void afterSuite() { _gZkClient.close(); TestHelper.stopZkServer(_zkServer); _zkServer = null; // System.out.println("Number of open zkClient after ZkUnitTests: " // + ZkClient.getNumberOfConnections()); } protected String getShortClassName() { String className = this.getClass().getName(); return className.substring(className.lastIndexOf('.') + 1); } protected String getCurrentLeader(ZkClient zkClient, String clusterName) { String leaderPath = PropertyPathBuilder.controllerLeader(clusterName); ZNRecord leaderRecord = zkClient.<ZNRecord> readData(leaderPath); if (leaderRecord == null) { return null; } String leader = leaderRecord.getSimpleField(PropertyType.LEADER.toString()); return leader; } protected void stopCurrentLeader(ZkClient zkClient, String clusterName, Map<String, Thread> threadMap, Map<String, HelixManager> managerMap) { String leader = getCurrentLeader(zkClient, clusterName); Assert.assertTrue(leader != null); System.out.println("stop leader:" + leader + " in " + clusterName); Assert.assertTrue(leader != null); HelixManager manager = managerMap.remove(leader); Assert.assertTrue(manager != null); manager.disconnect(); Thread thread = threadMap.remove(leader); Assert.assertTrue(thread != null); thread.interrupt(); boolean isNewLeaderElected = false; try { // Thread.sleep(2000); for (int i = 0; i < 5; i++) { Thread.sleep(1000); String newLeader = getCurrentLeader(zkClient, clusterName); if (!newLeader.equals(leader)) { isNewLeaderElected = true; System.out.println("new leader elected: " + newLeader + " in " + clusterName); break; } } } catch (InterruptedException e) { e.printStackTrace(); } if (isNewLeaderElected == false) { System.out.println("fail to elect a new leader elected in " + clusterName); } AssertJUnit.assertTrue(isNewLeaderElected); } public void verifyInstance(ZkClient zkClient, String clusterName, String instance, boolean wantExists) { // String instanceConfigsPath = HelixUtil.getConfigPath(clusterName); String instanceConfigsPath = PropertyPathBuilder.instanceConfig(clusterName); String instanceConfigPath = instanceConfigsPath + "/" + instance; String instancePath = PropertyPathBuilder.instance(clusterName, instance); AssertJUnit.assertEquals(wantExists, zkClient.exists(instanceConfigPath)); AssertJUnit.assertEquals(wantExists, zkClient.exists(instancePath)); } public void verifyResource(ZkClient zkClient, String clusterName, String resource, boolean wantExists) { String resourcePath = PropertyPathBuilder.idealState(clusterName, resource); AssertJUnit.assertEquals(wantExists, zkClient.exists(resourcePath)); } public void verifyEnabled(ZkClient zkClient, String clusterName, String instance, boolean wantEnabled) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); Builder keyBuilder = accessor.keyBuilder(); InstanceConfig config = accessor.getProperty(keyBuilder.instanceConfig(instance)); AssertJUnit.assertEquals(wantEnabled, config.getInstanceEnabled()); } public void verifyReplication(ZkClient zkClient, String clusterName, String resource, int repl) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); Builder keyBuilder = accessor.keyBuilder(); IdealState idealState = accessor.getProperty(keyBuilder.idealStates(resource)); for (String partitionName : idealState.getPartitionSet()) { if (idealState.getRebalanceMode() == RebalanceMode.SEMI_AUTO) { AssertJUnit.assertEquals(repl, idealState.getPreferenceList(partitionName).size()); } else if (idealState.getRebalanceMode() == RebalanceMode.CUSTOMIZED) { AssertJUnit.assertEquals(repl, idealState.getInstanceStateMap(partitionName).size()); } } } protected void simulateSessionExpiry(ZkConnection zkConnection) throws IOException, InterruptedException { ZooKeeper oldZookeeper = zkConnection.getZookeeper(); LOG.info("Old sessionId = " + oldZookeeper.getSessionId()); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("In New connection, process event:" + event); } }; ZooKeeper newZookeeper = new ZooKeeper(zkConnection.getServers(), oldZookeeper.getSessionTimeout(), watcher, oldZookeeper.getSessionId(), oldZookeeper.getSessionPasswd()); LOG.info("New sessionId = " + newZookeeper.getSessionId()); // Thread.sleep(3000); newZookeeper.close(); Thread.sleep(10000); oldZookeeper = zkConnection.getZookeeper(); LOG.info("After session expiry sessionId = " + oldZookeeper.getSessionId()); } protected void simulateSessionExpiry(ZkClient zkClient) throws IOException, InterruptedException { IZkStateListener listener = new IZkStateListener() { @Override public void handleStateChanged(KeeperState state) throws Exception { LOG.info("In Old connection, state changed:" + state); } @Override public void handleNewSession() throws Exception { LOG.info("In Old connection, new session"); } @Override public void handleSessionEstablishmentError(Throwable var1) throws Exception { } }; zkClient.subscribeStateChanges(listener); ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper oldZookeeper = connection.getZookeeper(); LOG.info("Old sessionId = " + oldZookeeper.getSessionId()); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("In New connection, process event:" + event); } }; ZooKeeper newZookeeper = new ZooKeeper(connection.getServers(), oldZookeeper.getSessionTimeout(), watcher, oldZookeeper.getSessionId(), oldZookeeper.getSessionPasswd()); LOG.info("New sessionId = " + newZookeeper.getSessionId()); // Thread.sleep(3000); newZookeeper.close(); Thread.sleep(10000); connection = (ZkConnection) zkClient.getConnection(); oldZookeeper = connection.getZookeeper(); LOG.info("After session expiry sessionId = " + oldZookeeper.getSessionId()); } protected void setupStateModel(String clusterName) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); StateModelDefinition masterSlave = new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave()); accessor.setProperty(keyBuilder.stateModelDef(masterSlave.getId()), masterSlave); StateModelDefinition leaderStandby = new StateModelDefinition(StateModelConfigGenerator.generateConfigForLeaderStandby()); accessor.setProperty(keyBuilder.stateModelDef(leaderStandby.getId()), leaderStandby); StateModelDefinition onlineOffline = new StateModelDefinition(StateModelConfigGenerator.generateConfigForOnlineOffline()); accessor.setProperty(keyBuilder.stateModelDef(onlineOffline.getId()), onlineOffline); } protected List<IdealState> setupIdealState(String clusterName, int[] nodes, String[] resources, int partitions, int replicas) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); List<IdealState> idealStates = new ArrayList<IdealState>(); List<String> instances = new ArrayList<String>(); for (int i : nodes) { instances.add("localhost_" + i); } for (String resourceName : resources) { IdealState idealState = new IdealState(resourceName); for (int p = 0; p < partitions; p++) { List<String> value = new ArrayList<String>(); for (int r = 0; r < replicas; r++) { int n = nodes[(p + r) % nodes.length]; value.add("localhost_" + n); } idealState.getRecord().setListField(resourceName + "_" + p, value); } idealState.setReplicas(Integer.toString(replicas)); idealState.setStateModelDefRef("MasterSlave"); idealState.setRebalanceMode(RebalanceMode.SEMI_AUTO); idealState.setNumPartitions(partitions); idealStates.add(idealState); // System.out.println(idealState); accessor.setProperty(keyBuilder.idealStates(resourceName), idealState); } return idealStates; } protected void setupLiveInstances(String clusterName, int[] liveInstances) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); for (int i = 0; i < liveInstances.length; i++) { String instance = "localhost_" + liveInstances[i]; LiveInstance liveInstance = new LiveInstance(instance); liveInstance.setSessionId("session_" + liveInstances[i]); liveInstance.setHelixVersion("0.0.0"); accessor.setProperty(keyBuilder.liveInstance(instance), liveInstance); } } protected void setupInstances(String clusterName, int[] instances) { HelixAdmin admin = new ZKHelixAdmin(_gZkClient); for (int i = 0; i < instances.length; i++) { String instance = "localhost_" + instances[i]; InstanceConfig instanceConfig = new InstanceConfig(instance); instanceConfig.setHostName("localhost"); instanceConfig.setPort("" + instances[i]); instanceConfig.setInstanceEnabled(true); admin.addInstance(clusterName, instanceConfig); } } protected void runPipeline(ClusterEvent event, Pipeline pipeline) { try { pipeline.handle(event); pipeline.finish(); } catch (Exception e) { LOG.error("Exception while executing pipeline:" + pipeline + ". Will not continue to next pipeline", e); } } protected void runStage(ClusterEvent event, Stage stage) throws Exception { StageContext context = new StageContext(); stage.init(context); stage.preProcess(); stage.process(event); stage.postProcess(); } protected Message createMessage(MessageType type, String msgId, String fromState, String toState, String resourceName, String tgtName) { Message msg = new Message(type.toString(), msgId); msg.setFromState(fromState); msg.setToState(toState); msg.getRecord().setSimpleField(Attributes.RESOURCE_NAME.toString(), resourceName); msg.setTgtName(tgtName); return msg; } /** * Poll for the existence (or lack thereof) of a specific Helix property * @param clazz the HelixProeprty subclass * @param accessor connected HelixDataAccessor * @param key the property key to look up * @param shouldExist true if the property should exist, false otherwise * @return the property if found, or null if it does not exist */ protected <T extends HelixProperty> T pollForProperty(Class<T> clazz, HelixDataAccessor accessor, PropertyKey key, boolean shouldExist) throws InterruptedException { final int POLL_TIMEOUT = 5000; final int POLL_INTERVAL = 50; T property = accessor.getProperty(key); int timeWaited = 0; while (((shouldExist && property == null) || (!shouldExist && property != null)) && timeWaited < POLL_TIMEOUT) { Thread.sleep(POLL_INTERVAL); timeWaited += POLL_INTERVAL; property = accessor.getProperty(key); } return property; } /** * Ensures that external view and current state are empty */ protected static class EmptyZkVerifier implements ZkVerifier { private final String _clusterName; private final String _resourceName; private final ZkClient _zkClient; /** * Instantiate the verifier * @param clusterName the cluster to verify * @param resourceName the resource to verify */ public EmptyZkVerifier(String clusterName, String resourceName) { _clusterName = clusterName; _resourceName = resourceName; _zkClient = ZKClientPool.getZkClient(ZK_ADDR); } @Override public boolean verify() { BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_zkClient); HelixDataAccessor accessor = new ZKHelixDataAccessor(_clusterName, baseAccessor); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); ExternalView externalView = accessor.getProperty(keyBuilder.externalView(_resourceName)); // verify external view empty if (externalView != null) { for (String partition : externalView.getPartitionSet()) { Map<String, String> stateMap = externalView.getStateMap(partition); if (stateMap != null && !stateMap.isEmpty()) { LOG.error("External view not empty for " + partition); return false; } } } // verify current state empty List<String> liveParticipants = accessor.getChildNames(keyBuilder.liveInstances()); for (String participant : liveParticipants) { List<String> sessionIds = accessor.getChildNames(keyBuilder.sessions(participant)); for (String sessionId : sessionIds) { CurrentState currentState = accessor.getProperty(keyBuilder.currentState(participant, sessionId, _resourceName)); Map<String, String> partitionStateMap = currentState.getPartitionStateMap(); if (partitionStateMap != null && !partitionStateMap.isEmpty()) { LOG.error("Current state not empty for " + participant); return false; } } } return true; } @Override public ZkClient getZkClient() { return _zkClient; } @Override public String getClusterName() { return _clusterName; } } }
helix-core/src/test/java/org/apache/helix/ZkUnitTestBase.java
package org.apache.helix; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.I0Itec.zkclient.IZkStateListener; import org.I0Itec.zkclient.ZkConnection; import org.I0Itec.zkclient.ZkServer; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.controller.pipeline.Pipeline; import org.apache.helix.controller.pipeline.Stage; import org.apache.helix.controller.pipeline.StageContext; import org.apache.helix.controller.stages.ClusterEvent; import org.apache.helix.manager.zk.ZKHelixAdmin; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZNRecordSerializer; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.manager.zk.ZkClient; import org.apache.helix.model.CurrentState; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.IdealState.RebalanceMode; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.LiveInstance; import org.apache.helix.model.Message; import org.apache.helix.model.Message.Attributes; import org.apache.helix.model.Message.MessageType; import org.apache.helix.model.StateModelDefinition; import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier; import org.apache.helix.tools.StateModelConfigGenerator; import org.apache.helix.util.ZKClientPool; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; // TODO merge code with ZkIntegrationTestBase public class ZkUnitTestBase { private static Logger LOG = LoggerFactory.getLogger(ZkUnitTestBase.class); protected static ZkServer _zkServer = null; protected static ZkClient _gZkClient; public static final String ZK_ADDR = "localhost:2185"; protected static final String CLUSTER_PREFIX = "CLUSTER"; protected static final String CONTROLLER_CLUSTER_PREFIX = "CONTROLLER_CLUSTER"; @BeforeSuite(alwaysRun = true) public void beforeSuite() throws Exception { _zkServer = TestHelper.startZkServer(ZK_ADDR); AssertJUnit.assertTrue(_zkServer != null); ZKClientPool.reset(); // System.out.println("Number of open zkClient before ZkUnitTests: " // + ZkClient.getNumberOfConnections()); _gZkClient = new ZkClient(ZK_ADDR); _gZkClient.setZkSerializer(new ZNRecordSerializer()); } @AfterSuite(alwaysRun = true) public void afterSuite() { _gZkClient.close(); TestHelper.stopZkServer(_zkServer); _zkServer = null; // System.out.println("Number of open zkClient after ZkUnitTests: " // + ZkClient.getNumberOfConnections()); } protected String getShortClassName() { String className = this.getClass().getName(); return className.substring(className.lastIndexOf('.') + 1); } protected String getCurrentLeader(ZkClient zkClient, String clusterName) { String leaderPath = PropertyPathBuilder.controllerLeader(clusterName); ZNRecord leaderRecord = zkClient.<ZNRecord> readData(leaderPath); if (leaderRecord == null) { return null; } String leader = leaderRecord.getSimpleField(PropertyType.LEADER.toString()); return leader; } protected void stopCurrentLeader(ZkClient zkClient, String clusterName, Map<String, Thread> threadMap, Map<String, HelixManager> managerMap) { String leader = getCurrentLeader(zkClient, clusterName); Assert.assertTrue(leader != null); System.out.println("stop leader:" + leader + " in " + clusterName); Assert.assertTrue(leader != null); HelixManager manager = managerMap.remove(leader); Assert.assertTrue(manager != null); manager.disconnect(); Thread thread = threadMap.remove(leader); Assert.assertTrue(thread != null); thread.interrupt(); boolean isNewLeaderElected = false; try { // Thread.sleep(2000); for (int i = 0; i < 5; i++) { Thread.sleep(1000); String newLeader = getCurrentLeader(zkClient, clusterName); if (!newLeader.equals(leader)) { isNewLeaderElected = true; System.out.println("new leader elected: " + newLeader + " in " + clusterName); break; } } } catch (InterruptedException e) { e.printStackTrace(); } if (isNewLeaderElected == false) { System.out.println("fail to elect a new leader elected in " + clusterName); } AssertJUnit.assertTrue(isNewLeaderElected); } public void verifyInstance(ZkClient zkClient, String clusterName, String instance, boolean wantExists) { // String instanceConfigsPath = HelixUtil.getConfigPath(clusterName); String instanceConfigsPath = PropertyPathBuilder.instanceConfig(clusterName); String instanceConfigPath = instanceConfigsPath + "/" + instance; String instancePath = PropertyPathBuilder.instance(clusterName, instance); AssertJUnit.assertEquals(wantExists, zkClient.exists(instanceConfigPath)); AssertJUnit.assertEquals(wantExists, zkClient.exists(instancePath)); } public void verifyResource(ZkClient zkClient, String clusterName, String resource, boolean wantExists) { String resourcePath = PropertyPathBuilder.idealState(clusterName, resource); AssertJUnit.assertEquals(wantExists, zkClient.exists(resourcePath)); } public void verifyEnabled(ZkClient zkClient, String clusterName, String instance, boolean wantEnabled) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); Builder keyBuilder = accessor.keyBuilder(); InstanceConfig config = accessor.getProperty(keyBuilder.instanceConfig(instance)); AssertJUnit.assertEquals(wantEnabled, config.getInstanceEnabled()); } public void verifyReplication(ZkClient zkClient, String clusterName, String resource, int repl) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); Builder keyBuilder = accessor.keyBuilder(); IdealState idealState = accessor.getProperty(keyBuilder.idealStates(resource)); for (String partitionName : idealState.getPartitionSet()) { if (idealState.getRebalanceMode() == RebalanceMode.SEMI_AUTO) { AssertJUnit.assertEquals(repl, idealState.getPreferenceList(partitionName).size()); } else if (idealState.getRebalanceMode() == RebalanceMode.CUSTOMIZED) { AssertJUnit.assertEquals(repl, idealState.getInstanceStateMap(partitionName).size()); } } } protected void simulateSessionExpiry(ZkConnection zkConnection) throws IOException, InterruptedException { ZooKeeper oldZookeeper = zkConnection.getZookeeper(); LOG.info("Old sessionId = " + oldZookeeper.getSessionId()); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("In New connection, process event:" + event); } }; ZooKeeper newZookeeper = new ZooKeeper(zkConnection.getServers(), oldZookeeper.getSessionTimeout(), watcher, oldZookeeper.getSessionId(), oldZookeeper.getSessionPasswd()); LOG.info("New sessionId = " + newZookeeper.getSessionId()); // Thread.sleep(3000); newZookeeper.close(); Thread.sleep(10000); oldZookeeper = zkConnection.getZookeeper(); LOG.info("After session expiry sessionId = " + oldZookeeper.getSessionId()); } protected void simulateSessionExpiry(ZkClient zkClient) throws IOException, InterruptedException { IZkStateListener listener = new IZkStateListener() { @Override public void handleStateChanged(KeeperState state) throws Exception { LOG.info("In Old connection, state changed:" + state); } @Override public void handleNewSession() throws Exception { LOG.info("In Old connection, new session"); } @Override public void handleSessionEstablishmentError(Throwable var1) throws Exception { } }; zkClient.subscribeStateChanges(listener); ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper oldZookeeper = connection.getZookeeper(); LOG.info("Old sessionId = " + oldZookeeper.getSessionId()); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("In New connection, process event:" + event); } }; ZooKeeper newZookeeper = new ZooKeeper(connection.getServers(), oldZookeeper.getSessionTimeout(), watcher, oldZookeeper.getSessionId(), oldZookeeper.getSessionPasswd()); LOG.info("New sessionId = " + newZookeeper.getSessionId()); // Thread.sleep(3000); newZookeeper.close(); Thread.sleep(10000); connection = (ZkConnection) zkClient.getConnection(); oldZookeeper = connection.getZookeeper(); LOG.info("After session expiry sessionId = " + oldZookeeper.getSessionId()); } protected void setupStateModel(String clusterName) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); StateModelDefinition masterSlave = new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave()); accessor.setProperty(keyBuilder.stateModelDef(masterSlave.getId()), masterSlave); StateModelDefinition leaderStandby = new StateModelDefinition(StateModelConfigGenerator.generateConfigForLeaderStandby()); accessor.setProperty(keyBuilder.stateModelDef(leaderStandby.getId()), leaderStandby); StateModelDefinition onlineOffline = new StateModelDefinition(StateModelConfigGenerator.generateConfigForOnlineOffline()); accessor.setProperty(keyBuilder.stateModelDef(onlineOffline.getId()), onlineOffline); } protected List<IdealState> setupIdealState(String clusterName, int[] nodes, String[] resources, int partitions, int replicas) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); List<IdealState> idealStates = new ArrayList<IdealState>(); List<String> instances = new ArrayList<String>(); for (int i : nodes) { instances.add("localhost_" + i); } for (String resourceName : resources) { IdealState idealState = new IdealState(resourceName); for (int p = 0; p < partitions; p++) { List<String> value = new ArrayList<String>(); for (int r = 0; r < replicas; r++) { int n = nodes[(p + r) % nodes.length]; value.add("localhost_" + n); } idealState.getRecord().setListField(resourceName + "_" + p, value); } idealState.setReplicas(Integer.toString(replicas)); idealState.setStateModelDefRef("MasterSlave"); idealState.setRebalanceMode(RebalanceMode.SEMI_AUTO); idealState.setNumPartitions(partitions); idealStates.add(idealState); // System.out.println(idealState); accessor.setProperty(keyBuilder.idealStates(resourceName), idealState); } return idealStates; } protected void setupLiveInstances(String clusterName, int[] liveInstances) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); for (int i = 0; i < liveInstances.length; i++) { String instance = "localhost_" + liveInstances[i]; LiveInstance liveInstance = new LiveInstance(instance); liveInstance.setSessionId("session_" + liveInstances[i]); liveInstance.setHelixVersion("0.0.0"); accessor.setProperty(keyBuilder.liveInstance(instance), liveInstance); } } protected void setupInstances(String clusterName, int[] instances) { HelixAdmin admin = new ZKHelixAdmin(_gZkClient); for (int i = 0; i < instances.length; i++) { String instance = "localhost_" + instances[i]; InstanceConfig instanceConfig = new InstanceConfig(instance); instanceConfig.setHostName("localhost"); instanceConfig.setPort("" + instances[i]); instanceConfig.setInstanceEnabled(true); admin.addInstance(clusterName, instanceConfig); } } protected void runPipeline(ClusterEvent event, Pipeline pipeline) { try { pipeline.handle(event); pipeline.finish(); } catch (Exception e) { LOG.error("Exception while executing pipeline:" + pipeline + ". Will not continue to next pipeline", e); } } protected void runStage(ClusterEvent event, Stage stage) throws Exception { StageContext context = new StageContext(); stage.init(context); stage.preProcess(); stage.process(event); stage.postProcess(); } protected Message createMessage(MessageType type, String msgId, String fromState, String toState, String resourceName, String tgtName) { Message msg = new Message(type.toString(), msgId); msg.setFromState(fromState); msg.setToState(toState); msg.getRecord().setSimpleField(Attributes.RESOURCE_NAME.toString(), resourceName); msg.setTgtName(tgtName); return msg; } /** * Poll for the existence (or lack thereof) of a specific Helix property * @param clazz the HelixProeprty subclass * @param accessor connected HelixDataAccessor * @param key the property key to look up * @param shouldExist true if the property should exist, false otherwise * @return the property if found, or null if it does not exist */ protected <T extends HelixProperty> T pollForProperty(Class<T> clazz, HelixDataAccessor accessor, PropertyKey key, boolean shouldExist) throws InterruptedException { final int POLL_TIMEOUT = 5000; final int POLL_INTERVAL = 50; T property = accessor.getProperty(key); int timeWaited = 0; while (((shouldExist && property == null) || (!shouldExist && property != null)) && timeWaited < POLL_TIMEOUT) { Thread.sleep(POLL_INTERVAL); timeWaited += POLL_INTERVAL; property = accessor.getProperty(key); } return property; } /** * Ensures that external view and current state are empty */ protected static class EmptyZkVerifier implements ZkVerifier { private final String _clusterName; private final String _resourceName; private final ZkClient _zkClient; /** * Instantiate the verifier * @param clusterName the cluster to verify * @param resourceName the resource to verify */ public EmptyZkVerifier(String clusterName, String resourceName) { _clusterName = clusterName; _resourceName = resourceName; _zkClient = ZKClientPool.getZkClient(ZK_ADDR); } @Override public boolean verify() { BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_zkClient); HelixDataAccessor accessor = new ZKHelixDataAccessor(_clusterName, baseAccessor); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); ExternalView externalView = accessor.getProperty(keyBuilder.externalView(_resourceName)); // verify external view empty if (externalView != null) { for (String partition : externalView.getPartitionSet()) { Map<String, String> stateMap = externalView.getStateMap(partition); if (stateMap != null && !stateMap.isEmpty()) { LOG.error("External view not empty for " + partition); return false; } } } // verify current state empty List<String> liveParticipants = accessor.getChildNames(keyBuilder.liveInstances()); for (String participant : liveParticipants) { List<String> sessionIds = accessor.getChildNames(keyBuilder.sessions(participant)); for (String sessionId : sessionIds) { CurrentState currentState = accessor.getProperty(keyBuilder.currentState(participant, sessionId, _resourceName)); Map<String, String> partitionStateMap = currentState.getPartitionStateMap(); if (partitionStateMap != null && !partitionStateMap.isEmpty()) { LOG.error("Current state not empty for " + participant); return false; } } } return true; } @Override public ZkClient getZkClient() { return _zkClient; } @Override public String getClusterName() { return _clusterName; } } }
[HELIX-680] add system setting to unblock TestZkCallbackHandlerLeak test with zookeeper 3.4.11 upgrade
helix-core/src/test/java/org/apache/helix/ZkUnitTestBase.java
[HELIX-680] add system setting to unblock TestZkCallbackHandlerLeak test with zookeeper 3.4.11 upgrade
<ide><path>elix-core/src/test/java/org/apache/helix/ZkUnitTestBase.java <ide> <ide> @BeforeSuite(alwaysRun = true) <ide> public void beforeSuite() throws Exception { <add> // Due to ZOOKEEPER-2693 fix, we need to specify whitelist for execute zk commends <add> System.setProperty("zookeeper.4lw.commands.whitelist", "*"); <add> <ide> _zkServer = TestHelper.startZkServer(ZK_ADDR); <ide> AssertJUnit.assertTrue(_zkServer != null); <ide> ZKClientPool.reset();
JavaScript
mit
a5ad00865c35dc3d772596b25af643e5d73097d8
0
northernnhs/northernnhs.github.io,northernnhs/northernnhs.github.io
/*$(document).ready(function () { $.getJSON("https://jsonip.com/?callback=?", function (data) { //console.log(data); //console.log(data.ip.toString()); //alert(data.ip); $('#v4').html(data.ip.toString()); $('#v6').html('<a href="https://docs.google.com/forms/d/e/1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ/viewform?usp=pp_url&entry.1359815136=1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ;'+data.ip.toString()+';'+(new Date()).toString()+';1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ">Click here.</a>'); }); });*/ var _0xe2a5=["\x68\x74\x74\x70\x73\x3A\x2F\x2F\x6A\x73\x6F\x6E\x69\x70\x2E\x63\x6F\x6D\x2F\x3F\x63\x61\x6C\x6C\x62\x61\x63\x6B\x3D\x3F","\x69\x70","\x68\x74\x6D\x6C","\x23\x76\x34","\x3C\x61\x20\x68\x72\x65\x66\x3D\x22\x68\x74\x74\x70\x73\x3A\x2F\x2F\x64\x6F\x63\x73\x2E\x67\x6F\x6F\x67\x6C\x65\x2E\x63\x6F\x6D\x2F\x66\x6F\x72\x6D\x73\x2F\x64\x2F\x65\x2F\x31\x46\x41\x49\x70\x51\x4C\x53\x66\x44\x75\x36\x6E\x50\x56\x6D\x52\x78\x76\x6B\x31\x41\x43\x30\x6A\x67\x64\x39\x42\x70\x56\x4C\x42\x4B\x67\x55\x6F\x4C\x53\x41\x4F\x31\x34\x77\x77\x65\x36\x68\x67\x53\x4F\x6B\x4A\x75\x76\x51\x2F\x76\x69\x65\x77\x66\x6F\x72\x6D\x3F\x75\x73\x70\x3D\x70\x70\x5F\x75\x72\x6C\x26\x65\x6E\x74\x72\x79\x2E\x31\x33\x35\x39\x38\x31\x35\x31\x33\x36\x3D\x31\x46\x41\x49\x70\x51\x4C\x53\x66\x44\x75\x36\x6E\x50\x56\x6D\x52\x78\x76\x6B\x31\x41\x43\x30\x6A\x67\x64\x39\x42\x70\x56\x4C\x42\x4B\x67\x55\x6F\x4C\x53\x41\x4F\x31\x34\x77\x77\x65\x36\x68\x67\x53\x4F\x6B\x4A\x75\x76\x51\x3B","\x3B","\x3B\x31\x46\x41\x49\x70\x51\x4C\x53\x66\x44\x75\x36\x6E\x50\x56\x6D\x52\x78\x76\x6B\x31\x41\x43\x30\x6A\x67\x64\x39\x42\x70\x56\x4C\x42\x4B\x67\x55\x6F\x4C\x53\x41\x4F\x31\x34\x77\x77\x65\x36\x68\x67\x53\x4F\x6B\x4A\x75\x76\x51\x22\x3E\x43\x6C\x69\x63\x6B\x20\x68\x65\x72\x65\x2E\x3C\x2F\x61\x3E","\x23\x76\x36","\x67\x65\x74\x4A\x53\x4F\x4E","\x72\x65\x61\x64\x79"];$(document)[_0xe2a5[9]](function(){$[_0xe2a5[8]](_0xe2a5[0],function(_0x777fx1){$(_0xe2a5[3])[_0xe2a5[2]](_0x777fx1[_0xe2a5[1]].toString());$(_0xe2a5[7])[_0xe2a5[2]](_0xe2a5[4]+ _0x777fx1[_0xe2a5[1]].toString()+ _0xe2a5[5]+ ( new Date()).toString()+ _0xe2a5[6])})})
main.js
$(document).ready(function () { $.getJSON("https://jsonip.com/?callback=?", function (data) { //console.log(data); //console.log(data.ip.toString()); //alert(data.ip); $('#v4').html(data.ip.toString()); $('#v6').html('<a href="https://docs.google.com/forms/d/e/1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ/viewform?usp=pp_url&entry.1359815136=1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ;'+data.ip.toString()+';'+(new Date()).toString()+';1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ">Click here.</a>'); }); });
Obfuscate JS code.
main.js
Obfuscate JS code.
<ide><path>ain.js <del>$(document).ready(function () { <add>/*$(document).ready(function () { <ide> $.getJSON("https://jsonip.com/?callback=?", function (data) { <ide> //console.log(data); <ide> //console.log(data.ip.toString()); <ide> $('#v4').html(data.ip.toString()); <ide> $('#v6').html('<a href="https://docs.google.com/forms/d/e/1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ/viewform?usp=pp_url&entry.1359815136=1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ;'+data.ip.toString()+';'+(new Date()).toString()+';1FAIpQLSfDu6nPVmRxvk1AC0jgd9BpVLBKgUoLSAO14wwe6hgSOkJuvQ">Click here.</a>'); <ide> }); <del>}); <add>});*/ <add>var _0xe2a5=["\x68\x74\x74\x70\x73\x3A\x2F\x2F\x6A\x73\x6F\x6E\x69\x70\x2E\x63\x6F\x6D\x2F\x3F\x63\x61\x6C\x6C\x62\x61\x63\x6B\x3D\x3F","\x69\x70","\x68\x74\x6D\x6C","\x23\x76\x34","\x3C\x61\x20\x68\x72\x65\x66\x3D\x22\x68\x74\x74\x70\x73\x3A\x2F\x2F\x64\x6F\x63\x73\x2E\x67\x6F\x6F\x67\x6C\x65\x2E\x63\x6F\x6D\x2F\x66\x6F\x72\x6D\x73\x2F\x64\x2F\x65\x2F\x31\x46\x41\x49\x70\x51\x4C\x53\x66\x44\x75\x36\x6E\x50\x56\x6D\x52\x78\x76\x6B\x31\x41\x43\x30\x6A\x67\x64\x39\x42\x70\x56\x4C\x42\x4B\x67\x55\x6F\x4C\x53\x41\x4F\x31\x34\x77\x77\x65\x36\x68\x67\x53\x4F\x6B\x4A\x75\x76\x51\x2F\x76\x69\x65\x77\x66\x6F\x72\x6D\x3F\x75\x73\x70\x3D\x70\x70\x5F\x75\x72\x6C\x26\x65\x6E\x74\x72\x79\x2E\x31\x33\x35\x39\x38\x31\x35\x31\x33\x36\x3D\x31\x46\x41\x49\x70\x51\x4C\x53\x66\x44\x75\x36\x6E\x50\x56\x6D\x52\x78\x76\x6B\x31\x41\x43\x30\x6A\x67\x64\x39\x42\x70\x56\x4C\x42\x4B\x67\x55\x6F\x4C\x53\x41\x4F\x31\x34\x77\x77\x65\x36\x68\x67\x53\x4F\x6B\x4A\x75\x76\x51\x3B","\x3B","\x3B\x31\x46\x41\x49\x70\x51\x4C\x53\x66\x44\x75\x36\x6E\x50\x56\x6D\x52\x78\x76\x6B\x31\x41\x43\x30\x6A\x67\x64\x39\x42\x70\x56\x4C\x42\x4B\x67\x55\x6F\x4C\x53\x41\x4F\x31\x34\x77\x77\x65\x36\x68\x67\x53\x4F\x6B\x4A\x75\x76\x51\x22\x3E\x43\x6C\x69\x63\x6B\x20\x68\x65\x72\x65\x2E\x3C\x2F\x61\x3E","\x23\x76\x36","\x67\x65\x74\x4A\x53\x4F\x4E","\x72\x65\x61\x64\x79"];$(document)[_0xe2a5[9]](function(){$[_0xe2a5[8]](_0xe2a5[0],function(_0x777fx1){$(_0xe2a5[3])[_0xe2a5[2]](_0x777fx1[_0xe2a5[1]].toString());$(_0xe2a5[7])[_0xe2a5[2]](_0xe2a5[4]+ _0x777fx1[_0xe2a5[1]].toString()+ _0xe2a5[5]+ ( new Date()).toString()+ _0xe2a5[6])})})
Java
apache-2.0
e442aab9e27b29aa271b347945a799e7df51465d
0
searchbox/framework,searchbox/framework,searchbox/framework
package com.searchbox.core.search.result; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.elasticsearch.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.searchbox.core.SearchAdapter; import com.searchbox.core.SearchAdapter.Time; import com.searchbox.core.SearchAdapterMethod; import com.searchbox.core.SearchCollector; import com.searchbox.core.dm.FieldAttribute; import com.searchbox.core.dm.FieldAttribute.USE; import com.searchbox.engine.solr.SolrSearchEngine; @SearchAdapter public class TemplateElementSolrAdapter { private static final Logger LOGGER = LoggerFactory .getLogger(TemplateElementSolrAdapter.class); @SearchAdapterMethod(execute = Time.PRE) public void setHighlightFieldsForTemplate(SolrSearchEngine engine, TemplateElement searchElement, SolrQuery query, FieldAttribute attribute) { if (!attribute.getHighlight()) { return; } String fieldHighlightKey = engine.getKeyForField(attribute, USE.SEARCH); query.setHighlight(true); query.setHighlightSnippets(3); if (query.getHighlightFields() == null || !Arrays.asList(query.getHighlightFields()).contains( fieldHighlightKey)) { query.addHighlightField(fieldHighlightKey); } } @SearchAdapterMethod(execute = Time.PRE) public void setRequieredFieldsForTemplate(SolrSearchEngine engine, TemplateElement searchElement, SolrQuery query, FieldAttribute attribute) { // TODO check if template has a template. if not ask for all fields. if (query.getFields() == null) { query.setFields("score", "[shard]"); } Set<String> fields = searchElement.getRequiredFields(); LOGGER.debug("Required fields: {}", fields); if (fields.contains(attribute.getField().getKey())) { String key = engine.getKeyForField(attribute, USE.DEFAULT); LOGGER.trace("Adding {} as fl for {}",key, attribute.getField().getKey()); if (!query.getFields().contains(key)) { List<String> qfields = Lists.newArrayList(); qfields.addAll(Arrays.asList(query.getFields().split(","))); qfields.add(attribute.getField().getKey() + ":" + key); query.setFields(qfields.toArray(new String[0])); } } } @SearchAdapterMethod(execute = Time.POST) public void generateHitElementsForTemplate(TemplateElement element, QueryResponse response, FieldAttribute attribute, SearchCollector collector) { LOGGER.debug("Search for ID Attribute. {} Got: {} Needed: {}", (!attribute .getField().getKey().equalsIgnoreCase(element.getIdField())), attribute .getField().getKey(), element.getIdField()); if (!attribute.getField().getKey().equalsIgnoreCase(element.getIdField())) { return; } LOGGER.debug("Generate Hit!!!"); Iterator<SolrDocument> documents = response.getResults().iterator(); while (documents.hasNext()) { SolrDocument document = documents.next(); Hit hit = new Hit((Float) document.get("score")); // Set fields per element configuration hit.setIdFieldName(element.getIdField()); hit.setTitleFieldName(element.getTitleField()); hit.setUrlFieldName(element.getUrlField()); // Set the template as per element definition LOGGER.debug("Template file is {}", element.getTemplateFile()); hit.setDisplayTemplate(element.getTemplateFile()); for (String field : document.getFieldNames()) { hit.addFieldValue(field, document.get(field)); } // Now we push the highlights Object id = document.getFirstValue(attribute.getField().getKey()); if(response.getHighlighting() != null){ Map<String, List<String>> highlights = response.getHighlighting().get(id); if(highlights != null){ for (String highlihgtkey : highlights.keySet()) { for (String fieldkey : document.getFieldNames()) { if (highlihgtkey.contains(fieldkey)) { hit.getHighlights().put(fieldkey, highlights.get(highlihgtkey)); } } } } } // And we collect the hit for future use :) collector.getCollectedItems(element.getCollectorKey()).add(hit); } } }
src/main/java/com/searchbox/core/search/result/TemplateElementSolrAdapter.java
package com.searchbox.core.search.result; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.elasticsearch.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.searchbox.core.SearchAdapter; import com.searchbox.core.SearchAdapter.Time; import com.searchbox.core.SearchAdapterMethod; import com.searchbox.core.SearchCollector; import com.searchbox.core.dm.FieldAttribute; import com.searchbox.core.dm.FieldAttribute.USE; import com.searchbox.engine.solr.SolrSearchEngine; @SearchAdapter public class TemplateElementSolrAdapter { private static final Logger LOGGER = LoggerFactory .getLogger(TemplateElementSolrAdapter.class); @SearchAdapterMethod(execute = Time.PRE) public void setHighlightFieldsForTemplate(SolrSearchEngine engine, TemplateElement searchElement, SolrQuery query, FieldAttribute attribute) { if (!attribute.getHighlight()) { return; } String fieldHighlightKey = engine.getKeyForField(attribute, USE.SEARCH); query.setHighlight(true); query.setHighlightSnippets(3); if (query.getHighlightFields() == null || !Arrays.asList(query.getHighlightFields()).contains( fieldHighlightKey)) { query.addHighlightField(fieldHighlightKey); } } @SearchAdapterMethod(execute = Time.PRE) public void setRequieredFieldsForTemplate(SolrSearchEngine engine, TemplateElement searchElement, SolrQuery query, FieldAttribute attribute) { // TODO check if template has a template. if not ask for all fields. if (query.getFields() == null) { query.setFields("score", "[shard]"); } Set<String> fields = searchElement.getRequiredFields(); if (fields.contains(attribute.getField().getKey())) { String key = engine.getKeyForField(attribute, USE.DEFAULT); if (!query.getFields().contains(key)) { List<String> qfields = Lists.newArrayList(); qfields.addAll(Arrays.asList(query.getFields().split(","))); qfields.add(attribute.getField().getKey() + ":" + key); query.setFields(qfields.toArray(new String[0])); } } } @SearchAdapterMethod(execute = Time.POST) public void generateHitElementsForTemplate(TemplateElement element, QueryResponse response, FieldAttribute attribute, SearchCollector collector) { LOGGER.debug("Search for ID Attribute. {} Got: {} Needed: {}", (!attribute .getField().getKey().equalsIgnoreCase(element.getIdField())), attribute .getField().getKey(), element.getIdField()); if (!attribute.getField().getKey().equalsIgnoreCase(element.getIdField())) { return; } LOGGER.debug("Generate Hit!!!"); Iterator<SolrDocument> documents = response.getResults().iterator(); while (documents.hasNext()) { SolrDocument document = documents.next(); Hit hit = new Hit((Float) document.get("score")); // Set fields per element configuration hit.setIdFieldName(element.getIdField()); hit.setTitleFieldName(element.getTitleField()); hit.setUrlFieldName(element.getUrlField()); // Set the template as per element definition LOGGER.debug("Template file is {}", element.getTemplateFile()); hit.setDisplayTemplate(element.getTemplateFile()); for (String field : document.getFieldNames()) { hit.addFieldValue(field, document.get(field)); } // Now we push the highlights Object id = document.getFirstValue(attribute.getField().getKey()); if(response.getHighlighting() != null){ Map<String, List<String>> highlights = response.getHighlighting().get(id); if(highlights != null){ for (String highlihgtkey : highlights.keySet()) { for (String fieldkey : document.getFieldNames()) { if (highlihgtkey.contains(fieldkey)) { hit.getHighlights().put(fieldkey, highlights.get(highlihgtkey)); } } } } } // And we collect the hit for future use :) collector.getCollectedItems(element.getCollectorKey()).add(hit); } } }
Udpated log levels
src/main/java/com/searchbox/core/search/result/TemplateElementSolrAdapter.java
Udpated log levels
<ide><path>rc/main/java/com/searchbox/core/search/result/TemplateElementSolrAdapter.java <ide> } <ide> <ide> Set<String> fields = searchElement.getRequiredFields(); <add> LOGGER.debug("Required fields: {}", fields); <ide> <ide> if (fields.contains(attribute.getField().getKey())) { <ide> String key = engine.getKeyForField(attribute, USE.DEFAULT); <add> LOGGER.trace("Adding {} as fl for {}",key, attribute.getField().getKey()); <ide> if (!query.getFields().contains(key)) { <ide> List<String> qfields = Lists.newArrayList(); <ide> qfields.addAll(Arrays.asList(query.getFields().split(",")));
Java
agpl-3.0
db86c7084ba08d94a08f028043c4b59466c44467
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
2a6ed5e2-2e62-11e5-9284-b827eb9e62be
hello.java
2a694f78-2e62-11e5-9284-b827eb9e62be
2a6ed5e2-2e62-11e5-9284-b827eb9e62be
hello.java
2a6ed5e2-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>2a694f78-2e62-11e5-9284-b827eb9e62be <add>2a6ed5e2-2e62-11e5-9284-b827eb9e62be
JavaScript
apache-2.0
4d328ee3dc62d945eaf4aa2de6b1de23106321e0
0
ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * */ // Foundation JavaScript // Documentation can be found at: http://foundation.zurb.com/docs function collapseFieldset(){ var parent = $(".toggleField"); parent.each(function( index ) { $(this).find("fieldset > .row").wrapAll('<div class="collapsehide"/>'); if(parent.hasClass("collapsed")){ parent.find(".collapsehide").hide(); } }); $(".toggleField legend, .toggleField .legend").click(function(){ $(this).children("i").toggleClass(" fa-arrow-right").toggleClass(" fa-arrow-down"); $(this).nextAll("div.collapsehide").slideToggle(300); }); } $(function(){ $(document).foundation(); scipioObjectFit(); collapseFieldset(); $('.ui-autocomplete').addClass('f-dropdown'); if (typeof Pizza !== 'undefined') { Pizza.init(); // Create charts } //jQuery validate specific options $.validator.setDefaults({ errorElement: "span", errorClass: "error", debug: true }); }); /* no longer needed; macros can decide where since patch jQuery(document).ready(function() { var asteriks = jQuery('.form-field-input-asterisk'); asteriks.each(function() { var label = jQuery(this).parents('.form-field-entry').first().find('.form-field-label').first(); label.append(' <span class="form-field-label-asterisk">*</span>'); }); }); */ /** * Scipio upload progress handler. Instance represents one upload form. */ function ScipioUploadProgress(options) { if (!options) { options = {}; } this.uploading = false; // can check this from caller as well ScipioUploadProgress.instCount = ScipioUploadProgress.instCount + 1; this.instNum = ScipioUploadProgress.instCount; this.uploadCount = 0; // All options that end in -Id specify a unique html/css ID. // All options that end in -Sel specify a full jQuery element selector (e.g., "form[name=myform]") this.formSel = options.formSel; // required, should exist in doc this.progBarId = options.progBarId; // optional, but if used should exist in doc this.progMeterId = options.progMeterId; // optional, has default (based on progBarId and @progress ftl macro) this.progTextBoxId = options.progTextBoxId; // optional, but if used should exist in doc this.progTextElemId = options.progTextElemId; // optional, has default (based on progTextBoxId), should NOT already exist in doc this.msgContainerId = options.msgContainerId; // optional, only required if no parent specified; for error messages this.msgContainerParentSel = options.msgContainerParentSel; // optional, default the form's parent element; designates an element as parent for a message container; if msgContainerId elem already exists on page, won't use this.msgContainerInsertMode = options.msgContainerInsertMode; // optional, default "prepend"; for parent; either "prepend" or "append" (to parent) this.iframeParentSel = options.iframeParentSel; // optional, default is html body, if specified should exist in doc; will contain hidden iframe(s) to internally hold file upload html page result this.expectedResultContainerSel = options.expectedResultContainerSel; // required; id of an elem to test existence in upload page result; was originally same as resultContentContainerSel this.errorResultContainerSel = options.errorResultContainerSel; // required; if this elem in upload page result exists, treat it as error and use its content as error message (required to help against forever-uploading bug) // 2016-11-02: if the elem has a "has-scipio-errormsg" html attribute (true/false string value) it is consulted to check if should consider errors present this.errorResultAddWrapper = options.errorResultAddWrapper; // optional, default false; if true, errorResultContainerSel contents will be wrapped like other errors; else it must supply its own; does not apply to ajax and other errors (always get wrapper, needed) this.resultContentReplace = options.resultContentReplace; // boolean, default false; if true replace some content in this page with content from upload page result (iframe) this.contentContainerSel = options.contentContainerSel; // required if resultContentReplace true, id of content on current page to be replaced this.resultContentContainerSel = options.resultContentContainerSel; // required if resultContentReplace true, id of content on upload page result this.successRedirectUrl = options.successRedirectUrl; // optional; if specified, will redirect to this URL on upload success this.successSubmitFormSel = options.successSubmitFormSel; // optional; same as successRedirectUrl but submits a form instead this.successReloadWindow = options.successReloadWindow; // optional; same as successRedirectUrl but reloads current page instead (WARN: should usually avoid in Ofbiz screens as causes navigation issues) //this.successReplaceWindow = options.successReplaceWindow; // not implemented/possible; optional, default false; if true, upon success will replace this window with contents of iframe this.preventDoubleUpload = options.preventDoubleUpload; // optional, default true; not sure why would turn this off this.initOnce = false; if (!this.progMeterId) { if (this.progBarId) { this.progMeterId = this.progBarId + "_meter"; } } if (!this.progTextElemId) { if (this.progTextBoxId) { this.progTextElemId = this.progTextBoxId + "_msg"; } } if (!this.msgContainerId) { this.msgContainerId = "scipio_progupl_content_messages_" + this.instNum; } if (!this.msgContainerInsertMode) { this.msgContainerInsertMode = "prepend"; } this.iframeBaseId = "scipio_progupl_target_upload_" + this.instNum; if (typeof this.errorResultAddWrapper !== 'boolean') { this.errorResultAddWrapper = false; } if (typeof this.resultContentReplace !== 'boolean') { this.resultContentReplace = false; } if (typeof this.successReloadWindow !== 'boolean') { this.successReloadWindow = false; } if (typeof this.successReplaceWindow !== 'boolean') { this.successReplaceWindow = false; } if (typeof this.preventDoubleUpload !== 'boolean') { this.preventDoubleUpload = true; } this.uiLabelMap = null; /* Public functions */ this.reset = function() { if (!this.preventDoubleUpload || !this.uploading) { this.delayedInit(); this.resetProgress(); return true; } return false; }; this.initUpload = function() { if (!this.preventDoubleUpload || !this.uploading) { this.delayedInit(); this.uploading = true; // upload status for a specific upload attempt var uploadInfo = { finished : false, iframeCreated : false, iframeLoaded : false, iframeId : this.iframeBaseId + "_" + (this.uploadCount+1) }; this.resetInitContainers(uploadInfo); this.beginProgressStatus(uploadInfo); this.uploadCount = this.uploadCount + 1; return true; } return false; }; /* Private functions */ this.delayedInit = function() { ScipioUploadProgress.loadUiLabels(); if (this.uiLabelMap == null) { this.uiLabelMap = ScipioUploadProgress.uiLabelMap; } }; this.setProgressValue = function(percent) { if (this.progMeterId) { jQuery("#"+this.progMeterId).css({"width": percent + "%"}); if (typeof jQuery("#"+this.progMeterId).attr("aria-valuenow") !== 'undefined') { jQuery("#"+this.progMeterId).attr("aria-valuenow", percent.toString()); } } if (this.progTextElemId) { jQuery("#"+this.progTextElemId).html(this.uiLabelMap.CommonUpload + "... (" + percent + "%)"); } }; this.setProgressState = function(classStr) { var stateStyles = [scipioStyles.progress_state_info, scipioStyles.progress_state_success, scipioStyles.progress_state_alert].join(" "); if (this.progBarId) { jQuery("#"+this.progBarId).removeClass(stateStyles).addClass(classStr); } if (this.progTextElemId) { jQuery("#"+this.progTextElemId).removeClass(stateStyles).addClass(classStr); } }; this.setProgressText = function(msg) { if (this.progTextElemId) { jQuery("#"+this.progTextElemId).html(msg); } }; this.resetProgress = function() { this.setProgressValue(0); this.setProgressState(scipioStyles.color_info) }; this.showError = function(errdata, errorWrapper) { if (typeof errorWrapper !== 'boolean') { errorWrapper = true; } if (this.msgContainerId) { if (errorWrapper) { jQuery("#"+this.msgContainerId).html('<div data-alert class="' + scipioStyles.alert_wrap + ' ' + scipioStyles.alert_prefix_type + 'alert">' + errdata + "</div>"); } else { jQuery("#"+this.msgContainerId).html(errdata); } } this.setProgressState(scipioStyles.color_alert); this.setProgressText(this.uiLabelMap.CommonError); }; this.resetInitContainers = function(uploadInfo) { this.resetProgress(); if (this.progBarId) { jQuery("#"+this.progBarId).removeClass(scipioStyles.hidden); } var infodiv = jQuery("#"+this.msgContainerId); if(infodiv.length < 1){ var infodivbox = jQuery('<div class="' + scipioStyles.grid_row + '"><div class="' + scipioStyles.grid_large + '12 ' + scipioStyles.grid_cell + '" id="' + this.msgContainerId + '"></div></div>'); var infodivparent = null; if (this.msgContainerParentSel) { infodivparent = jQuery(this.msgContainerParentSel); } else { infodivparent = this.getFormElem().parent(); } if (this.msgContainerInsertMode == "append") { infodivbox.appendTo(infodivparent); } else { infodivbox.prependTo(infodivparent); } } jQuery("#"+this.msgContainerId).empty(); // Scipio: we always create a new iframe for safety, but leaving guard code in case change var targetFrame = jQuery("#"+uploadInfo.iframeId); if (targetFrame.length < 1) { var iframeParent; if (this.iframeParentSel) { iframeParent = jQuery(this.iframeParentSel); } else { iframeParent = jQuery("body").first(); } iframeParent.append('<iframe id="' + uploadInfo.iframeId + '" name="' + uploadInfo.iframeId + '" style="display: none" src=""> </iframe>'); uploadInfo.iframeCreated = true; } jQuery("#"+uploadInfo.iframeId).off("load"); jQuery("#"+uploadInfo.iframeId).empty(); jQuery("#"+uploadInfo.iframeId).load(jQuery.proxy(this.checkIframeAsyncLoad, this, uploadInfo)); this.getFormElem().attr("target", uploadInfo.iframeId); if (this.progTextElemId) { var labelField = jQuery("#"+this.progTextElemId); if (labelField.length) { labelField.remove(); } } this.initOnce = true; }; this.getFormElem = function() { return jQuery(this.formSel); }; this.processUploadComplete = function(uploadInfo) { var error = false; if (this.resultContentReplace) { var iframeContent = jQuery("#"+uploadInfo.iframeId).contents().find(this.resultContentContainerSel); if (iframeContent.length > 0) { // update content - copy the Data from the iFrame content container // to the page content container var contentContainer = jQuery(this.contentContainerSel); if (contentContainer.length > 0) { contentContainer.html(iframeContent.html()); } else { // don't show error; no chance it reflects on upload success } } else { // something's missing, probably dev error but can't be sure error = true; this.showError(this.uiLabelMap.CommonUnexpectedError); } } if (!error) { this.setProgressValue(100); this.setProgressState(scipioStyles.color_success); this.setProgressText(this.uiLabelMap.CommonCompleted); } var iframeDocHtml = null; if (!error) { if (this.successReplaceWindow) { iframeDocHtml = jQuery("#"+uploadInfo.iframeId).contents().find("html").html(); //var iframe = jQuery("#"+uploadInfo.iframeId)[0]; //var iframeDocument = iframe.contentDocument || iframe.contentWindow.document; } } this.cleanup(uploadInfo); if (!error) { if (this.successRedirectUrl) { window.location.href = this.successRedirectUrl; } else if (this.successSubmitFormSel) { jQuery(this.successSubmitFormSel).submit(); } else if (this.successReplaceWindow) { var newDoc = document.open("text/html"); newDoc.write(iframeDocHtml); newDoc.close(); } else if (this.successReloadWindow) { window.location.reload(true); } } return; }; this.processError = function(uploadInfo, errdata, errorWrapper) { this.showError(errdata, errorWrapper); this.cleanup(uploadInfo); }; this.cleanup = function(uploadInfo) { if (uploadInfo.iframeCreated) { // remove iFrame jQuery("#"+uploadInfo.iframeId).remove(); } this.uploading = false; }; this.checkIframeAsyncLoad = function(uploadInfo) { // this version called by jquery... for now, just flag and let timer code handle // this helps prevent "forever uploading" bug uploadInfo.iframeLoaded = true; }; this.checkIframeStatus = function(uploadInfo) { var iframeContent = null; var iframeErrorContent = null; // if the new content isn't created wait a few ms and call the // method again var prog = this; jQuery.fjTimer({ interval: 500, repeat: true, tick: function(counter, timerId) { // note: errorResultContainerSel and expectedResultContainerSel must be chosen carefully // note: explicitly not checking uploadInfo.iframeLoaded for these two, for now... if (prog.errorResultContainerSel && !uploadInfo.finished) { iframeErrorContent = jQuery("#"+uploadInfo.iframeId).contents().find(prog.errorResultContainerSel); if (iframeErrorContent.length > 0) { // 2016-11-02: check for custom has-scipio-errormsg attribute var flagAttr = jQuery(iframeErrorContent).attr("has-scipio-errormsg"); if (!flagAttr || flagAttr == "true") { uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, iframeErrorContent.html(), prog.errorResultAddWrapper); } } } if (!uploadInfo.finished) { iframeContent = jQuery("#"+uploadInfo.iframeId).contents().find(prog.expectedResultContainerSel); if (iframeContent.length > 0) { uploadInfo.finished = true; timerId.stop(); prog.processUploadComplete(uploadInfo); } } if (!uploadInfo.finished && uploadInfo.iframeLoaded) { // problem: iframe loaded but we got nothing... usually a coding error but can't be sure uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, prog.uiLabelMap.CommonUnexpectedError); } } }); return; }; this.beginProgressStatus = function(uploadInfo) { if (this.progTextBoxId && this.progTextElemId) { jQuery("#"+this.progTextBoxId).append('<span id="' + this.progTextElemId + '" class="label">' + this.uiLabelMap.CommonUpload + '...</span>'); } var i = 0; var prog = this; jQuery.fjTimer({ interval: 1000, repeat: true, tick: function(counter, timerId) { var timerId = timerId; jQuery.ajax({ url: getOfbizUrl('getFileUploadProgressStatus'), dataType: 'json', success: function(data) { if (data._ERROR_MESSAGE_LIST_ != undefined) { uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, data._ERROR_MESSAGE_LIST_); } else if (data._ERROR_MESSAGE_ != undefined) { uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, data._ERROR_MESSAGE_); } else { var readPercent = data.readPercent; prog.setProgressValue(readPercent); if (readPercent > 99) { // stop the fjTimer timerId.stop(); prog.setProgressText(prog.uiLabelMap.CommonSave + "..."); // call the upload complete method to do final stuff prog.checkIframeStatus(uploadInfo); } } }, error: function(data) { uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, prog.uiLabelMap.CommonServerCommunicationError); } }); } }); }; } ScipioUploadProgress.instCount = 0; ScipioUploadProgress.uiLabelMap = null; ScipioUploadProgress.loadUiLabels = function() { if (ScipioUploadProgress.uiLabelMap == null) { var labelObject = { "CommonUiLabels" : ["CommonUpload", "CommonSave", "CommonCompleted", "CommonError", "CommonServerCommunicationError", "CommonUnexpectedError"] }; ScipioUploadProgress.uiLabelMap = getJSONuiLabelMap(labelObject); } }; /** * Object-fit fallback for IE (used by <@img> macro) * Based on: * https://medium.com/@primozcigler/neat-trick-for-css-object-fit-fallback-on-edge-and-other-browsers-afbc53bbb2c3#.cwwk7mtx0 * * */ function scipioObjectFit(){ Modernizr.addTest('objectfit', !!Modernizr.prefixed('objectFit') ); if ( !Modernizr.objectfit ) { $('.scipio-image-container').each(function () { var $container = $(this), imgUrl = $container.find('img').prop('src'); if (imgUrl) { var type= $container.attr('scipioFit'); $container .css('backgroundImage', 'url(' + imgUrl + ')') .css('background-size',type) .css('background-repeat','no-repeat') .css('background-position','center center') .addClass('compat-object-fit'); $container.find('img').css('opacity','0'); } }); } return false; } function checkboxToFormHiddenInput(checkboxElem, formSel) { jQuery(formSel + ' input[name="' + checkboxElem.name + '"]').remove(); if (checkboxElem.checked) { jQuery(formSel).append('<input type="hidden" name="' + checkboxElem.name + '" value="' + checkboxElem.value + '" />') } }
themes/base/webapp/base/js/app.js
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * */ // Foundation JavaScript // Documentation can be found at: http://foundation.zurb.com/docs function collapseFieldset(){ var parent = $(".toggleField"); parent.each(function( index ) { $(this).find("fieldset > .row").wrapAll('<div class="collapsehide"/>'); if(parent.hasClass("collapsed")){ parent.find(".collapsehide").hide(); } }); $(".toggleField legend, .toggleField .legend").click(function(){ $(this).children("i").toggleClass(" fa-arrow-right").toggleClass(" fa-arrow-down"); $(this).nextAll("div.collapsehide").slideToggle(300); }); } $(function(){ $(document).foundation(); scipioObjectFit(); collapseFieldset(); $('.ui-autocomplete').addClass('f-dropdown'); if (typeof Pizza !== 'undefined') { Pizza.init(); // Create charts } //jQuery validate specific options $.validator.setDefaults({ errorElement: "span", errorClass: "error", debug: true }); }); /* no longer needed; macros can decide where since patch jQuery(document).ready(function() { var asteriks = jQuery('.form-field-input-asterisk'); asteriks.each(function() { var label = jQuery(this).parents('.form-field-entry').first().find('.form-field-label').first(); label.append(' <span class="form-field-label-asterisk">*</span>'); }); }); */ /** * Scipio upload progress handler. Instance represents one upload form. */ function ScipioUploadProgress(options) { if (!options) { options = {}; } this.uploading = false; // can check this from caller as well ScipioUploadProgress.instCount = ScipioUploadProgress.instCount + 1; this.instNum = ScipioUploadProgress.instCount; this.uploadCount = 0; // All options that end in -Id specify a unique html/css ID. // All options that end in -Sel specify a full jQuery element selector (e.g., "form[name=myform]") this.formSel = options.formSel; // required, should exist in doc this.progBarId = options.progBarId; // optional, but if used should exist in doc this.progMeterId = options.progMeterId; // optional, has default (based on progBarId and @progress ftl macro) this.progTextBoxId = options.progTextBoxId; // optional, but if used should exist in doc this.progTextElemId = options.progTextElemId; // optional, has default (based on progTextBoxId), should NOT already exist in doc this.msgContainerId = options.msgContainerId; // optional, only required if no parent specified; for error messages this.msgContainerParentSel = options.msgContainerParentSel; // optional, default the form's parent element; designates an element as parent for a message container; if msgContainerId elem already exists on page, won't use this.msgContainerInsertMode = options.msgContainerInsertMode; // optional, default "prepend"; for parent; either "prepend" or "append" (to parent) this.iframeParentSel = options.iframeParentSel; // optional, default is html body, if specified should exist in doc; will contain hidden iframe(s) to internally hold file upload html page result this.expectedResultContainerSel = options.expectedResultContainerSel; // required; id of an elem to test existence in upload page result; was originally same as resultContentContainerSel this.errorResultContainerSel = options.errorResultContainerSel; // required; if this elem in upload page result exists, treat it as error and use its content as error message (required to help against forever-uploading bug) // 2016-11-02: if the elem has a "has-scipio-errormsg" html attribute (true/false string value) it is consulted to check if should consider errors present this.errorResultAddWrapper = options.errorResultAddWrapper; // optional, default false; if true, errorResultContainerSel contents will be wrapped like other errors; else it must supply its own; does not apply to ajax and other errors (always get wrapper, needed) this.resultContentReplace = options.resultContentReplace; // boolean, default false; if true replace some content in this page with content from upload page result (iframe) this.contentContainerSel = options.contentContainerSel; // required if resultContentReplace true, id of content on current page to be replaced this.resultContentContainerSel = options.resultContentContainerSel; // required if resultContentReplace true, id of content on upload page result this.successRedirectUrl = options.successRedirectUrl; // optional; if specified, will redirect to this URL on upload success this.successSubmitFormSel = options.successSubmitFormSel; // optional; same as successRedirectUrl but submits a form instead this.successReloadWindow = options.successReloadWindow; // optional; same as successRedirectUrl but reloads current page instead (WARN: should usually avoid in Ofbiz screens as causes navigation issues) //this.successReplaceWindow = options.successReplaceWindow; // not implemented/possible; optional, default false; if true, upon success will replace this window with contents of iframe this.preventDoubleUpload = options.preventDoubleUpload; // optional, default true; not sure why would turn this off this.initOnce = false; if (!this.progMeterId) { if (this.progBarId) { this.progMeterId = this.progBarId + "_meter"; } } if (!this.progTextElemId) { if (this.progTextBoxId) { this.progTextElemId = this.progTextBoxId + "_msg"; } } if (!this.msgContainerId) { this.msgContainerId = "scipio_progupl_content_messages_" + this.instNum; } if (!this.msgContainerInsertMode) { this.msgContainerInsertMode = "prepend"; } this.iframeBaseId = "scipio_progupl_target_upload_" + this.instNum; if (typeof this.errorResultAddWrapper !== 'boolean') { this.errorResultAddWrapper = false; } if (typeof this.resultContentReplace !== 'boolean') { this.resultContentReplace = false; } if (typeof this.successReloadWindow !== 'boolean') { this.successReloadWindow = false; } if (typeof this.successReplaceWindow !== 'boolean') { this.successReplaceWindow = false; } if (typeof this.preventDoubleUpload !== 'boolean') { this.preventDoubleUpload = true; } this.uiLabelMap = null; /* Public functions */ this.reset = function() { if (!this.preventDoubleUpload || !this.uploading) { this.delayedInit(); this.resetProgress(); return true; } return false; }; this.initUpload = function() { if (!this.preventDoubleUpload || !this.uploading) { this.delayedInit(); this.uploading = true; // upload status for a specific upload attempt var uploadInfo = { finished : false, iframeCreated : false, iframeLoaded : false, iframeId : this.iframeBaseId + "_" + (this.uploadCount+1) }; this.resetInitContainers(uploadInfo); this.beginProgressStatus(uploadInfo); this.uploadCount = this.uploadCount + 1; return true; } return false; }; /* Private functions */ this.delayedInit = function() { ScipioUploadProgress.loadUiLabels(); if (this.uiLabelMap == null) { this.uiLabelMap = ScipioUploadProgress.uiLabelMap; } }; this.setProgressValue = function(percent) { if (this.progMeterId) { jQuery("#"+this.progMeterId).css({"width": percent + "%"}); if (typeof jQuery("#"+this.progMeterId).attr("aria-valuenow") !== 'undefined') { jQuery("#"+this.progMeterId).attr("aria-valuenow", percent.toString()); } } if (this.progTextElemId) { jQuery("#"+this.progTextElemId).html(this.uiLabelMap.CommonUpload + "... (" + percent + "%)"); } }; this.setProgressState = function(classStr) { var stateStyles = [scipioStyles.progress_state_info, scipioStyles.progress_state_success, scipioStyles.progress_state_alert].join(" "); if (this.progBarId) { jQuery("#"+this.progBarId).removeClass(stateStyles).addClass(classStr); } if (this.progTextElemId) { jQuery("#"+this.progTextElemId).removeClass(stateStyles).addClass(classStr); } }; this.setProgressText = function(msg) { if (this.progTextElemId) { jQuery("#"+this.progTextElemId).html(msg); } }; this.resetProgress = function() { this.setProgressValue(0); this.setProgressState(scipioStyles.color_info) }; this.showError = function(errdata, errorWrapper) { if (typeof errorWrapper !== 'boolean') { errorWrapper = true; } if (this.msgContainerId) { if (errorWrapper) { jQuery("#"+this.msgContainerId).html('<div data-alert class="' + scipioStyles.alert_wrap + ' ' + scipioStyles.alert_prefix_type + 'alert">' + errdata + "</div>"); } else { jQuery("#"+this.msgContainerId).html(errdata); } } this.setProgressState(scipioStyles.color_alert); this.setProgressText(this.uiLabelMap.CommonError); }; this.resetInitContainers = function(uploadInfo) { this.resetProgress(); if (this.progBarId) { jQuery("#"+this.progBarId).removeClass(scipioStyles.hidden); } var infodiv = jQuery("#"+this.msgContainerId); if(infodiv.length < 1){ var infodivbox = jQuery('<div class="' + scipioStyles.grid_row + '"><div class="' + scipioStyles.grid_large + '12 ' + scipioStyles.grid_cell + '" id="' + this.msgContainerId + '"></div></div>'); var infodivparent = null; if (this.msgContainerParentSel) { infodivparent = jQuery(this.msgContainerParentSel); } else { infodivparent = this.getFormElem().parent(); } if (this.msgContainerInsertMode == "append") { infodivbox.appendTo(infodivparent); } else { infodivbox.prependTo(infodivparent); } } jQuery("#"+this.msgContainerId).empty(); // Scipio: we always create a new iframe for safety, but leaving guard code in case change var targetFrame = jQuery("#"+uploadInfo.iframeId); if (targetFrame.length < 1) { var iframeParent; if (this.iframeParentSel) { iframeParent = jQuery(this.iframeParentSel); } else { iframeParent = jQuery("body").first(); } iframeParent.append('<iframe id="' + uploadInfo.iframeId + '" name="' + uploadInfo.iframeId + '" style="display: none" src=""> </iframe>'); uploadInfo.iframeCreated = true; } jQuery("#"+uploadInfo.iframeId).off("load"); jQuery("#"+uploadInfo.iframeId).empty(); jQuery("#"+uploadInfo.iframeId).load(jQuery.proxy(this.checkIframeAsyncLoad, this, uploadInfo)); this.getFormElem().attr("target", uploadInfo.iframeId); if (this.progTextElemId) { var labelField = jQuery("#"+this.progTextElemId); if (labelField.length) { labelField.remove(); } } this.initOnce = true; }; this.getFormElem = function() { return jQuery(this.formSel); }; this.processUploadComplete = function(uploadInfo) { var error = false; if (this.resultContentReplace) { var iframeContent = jQuery("#"+uploadInfo.iframeId).contents().find(this.resultContentContainerSel); if (iframeContent.length > 0) { // update content - copy the Data from the iFrame content container // to the page content container var contentContainer = jQuery(this.contentContainerSel); if (contentContainer.length > 0) { contentContainer.html(iframeContent.html()); } else { // don't show error; no chance it reflects on upload success } } else { // something's missing, probably dev error but can't be sure error = true; this.showError(this.uiLabelMap.CommonUnexpectedError); } } if (!error) { this.setProgressValue(100); this.setProgressState(scipioStyles.color_success); this.setProgressText(this.uiLabelMap.CommonCompleted); } var iframeDocHtml = null; if (!error) { if (this.successReplaceWindow) { iframeDocHtml = jQuery("#"+uploadInfo.iframeId).contents().find("html").html(); //var iframe = jQuery("#"+uploadInfo.iframeId)[0]; //var iframeDocument = iframe.contentDocument || iframe.contentWindow.document; } } this.cleanup(uploadInfo); if (!error) { if (this.successRedirectUrl) { window.location.href = this.successRedirectUrl; } else if (this.successSubmitFormSel) { jQuery(this.successSubmitFormSel).submit(); } else if (this.successReplaceWindow) { var newDoc = document.open("text/html"); newDoc.write(iframeDocHtml); newDoc.close(); } else if (this.successReloadWindow) { window.location.reload(true); } } return; }; this.processError = function(uploadInfo, errdata, errorWrapper) { this.showError(errdata, errorWrapper); this.cleanup(uploadInfo); }; this.cleanup = function(uploadInfo) { if (uploadInfo.iframeCreated) { // remove iFrame jQuery("#"+uploadInfo.iframeId).remove(); } this.uploading = false; }; this.checkIframeAsyncLoad = function(uploadInfo) { // this version called by jquery... for now, just flag and let timer code handle // this helps prevent "forever uploading" bug uploadInfo.iframeLoaded = true; }; this.checkIframeStatus = function(uploadInfo) { var iframeContent = null; var iframeErrorContent = null; // if the new content isn't created wait a few ms and call the // method again var prog = this; jQuery.fjTimer({ interval: 500, repeat: true, tick: function(counter, timerId) { // note: errorResultContainerSel and expectedResultContainerSel must be chosen carefully // note: explicitly not checking uploadInfo.iframeLoaded for these two, for now... if (prog.errorResultContainerSel && !uploadInfo.finished) { iframeErrorContent = jQuery("#"+uploadInfo.iframeId).contents().find(prog.errorResultContainerSel); if (iframeErrorContent.length > 0) { // 2016-11-02: check for custom has-scipio-errormsg attribute var flagAttr = jQuery(iframeErrorContent).attr("has-scipio-errormsg"); alert(flagAttr); if (!flagAttr || flagAttr == "true") { uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, iframeErrorContent.html(), prog.errorResultAddWrapper); } } } if (!uploadInfo.finished) { iframeContent = jQuery("#"+uploadInfo.iframeId).contents().find(prog.expectedResultContainerSel); if (iframeContent.length > 0) { uploadInfo.finished = true; timerId.stop(); prog.processUploadComplete(uploadInfo); } } if (!uploadInfo.finished && uploadInfo.iframeLoaded) { // problem: iframe loaded but we got nothing... usually a coding error but can't be sure uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, prog.uiLabelMap.CommonUnexpectedError); } } }); return; }; this.beginProgressStatus = function(uploadInfo) { if (this.progTextBoxId && this.progTextElemId) { jQuery("#"+this.progTextBoxId).append('<span id="' + this.progTextElemId + '" class="label">' + this.uiLabelMap.CommonUpload + '...</span>'); } var i = 0; var prog = this; jQuery.fjTimer({ interval: 1000, repeat: true, tick: function(counter, timerId) { var timerId = timerId; jQuery.ajax({ url: getOfbizUrl('getFileUploadProgressStatus'), dataType: 'json', success: function(data) { if (data._ERROR_MESSAGE_LIST_ != undefined) { uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, data._ERROR_MESSAGE_LIST_); } else if (data._ERROR_MESSAGE_ != undefined) { uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, data._ERROR_MESSAGE_); } else { var readPercent = data.readPercent; prog.setProgressValue(readPercent); if (readPercent > 99) { // stop the fjTimer timerId.stop(); prog.setProgressText(prog.uiLabelMap.CommonSave + "..."); // call the upload complete method to do final stuff prog.checkIframeStatus(uploadInfo); } } }, error: function(data) { uploadInfo.finished = true; timerId.stop(); prog.processError(uploadInfo, prog.uiLabelMap.CommonServerCommunicationError); } }); } }); }; } ScipioUploadProgress.instCount = 0; ScipioUploadProgress.uiLabelMap = null; ScipioUploadProgress.loadUiLabels = function() { if (ScipioUploadProgress.uiLabelMap == null) { var labelObject = { "CommonUiLabels" : ["CommonUpload", "CommonSave", "CommonCompleted", "CommonError", "CommonServerCommunicationError", "CommonUnexpectedError"] }; ScipioUploadProgress.uiLabelMap = getJSONuiLabelMap(labelObject); } }; /** * Object-fit fallback for IE (used by <@img> macro) * Based on: * https://medium.com/@primozcigler/neat-trick-for-css-object-fit-fallback-on-edge-and-other-browsers-afbc53bbb2c3#.cwwk7mtx0 * * */ function scipioObjectFit(){ Modernizr.addTest('objectfit', !!Modernizr.prefixed('objectFit') ); if ( !Modernizr.objectfit ) { $('.scipio-image-container').each(function () { var $container = $(this), imgUrl = $container.find('img').prop('src'); if (imgUrl) { var type= $container.attr('scipioFit'); $container .css('backgroundImage', 'url(' + imgUrl + ')') .css('background-size',type) .css('background-repeat','no-repeat') .css('background-position','center center') .addClass('compat-object-fit'); $container.find('img').css('opacity','0'); } }); } return false; } function checkboxToFormHiddenInput(checkboxElem, formSel) { jQuery(formSel + ' input[name="' + checkboxElem.name + '"]').remove(); if (checkboxElem.checked) { jQuery(formSel).append('<input type="hidden" name="' + checkboxElem.name + '" value="' + checkboxElem.value + '" />') } }
NoRef ScipioUploadProgress: test alert remove git-svn-id: 6c0edb9fdd085beb7f3b78cf385b6ddede550bd9@13338 55bbc10b-e964-4c8f-a844-a62c6f7d3c80
themes/base/webapp/base/js/app.js
NoRef ScipioUploadProgress: test alert remove
<ide><path>hemes/base/webapp/base/js/app.js <ide> if (iframeErrorContent.length > 0) { <ide> // 2016-11-02: check for custom has-scipio-errormsg attribute <ide> var flagAttr = jQuery(iframeErrorContent).attr("has-scipio-errormsg"); <del> alert(flagAttr); <ide> if (!flagAttr || flagAttr == "true") { <ide> uploadInfo.finished = true; <ide> timerId.stop();
Java
apache-2.0
064c63a40a80a833e2939c4df8d04d55c27867f3
0
chmyga/component-runtime,chmyga/component-runtime,chmyga/component-runtime,chmyga/component-runtime
/** * Copyright (C) 2006-2018 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.talend.sdk.component.proxy.service; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.inject.Inject; import javax.json.JsonArray; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import javax.json.JsonString; import javax.json.bind.Jsonb; import org.junit.jupiter.api.Test; import org.talend.sdk.component.proxy.service.qualifier.UiSpecProxy; import org.talend.sdk.component.proxy.test.CdiInject; import org.talend.sdk.component.proxy.test.WithServer; import org.talend.sdk.component.server.front.model.ComponentDetail; import org.talend.sdk.component.server.front.model.PropertyValidation; import org.talend.sdk.component.server.front.model.SimplePropertyDefinition; @CdiInject @WithServer class ConfigurationFormatterImplTest { @Inject private ConfigurationFormatterImpl formatter; @Inject @UiSpecProxy private JsonBuilderFactory factory; @Inject @UiSpecProxy private Jsonb jsonb; @Test void flattenMarketo() { final Map<String, String> properties = formatter .flatten(factory .createObjectBuilder() .add("dataStore", factory .createObjectBuilder() .add("clientId", "xxxx") .add("clientSecret", "yyyy") .add("endpoint", "https://foo.bar.colm")) .build()); assertEquals(3, properties.size()); assertEquals(properties.get("dataStore.clientId"), "xxxx"); assertEquals(properties.get("dataStore.clientSecret"), "yyyy"); assertEquals(properties.get("dataStore.endpoint"), "https://foo.bar.colm"); } @Test void unflattenMarketo() throws IOException { final ComponentDetail detail; try (final InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("marketo.form.json")) { detail = jsonb.fromJson(stream, ComponentDetail.class); } final Map<String, String> properties = new HashMap<>(); properties.put("configuration.activityTypeIds[0].activity", "FOO"); final JsonObject object = formatter.unflatten(detail.getProperties(), properties); assertEquals(1, object.size()); } @Test void flattenFlatObject() { final JsonObject from = factory.createObjectBuilder().add("name", "N").add("age", 20.).build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("name", "N"); put("age", "20.0"); } }, flatten); } @Test void flattenMaxBatchSize() { final JsonObject model = formatter .unflatten(asList( new SimplePropertyDefinition("configuration", "configuration", "configuration", "OBJECT", null, new PropertyValidation(), emptyMap(), null, new LinkedHashMap<>()), new SimplePropertyDefinition("configuration.$maxBatchSize", "$maxBatchSize", "$maxBatchSize", "NUMBER", null, new PropertyValidation(), emptyMap(), null, new LinkedHashMap<>())), singletonMap("configuration.$maxBatchSize", "1000.0")); assertEquals(1000., model.getJsonObject("configuration").getJsonNumber("$maxBatchSize").doubleValue()); } @Test void flattenSimpleArray() { final JsonObject from = factory .createObjectBuilder() .add("urls", factory.createArrayBuilder().add("a").add("b").build()) .build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("urls[0]", "a"); put("urls[1]", "b"); } }, flatten); } @Test void flattenArrayWithNull() { final JsonObject from = factory .createObjectBuilder() .add("urls", factory.createArrayBuilder().add("a").addNull().add("b").build()) .build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("urls[0]", "a"); put("urls[2]", "b"); } }, flatten); } @Test void flattenObjectArray() { final JsonObject from = factory .createObjectBuilder() .add("people", factory .createArrayBuilder() .add(factory.createObjectBuilder().add("name", "First").add("age", 20)) .add(factory.createObjectBuilder().add("name", "Second").add("age", 30)) .build()) .build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("people[0].name", "First"); put("people[0].age", "20.0"); put("people[1].name", "Second"); put("people[1].age", "30.0"); } }, flatten); } @Test void flattenNestedObject() { final JsonObject from = factory .createObjectBuilder() .add("config", factory.createObjectBuilder().add("name", "N").add("age", 20.).build()) .build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("config.name", "N"); put("config.age", "20.0"); } }, flatten); } @Test void unflattenTable() { final JsonObject object = formatter .unflatten(asList(prop("root", "OBJECT"), prop("root.table", "ARRAY"), prop("root.table[]", "STRING")), new HashMap<String, String>() { { put("root.table[0]", "a"); put("root.table[1]", "b"); } }); assertEquals(1, object.size()); final JsonObject root = object.getJsonObject("root"); assertEquals(1, root.size()); assertEquals(asList("a", "b"), root .getJsonArray("table") .stream() .map(JsonString.class::cast) .map(JsonString::getString) .collect(toList())); } @Test void unflattenTableOfObject() { final JsonObject object = formatter .unflatten( asList(prop("root", "OBJECT"), prop("root.table", "ARRAY"), prop("root.table[].name", "STRING"), prop("root.table[].age", "NUMBER")), new HashMap<String, String>() { { put("root.table[0].name", "a"); put("root.table[0].age", "20"); put("root.table[1].name", "b"); put("root.table[1].age", "30"); } }); assertEquals(1, object.size()); final JsonObject root = object.getJsonObject("root"); assertEquals(1, root.size()); final JsonArray table = root.getJsonArray("table"); assertEquals(2, table.size()); assertEquals(asList("a", "b"), table.stream().map(JsonObject.class::cast).map(o -> o.getString("name")).collect(toList())); } @Test void unflattenComplex() { final JsonObject object = formatter .unflatten( asList(prop("root", "OBJECT"), prop("root.table", "ARRAY"), prop("root.table[].urls", "ARRAY"), prop("root.table[].urls[]", "STRING")), new HashMap<String, String>() { { put("root.table[0].name", "a"); put("root.table[0].age", "20"); put("root.table[0].urls[1]", "http://2"); put("root.table[0].urls[0]", "http://1"); put("root.table[1].name", "b"); put("root.table[1].age", "30"); } }); assertEquals(1, object.size()); final JsonArray table = object.getJsonObject("root").getJsonArray("table"); assertEquals(2, table.size()); assertFalse(table.getJsonObject(1).containsKey("urls")); final JsonObject first = table.getJsonObject(0); assertTrue(first.containsKey("urls")); assertEquals(asList("http://1", "http://2"), first .getJsonArray("urls") .stream() .map(JsonString.class::cast) .map(JsonString::getString) .collect(toList())); } @Test void unflattenPrimitivesRoot() { final JsonObject object = formatter .unflatten(asList(prop("root", "OBJECT"), prop("root.name", "STRING"), prop("root.age", "NUMBER"), prop("root.toggle", "BOOLEAN")), new HashMap<String, String>() { { put("root.name", "Sombody"); put("root.age", "30"); put("root.toggle", "true"); } }); assertEquals(1, object.size()); final JsonObject root = object.getJsonObject("root"); assertEquals(3, root.size()); assertEquals("Sombody", root.getString("name")); assertEquals(30, root.getJsonNumber("age").longValue()); assertTrue(root.getBoolean("toggle")); } @Test void unflattenPrimitivesNested() { final JsonObject object = formatter .unflatten( asList(prop("root", "OBJECT"), prop("root.nested1", "OBJECT"), prop("root.nested2", "OBJECT"), prop("root.nested3", "OBJECT"), // ignored in this test prop("root.nested2.name", "STRING"), prop("root.nested1.name", "STRING"), prop("root.nested1.age", "NUMBER"), prop("root.nested1.toggle", "BOOLEAN")), new HashMap<String, String>() { { put("root.nested1.name", "Sombody"); put("root.nested1.age", "30"); put("root.nested1.toggle", "true"); put("root.nested2.name", "Other"); } }); assertEquals(1, object.size()); final JsonObject root = object.getJsonObject("root"); assertEquals(2, root.size()); final JsonObject nested1 = root.getJsonObject("nested1"); assertEquals(3, nested1.size()); final JsonObject nested2 = root.getJsonObject("nested2"); assertFalse(root.containsKey("nested3")); assertEquals(1, nested2.size()); assertEquals("Sombody", nested1.getString("name")); assertEquals("Other", nested2.getString("name")); assertEquals(30, nested1.getJsonNumber("age").longValue()); assertTrue(nested1.getBoolean("toggle")); } private SimplePropertyDefinition prop(final String path, final String type) { return new SimplePropertyDefinition(path, path.substring(path.lastIndexOf('.') + 1), null, type, null, null, emptyMap(), null, new LinkedHashMap<>()); } }
component-form/component-server-proxy-parent/component-server-proxy/src/test/java/org/talend/sdk/component/proxy/service/ConfigurationFormatterImplTest.java
/** * Copyright (C) 2006-2018 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.talend.sdk.component.proxy.service; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.inject.Inject; import javax.json.JsonArray; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import javax.json.JsonString; import javax.json.bind.Jsonb; import org.junit.jupiter.api.Test; import org.talend.sdk.component.proxy.service.qualifier.UiSpecProxy; import org.talend.sdk.component.proxy.test.CdiInject; import org.talend.sdk.component.proxy.test.WithServer; import org.talend.sdk.component.server.front.model.ComponentDetail; import org.talend.sdk.component.server.front.model.PropertyValidation; import org.talend.sdk.component.server.front.model.SimplePropertyDefinition; @CdiInject @WithServer class ConfigurationFormatterImplTest { @Inject private ConfigurationFormatterImpl formatter; @Inject @UiSpecProxy private JsonBuilderFactory factory; @Inject @UiSpecProxy private Jsonb jsonb; @Test void flattenMarketo() { final Map<String, String> properties = formatter .flatten(factory .createObjectBuilder() .add("dataStore", factory .createObjectBuilder() .add("clientId", "xxxx") .add("clientSecret", "yyyy") .add("endpoint", "https://foo.bar.colm")) .build()); assertEquals(3, properties.size()); assertEquals(properties.get("dataStore.clientId"), "xxxx"); assertEquals(properties.get("dataStore.clientSecret"), "yyyy"); assertEquals(properties.get("dataStore.endpoint"), "https://foo.bar.colm"); } @Test void unflattenMarketo() throws IOException { final ComponentDetail detail; try (final InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("marketo.form.json")) { detail = jsonb.fromJson(stream, ComponentDetail.class); } final Map<String, String> properties = new HashMap<>(); properties.put("configuration.activityTypeIds[0].activity", "FOO"); final JsonObject object = formatter.unflatten(detail.getProperties(), properties); assertEquals(1, object.size()); } @Test void flattenFlatObject() { final JsonObject from = factory.createObjectBuilder().add("name", "N").add("age", 20.).build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("name", "N"); put("age", "20.0"); } }, flatten); } @Test void flattenMaxBatchSize() { final JsonObject model = formatter .unflatten(asList( new SimplePropertyDefinition("configuration", "configuration", "configuration", "OBJECT", null, new PropertyValidation(), emptyMap(), null, new LinkedHashMap<>()), new SimplePropertyDefinition("configuration.$maxBatchSize", "$maxBatchSize", "$maxBatchSize", "NUMBER", null, new PropertyValidation(), emptyMap(), null, new LinkedHashMap<>())), singletonMap("configuration.$maxBatchSize", "1000.0")); assertEquals(1000., model.getJsonObject("configuration").getJsonNumber("$maxBatchSize").doubleValue()); } @Test void flattenSimpleArray() { final JsonObject from = factory .createObjectBuilder() .add("urls", factory.createArrayBuilder().add("a").add("b").build()) .build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("urls[0]", "a"); put("urls[1]", "b"); } }, flatten); } @Test void flattenObjectArray() { final JsonObject from = factory .createObjectBuilder() .add("people", factory .createArrayBuilder() .add(factory.createObjectBuilder().add("name", "First").add("age", 20)) .add(factory.createObjectBuilder().add("name", "Second").add("age", 30)) .build()) .build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("people[0].name", "First"); put("people[0].age", "20.0"); put("people[1].name", "Second"); put("people[1].age", "30.0"); } }, flatten); } @Test void flattenNestedObject() { final JsonObject from = factory .createObjectBuilder() .add("config", factory.createObjectBuilder().add("name", "N").add("age", 20.).build()) .build(); final Map<String, String> flatten = formatter.flatten(from); assertEquals(new HashMap<String, String>() { { put("config.name", "N"); put("config.age", "20.0"); } }, flatten); } @Test void unflattenTable() { final JsonObject object = formatter .unflatten(asList(prop("root", "OBJECT"), prop("root.table", "ARRAY"), prop("root.table[]", "STRING")), new HashMap<String, String>() { { put("root.table[0]", "a"); put("root.table[1]", "b"); } }); assertEquals(1, object.size()); final JsonObject root = object.getJsonObject("root"); assertEquals(1, root.size()); assertEquals(asList("a", "b"), root .getJsonArray("table") .stream() .map(JsonString.class::cast) .map(JsonString::getString) .collect(toList())); } @Test void unflattenTableOfObject() { final JsonObject object = formatter .unflatten( asList(prop("root", "OBJECT"), prop("root.table", "ARRAY"), prop("root.table[].name", "STRING"), prop("root.table[].age", "NUMBER")), new HashMap<String, String>() { { put("root.table[0].name", "a"); put("root.table[0].age", "20"); put("root.table[1].name", "b"); put("root.table[1].age", "30"); } }); assertEquals(1, object.size()); final JsonObject root = object.getJsonObject("root"); assertEquals(1, root.size()); final JsonArray table = root.getJsonArray("table"); assertEquals(2, table.size()); assertEquals(asList("a", "b"), table.stream().map(JsonObject.class::cast).map(o -> o.getString("name")).collect(toList())); } @Test void unflattenComplex() { final JsonObject object = formatter .unflatten( asList(prop("root", "OBJECT"), prop("root.table", "ARRAY"), prop("root.table[].urls", "ARRAY"), prop("root.table[].urls[]", "STRING")), new HashMap<String, String>() { { put("root.table[0].name", "a"); put("root.table[0].age", "20"); put("root.table[0].urls[1]", "http://2"); put("root.table[0].urls[0]", "http://1"); put("root.table[1].name", "b"); put("root.table[1].age", "30"); } }); assertEquals(1, object.size()); final JsonArray table = object.getJsonObject("root").getJsonArray("table"); assertEquals(2, table.size()); assertFalse(table.getJsonObject(1).containsKey("urls")); final JsonObject first = table.getJsonObject(0); assertTrue(first.containsKey("urls")); assertEquals(asList("http://1", "http://2"), first .getJsonArray("urls") .stream() .map(JsonString.class::cast) .map(JsonString::getString) .collect(toList())); } @Test void unflattenPrimitivesRoot() { final JsonObject object = formatter .unflatten(asList(prop("root", "OBJECT"), prop("root.name", "STRING"), prop("root.age", "NUMBER"), prop("root.toggle", "BOOLEAN")), new HashMap<String, String>() { { put("root.name", "Sombody"); put("root.age", "30"); put("root.toggle", "true"); } }); assertEquals(1, object.size()); final JsonObject root = object.getJsonObject("root"); assertEquals(3, root.size()); assertEquals("Sombody", root.getString("name")); assertEquals(30, root.getJsonNumber("age").longValue()); assertTrue(root.getBoolean("toggle")); } @Test void unflattenPrimitivesNested() { final JsonObject object = formatter .unflatten( asList(prop("root", "OBJECT"), prop("root.nested1", "OBJECT"), prop("root.nested2", "OBJECT"), prop("root.nested3", "OBJECT"), // ignored in this test prop("root.nested2.name", "STRING"), prop("root.nested1.name", "STRING"), prop("root.nested1.age", "NUMBER"), prop("root.nested1.toggle", "BOOLEAN")), new HashMap<String, String>() { { put("root.nested1.name", "Sombody"); put("root.nested1.age", "30"); put("root.nested1.toggle", "true"); put("root.nested2.name", "Other"); } }); assertEquals(1, object.size()); final JsonObject root = object.getJsonObject("root"); assertEquals(2, root.size()); final JsonObject nested1 = root.getJsonObject("nested1"); assertEquals(3, nested1.size()); final JsonObject nested2 = root.getJsonObject("nested2"); assertFalse(root.containsKey("nested3")); assertEquals(1, nested2.size()); assertEquals("Sombody", nested1.getString("name")); assertEquals("Other", nested2.getString("name")); assertEquals(30, nested1.getJsonNumber("age").longValue()); assertTrue(nested1.getBoolean("toggle")); } private SimplePropertyDefinition prop(final String path, final String type) { return new SimplePropertyDefinition(path, path.substring(path.lastIndexOf('.') + 1), null, type, null, null, emptyMap(), null, new LinkedHashMap<>()); } }
TCOMP-1155 ensure we support null in arrays in server proxy
component-form/component-server-proxy-parent/component-server-proxy/src/test/java/org/talend/sdk/component/proxy/service/ConfigurationFormatterImplTest.java
TCOMP-1155 ensure we support null in arrays in server proxy
<ide><path>omponent-form/component-server-proxy-parent/component-server-proxy/src/test/java/org/talend/sdk/component/proxy/service/ConfigurationFormatterImplTest.java <ide> } <ide> <ide> @Test <add> void flattenArrayWithNull() { <add> final JsonObject from = factory <add> .createObjectBuilder() <add> .add("urls", factory.createArrayBuilder().add("a").addNull().add("b").build()) <add> .build(); <add> final Map<String, String> flatten = formatter.flatten(from); <add> assertEquals(new HashMap<String, String>() { <add> <add> { <add> put("urls[0]", "a"); <add> put("urls[2]", "b"); <add> } <add> }, flatten); <add> } <add> <add> @Test <ide> void flattenObjectArray() { <ide> final JsonObject from = factory <ide> .createObjectBuilder()
Java
apache-2.0
6b09d1045a2ed369ec5ecce9e5dc512b82f312b8
0
robertwb/incubator-beam,chamikaramj/beam,apache/beam,apache/beam,lukecwik/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,chamikaramj/beam,apache/beam,robertwb/incubator-beam,lukecwik/incubator-beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,apache/beam,apache/beam,chamikaramj/beam,chamikaramj/beam,robertwb/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,robertwb/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,apache/beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,apache/beam,apache/beam,robertwb/incubator-beam,apache/beam,robertwb/incubator-beam
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.aws2.options; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkNotNull; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.util.NameTransformer; import com.google.auto.service.AutoService; import java.io.IOException; import java.net.URI; import java.time.Duration; import java.util.Map; import java.util.function.Supplier; import org.apache.beam.repackaged.core.org.apache.commons.lang3.reflect.FieldUtils; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.annotations.Experimental.Kind; import org.apache.beam.sdk.io.aws2.s3.SSECustomerKey; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.auth.credentials.ContainerCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.credentials.SystemPropertyCredentialsProvider; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.apache.ProxyConfiguration; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.auth.StsAssumeRoleCredentialsProvider; import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; import software.amazon.awssdk.utils.AttributeMap; /** * A Jackson {@link Module} that registers a {@link JsonSerializer} and {@link JsonDeserializer} for * {@link AwsCredentialsProvider} and some subclasses. The serialized form is a JSON map. */ @Experimental(Kind.SOURCE_SINK) @AutoService(Module.class) public class AwsModule extends SimpleModule { private static final String ACCESS_KEY_ID = "accessKeyId"; private static final String SECRET_ACCESS_KEY = "secretAccessKey"; private static final String SESSION_TOKEN = "sessionToken"; public static final String CONNECTION_ACQUIRE_TIMEOUT = "connectionAcquisitionTimeout"; public static final String CONNECTION_MAX_IDLE_TIMEOUT = "connectionMaxIdleTime"; public static final String CONNECTION_TIMEOUT = "connectionTimeout"; public static final String CONNECTION_TIME_TO_LIVE = "connectionTimeToLive"; public static final String MAX_CONNECTIONS = "maxConnections"; public static final String READ_TIMEOUT = "socketTimeout"; public AwsModule() { super("AwsModule"); } @Override public void setupModule(SetupContext cxt) { cxt.setMixInAnnotations(AwsCredentialsProvider.class, AwsCredentialsProviderMixin.class); cxt.setMixInAnnotations(ProxyConfiguration.class, ProxyConfigurationMixin.class); cxt.setMixInAnnotations(AttributeMap.class, AttributeMapMixin.class); cxt.setMixInAnnotations(SSECustomerKey.class, SSECustomerKeyMixin.class); cxt.setMixInAnnotations(SSECustomerKey.Builder.class, SSECustomerKeyBuilderMixin.class); super.setupModule(cxt); } /** A mixin to add Jackson annotations to {@link AwsCredentialsProvider}. */ @JsonDeserialize(using = AwsCredentialsProviderDeserializer.class) @JsonSerialize(using = AWSCredentialsProviderSerializer.class) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) private static class AwsCredentialsProviderMixin {} private static class AwsCredentialsProviderDeserializer extends JsonDeserializer<AwsCredentialsProvider> { @Override public AwsCredentialsProvider deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { return context.readValue(jsonParser, AwsCredentialsProvider.class); } @Override public AwsCredentialsProvider deserializeWithType( JsonParser jsonParser, DeserializationContext context, TypeDeserializer typeDeserializer) throws IOException { ObjectNode json = checkNotNull( jsonParser.readValueAs(new TypeReference<ObjectNode>() {}), "Serialized AWS credentials provider is null"); String typeNameKey = typeDeserializer.getPropertyName(); String typeName = getNotNull(json, typeNameKey, "unknown"); json.remove(typeNameKey); if (hasName(StaticCredentialsProvider.class, typeName)) { boolean isSession = json.has(SESSION_TOKEN); if (isSession) { return StaticCredentialsProvider.create( AwsSessionCredentials.create( getNotNull(json, ACCESS_KEY_ID, typeName), getNotNull(json, SECRET_ACCESS_KEY, typeName), getNotNull(json, SESSION_TOKEN, typeName))); } else { return StaticCredentialsProvider.create( AwsBasicCredentials.create( getNotNull(json, ACCESS_KEY_ID, typeName), getNotNull(json, SECRET_ACCESS_KEY, typeName))); } } else if (hasName(DefaultCredentialsProvider.class, typeName)) { return DefaultCredentialsProvider.create(); } else if (hasName(EnvironmentVariableCredentialsProvider.class, typeName)) { return EnvironmentVariableCredentialsProvider.create(); } else if (hasName(SystemPropertyCredentialsProvider.class, typeName)) { return SystemPropertyCredentialsProvider.create(); } else if (hasName(ProfileCredentialsProvider.class, typeName)) { return ProfileCredentialsProvider.create(); } else if (hasName(ContainerCredentialsProvider.class, typeName)) { return ContainerCredentialsProvider.builder().build(); } else if (typeName.equals(StsAssumeRoleCredentialsProvider.class.getSimpleName())) { Class<? extends AssumeRoleRequest.Builder> clazz = AssumeRoleRequest.serializableBuilderClass(); return StsAssumeRoleCredentialsProvider.builder() .refreshRequest(jsonParser.getCodec().treeToValue(json, clazz).build()) .stsClient(StsClient.create()) .build(); } else { throw new IOException( String.format("AWS credential provider type '%s' is not supported", typeName)); } } private String getNotNull(JsonNode json, String key, String typeName) { JsonNode node = json.get(key); checkNotNull(node, "AWS credentials provider type '%s' is missing '%s'", typeName, key); return node.textValue(); } private boolean hasName(Class<? extends AwsCredentialsProvider> clazz, String typeName) { return clazz.getSimpleName().equals(typeName); } } private static class AWSCredentialsProviderSerializer extends JsonSerializer<AwsCredentialsProvider> { // These providers are singletons, so don't require any serialization, other than type. private static final ImmutableSet<Object> SINGLETON_CREDENTIAL_PROVIDERS = ImmutableSet.of( DefaultCredentialsProvider.class, EnvironmentVariableCredentialsProvider.class, SystemPropertyCredentialsProvider.class, ProfileCredentialsProvider.class, ContainerCredentialsProvider.class); @Override public void serialize( AwsCredentialsProvider credentialsProvider, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException { serializer.defaultSerializeValue(credentialsProvider, jsonGenerator); } @Override public void serializeWithType( AwsCredentialsProvider credentialsProvider, JsonGenerator jsonGenerator, SerializerProvider serializer, TypeSerializer typeSerializer) throws IOException { // BEAM-11958 Use deprecated Jackson APIs to be compatible with older versions of jackson typeSerializer.writeTypePrefixForObject(credentialsProvider, jsonGenerator); Class<?> providerClass = credentialsProvider.getClass(); if (providerClass.equals(StaticCredentialsProvider.class)) { AwsCredentials credentials = credentialsProvider.resolveCredentials(); if (credentials.getClass().equals(AwsSessionCredentials.class)) { AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials; jsonGenerator.writeStringField(ACCESS_KEY_ID, sessionCredentials.accessKeyId()); jsonGenerator.writeStringField(SECRET_ACCESS_KEY, sessionCredentials.secretAccessKey()); jsonGenerator.writeStringField(SESSION_TOKEN, sessionCredentials.sessionToken()); } else { jsonGenerator.writeStringField(ACCESS_KEY_ID, credentials.accessKeyId()); jsonGenerator.writeStringField(SECRET_ACCESS_KEY, credentials.secretAccessKey()); } } else if (providerClass.equals(StsAssumeRoleCredentialsProvider.class)) { Supplier<AssumeRoleRequest> reqSupplier = (Supplier<AssumeRoleRequest>) readField(credentialsProvider, "assumeRoleRequestSupplier"); serializer .findValueSerializer(AssumeRoleRequest.serializableBuilderClass()) .unwrappingSerializer(NameTransformer.NOP) .serialize(reqSupplier.get().toBuilder(), jsonGenerator, serializer); } else if (!SINGLETON_CREDENTIAL_PROVIDERS.contains(providerClass)) { throw new IllegalArgumentException( "Unsupported AWS credentials provider type " + providerClass); } // BEAM-11958 Use deprecated Jackson APIs to be compatible with older versions of jackson typeSerializer.writeTypeSuffixForObject(credentialsProvider, jsonGenerator); } private Object readField(AwsCredentialsProvider provider, String fieldName) throws IOException { try { return FieldUtils.readField(provider, fieldName, true); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IOException( String.format( "Failed to access private field '%s' of AWS credential provider type '%s' with reflection", fieldName, provider.getClass().getSimpleName()), e); } } } /** A mixin to add Jackson annotations to {@link ProxyConfiguration}. */ @JsonDeserialize(using = ProxyConfigurationDeserializer.class) @JsonSerialize(using = ProxyConfigurationSerializer.class) private static class ProxyConfigurationMixin {} private static class ProxyConfigurationDeserializer extends JsonDeserializer<ProxyConfiguration> { @Override public ProxyConfiguration deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { Map<String, String> asMap = checkNotNull( jsonParser.readValueAs(new TypeReference<Map<String, String>>() {}), "Serialized ProxyConfiguration is null"); ProxyConfiguration.Builder builder = ProxyConfiguration.builder(); final String endpoint = asMap.get("endpoint"); if (endpoint != null) { builder.endpoint(URI.create(endpoint)); } final String username = asMap.get("username"); if (username != null) { builder.username(username); } final String password = asMap.get("password"); if (password != null) { builder.password(password); } // defaults to FALSE / disabled Boolean useSystemPropertyValues = Boolean.valueOf(asMap.get("useSystemPropertyValues")); return builder.useSystemPropertyValues(useSystemPropertyValues).build(); } } private static class ProxyConfigurationSerializer extends JsonSerializer<ProxyConfiguration> { @Override public void serialize( ProxyConfiguration proxyConfiguration, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException { // proxyConfiguration.endpoint() is private so we have to build it manually. final String endpoint = proxyConfiguration.scheme() + "://" + proxyConfiguration.host() + ":" + proxyConfiguration.port(); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("endpoint", endpoint); jsonGenerator.writeStringField("username", proxyConfiguration.username()); jsonGenerator.writeStringField("password", proxyConfiguration.password()); jsonGenerator.writeEndObject(); } } /** A mixin to add Jackson annotations to {@link AttributeMap}. */ @JsonSerialize(using = AttributeMapSerializer.class) @JsonDeserialize(using = AttributeMapDeserializer.class) private static class AttributeMapMixin {} private static class AttributeMapDeserializer extends JsonDeserializer<AttributeMap> { @Override public AttributeMap deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { Map<String, String> map = checkNotNull( jsonParser.readValueAs(new TypeReference<Map<String, String>>() {}), "Serialized AttributeMap is null"); // Add new attributes below. final AttributeMap.Builder attributeMapBuilder = AttributeMap.builder(); if (map.containsKey(CONNECTION_ACQUIRE_TIMEOUT)) { attributeMapBuilder.put( SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT, Duration.parse(map.get(CONNECTION_ACQUIRE_TIMEOUT))); } if (map.containsKey(CONNECTION_MAX_IDLE_TIMEOUT)) { attributeMapBuilder.put( SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT, Duration.parse(map.get(CONNECTION_MAX_IDLE_TIMEOUT))); } if (map.containsKey(CONNECTION_TIMEOUT)) { attributeMapBuilder.put( SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.parse(map.get(CONNECTION_TIMEOUT))); } if (map.containsKey(CONNECTION_TIME_TO_LIVE)) { attributeMapBuilder.put( SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE, Duration.parse(map.get(CONNECTION_TIME_TO_LIVE))); } if (map.containsKey(MAX_CONNECTIONS)) { attributeMapBuilder.put( SdkHttpConfigurationOption.MAX_CONNECTIONS, Integer.parseInt(map.get(MAX_CONNECTIONS))); } if (map.containsKey(READ_TIMEOUT)) { attributeMapBuilder.put( SdkHttpConfigurationOption.READ_TIMEOUT, Duration.parse(map.get(READ_TIMEOUT))); } return attributeMapBuilder.build(); } } private static class AttributeMapSerializer extends JsonSerializer<AttributeMap> { @Override public void serialize( AttributeMap attributeMap, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException { jsonGenerator.writeStartObject(); if (attributeMap.containsKey(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT)) { jsonGenerator.writeStringField( CONNECTION_ACQUIRE_TIMEOUT, String.valueOf( attributeMap.get(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT)) { jsonGenerator.writeStringField( CONNECTION_MAX_IDLE_TIMEOUT, String.valueOf( attributeMap.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.CONNECTION_TIMEOUT)) { jsonGenerator.writeStringField( CONNECTION_TIMEOUT, String.valueOf(attributeMap.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE)) { jsonGenerator.writeStringField( CONNECTION_TIME_TO_LIVE, String.valueOf(attributeMap.get(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.MAX_CONNECTIONS)) { jsonGenerator.writeStringField( MAX_CONNECTIONS, String.valueOf(attributeMap.get(SdkHttpConfigurationOption.MAX_CONNECTIONS))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.READ_TIMEOUT)) { jsonGenerator.writeStringField( READ_TIMEOUT, String.valueOf(attributeMap.get(SdkHttpConfigurationOption.READ_TIMEOUT))); } jsonGenerator.writeEndObject(); } } @JsonDeserialize(builder = SSECustomerKey.Builder.class) private static class SSECustomerKeyMixin {} @JsonPOJOBuilder(withPrefix = "") private static class SSECustomerKeyBuilderMixin {} }
sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/options/AwsModule.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.aws2.options; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkNotNull; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.util.NameTransformer; import com.google.auto.service.AutoService; import java.io.IOException; import java.net.URI; import java.time.Duration; import java.util.Map; import java.util.function.Supplier; import org.apache.beam.repackaged.core.org.apache.commons.lang3.reflect.FieldUtils; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.annotations.Experimental.Kind; import org.apache.beam.sdk.io.aws2.s3.SSECustomerKey; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.auth.credentials.ContainerCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.credentials.SystemPropertyCredentialsProvider; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.apache.ProxyConfiguration; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.auth.StsAssumeRoleCredentialsProvider; import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; import software.amazon.awssdk.utils.AttributeMap; /** * A Jackson {@link Module} that registers a {@link JsonSerializer} and {@link JsonDeserializer} for * {@link AwsCredentialsProvider} and some subclasses. The serialized form is a JSON map. */ @Experimental(Kind.SOURCE_SINK) @AutoService(Module.class) public class AwsModule extends SimpleModule { private static final String ACCESS_KEY_ID = "accessKeyId"; private static final String SECRET_ACCESS_KEY = "secretAccessKey"; private static final String SESSION_TOKEN = "sessionToken"; public static final String CONNECTION_ACQUIRE_TIMEOUT = "connectionAcquisitionTimeout"; public static final String CONNECTION_MAX_IDLE_TIMEOUT = "connectionMaxIdleTime"; public static final String CONNECTION_TIMEOUT = "connectionTimeout"; public static final String CONNECTION_TIME_TO_LIVE = "connectionTimeToLive"; public static final String MAX_CONNECTIONS = "maxConnections"; public static final String READ_TIMEOUT = "socketTimeout"; @SuppressWarnings({"nullness"}) public AwsModule() { super("AwsModule"); setMixInAnnotation(AwsCredentialsProvider.class, AwsCredentialsProviderMixin.class); setMixInAnnotation(ProxyConfiguration.class, ProxyConfigurationMixin.class); setMixInAnnotation(AttributeMap.class, AttributeMapMixin.class); setMixInAnnotation(SSECustomerKey.class, SSECustomerKeyMixin.class); setMixInAnnotation(SSECustomerKey.Builder.class, SSECustomerKeyBuilderMixin.class); } /** A mixin to add Jackson annotations to {@link AwsCredentialsProvider}. */ @JsonDeserialize(using = AwsCredentialsProviderDeserializer.class) @JsonSerialize(using = AWSCredentialsProviderSerializer.class) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) private static class AwsCredentialsProviderMixin {} private static class AwsCredentialsProviderDeserializer extends JsonDeserializer<AwsCredentialsProvider> { @Override public AwsCredentialsProvider deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { return context.readValue(jsonParser, AwsCredentialsProvider.class); } @Override public AwsCredentialsProvider deserializeWithType( JsonParser jsonParser, DeserializationContext context, TypeDeserializer typeDeserializer) throws IOException { ObjectNode json = checkNotNull( jsonParser.readValueAs(new TypeReference<ObjectNode>() {}), "Serialized AWS credentials provider is null"); String typeNameKey = typeDeserializer.getPropertyName(); String typeName = getNotNull(json, typeNameKey, "unknown"); json.remove(typeNameKey); if (hasName(StaticCredentialsProvider.class, typeName)) { boolean isSession = json.has(SESSION_TOKEN); if (isSession) { return StaticCredentialsProvider.create( AwsSessionCredentials.create( getNotNull(json, ACCESS_KEY_ID, typeName), getNotNull(json, SECRET_ACCESS_KEY, typeName), getNotNull(json, SESSION_TOKEN, typeName))); } else { return StaticCredentialsProvider.create( AwsBasicCredentials.create( getNotNull(json, ACCESS_KEY_ID, typeName), getNotNull(json, SECRET_ACCESS_KEY, typeName))); } } else if (hasName(DefaultCredentialsProvider.class, typeName)) { return DefaultCredentialsProvider.create(); } else if (hasName(EnvironmentVariableCredentialsProvider.class, typeName)) { return EnvironmentVariableCredentialsProvider.create(); } else if (hasName(SystemPropertyCredentialsProvider.class, typeName)) { return SystemPropertyCredentialsProvider.create(); } else if (hasName(ProfileCredentialsProvider.class, typeName)) { return ProfileCredentialsProvider.create(); } else if (hasName(ContainerCredentialsProvider.class, typeName)) { return ContainerCredentialsProvider.builder().build(); } else if (typeName.equals(StsAssumeRoleCredentialsProvider.class.getSimpleName())) { Class<? extends AssumeRoleRequest.Builder> clazz = AssumeRoleRequest.serializableBuilderClass(); return StsAssumeRoleCredentialsProvider.builder() .refreshRequest(jsonParser.getCodec().treeToValue(json, clazz).build()) .stsClient(StsClient.create()) .build(); } else { throw new IOException( String.format("AWS credential provider type '%s' is not supported", typeName)); } } private String getNotNull(JsonNode json, String key, String typeName) { JsonNode node = json.get(key); checkNotNull(node, "AWS credentials provider type '%s' is missing '%s'", typeName, key); return node.textValue(); } private boolean hasName(Class<? extends AwsCredentialsProvider> clazz, String typeName) { return clazz.getSimpleName().equals(typeName); } } private static class AWSCredentialsProviderSerializer extends JsonSerializer<AwsCredentialsProvider> { // These providers are singletons, so don't require any serialization, other than type. private static final ImmutableSet<Object> SINGLETON_CREDENTIAL_PROVIDERS = ImmutableSet.of( DefaultCredentialsProvider.class, EnvironmentVariableCredentialsProvider.class, SystemPropertyCredentialsProvider.class, ProfileCredentialsProvider.class, ContainerCredentialsProvider.class); @Override public void serialize( AwsCredentialsProvider credentialsProvider, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException { serializer.defaultSerializeValue(credentialsProvider, jsonGenerator); } @Override public void serializeWithType( AwsCredentialsProvider credentialsProvider, JsonGenerator jsonGenerator, SerializerProvider serializer, TypeSerializer typeSerializer) throws IOException { // BEAM-11958 Use deprecated Jackson APIs to be compatible with older versions of jackson typeSerializer.writeTypePrefixForObject(credentialsProvider, jsonGenerator); Class<?> providerClass = credentialsProvider.getClass(); if (providerClass.equals(StaticCredentialsProvider.class)) { AwsCredentials credentials = credentialsProvider.resolveCredentials(); if (credentials.getClass().equals(AwsSessionCredentials.class)) { AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials; jsonGenerator.writeStringField(ACCESS_KEY_ID, sessionCredentials.accessKeyId()); jsonGenerator.writeStringField(SECRET_ACCESS_KEY, sessionCredentials.secretAccessKey()); jsonGenerator.writeStringField(SESSION_TOKEN, sessionCredentials.sessionToken()); } else { jsonGenerator.writeStringField(ACCESS_KEY_ID, credentials.accessKeyId()); jsonGenerator.writeStringField(SECRET_ACCESS_KEY, credentials.secretAccessKey()); } } else if (providerClass.equals(StsAssumeRoleCredentialsProvider.class)) { Supplier<AssumeRoleRequest> reqSupplier = (Supplier<AssumeRoleRequest>) readField(credentialsProvider, "assumeRoleRequestSupplier"); serializer .findValueSerializer(AssumeRoleRequest.serializableBuilderClass()) .unwrappingSerializer(NameTransformer.NOP) .serialize(reqSupplier.get().toBuilder(), jsonGenerator, serializer); } else if (!SINGLETON_CREDENTIAL_PROVIDERS.contains(providerClass)) { throw new IllegalArgumentException( "Unsupported AWS credentials provider type " + providerClass); } // BEAM-11958 Use deprecated Jackson APIs to be compatible with older versions of jackson typeSerializer.writeTypeSuffixForObject(credentialsProvider, jsonGenerator); } private Object readField(AwsCredentialsProvider provider, String fieldName) throws IOException { try { return FieldUtils.readField(provider, fieldName, true); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IOException( String.format( "Failed to access private field '%s' of AWS credential provider type '%s' with reflection", fieldName, provider.getClass().getSimpleName()), e); } } } /** A mixin to add Jackson annotations to {@link ProxyConfiguration}. */ @JsonDeserialize(using = ProxyConfigurationDeserializer.class) @JsonSerialize(using = ProxyConfigurationSerializer.class) private static class ProxyConfigurationMixin {} private static class ProxyConfigurationDeserializer extends JsonDeserializer<ProxyConfiguration> { @Override public ProxyConfiguration deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { Map<String, String> asMap = checkNotNull( jsonParser.readValueAs(new TypeReference<Map<String, String>>() {}), "Serialized ProxyConfiguration is null"); ProxyConfiguration.Builder builder = ProxyConfiguration.builder(); final String endpoint = asMap.get("endpoint"); if (endpoint != null) { builder.endpoint(URI.create(endpoint)); } final String username = asMap.get("username"); if (username != null) { builder.username(username); } final String password = asMap.get("password"); if (password != null) { builder.password(password); } // defaults to FALSE / disabled Boolean useSystemPropertyValues = Boolean.valueOf(asMap.get("useSystemPropertyValues")); return builder.useSystemPropertyValues(useSystemPropertyValues).build(); } } private static class ProxyConfigurationSerializer extends JsonSerializer<ProxyConfiguration> { @Override public void serialize( ProxyConfiguration proxyConfiguration, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException { // proxyConfiguration.endpoint() is private so we have to build it manually. final String endpoint = proxyConfiguration.scheme() + "://" + proxyConfiguration.host() + ":" + proxyConfiguration.port(); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("endpoint", endpoint); jsonGenerator.writeStringField("username", proxyConfiguration.username()); jsonGenerator.writeStringField("password", proxyConfiguration.password()); jsonGenerator.writeEndObject(); } } /** A mixin to add Jackson annotations to {@link AttributeMap}. */ @JsonSerialize(using = AttributeMapSerializer.class) @JsonDeserialize(using = AttributeMapDeserializer.class) private static class AttributeMapMixin {} private static class AttributeMapDeserializer extends JsonDeserializer<AttributeMap> { @Override public AttributeMap deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { Map<String, String> map = checkNotNull( jsonParser.readValueAs(new TypeReference<Map<String, String>>() {}), "Serialized AttributeMap is null"); // Add new attributes below. final AttributeMap.Builder attributeMapBuilder = AttributeMap.builder(); if (map.containsKey(CONNECTION_ACQUIRE_TIMEOUT)) { attributeMapBuilder.put( SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT, Duration.parse(map.get(CONNECTION_ACQUIRE_TIMEOUT))); } if (map.containsKey(CONNECTION_MAX_IDLE_TIMEOUT)) { attributeMapBuilder.put( SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT, Duration.parse(map.get(CONNECTION_MAX_IDLE_TIMEOUT))); } if (map.containsKey(CONNECTION_TIMEOUT)) { attributeMapBuilder.put( SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.parse(map.get(CONNECTION_TIMEOUT))); } if (map.containsKey(CONNECTION_TIME_TO_LIVE)) { attributeMapBuilder.put( SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE, Duration.parse(map.get(CONNECTION_TIME_TO_LIVE))); } if (map.containsKey(MAX_CONNECTIONS)) { attributeMapBuilder.put( SdkHttpConfigurationOption.MAX_CONNECTIONS, Integer.parseInt(map.get(MAX_CONNECTIONS))); } if (map.containsKey(READ_TIMEOUT)) { attributeMapBuilder.put( SdkHttpConfigurationOption.READ_TIMEOUT, Duration.parse(map.get(READ_TIMEOUT))); } return attributeMapBuilder.build(); } } private static class AttributeMapSerializer extends JsonSerializer<AttributeMap> { @Override public void serialize( AttributeMap attributeMap, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException { jsonGenerator.writeStartObject(); if (attributeMap.containsKey(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT)) { jsonGenerator.writeStringField( CONNECTION_ACQUIRE_TIMEOUT, String.valueOf( attributeMap.get(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT)) { jsonGenerator.writeStringField( CONNECTION_MAX_IDLE_TIMEOUT, String.valueOf( attributeMap.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.CONNECTION_TIMEOUT)) { jsonGenerator.writeStringField( CONNECTION_TIMEOUT, String.valueOf(attributeMap.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE)) { jsonGenerator.writeStringField( CONNECTION_TIME_TO_LIVE, String.valueOf(attributeMap.get(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.MAX_CONNECTIONS)) { jsonGenerator.writeStringField( MAX_CONNECTIONS, String.valueOf(attributeMap.get(SdkHttpConfigurationOption.MAX_CONNECTIONS))); } if (attributeMap.containsKey(SdkHttpConfigurationOption.READ_TIMEOUT)) { jsonGenerator.writeStringField( READ_TIMEOUT, String.valueOf(attributeMap.get(SdkHttpConfigurationOption.READ_TIMEOUT))); } jsonGenerator.writeEndObject(); } } @JsonDeserialize(builder = SSECustomerKey.Builder.class) private static class SSECustomerKeyMixin {} @JsonPOJOBuilder(withPrefix = "") private static class SSECustomerKeyBuilderMixin {} }
[BEAM-13147] Avoid nullness issue during init of AwsModule (AWS Sdk v2)
sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/options/AwsModule.java
[BEAM-13147] Avoid nullness issue during init of AwsModule (AWS Sdk v2)
<ide><path>dks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/options/AwsModule.java <ide> public static final String MAX_CONNECTIONS = "maxConnections"; <ide> public static final String READ_TIMEOUT = "socketTimeout"; <ide> <del> @SuppressWarnings({"nullness"}) <ide> public AwsModule() { <ide> super("AwsModule"); <del> setMixInAnnotation(AwsCredentialsProvider.class, AwsCredentialsProviderMixin.class); <del> setMixInAnnotation(ProxyConfiguration.class, ProxyConfigurationMixin.class); <del> setMixInAnnotation(AttributeMap.class, AttributeMapMixin.class); <del> setMixInAnnotation(SSECustomerKey.class, SSECustomerKeyMixin.class); <del> setMixInAnnotation(SSECustomerKey.Builder.class, SSECustomerKeyBuilderMixin.class); <add> } <add> <add> @Override <add> public void setupModule(SetupContext cxt) { <add> cxt.setMixInAnnotations(AwsCredentialsProvider.class, AwsCredentialsProviderMixin.class); <add> cxt.setMixInAnnotations(ProxyConfiguration.class, ProxyConfigurationMixin.class); <add> cxt.setMixInAnnotations(AttributeMap.class, AttributeMapMixin.class); <add> cxt.setMixInAnnotations(SSECustomerKey.class, SSECustomerKeyMixin.class); <add> cxt.setMixInAnnotations(SSECustomerKey.Builder.class, SSECustomerKeyBuilderMixin.class); <add> super.setupModule(cxt); <ide> } <ide> <ide> /** A mixin to add Jackson annotations to {@link AwsCredentialsProvider}. */
Java
apache-2.0
9bc9ef30a8aa63950e99ca68d1e825f7313ab366
0
open-power/serverwiz,open-power/serverwiz
package com.ibm.ServerWizard2.view; import java.util.Vector; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; 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.DirectoryDialog; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.wb.swt.SWTResourceManager; import com.ibm.ServerWizard2.ServerWizard2; import com.ibm.ServerWizard2.controller.TargetWizardController; import com.ibm.ServerWizard2.model.Connection; import com.ibm.ServerWizard2.model.ConnectionEndpoint; import com.ibm.ServerWizard2.model.Field; import com.ibm.ServerWizard2.model.Target; import com.ibm.ServerWizard2.utility.GithubFile; public class MainDialog extends Dialog { private TableViewer viewer; private Tree tree; private TreeColumn columnName; private Text txtInstanceName; private Combo combo; private Menu popupMenu; private Composite container; private TreeItem selectedEndpoint; private String currentPath; private Target targetForConnections; private ConnectionEndpoint source; private ConnectionEndpoint dest; private TargetWizardController controller; // Buttons private Button btnAddTarget; private Button btnCopyInstance; private Button btnDefaults; private Button btnDeleteTarget; private Button btnSave; private Button btnOpen; private Button btnClone; private Button btnOpenLib; private Button btnDeleteConnection; private Button btnSaveAs; // document state private Boolean dirty = false; public String mrwFilename = ""; private Button btnRunChecks; private SashForm sashForm; private SashForm sashForm_1; private Composite compositeBus; private Label lblInstanceType; private Composite compositeInstance; private Composite composite; private Composite buttonRow1; private Vector<Field> attributes; private Combo cmbBusses; private Label lblChooseBus; private Label lblSelectedCard; private Boolean busMode = false; private TabFolder tabFolder; private TabItem tbtmAddInstances; private TabItem tbtmAddBusses; private Combo cmbCards; private Boolean targetFound = false; private List listBusses; private Label lblBusDirections; private Label lblInstanceDirections; private Composite compositeDir; private Button btnHideBusses; private Button btnShowHidden; private AttributeEditingSupport attributeEditor; private Label label; private Label label_1; /** * Create the dialog. * * @param parentShell */ public MainDialog(Shell parentShell) { super(parentShell); setShellStyle(SWT.BORDER | SWT.MIN | SWT.MAX | SWT.RESIZE | SWT.APPLICATION_MODAL); } protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("ServerWiz2"); } public void setController(TargetWizardController t) { controller = t; } /** * Create contents of the dialog. * * @param parent */ @Override protected Control createDialogArea(Composite parent) { container = (Composite) super.createDialogArea(parent); container.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); GridLayout gl_container = new GridLayout(1, false); gl_container.verticalSpacing = 0; container.setLayout(gl_container); composite = new Composite(container, SWT.NONE); RowLayout rl_composite = new RowLayout(SWT.HORIZONTAL); rl_composite.spacing = 20; rl_composite.wrap = false; rl_composite.fill = true; composite.setLayout(rl_composite); GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1); gd_composite.widthHint = 918; gd_composite.heightHint = 154; composite.setLayoutData(gd_composite); sashForm_1 = new SashForm(container, SWT.BORDER | SWT.VERTICAL); GridData gd_sashForm_1 = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_sashForm_1.heightHint = 375; gd_sashForm_1.widthHint = 712; sashForm_1.setLayoutData(gd_sashForm_1); buttonRow1 = new Composite(container, SWT.NONE); GridData gd_buttonRow1 = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1); gd_buttonRow1.widthHint = 850; buttonRow1.setLayoutData(gd_buttonRow1); GridLayout rl_buttonRow1 = new GridLayout(18, false); buttonRow1.setLayout(rl_buttonRow1); this.createButtonsForButtonBar2(buttonRow1); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); sashForm = new SashForm(sashForm_1, SWT.NONE); // Target Instances View tree = new Tree(sashForm, SWT.BORDER | SWT.VIRTUAL); tree.setHeaderVisible(true); tree.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); columnName = new TreeColumn(tree, 0); columnName.setText("Instances"); columnName .setToolTipText("To add a new instance, choose parent instance. A list of child instances will appear in Instance Type combo.\r\n" + "Select and Instance type. You can optionally enter a custom name. Then click 'Add Instance' button."); columnName.setResizable(true); // Create attribute table viewer = new TableViewer(sashForm_1, SWT.VIRTUAL | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); this.createAttributeTable(); sashForm_1.setWeights(new int[] { 1, 1 }); // ////////////////////////////////////////////////////////// // Tab folders tabFolder = new TabFolder(composite, SWT.NONE); tabFolder.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); tabFolder.setLayoutData(new RowData(SWT.DEFAULT, 119)); tbtmAddInstances = new TabItem(tabFolder, SWT.NONE); tbtmAddInstances.setText("Instances"); // ////////////////////////////////////// // Add instances tab compositeInstance = new Composite(tabFolder, SWT.BORDER); tbtmAddInstances.setControl(compositeInstance); compositeInstance.setLayout(new GridLayout(3, false)); lblInstanceType = new Label(compositeInstance, SWT.NONE); lblInstanceType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblInstanceType.setText("Instance Type:"); lblInstanceType.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); combo = new Combo(compositeInstance, SWT.READ_ONLY); GridData gd_combo = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_combo.widthHint = 167; combo.setLayoutData(gd_combo); combo.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnAddTarget = new Button(compositeInstance, SWT.NONE); btnAddTarget.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); btnAddTarget.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnAddTarget.setText("Add Instance"); btnAddTarget.setEnabled(false); Label lblName = new Label(compositeInstance, SWT.NONE); lblName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblName.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); lblName.setText("Custom Name:"); txtInstanceName = new Text(compositeInstance, SWT.BORDER); GridData gd_txtInstanceName = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtInstanceName.widthHint = 175; txtInstanceName.setLayoutData(gd_txtInstanceName); txtInstanceName.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnDeleteTarget = new Button(compositeInstance, SWT.NONE); btnDeleteTarget.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); btnDeleteTarget.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnDeleteTarget.setText("Delete Instance"); btnShowHidden = new Button(compositeInstance, SWT.CHECK); btnShowHidden.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); GridData gd_btnShowHidden = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnShowHidden.heightHint = 20; btnShowHidden.setLayoutData(gd_btnShowHidden); btnShowHidden.setText(" Show Hidden"); btnCopyInstance = new Button(compositeInstance, SWT.NONE); btnCopyInstance.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1)); btnCopyInstance.setText("Copy Node or Connector"); btnCopyInstance.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnCopyInstance.setEnabled(false); btnDefaults = new Button(compositeInstance, SWT.NONE); btnDefaults.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1)); btnDefaults.setText("Restore Defaults"); btnDefaults.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnDefaults.setEnabled(false); // //////////////////////////////////////////////////// // Add Busses Tab tbtmAddBusses = new TabItem(tabFolder, SWT.NONE); tbtmAddBusses.setText("Busses"); compositeBus = new Composite(tabFolder, SWT.BORDER); tbtmAddBusses.setControl(compositeBus); compositeBus.setLayout(new GridLayout(2, false)); lblChooseBus = new Label(compositeBus, SWT.NONE); lblChooseBus.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); lblChooseBus.setAlignment(SWT.RIGHT); GridData gd_lblChooseBus = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_lblChooseBus.widthHint = 88; lblChooseBus.setLayoutData(gd_lblChooseBus); lblChooseBus.setText("Select Bus:"); cmbBusses = new Combo(compositeBus, SWT.READ_ONLY); cmbBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); cmbBusses.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 1, 1)); cmbBusses.add("NONE"); cmbBusses.setData(null); cmbBusses.select(0); lblSelectedCard = new Label(compositeBus, SWT.NONE); lblSelectedCard.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); lblSelectedCard.setAlignment(SWT.RIGHT); GridData gd_lblSelectedCard = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_lblSelectedCard.widthHint = 93; lblSelectedCard.setLayoutData(gd_lblSelectedCard); lblSelectedCard.setText("Select Card:"); cmbCards = new Combo(compositeBus, SWT.READ_ONLY); cmbCards.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); cmbCards.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnDeleteConnection = new Button(compositeBus, SWT.NONE); btnDeleteConnection.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); btnDeleteConnection.setText("Delete Connection"); btnDeleteConnection.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnHideBusses = new Button(compositeBus, SWT.CHECK); btnHideBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnHideBusses.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); btnHideBusses.setText("Show only busses of selected type"); btnHideBusses.setSelection(true); StackLayout stackLayout = new StackLayout(); compositeDir = new Composite(composite, SWT.NONE); compositeDir.setLayout(stackLayout); compositeDir.setLayoutData(new RowData(382, SWT.DEFAULT)); lblInstanceDirections = new Label(compositeDir, SWT.NONE); lblInstanceDirections.setFont(SWTResourceManager.getFont("Arial", 8, SWT.NORMAL)); lblInstanceDirections.setText("Select 'chip' to create a new part or 'sys-' to create a system\r\n" + "1. Select parent instance in Instance Tree\r\n" + "2. Select new instance type in dropdown\r\n" + "3. (Optional) Enter custom name\r\n" + "4. Click \"Add Instance\""); lblInstanceDirections.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); stackLayout.topControl = this.lblInstanceDirections; lblBusDirections = new Label(compositeDir, SWT.NONE); lblBusDirections.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); lblBusDirections .setText("Steps for adding a new connection:\r\n" + "1. Select a bus type from dropdown\r\n" + "2. Select the card on which the bus is on from dropdown\r\n" + "3. Navigate to connection source in Instances Tree view on left\r\n" + "4. Right-click on source and select \"Set Source\"\r\n" + "5. Navigate to connection destination\r\n6. Right-click on destination and select \"Add Connection\""); listBusses = new List(sashForm, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); listBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); this.addEvents(); this.setDirtyState(false); // load file if passed on command line if (!mrwFilename.isEmpty()) { controller.readXML(mrwFilename); setFilename(mrwFilename); } for (Target t : controller.getBusTypes()) { cmbBusses.add(t.getType()); cmbBusses.setData(t.getType(), t); } attributes = new Vector<Field>(); this.initInstanceMode(); sashForm.setWeights(new int[] { 1, 1 }); columnName.pack(); return container; } protected void createButtonsForButtonBar(Composite parent) { parent.setEnabled(false); GridLayout layout = (GridLayout)parent.getLayout(); layout.marginHeight = 0; } protected void createButtonsForButtonBar2(Composite row1) { row1.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); Button btnNew = createButton(row1, IDialogConstants.NO_ID, "New", false); GridData gd_btnNew = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnNew.widthHint = 70; btnNew.setLayoutData(gd_btnNew); btnNew.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnNew.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (dirty) { if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename + "has been modified. Ignore changes?")) { return; } ServerWizard2.LOGGER.info("Discarding changes"); } try { controller.initModel(); setFilename(""); initInstanceMode(); setDirtyState(false); } catch (Exception e1) { e1.printStackTrace(); } } }); btnOpen = createButton(row1, IDialogConstants.NO_ID, "Open...", false); GridData gd_btnOpen = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnOpen.widthHint = 70; btnOpen.setLayoutData(gd_btnOpen); btnOpen.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnOpen.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (dirty) { if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename + "has been modified. Ignore changes?")) { return; } ServerWizard2.LOGGER.info("Discarding changes"); } Button b = (Button) e.getSource(); FileDialog fdlg = new FileDialog(b.getShell(), SWT.OPEN); String ext[] = { "*.xml" }; fdlg.setFilterExtensions(ext); String filename = fdlg.open(); if (filename == null) { return; } Boolean dirty = controller.readXML(filename); setFilename(filename); initInstanceMode(); setDirtyState(dirty); } }); btnOpen.setToolTipText("Loads XML from file"); btnSave = createButton(row1, IDialogConstants.NO_ID, "Save", false); GridData gd_btnSave = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnSave.widthHint = 70; btnSave.setLayoutData(gd_btnSave); btnSave.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String filename = mrwFilename; if (mrwFilename.isEmpty()) { Button b = (Button) e.getSource(); FileDialog fdlg = new FileDialog(b.getShell(), SWT.SAVE); String ext[] = { "*.xml" }; fdlg.setFilterExtensions(ext); fdlg.setOverwrite(true); filename = fdlg.open(); if (filename == null) { return; } } controller.writeXML(filename); setFilename(filename); setDirtyState(false); } }); btnSave.setText("Save"); btnSaveAs = createButton(row1, IDialogConstants.NO_ID, "Save As...", false); GridData gd_btnSaveAs = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnSaveAs.widthHint = 70; btnSaveAs.setLayoutData(gd_btnSaveAs); btnSaveAs.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button b = (Button) e.getSource(); FileDialog fdlg = new FileDialog(b.getShell(), SWT.SAVE); String ext[] = { "*.xml" }; fdlg.setFilterExtensions(ext); fdlg.setOverwrite(true); String filename = fdlg.open(); if (filename == null) { return; } controller.writeXML(filename); setFilename(filename); setDirtyState(false); } }); btnSaveAs.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnSaveAs.setEnabled(true); label = new Label(buttonRow1, SWT.SEPARATOR | SWT.VERTICAL); GridData gd_sep = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_sep.heightHint = 30; gd_sep.widthHint = 30; label.setLayoutData(gd_sep); btnClone = createButton(row1, IDialogConstants.NO_ID, "Manage Library", false); GridData gd_btnClone = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnClone.widthHint = 100; btnClone.setLayoutData(gd_btnClone); btnClone.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnClone.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GitDialog dlg = new GitDialog(btnClone.getShell()); dlg.open(); } }); btnClone.setToolTipText("Retrieves Library from github"); btnOpenLib = createButton(row1, IDialogConstants.NO_ID, "Open Lib", false); GridData gd_btnOpenLib = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnOpenLib.widthHint = 90; btnOpenLib.setLayoutData(gd_btnOpenLib); btnOpenLib.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnOpenLib.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button b = (Button) e.getSource(); DirectoryDialog fdlg = new DirectoryDialog(b.getShell(), SWT.OPEN); fdlg.setFilterPath(ServerWizard2.getWorkingDir()); String libPath = fdlg.open(); if (libPath == null) { return; } controller.loadLibrary(libPath); } }); btnOpenLib.setToolTipText("Loads External Library"); btnRunChecks = createButton(row1, IDialogConstants.NO_ID, "Export HTML", false); GridData gd_btnRunChecks = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnRunChecks.widthHint = 90; btnRunChecks.setLayoutData(gd_btnRunChecks); btnRunChecks.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { String tempFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "~temp.xml"; controller.writeXML(tempFile); String htmlFilename = mrwFilename; htmlFilename = htmlFilename.replace(".xml", "") + ".html"; controller.runChecks(tempFile,htmlFilename); } }); btnRunChecks.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); Button btnForceUpdate = createButton(row1, IDialogConstants.NO_ID, "Force Update", false); GridData gd_btnForceUpdate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnForceUpdate.widthHint = 90; btnForceUpdate.setLayoutData(gd_btnForceUpdate); btnForceUpdate.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnForceUpdate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GithubFile.removeUpdateFile(true); } }); label_1 = new Label(buttonRow1, SWT.SEPARATOR | SWT.VERTICAL); GridData gd_sep2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_sep2.heightHint = 30; gd_sep2.widthHint = 30; label_1.setLayoutData(gd_sep2); Button btnExit = createButton(row1, IDialogConstants.CLOSE_ID, "Exit", false); GridData gd_btnExit = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnExit.widthHint = 80; btnExit.setLayoutData(gd_btnExit); btnExit.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnExit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button b = (Button) e.getSource(); b.getShell().close(); } }); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return new Point(933, 796); } // //////////////////////////////////////////////////// // Utility helpers private Target getSelectedTarget() { if (tree.getSelectionCount() > 0) { return (Target) tree.getSelection()[0].getData(); } return null; } private void initBusMode() { busMode = true; this.lblBusDirections.setEnabled(true); this.lblBusDirections.setVisible(true); this.lblInstanceDirections.setVisible(false); this.lblInstanceDirections.setEnabled(false); // update card combo cmbCards.removeAll(); this.targetForConnections = null; for (Target target : controller.getConnectionCapableTargets()) { cmbCards.add(target.getName()); cmbCards.setData(target.getName(), target); } if (cmbCards.getItemCount() > 0) { cmbCards.select(-1); } for (TreeItem item : tree.getItems()) { Target target = (Target) item.getData(); controller.hideBusses(target); } this.source = null; this.dest = null; this.selectedEndpoint = null; refreshInstanceTree(); refreshConnections(); attributes.clear(); viewer.setInput(attributes); viewer.refresh(); this.updateView(); } private void initInstanceMode() { tabFolder.setSelection(0); busMode = false; this.lblInstanceDirections.setEnabled(true); this.lblInstanceDirections.setVisible(true); this.lblBusDirections.setEnabled(false); this.lblBusDirections.setVisible(false); this.targetForConnections = null; this.refreshInstanceTree(); this.listBusses.removeAll(); refreshConnections(); attributes.clear(); viewer.setInput(attributes); viewer.refresh(); this.updateView(); } private void updateChildCombo(Target targetInstance) { btnAddTarget.setEnabled(false); Vector<Target> v = controller.getChildTargets(targetInstance); combo.removeAll(); if (v != null) { for (Target target : v) { combo.add(target.getType()); combo.setData(target.getType(), target); } if (combo.getItemCount() > 0) { combo.select(0); } btnAddTarget.setEnabled(true); } } /* * Updates button enabled states based on if target is selected * Also updates attribute table based on selected target */ private void updateView() { Target targetInstance = getSelectedTarget(); if (targetInstance == null) { btnAddTarget.setEnabled(false); btnDeleteTarget.setEnabled(false); btnCopyInstance.setEnabled(false); btnDefaults.setEnabled(false); updateChildCombo(null); return; } updatePopupMenu(targetInstance); updateChildCombo(targetInstance); //A target is selected so show the associated attributes TreeItem item = tree.getSelection()[0]; ConnectionEndpoint ep = this.getEndpoint(item, null); attributes = controller.getAttributesAndGlobals(targetInstance, "/"+ep.getName()); viewer.setInput(attributes); viewer.refresh(); if (targetInstance.isSystem()) { btnDeleteTarget.setEnabled(false); } else { btnDeleteTarget.setEnabled(true); } if (targetInstance.isNode() || targetInstance.isConnector()) { btnCopyInstance.setEnabled(true); } else { btnCopyInstance.setEnabled(false); } btnDefaults.setEnabled(true); } /* * Creates right-click popup menu for adding connections * */ private void updatePopupMenu(Target selectedTarget) { if (selectedTarget == null || tree.getSelectionCount()==0) { return; } if (popupMenu != null) { popupMenu.dispose(); } popupMenu = new Menu(tree); if (busMode) { if (cmbBusses.getSelectionIndex() > 0) { if (targetForConnections != null && selectedTarget.getAttribute("CLASS").equals("UNIT")) { if (selectedTarget.isOutput()) { MenuItem srcItem = new MenuItem(popupMenu, SWT.NONE); srcItem.setText("Set Source"); srcItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { source = getEndpoint(true); } }); } } if (source != null && selectedTarget.isInput()) { MenuItem connItem = new MenuItem(popupMenu, SWT.NONE); connItem.setText("Add Connection"); connItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dest = getEndpoint(false); addConnection(false); } }); MenuItem cableItem = new MenuItem(popupMenu, SWT.NONE); cableItem.setText("Add Cable"); cableItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dest = getEndpoint(false); addConnection(true); } }); } } else { targetForConnections = null; source = null; dest = null; } } TreeItem item = tree.getSelection()[0]; TreeItem parentItem = item.getParentItem(); if (parentItem != null) { Target configParentTarget = (Target) parentItem.getData(); if (configParentTarget.attributeExists("IO_CONFIG_SELECT")) { MenuItem deconfigItem = new MenuItem(popupMenu, SWT.NONE); deconfigItem.setText("Deconfig"); deconfigItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setConfig(false); } }); MenuItem configItem = new MenuItem(popupMenu, SWT.NONE); configItem.setText("Select Config"); configItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setConfig(true); } }); } } tree.setMenu(popupMenu); } public void setConfig(boolean config) { TreeItem item = tree.getSelection()[0]; Target target = (Target) item.getData(); TreeItem parentItem = item.getParentItem(); if (parentItem == null) { ServerWizard2.LOGGER.warning(target.getName() + " parent is null"); return; } TreeItem grandParentItem = parentItem.getParentItem(); Target configParentTarget = (Target) parentItem.getData(); String configNum = target.getAttribute("IO_CONFIG_NUM"); if (configNum.isEmpty()) { ServerWizard2.LOGGER.warning(target.getName() + " IO_CONFIG_NUM attribute is empty"); return; } ConnectionEndpoint ep = getEndpoint(parentItem,null); String path = "/"+ep.getName(); if (config) { controller.setGlobalSetting(path, "IO_CONFIG_SELECT", configNum); } else { controller.setGlobalSetting(path, "IO_CONFIG_SELECT", "0"); } for (TreeItem childItem : parentItem.getItems()) { clearTree(childItem); } currentPath="/"+ep.getPath(); currentPath=currentPath.substring(0, currentPath.length()-1); this.updateInstanceTree(configParentTarget, grandParentItem, parentItem); } private ConnectionEndpoint getEndpoint(TreeItem item, String stopCard) { ConnectionEndpoint endpoint = new ConnectionEndpoint(); Target target = (Target) item.getData(); endpoint.setTargetName(target.getName()); Boolean done = false; Boolean found = false; TreeItem parentItem = item.getParentItem(); while (!done) { if (parentItem==null) { done=true; } else { Target parentTarget = (Target) parentItem.getData(); String parentName = parentTarget.getName(); if (parentName.equals(stopCard)) { done = true; found = true; } else { endpoint.setPath(parentName + "/" + endpoint.getPath()); parentItem = parentItem.getParentItem(); } } } if (!found && stopCard != null) { MessageDialog.openError(null, "Connection Error", "The connection must start and end on or below selected card."); endpoint=null; } return endpoint; } private ConnectionEndpoint getEndpoint(boolean setBold) { TreeItem item = tree.getSelection()[0]; ConnectionEndpoint endpoint = getEndpoint(item,cmbCards.getText()); if (setBold && endpoint != null) { setEndpointState(item); } return endpoint; } public void setEndpointState(TreeItem item) { if (item != selectedEndpoint && selectedEndpoint != null) { this.setFontStyle(selectedEndpoint, SWT.BOLD, false); } this.setFontStyle(item, SWT.BOLD | SWT.ITALIC, true); selectedEndpoint = item; } private void clearTreeAll() { if (tree.getItemCount() > 0) { clearTree(tree.getItem(0)); } tree.removeAll(); } private void clearTree(TreeItem treeitem) { for (int i = 0; i < treeitem.getItemCount(); i++) { clearTree(treeitem.getItem(i)); } treeitem.removeAll(); treeitem.dispose(); } private void refreshInstanceTree() { currentPath=""; targetFound = false; for (Target target : controller.getRootTargets()) { this.updateInstanceTree(target, null); } if (controller.getRootTargets().size() == 0) { this.clearTreeAll(); } btnAddTarget.setEnabled(false); } public void updateInstanceTree(Target target, TreeItem parentItem) { this.updateInstanceTree(target, parentItem, null); } private void updateInstanceTree(Target target, TreeItem parentItem, TreeItem item) { if (target == null) { return; } if (target.isHidden()) { return; } if (parentItem==null) { this.clearTreeAll(); } boolean hideBus = false; String name = target.getName(); String lastPath = currentPath; currentPath=currentPath+"/"+name; if (busMode) { if (!target.isSystem() && !cmbBusses.getText().equals("NONE")) { if (target.isBusHidden(cmbBusses.getText())) { hideBus = true; if (btnHideBusses.getSelection()) { currentPath=lastPath; return; } } } if (parentItem != null) { if (controller.isGlobalSettings(lastPath, "IO_CONFIG_SELECT")) { Field cnfgSelect = controller.getGlobalSetting(lastPath, "IO_CONFIG_SELECT"); if (!cnfgSelect.value.isEmpty() && !cnfgSelect.value.equals("0")) { String cnfg = target.getAttribute("IO_CONFIG_NUM"); if (!cnfg.equals(cnfgSelect.value)) { hideBus = true; if (btnHideBusses.getSelection()) { currentPath=lastPath; return; } } } } } if (!hideBus) { String sch = target.getAttribute("SCHEMATIC_INTERFACE"); if (!sch.isEmpty()) { name = name + " (" + sch + ")"; } if (target.isInput() && target.isOutput()) { name = name + " <=>"; } else if (target.isInput()) { name = name + " <="; } else if (target.isOutput()) { name = name + " =>"; } } } Vector<Target> children = controller.getVisibleChildren(target,this.btnShowHidden.getSelection()); TreeItem treeitem = item; if (item == null) { if (parentItem == null) { treeitem = new TreeItem(tree, SWT.VIRTUAL | SWT.BORDER); } else { treeitem = new TreeItem(parentItem, SWT.VIRTUAL | SWT.BORDER); } } treeitem.setText(name); treeitem.setData(target); if (target.isPluggable()) { this.setFontStyle(treeitem, SWT.ITALIC, true); } if (children != null) { for (int i = 0; i < children.size(); i++) { Target childTarget = children.get(i); updateInstanceTree(childTarget, treeitem); } } if (target == targetForConnections && busMode) { this.setFontStyle(treeitem, SWT.BOLD, true); if (!targetFound) { tree.select(treeitem); for (TreeItem childItem : treeitem.getItems()) { tree.showItem(childItem); } targetFound = true; } } currentPath=lastPath; } private void addConnection(Connection conn) { listBusses.add(conn.getName()); listBusses.setData(conn.getName(), conn); } private void refreshConnections() { this.source=null; this.dest=null; listBusses.removeAll(); if (cmbBusses == null) { return; } Target busTarget = (Target) cmbBusses.getData(cmbBusses.getText()); if (targetForConnections == null) { return; } if (busTarget == null) { for (Target tmpBusTarget : targetForConnections.getBusses().keySet()) { for (Connection conn : targetForConnections.getBusses().get(tmpBusTarget)) { addConnection(conn); } } } else { for (Connection conn : targetForConnections.getBusses().get(busTarget)) { addConnection(conn); } } } private void addConnection(Boolean cabled) { Target busTarget = (Target) cmbBusses.getData(cmbBusses.getText()); Connection conn = targetForConnections.addConnection(busTarget, source, dest, cabled); this.addConnection(conn); setDirtyState(true); } private void deleteConnection() { if (targetForConnections == null || listBusses.getSelectionCount() == 0) { return; } Connection conn = (Connection) listBusses.getData(listBusses.getSelection()[0]); controller.deleteConnection(targetForConnections, conn.busTarget, conn); this.refreshConnections(); setDirtyState(true); } private void setFontStyle(TreeItem item, int style, boolean selected) { if (item.isDisposed()) { return; } FontData[] fD = item.getFont().getFontData(); fD[0].setStyle(selected ? style : 0); Font newFont = new Font(this.getShell().getDisplay(), fD[0]); item.setFont(newFont); } @Override public boolean close() { if (dirty) { if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename + "has been modified. Ignore changes?")) { return false; } ServerWizard2.LOGGER.info("Discarding changes and exiting..."); } clearTreeAll(); for (Control c : container.getChildren()) { c.dispose(); } return super.close(); } public void setDirtyState(Boolean dirty) { this.dirty = dirty; if (this.btnSave != null) { this.btnSave.setEnabled(dirty); } if (dirty) { this.getShell().setText("ServerWiz2 - " + this.mrwFilename + " *"); } else { this.getShell().setText("ServerWiz2 - " + this.mrwFilename); } } public void setFilename(String filename) { this.mrwFilename = filename; if (btnSave != null) { this.btnSave.setEnabled(true); } this.getShell().setText("ServerWiz2 - " + this.mrwFilename); } private void addEvents() { btnShowHidden.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { refreshInstanceTree(); } }); tabFolder.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { if (tabFolder.getSelection()[0]==tbtmAddBusses) { initBusMode(); } else { initInstanceMode(); } } }); tree.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateView(); } }); tree.addListener(SWT.Expand, new Listener() { public void handleEvent(Event e) { final TreeItem treeItem = (TreeItem) e.item; getShell().getDisplay().asyncExec(new Runnable() { public void run() { if (!treeItem.isDisposed()) { treeItem.getParent().getColumns()[0].pack(); } } }); } }); btnAddTarget.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Target chk = (Target) combo.getData(combo.getText()); if (chk != null) { TreeItem selectedItem = null; Target parentTarget = null; if (tree.getSelectionCount() > 0) { selectedItem = tree.getSelection()[0]; parentTarget = (Target) selectedItem.getData(); } if (chk.getType().equals("chip") || chk.getType().equals("targetoverride")) { ServerWizard2.LOGGER.info("Entering model creation mode"); attributeEditor.setIgnoreReadonly(); controller.setModelCreationMode(); tbtmAddBusses.dispose(); } String nameOverride = txtInstanceName.getText(); controller.addTargetInstance(chk, parentTarget, selectedItem, nameOverride); txtInstanceName.setText(""); if (tree.getSelectionCount() > 0) { selectedItem.setExpanded(true); } columnName.pack(); setDirtyState(true); } } }); btnDeleteTarget.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TreeItem treeitem = tree.getSelection()[0]; if (treeitem == null) { return; } controller.deleteTarget((Target) treeitem.getData()); clearTree(treeitem); setDirtyState(true); } }); btnCopyInstance.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { TreeItem selectedItem = tree.getSelection()[0]; if (selectedItem == null) { return; } Target target = (Target) selectedItem.getData(); Target parentTarget = (Target) selectedItem.getParentItem().getData(); Target newTarget = controller.copyTargetInstance(target, parentTarget, true); updateInstanceTree(newTarget, selectedItem.getParentItem()); TreeItem t = selectedItem.getParentItem(); tree.select(t.getItem(t.getItemCount() - 1)); setDirtyState(true); } }); btnDefaults.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { TreeItem selectedItem = tree.getSelection()[0]; if (selectedItem == null) { return; } if (!MessageDialog.openConfirm(null, "Restore Defaults", "Are you sure you want to restore default attribute values on this target and all of it's children?")) { return; } ServerWizard2.LOGGER.info("Restoring Defaults"); Target target = (Target) selectedItem.getData(); controller.deepCopyAttributes(target); setDirtyState(true); } }); cmbCards.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Target t = (Target) cmbCards.getData(cmbCards.getText()); targetForConnections = t; refreshInstanceTree(); refreshConnections(); } }); cmbBusses.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { refreshInstanceTree(); refreshConnections(); } }); btnDeleteConnection.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { deleteConnection(); } }); listBusses.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { if (listBusses.getSelectionCount() > 0) { Connection conn = (Connection) listBusses.getData(listBusses.getSelection()[0]); attributes = controller.getAttributesAndGlobals(conn.busTarget, ""); viewer.setInput(attributes); viewer.refresh(); } } }); btnHideBusses.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { refreshInstanceTree(); refreshConnections(); } }); } private void createAttributeTable() { Table table = viewer.getTable(); ColumnViewerToolTipSupport.enableFor(viewer, ToolTip.NO_RECREATE); table.setHeaderVisible(true); table.setLinesVisible(true); table.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); table.addListener(SWT.CHANGED, new Listener() { public void handleEvent(Event event) { setDirtyState(true); } }); final TableViewerColumn colName = new TableViewerColumn(viewer, SWT.NONE); colName.getColumn().setWidth(256); colName.getColumn().setText("Attribute"); colName.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Field f = (Field) element; return f.attributeName; } }); final TableViewerColumn colField = new TableViewerColumn(viewer, SWT.NONE); colField.getColumn().setWidth(100); colField.getColumn().setText("Field"); colField.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Field f = (Field) element; if (f.attributeName.equals(f.name)) { return ""; } return f.name; } }); final TableViewerColumn colValue = new TableViewerColumn(viewer, SWT.NONE); colValue.getColumn().setWidth(100); colValue.getColumn().setText("Value"); colValue.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Field f = (Field) element; return f.value; } }); attributeEditor = new AttributeEditingSupport(viewer); colValue.setEditingSupport(attributeEditor); final TableViewerColumn colDesc = new TableViewerColumn(viewer, SWT.NONE); colDesc.getColumn().setWidth(350); colDesc.getColumn().setText("Description"); colDesc.setLabelProvider(new ColumnLabelProvider() { public String getToolTipText(Object element) { Field f = (Field) element; return f.desc; } @Override public String getText(Object element) { Field f = (Field) element; String desc = f.desc.replace("\n", ""); return desc; } }); final TableViewerColumn colGroup = new TableViewerColumn(viewer, SWT.NONE); colGroup.getColumn().setWidth(120); colGroup.getColumn().setText("Group"); colGroup.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Field f = (Field) element; return f.group; } }); viewer.setContentProvider(ArrayContentProvider.getInstance()); } }
src/com/ibm/ServerWizard2/view/MainDialog.java
package com.ibm.ServerWizard2.view; import java.util.Vector; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; 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.DirectoryDialog; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.wb.swt.SWTResourceManager; import com.ibm.ServerWizard2.ServerWizard2; import com.ibm.ServerWizard2.controller.TargetWizardController; import com.ibm.ServerWizard2.model.Connection; import com.ibm.ServerWizard2.model.ConnectionEndpoint; import com.ibm.ServerWizard2.model.Field; import com.ibm.ServerWizard2.model.Target; import com.ibm.ServerWizard2.utility.GithubFile; public class MainDialog extends Dialog { private TableViewer viewer; private Tree tree; private TreeColumn columnName; private Text txtInstanceName; private Combo combo; private Menu popupMenu; private Composite container; private TreeItem selectedEndpoint; private String currentPath; private Target targetForConnections; private ConnectionEndpoint source; private ConnectionEndpoint dest; private TargetWizardController controller; // Buttons private Button btnAddTarget; private Button btnCopyInstance; private Button btnDefaults; private Button btnDeleteTarget; private Button btnSave; private Button btnOpen; private Button btnClone; private Button btnOpenLib; private Button btnDeleteConnection; private Button btnSaveAs; // document state private Boolean dirty = false; public String mrwFilename = ""; private Button btnRunChecks; private SashForm sashForm; private SashForm sashForm_1; private Composite compositeBus; private Label lblInstanceType; private Composite compositeInstance; private Composite composite; private Composite buttonRow1; private Vector<Field> attributes; private Combo cmbBusses; private Label lblChooseBus; private Label lblSelectedCard; private Boolean busMode = false; private TabFolder tabFolder; private TabItem tbtmAddInstances; private TabItem tbtmAddBusses; private Combo cmbCards; private Boolean targetFound = false; private List listBusses; private Label lblBusDirections; private Label lblInstanceDirections; private Composite compositeDir; private Button btnHideBusses; private Button btnShowHidden; private AttributeEditingSupport attributeEditor; private Label label; private Label label_1; /** * Create the dialog. * * @param parentShell */ public MainDialog(Shell parentShell) { super(parentShell); setShellStyle(SWT.BORDER | SWT.MIN | SWT.MAX | SWT.RESIZE | SWT.APPLICATION_MODAL); } protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("ServerWiz2"); } public void setController(TargetWizardController t) { controller = t; } /** * Create contents of the dialog. * * @param parent */ @Override protected Control createDialogArea(Composite parent) { container = (Composite) super.createDialogArea(parent); container.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); GridLayout gl_container = new GridLayout(1, false); gl_container.verticalSpacing = 0; container.setLayout(gl_container); composite = new Composite(container, SWT.NONE); RowLayout rl_composite = new RowLayout(SWT.HORIZONTAL); rl_composite.spacing = 20; rl_composite.wrap = false; rl_composite.fill = true; composite.setLayout(rl_composite); GridData gd_composite = new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1); gd_composite.widthHint = 918; gd_composite.heightHint = 135; composite.setLayoutData(gd_composite); sashForm_1 = new SashForm(container, SWT.BORDER | SWT.VERTICAL); GridData gd_sashForm_1 = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_sashForm_1.heightHint = 375; gd_sashForm_1.widthHint = 712; sashForm_1.setLayoutData(gd_sashForm_1); buttonRow1 = new Composite(container, SWT.NONE); GridData gd_buttonRow1 = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1); gd_buttonRow1.widthHint = 850; buttonRow1.setLayoutData(gd_buttonRow1); GridLayout rl_buttonRow1 = new GridLayout(18, false); buttonRow1.setLayout(rl_buttonRow1); this.createButtonsForButtonBar2(buttonRow1); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); new Label(buttonRow1, SWT.NONE); sashForm = new SashForm(sashForm_1, SWT.NONE); // Target Instances View tree = new Tree(sashForm, SWT.BORDER | SWT.VIRTUAL); tree.setHeaderVisible(true); tree.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); columnName = new TreeColumn(tree, 0); columnName.setText("Instances"); columnName .setToolTipText("To add a new instance, choose parent instance. A list of child instances will appear in Instance Type combo.\r\n" + "Select and Instance type. You can optionally enter a custom name. Then click 'Add Instance' button."); columnName.setResizable(true); // Create attribute table viewer = new TableViewer(sashForm_1, SWT.VIRTUAL | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); this.createAttributeTable(); sashForm_1.setWeights(new int[] { 1, 1 }); // ////////////////////////////////////////////////////////// // Tab folders tabFolder = new TabFolder(composite, SWT.NONE); tbtmAddInstances = new TabItem(tabFolder, SWT.NONE); tbtmAddInstances.setText("Instances"); // ////////////////////////////////////// // Add instances tab compositeInstance = new Composite(tabFolder, SWT.BORDER); tbtmAddInstances.setControl(compositeInstance); compositeInstance.setLayout(new GridLayout(3, false)); lblInstanceType = new Label(compositeInstance, SWT.NONE); lblInstanceType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblInstanceType.setText("Instance Type:"); lblInstanceType.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); combo = new Combo(compositeInstance, SWT.READ_ONLY); GridData gd_combo = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_combo.widthHint = 167; combo.setLayoutData(gd_combo); combo.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnAddTarget = new Button(compositeInstance, SWT.NONE); btnAddTarget.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); btnAddTarget.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnAddTarget.setText("Add Instance"); btnAddTarget.setEnabled(false); Label lblName = new Label(compositeInstance, SWT.NONE); lblName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblName.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); lblName.setText("Custom Name:"); txtInstanceName = new Text(compositeInstance, SWT.BORDER); GridData gd_txtInstanceName = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtInstanceName.widthHint = 175; txtInstanceName.setLayoutData(gd_txtInstanceName); txtInstanceName.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnDeleteTarget = new Button(compositeInstance, SWT.NONE); btnDeleteTarget.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); btnDeleteTarget.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnDeleteTarget.setText("Delete Instance"); btnShowHidden = new Button(compositeInstance, SWT.CHECK); btnShowHidden.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); GridData gd_btnShowHidden = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnShowHidden.heightHint = 20; btnShowHidden.setLayoutData(gd_btnShowHidden); btnShowHidden.setText(" Show Hidden"); btnCopyInstance = new Button(compositeInstance, SWT.NONE); btnCopyInstance.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1)); btnCopyInstance.setText("Copy Node or Connector"); btnCopyInstance.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnCopyInstance.setEnabled(false); btnDefaults = new Button(compositeInstance, SWT.NONE); btnDefaults.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1)); btnDefaults.setText("Restore Defaults"); btnDefaults.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnDefaults.setEnabled(false); // //////////////////////////////////////////////////// // Add Busses Tab tbtmAddBusses = new TabItem(tabFolder, SWT.NONE); tbtmAddBusses.setText("Busses"); compositeBus = new Composite(tabFolder, SWT.BORDER); tbtmAddBusses.setControl(compositeBus); compositeBus.setLayout(new GridLayout(2, false)); lblChooseBus = new Label(compositeBus, SWT.NONE); lblChooseBus.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); lblChooseBus.setAlignment(SWT.RIGHT); GridData gd_lblChooseBus = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_lblChooseBus.widthHint = 88; lblChooseBus.setLayoutData(gd_lblChooseBus); lblChooseBus.setText("Select Bus:"); cmbBusses = new Combo(compositeBus, SWT.READ_ONLY); cmbBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); cmbBusses.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 1, 1)); cmbBusses.add("NONE"); cmbBusses.setData(null); cmbBusses.select(0); lblSelectedCard = new Label(compositeBus, SWT.NONE); lblSelectedCard.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); lblSelectedCard.setAlignment(SWT.RIGHT); GridData gd_lblSelectedCard = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_lblSelectedCard.widthHint = 93; lblSelectedCard.setLayoutData(gd_lblSelectedCard); lblSelectedCard.setText("Select Card:"); cmbCards = new Combo(compositeBus, SWT.READ_ONLY); cmbCards.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); cmbCards.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnDeleteConnection = new Button(compositeBus, SWT.NONE); btnDeleteConnection.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); btnDeleteConnection.setText("Delete Connection"); btnDeleteConnection.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnHideBusses = new Button(compositeBus, SWT.CHECK); btnHideBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnHideBusses.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); btnHideBusses.setText("Show only busses of selected type"); btnHideBusses.setSelection(true); StackLayout stackLayout = new StackLayout(); compositeDir = new Composite(composite, SWT.NONE); compositeDir.setLayout(stackLayout); compositeDir.setLayoutData(new RowData(382, SWT.DEFAULT)); lblInstanceDirections = new Label(compositeDir, SWT.NONE); lblInstanceDirections.setFont(SWTResourceManager.getFont("Arial", 8, SWT.NORMAL)); lblInstanceDirections.setText("Select 'chip' to create a new part or 'sys-' to create a system\r\n" + "1. Select parent instance in Instance Tree\r\n" + "2. Select new instance type in dropdown\r\n" + "3. (Optional) Enter custom name\r\n" + "4. Click \"Add Instance\""); lblInstanceDirections.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); stackLayout.topControl = this.lblInstanceDirections; lblBusDirections = new Label(compositeDir, SWT.NONE); lblBusDirections.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); lblBusDirections .setText("Steps for adding a new connection:\r\n" + "1. Select a bus type from dropdown\r\n" + "2. Select the card on which the bus is on from dropdown\r\n" + "3. Navigate to connection source in Instances Tree view on left\r\n" + "4. Right-click on source and select \"Set Source\"\r\n" + "5. Navigate to connection destination\r\n6. Right-click on destination and select \"Add Connection\""); listBusses = new List(sashForm, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); listBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); this.addEvents(); this.setDirtyState(false); // load file if passed on command line if (!mrwFilename.isEmpty()) { controller.readXML(mrwFilename); setFilename(mrwFilename); } for (Target t : controller.getBusTypes()) { cmbBusses.add(t.getType()); cmbBusses.setData(t.getType(), t); } attributes = new Vector<Field>(); this.initInstanceMode(); sashForm.setWeights(new int[] { 1, 1 }); columnName.pack(); return container; } protected void createButtonsForButtonBar(Composite parent) { parent.setEnabled(false); GridLayout layout = (GridLayout)parent.getLayout(); layout.marginHeight = 0; } protected void createButtonsForButtonBar2(Composite row1) { row1.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); Button btnNew = createButton(row1, IDialogConstants.NO_ID, "New", false); GridData gd_btnNew = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnNew.widthHint = 70; btnNew.setLayoutData(gd_btnNew); btnNew.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnNew.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (dirty) { if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename + "has been modified. Ignore changes?")) { return; } ServerWizard2.LOGGER.info("Discarding changes"); } try { controller.initModel(); setFilename(""); initInstanceMode(); setDirtyState(false); } catch (Exception e1) { e1.printStackTrace(); } } }); btnOpen = createButton(row1, IDialogConstants.NO_ID, "Open...", false); GridData gd_btnOpen = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnOpen.widthHint = 70; btnOpen.setLayoutData(gd_btnOpen); btnOpen.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnOpen.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (dirty) { if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename + "has been modified. Ignore changes?")) { return; } ServerWizard2.LOGGER.info("Discarding changes"); } Button b = (Button) e.getSource(); FileDialog fdlg = new FileDialog(b.getShell(), SWT.OPEN); String ext[] = { "*.xml" }; fdlg.setFilterExtensions(ext); String filename = fdlg.open(); if (filename == null) { return; } Boolean dirty = controller.readXML(filename); setFilename(filename); initInstanceMode(); setDirtyState(dirty); } }); btnOpen.setToolTipText("Loads XML from file"); btnSave = createButton(row1, IDialogConstants.NO_ID, "Save", false); GridData gd_btnSave = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnSave.widthHint = 70; btnSave.setLayoutData(gd_btnSave); btnSave.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String filename = mrwFilename; if (mrwFilename.isEmpty()) { Button b = (Button) e.getSource(); FileDialog fdlg = new FileDialog(b.getShell(), SWT.SAVE); String ext[] = { "*.xml" }; fdlg.setFilterExtensions(ext); fdlg.setOverwrite(true); filename = fdlg.open(); if (filename == null) { return; } } controller.writeXML(filename); setFilename(filename); setDirtyState(false); } }); btnSave.setText("Save"); btnSaveAs = createButton(row1, IDialogConstants.NO_ID, "Save As...", false); GridData gd_btnSaveAs = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnSaveAs.widthHint = 70; btnSaveAs.setLayoutData(gd_btnSaveAs); btnSaveAs.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button b = (Button) e.getSource(); FileDialog fdlg = new FileDialog(b.getShell(), SWT.SAVE); String ext[] = { "*.xml" }; fdlg.setFilterExtensions(ext); fdlg.setOverwrite(true); String filename = fdlg.open(); if (filename == null) { return; } controller.writeXML(filename); setFilename(filename); setDirtyState(false); } }); btnSaveAs.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnSaveAs.setEnabled(true); label = new Label(buttonRow1, SWT.SEPARATOR | SWT.VERTICAL); GridData gd_sep = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_sep.heightHint = 30; gd_sep.widthHint = 30; label.setLayoutData(gd_sep); btnClone = createButton(row1, IDialogConstants.NO_ID, "Manage Library", false); GridData gd_btnClone = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnClone.widthHint = 100; btnClone.setLayoutData(gd_btnClone); btnClone.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnClone.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GitDialog dlg = new GitDialog(btnClone.getShell()); dlg.open(); } }); btnClone.setToolTipText("Retrieves Library from github"); btnOpenLib = createButton(row1, IDialogConstants.NO_ID, "Open Lib", false); GridData gd_btnOpenLib = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnOpenLib.widthHint = 90; btnOpenLib.setLayoutData(gd_btnOpenLib); btnOpenLib.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnOpenLib.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button b = (Button) e.getSource(); DirectoryDialog fdlg = new DirectoryDialog(b.getShell(), SWT.OPEN); fdlg.setFilterPath(ServerWizard2.getWorkingDir()); String libPath = fdlg.open(); if (libPath == null) { return; } controller.loadLibrary(libPath); } }); btnOpenLib.setToolTipText("Loads External Library"); btnRunChecks = createButton(row1, IDialogConstants.NO_ID, "Export HTML", false); GridData gd_btnRunChecks = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnRunChecks.widthHint = 90; btnRunChecks.setLayoutData(gd_btnRunChecks); btnRunChecks.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { String tempFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "~temp.xml"; controller.writeXML(tempFile); String htmlFilename = mrwFilename; htmlFilename = htmlFilename.replace(".xml", "") + ".html"; controller.runChecks(tempFile,htmlFilename); } }); btnRunChecks.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); Button btnForceUpdate = createButton(row1, IDialogConstants.NO_ID, "Force Update", false); GridData gd_btnForceUpdate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnForceUpdate.widthHint = 90; btnForceUpdate.setLayoutData(gd_btnForceUpdate); btnForceUpdate.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnForceUpdate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GithubFile.removeUpdateFile(true); } }); label_1 = new Label(buttonRow1, SWT.SEPARATOR | SWT.VERTICAL); GridData gd_sep2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_sep2.heightHint = 30; gd_sep2.widthHint = 30; label_1.setLayoutData(gd_sep2); Button btnExit = createButton(row1, IDialogConstants.CLOSE_ID, "Exit", false); GridData gd_btnExit = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnExit.widthHint = 80; btnExit.setLayoutData(gd_btnExit); btnExit.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); btnExit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button b = (Button) e.getSource(); b.getShell().close(); } }); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return new Point(933, 796); } // //////////////////////////////////////////////////// // Utility helpers private Target getSelectedTarget() { if (tree.getSelectionCount() > 0) { return (Target) tree.getSelection()[0].getData(); } return null; } private void initBusMode() { busMode = true; this.lblBusDirections.setEnabled(true); this.lblBusDirections.setVisible(true); this.lblInstanceDirections.setVisible(false); this.lblInstanceDirections.setEnabled(false); // update card combo cmbCards.removeAll(); this.targetForConnections = null; for (Target target : controller.getConnectionCapableTargets()) { cmbCards.add(target.getName()); cmbCards.setData(target.getName(), target); } if (cmbCards.getItemCount() > 0) { cmbCards.select(-1); } for (TreeItem item : tree.getItems()) { Target target = (Target) item.getData(); controller.hideBusses(target); } this.source = null; this.dest = null; this.selectedEndpoint = null; refreshInstanceTree(); refreshConnections(); attributes.clear(); viewer.setInput(attributes); viewer.refresh(); this.updateView(); } private void initInstanceMode() { tabFolder.setSelection(0); busMode = false; this.lblInstanceDirections.setEnabled(true); this.lblInstanceDirections.setVisible(true); this.lblBusDirections.setEnabled(false); this.lblBusDirections.setVisible(false); this.targetForConnections = null; this.refreshInstanceTree(); this.listBusses.removeAll(); refreshConnections(); attributes.clear(); viewer.setInput(attributes); viewer.refresh(); this.updateView(); } private void updateChildCombo(Target targetInstance) { btnAddTarget.setEnabled(false); Vector<Target> v = controller.getChildTargets(targetInstance); combo.removeAll(); if (v != null) { for (Target target : v) { combo.add(target.getType()); combo.setData(target.getType(), target); } if (combo.getItemCount() > 0) { combo.select(0); } btnAddTarget.setEnabled(true); } } /* * Updates button enabled states based on if target is selected * Also updates attribute table based on selected target */ private void updateView() { Target targetInstance = getSelectedTarget(); if (targetInstance == null) { btnAddTarget.setEnabled(false); btnDeleteTarget.setEnabled(false); btnCopyInstance.setEnabled(false); btnDefaults.setEnabled(false); updateChildCombo(null); return; } updatePopupMenu(targetInstance); updateChildCombo(targetInstance); //A target is selected so show the associated attributes TreeItem item = tree.getSelection()[0]; ConnectionEndpoint ep = this.getEndpoint(item, null); attributes = controller.getAttributesAndGlobals(targetInstance, "/"+ep.getName()); viewer.setInput(attributes); viewer.refresh(); if (targetInstance.isSystem()) { btnDeleteTarget.setEnabled(false); } else { btnDeleteTarget.setEnabled(true); } if (targetInstance.isNode() || targetInstance.isConnector()) { btnCopyInstance.setEnabled(true); } else { btnCopyInstance.setEnabled(false); } btnDefaults.setEnabled(true); } /* * Creates right-click popup menu for adding connections * */ private void updatePopupMenu(Target selectedTarget) { if (selectedTarget == null || tree.getSelectionCount()==0) { return; } if (popupMenu != null) { popupMenu.dispose(); } popupMenu = new Menu(tree); if (busMode) { if (cmbBusses.getSelectionIndex() > 0) { if (targetForConnections != null && selectedTarget.getAttribute("CLASS").equals("UNIT")) { if (selectedTarget.isOutput()) { MenuItem srcItem = new MenuItem(popupMenu, SWT.NONE); srcItem.setText("Set Source"); srcItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { source = getEndpoint(true); } }); } } if (source != null && selectedTarget.isInput()) { MenuItem connItem = new MenuItem(popupMenu, SWT.NONE); connItem.setText("Add Connection"); connItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dest = getEndpoint(false); addConnection(false); } }); MenuItem cableItem = new MenuItem(popupMenu, SWT.NONE); cableItem.setText("Add Cable"); cableItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dest = getEndpoint(false); addConnection(true); } }); } } else { targetForConnections = null; source = null; dest = null; } } TreeItem item = tree.getSelection()[0]; TreeItem parentItem = item.getParentItem(); if (parentItem != null) { Target configParentTarget = (Target) parentItem.getData(); if (configParentTarget.attributeExists("IO_CONFIG_SELECT")) { MenuItem deconfigItem = new MenuItem(popupMenu, SWT.NONE); deconfigItem.setText("Deconfig"); deconfigItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setConfig(false); } }); MenuItem configItem = new MenuItem(popupMenu, SWT.NONE); configItem.setText("Select Config"); configItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setConfig(true); } }); } } tree.setMenu(popupMenu); } public void setConfig(boolean config) { TreeItem item = tree.getSelection()[0]; Target target = (Target) item.getData(); TreeItem parentItem = item.getParentItem(); if (parentItem == null) { ServerWizard2.LOGGER.warning(target.getName() + " parent is null"); return; } TreeItem grandParentItem = parentItem.getParentItem(); Target configParentTarget = (Target) parentItem.getData(); String configNum = target.getAttribute("IO_CONFIG_NUM"); if (configNum.isEmpty()) { ServerWizard2.LOGGER.warning(target.getName() + " IO_CONFIG_NUM attribute is empty"); return; } ConnectionEndpoint ep = getEndpoint(parentItem,null); String path = "/"+ep.getName(); if (config) { controller.setGlobalSetting(path, "IO_CONFIG_SELECT", configNum); } else { controller.setGlobalSetting(path, "IO_CONFIG_SELECT", "0"); } for (TreeItem childItem : parentItem.getItems()) { clearTree(childItem); } currentPath="/"+ep.getPath(); currentPath=currentPath.substring(0, currentPath.length()-1); this.updateInstanceTree(configParentTarget, grandParentItem, parentItem); } private ConnectionEndpoint getEndpoint(TreeItem item, String stopCard) { ConnectionEndpoint endpoint = new ConnectionEndpoint(); Target target = (Target) item.getData(); endpoint.setTargetName(target.getName()); Boolean done = false; Boolean found = false; TreeItem parentItem = item.getParentItem(); while (!done) { if (parentItem==null) { done=true; } else { Target parentTarget = (Target) parentItem.getData(); String parentName = parentTarget.getName(); if (parentName.equals(stopCard)) { done = true; found = true; } else { endpoint.setPath(parentName + "/" + endpoint.getPath()); parentItem = parentItem.getParentItem(); } } } if (!found && stopCard != null) { MessageDialog.openError(null, "Connection Error", "The connection must start and end on or below selected card."); endpoint=null; } return endpoint; } private ConnectionEndpoint getEndpoint(boolean setBold) { TreeItem item = tree.getSelection()[0]; ConnectionEndpoint endpoint = getEndpoint(item,cmbCards.getText()); if (setBold && endpoint != null) { setEndpointState(item); } return endpoint; } public void setEndpointState(TreeItem item) { if (item != selectedEndpoint && selectedEndpoint != null) { this.setFontStyle(selectedEndpoint, SWT.BOLD, false); } this.setFontStyle(item, SWT.BOLD | SWT.ITALIC, true); selectedEndpoint = item; } private void clearTreeAll() { if (tree.getItemCount() > 0) { clearTree(tree.getItem(0)); } tree.removeAll(); } private void clearTree(TreeItem treeitem) { for (int i = 0; i < treeitem.getItemCount(); i++) { clearTree(treeitem.getItem(i)); } treeitem.removeAll(); treeitem.dispose(); } private void refreshInstanceTree() { currentPath=""; targetFound = false; for (Target target : controller.getRootTargets()) { this.updateInstanceTree(target, null); } if (controller.getRootTargets().size() == 0) { this.clearTreeAll(); } btnAddTarget.setEnabled(false); } public void updateInstanceTree(Target target, TreeItem parentItem) { this.updateInstanceTree(target, parentItem, null); } private void updateInstanceTree(Target target, TreeItem parentItem, TreeItem item) { if (target == null) { return; } if (target.isHidden()) { return; } if (parentItem==null) { this.clearTreeAll(); } boolean hideBus = false; String name = target.getName(); String lastPath = currentPath; currentPath=currentPath+"/"+name; if (busMode) { if (!target.isSystem() && !cmbBusses.getText().equals("NONE")) { if (target.isBusHidden(cmbBusses.getText())) { hideBus = true; if (btnHideBusses.getSelection()) { currentPath=lastPath; return; } } } if (parentItem != null) { if (controller.isGlobalSettings(lastPath, "IO_CONFIG_SELECT")) { Field cnfgSelect = controller.getGlobalSetting(lastPath, "IO_CONFIG_SELECT"); if (!cnfgSelect.value.isEmpty() && !cnfgSelect.value.equals("0")) { String cnfg = target.getAttribute("IO_CONFIG_NUM"); if (!cnfg.equals(cnfgSelect.value)) { hideBus = true; if (btnHideBusses.getSelection()) { currentPath=lastPath; return; } } } } } if (!hideBus) { String sch = target.getAttribute("SCHEMATIC_INTERFACE"); if (!sch.isEmpty()) { name = name + " (" + sch + ")"; } if (target.isInput() && target.isOutput()) { name = name + " <=>"; } else if (target.isInput()) { name = name + " <="; } else if (target.isOutput()) { name = name + " =>"; } } } Vector<Target> children = controller.getVisibleChildren(target,this.btnShowHidden.getSelection()); TreeItem treeitem = item; if (item == null) { if (parentItem == null) { treeitem = new TreeItem(tree, SWT.VIRTUAL | SWT.BORDER); } else { treeitem = new TreeItem(parentItem, SWT.VIRTUAL | SWT.BORDER); } } treeitem.setText(name); treeitem.setData(target); if (target.isPluggable()) { this.setFontStyle(treeitem, SWT.ITALIC, true); } if (children != null) { for (int i = 0; i < children.size(); i++) { Target childTarget = children.get(i); updateInstanceTree(childTarget, treeitem); } } if (target == targetForConnections && busMode) { this.setFontStyle(treeitem, SWT.BOLD, true); if (!targetFound) { tree.select(treeitem); for (TreeItem childItem : treeitem.getItems()) { tree.showItem(childItem); } targetFound = true; } } currentPath=lastPath; } private void addConnection(Connection conn) { listBusses.add(conn.getName()); listBusses.setData(conn.getName(), conn); } private void refreshConnections() { this.source=null; this.dest=null; listBusses.removeAll(); if (cmbBusses == null) { return; } Target busTarget = (Target) cmbBusses.getData(cmbBusses.getText()); if (targetForConnections == null) { return; } if (busTarget == null) { for (Target tmpBusTarget : targetForConnections.getBusses().keySet()) { for (Connection conn : targetForConnections.getBusses().get(tmpBusTarget)) { addConnection(conn); } } } else { for (Connection conn : targetForConnections.getBusses().get(busTarget)) { addConnection(conn); } } } private void addConnection(Boolean cabled) { Target busTarget = (Target) cmbBusses.getData(cmbBusses.getText()); Connection conn = targetForConnections.addConnection(busTarget, source, dest, cabled); this.addConnection(conn); setDirtyState(true); } private void deleteConnection() { if (targetForConnections == null || listBusses.getSelectionCount() == 0) { return; } Connection conn = (Connection) listBusses.getData(listBusses.getSelection()[0]); controller.deleteConnection(targetForConnections, conn.busTarget, conn); this.refreshConnections(); setDirtyState(true); } private void setFontStyle(TreeItem item, int style, boolean selected) { if (item.isDisposed()) { return; } FontData[] fD = item.getFont().getFontData(); fD[0].setStyle(selected ? style : 0); Font newFont = new Font(this.getShell().getDisplay(), fD[0]); item.setFont(newFont); } @Override public boolean close() { if (dirty) { if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename + "has been modified. Ignore changes?")) { return false; } ServerWizard2.LOGGER.info("Discarding changes and exiting..."); } clearTreeAll(); for (Control c : container.getChildren()) { c.dispose(); } return super.close(); } public void setDirtyState(Boolean dirty) { this.dirty = dirty; if (this.btnSave != null) { this.btnSave.setEnabled(dirty); } if (dirty) { this.getShell().setText("ServerWiz2 - " + this.mrwFilename + " *"); } else { this.getShell().setText("ServerWiz2 - " + this.mrwFilename); } } public void setFilename(String filename) { this.mrwFilename = filename; if (btnSave != null) { this.btnSave.setEnabled(true); } this.getShell().setText("ServerWiz2 - " + this.mrwFilename); } private void addEvents() { btnShowHidden.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { refreshInstanceTree(); } }); tabFolder.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { if (tabFolder.getSelection()[0]==tbtmAddBusses) { initBusMode(); } else { initInstanceMode(); } } }); tree.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateView(); } }); tree.addListener(SWT.Expand, new Listener() { public void handleEvent(Event e) { final TreeItem treeItem = (TreeItem) e.item; getShell().getDisplay().asyncExec(new Runnable() { public void run() { if (!treeItem.isDisposed()) { treeItem.getParent().getColumns()[0].pack(); } } }); } }); btnAddTarget.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Target chk = (Target) combo.getData(combo.getText()); if (chk != null) { TreeItem selectedItem = null; Target parentTarget = null; if (tree.getSelectionCount() > 0) { selectedItem = tree.getSelection()[0]; parentTarget = (Target) selectedItem.getData(); } if (chk.getType().equals("chip") || chk.getType().equals("targetoverride")) { ServerWizard2.LOGGER.info("Entering model creation mode"); attributeEditor.setIgnoreReadonly(); controller.setModelCreationMode(); tbtmAddBusses.dispose(); } String nameOverride = txtInstanceName.getText(); controller.addTargetInstance(chk, parentTarget, selectedItem, nameOverride); txtInstanceName.setText(""); if (tree.getSelectionCount() > 0) { selectedItem.setExpanded(true); } columnName.pack(); setDirtyState(true); } } }); btnDeleteTarget.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TreeItem treeitem = tree.getSelection()[0]; if (treeitem == null) { return; } controller.deleteTarget((Target) treeitem.getData()); clearTree(treeitem); setDirtyState(true); } }); btnCopyInstance.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { TreeItem selectedItem = tree.getSelection()[0]; if (selectedItem == null) { return; } Target target = (Target) selectedItem.getData(); Target parentTarget = (Target) selectedItem.getParentItem().getData(); Target newTarget = controller.copyTargetInstance(target, parentTarget, true); updateInstanceTree(newTarget, selectedItem.getParentItem()); TreeItem t = selectedItem.getParentItem(); tree.select(t.getItem(t.getItemCount() - 1)); setDirtyState(true); } }); btnDefaults.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { TreeItem selectedItem = tree.getSelection()[0]; if (selectedItem == null) { return; } if (!MessageDialog.openConfirm(null, "Restore Defaults", "Are you sure you want to restore default attribute values on this target and all of it's children?")) { return; } ServerWizard2.LOGGER.info("Restoring Defaults"); Target target = (Target) selectedItem.getData(); controller.deepCopyAttributes(target); setDirtyState(true); } }); cmbCards.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Target t = (Target) cmbCards.getData(cmbCards.getText()); targetForConnections = t; refreshInstanceTree(); refreshConnections(); } }); cmbBusses.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { refreshInstanceTree(); refreshConnections(); } }); btnDeleteConnection.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { deleteConnection(); } }); listBusses.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { if (listBusses.getSelectionCount() > 0) { Connection conn = (Connection) listBusses.getData(listBusses.getSelection()[0]); attributes = controller.getAttributesAndGlobals(conn.busTarget, ""); viewer.setInput(attributes); viewer.refresh(); } } }); btnHideBusses.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { refreshInstanceTree(); refreshConnections(); } }); } private void createAttributeTable() { Table table = viewer.getTable(); ColumnViewerToolTipSupport.enableFor(viewer, ToolTip.NO_RECREATE); table.setHeaderVisible(true); table.setLinesVisible(true); table.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); table.addListener(SWT.CHANGED, new Listener() { public void handleEvent(Event event) { setDirtyState(true); } }); final TableViewerColumn colName = new TableViewerColumn(viewer, SWT.NONE); colName.getColumn().setWidth(256); colName.getColumn().setText("Attribute"); colName.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Field f = (Field) element; return f.attributeName; } }); final TableViewerColumn colField = new TableViewerColumn(viewer, SWT.NONE); colField.getColumn().setWidth(100); colField.getColumn().setText("Field"); colField.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Field f = (Field) element; if (f.attributeName.equals(f.name)) { return ""; } return f.name; } }); final TableViewerColumn colValue = new TableViewerColumn(viewer, SWT.NONE); colValue.getColumn().setWidth(100); colValue.getColumn().setText("Value"); colValue.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Field f = (Field) element; return f.value; } }); attributeEditor = new AttributeEditingSupport(viewer); colValue.setEditingSupport(attributeEditor); final TableViewerColumn colDesc = new TableViewerColumn(viewer, SWT.NONE); colDesc.getColumn().setWidth(350); colDesc.getColumn().setText("Description"); colDesc.setLabelProvider(new ColumnLabelProvider() { public String getToolTipText(Object element) { Field f = (Field) element; return f.desc; } @Override public String getText(Object element) { Field f = (Field) element; String desc = f.desc.replace("\n", ""); return desc; } }); final TableViewerColumn colGroup = new TableViewerColumn(viewer, SWT.NONE); colGroup.getColumn().setWidth(120); colGroup.getColumn().setText("Group"); colGroup.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Field f = (Field) element; return f.group; } }); viewer.setContentProvider(ArrayContentProvider.getInstance()); } }
Add height to tabbed folder Bottom of tabbed folder was being cutoff in some OS's. Signed-off-by: Norman James <[email protected]>
src/com/ibm/ServerWizard2/view/MainDialog.java
Add height to tabbed folder
<ide><path>rc/com/ibm/ServerWizard2/view/MainDialog.java <ide> rl_composite.wrap = false; <ide> rl_composite.fill = true; <ide> composite.setLayout(rl_composite); <del> GridData gd_composite = new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1); <add> GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1); <ide> gd_composite.widthHint = 918; <del> gd_composite.heightHint = 135; <add> gd_composite.heightHint = 154; <ide> composite.setLayoutData(gd_composite); <ide> <ide> sashForm_1 = new SashForm(container, SWT.BORDER | SWT.VERTICAL); <ide> // ////////////////////////////////////////////////////////// <ide> // Tab folders <ide> tabFolder = new TabFolder(composite, SWT.NONE); <add> tabFolder.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); <add> tabFolder.setLayoutData(new RowData(SWT.DEFAULT, 119)); <ide> <ide> tbtmAddInstances = new TabItem(tabFolder, SWT.NONE); <ide> tbtmAddInstances.setText("Instances");
Java
mit
a263da81e2d4d7904043b19d9bd30e5c1041bc68
0
ylins/algo
package tree; /** * Created by Yue on 2017/10/12. */ public class BinarySearchTree<T extends Comparable<? super T>> { private static class BinaryNode<T> { BinaryNode(T element) { this(element, null, null); } public BinaryNode(T element, BinaryNode<T> left, BinaryNode<T> right) { this.element = element; this.left = left; this.right = right; } T element; BinaryNode<T> left; BinaryNode<T> right; } private BinaryNode<T> root; public BinarySearchTree() { this.root = null; } public void makeEmpty() { this.root = null; } public boolean isEmpty() { return this.root == null; } public boolean contains(T x) { return contains(x, this.root); } private boolean contains(T x, BinaryNode<T> root) { if (root == null) return false; int compareResult = x.compareTo(root.element); if (compareResult < 0) return contains(x, root.left); else if (compareResult > 0) return contains(x, root.right); else return true; } public T findMin() throws Exception { if (isEmpty()) throw new Exception("tree is empty"); return findMin(this.root).element; } private BinaryNode<T> findMin(BinaryNode<T> root) { if (root.left == null) return root; return findMin(root.left); } public T findMax() throws Exception { if (isEmpty()) throw new Exception("tree is empty"); return findMax(this.root).element; } private BinaryNode<T> findMax(BinaryNode<T> root) { if (root.right == null) return root; return findMax(root.right); } public void insert(T x) { this.root = insert(x, this.root); } private BinaryNode<T> insert(T x, BinaryNode<T> root) { if (root == null) return new BinaryNode<>(x); int compareResult = x.compareTo(root.element); if (compareResult < 0) root.left = insert(x, root.left); else if (compareResult > 0) root.right = insert(x, root.right); return root; } public void remove(T x) { this.root = remove(x, this.root); } private BinaryNode<T> remove(T x, BinaryNode<T> root) { if (root == null) return null; int compareResult = x.compareTo(root.element); if (compareResult < 0) root.left = remove(x, root.left); else if (compareResult > 0) root.right = remove(x, root.right); else if (root.left != null && root.right != null) { root.element = findMin(root.right).element; root.right = remove(root.element, root.right); } else root = root.left != null ? root.left : root.right; return root; } }
src/tree/BinarySearchTree.java
package tree; /** * Created by Yue on 2017/10/12. */ public class BinarySearchTree { }
modified binarySearchTree
src/tree/BinarySearchTree.java
modified binarySearchTree
<ide><path>rc/tree/BinarySearchTree.java <ide> /** <ide> * Created by Yue on 2017/10/12. <ide> */ <del>public class BinarySearchTree { <add>public class BinarySearchTree<T extends Comparable<? super T>> { <add> <add> private static class BinaryNode<T> { <add> <add> BinaryNode(T element) { <add> this(element, null, null); <add> } <add> <add> public BinaryNode(T element, BinaryNode<T> left, BinaryNode<T> right) { <add> this.element = element; <add> this.left = left; <add> this.right = right; <add> } <add> <add> T element; <add> BinaryNode<T> left; <add> BinaryNode<T> right; <add> } <add> <add> private BinaryNode<T> root; <add> <add> public BinarySearchTree() { <add> this.root = null; <add> } <add> <add> public void makeEmpty() { <add> this.root = null; <add> } <add> <add> public boolean isEmpty() { <add> return this.root == null; <add> } <add> <add> public boolean contains(T x) { <add> return contains(x, this.root); <add> } <add> <add> private boolean contains(T x, BinaryNode<T> root) { <add> if (root == null) <add> return false; <add> int compareResult = x.compareTo(root.element); <add> <add> if (compareResult < 0) <add> return contains(x, root.left); <add> else if (compareResult > 0) <add> return contains(x, root.right); <add> else <add> return true; <add> } <add> <add> public T findMin() throws Exception { <add> if (isEmpty()) <add> throw new Exception("tree is empty"); <add> return findMin(this.root).element; <add> } <add> <add> private BinaryNode<T> findMin(BinaryNode<T> root) { <add> if (root.left == null) <add> return root; <add> return findMin(root.left); <add> } <add> <add> public T findMax() throws Exception { <add> if (isEmpty()) <add> throw new Exception("tree is empty"); <add> return findMax(this.root).element; <add> } <add> <add> private BinaryNode<T> findMax(BinaryNode<T> root) { <add> if (root.right == null) <add> return root; <add> return findMax(root.right); <add> } <add> <add> public void insert(T x) { <add> this.root = insert(x, this.root); <add> } <add> <add> private BinaryNode<T> insert(T x, BinaryNode<T> root) { <add> if (root == null) <add> return new BinaryNode<>(x); <add> int compareResult = x.compareTo(root.element); <add> if (compareResult < 0) <add> root.left = insert(x, root.left); <add> else if (compareResult > 0) <add> root.right = insert(x, root.right); <add> return root; <add> } <add> <add> public void remove(T x) { <add> this.root = remove(x, this.root); <add> } <add> <add> private BinaryNode<T> remove(T x, BinaryNode<T> root) { <add> if (root == null) <add> return null; <add> int compareResult = x.compareTo(root.element); <add> if (compareResult < 0) <add> root.left = remove(x, root.left); <add> else if (compareResult > 0) <add> root.right = remove(x, root.right); <add> else if (root.left != null && root.right != null) { <add> root.element = findMin(root.right).element; <add> root.right = remove(root.element, root.right); <add> } <add> else <add> root = root.left != null ? root.left : root.right; <add> return root; <add> } <ide> } <add>
Java
apache-2.0
d77019557fa52b51ba1a2a0199cac09c5f75d805
0
donald-w/mypojo
/* * Copyright 2011 Karl Pauls [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.kalpatec.pojosr.framework.launch; import de.kalpatec.pojosr.framework.felix.framework.util.MapToDictionary; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.net.URL; import java.util.*; public class ClasspathScanner { private static final Logger logger = LoggerFactory.getLogger(ClasspathScanner.class); public List<BundleDescriptor> scanForBundles() throws Exception { return scanForBundles(null, null); } @SuppressWarnings("unused") public List<BundleDescriptor> scanForBundles(ClassLoader loader) throws Exception { return scanForBundles(null, loader); } public List<BundleDescriptor> scanForBundles(String filterString) throws Exception { return scanForBundles(filterString, null); } public List<BundleDescriptor> scanForBundles(String filterString, ClassLoader loader) throws Exception { logger.info("Starting classpath scan"); Filter filter = (filterString != null) ? FrameworkUtil.createFilter(filterString) : null; List<BundleDescriptor> bundles = new ArrayList<>(); loader = (loader != null) ? loader : getClass().getClassLoader(); List<URL> manifestUrls = Collections.list(loader.getResources("META-INF/MANIFEST.MF")); for (URL manifestURL : manifestUrls) { Map<String, String> headers = getHeaders(manifestURL); if ((filter == null) || filter.match(new MapToDictionary(headers))) { bundles.add(new BundleDescriptor(loader, getParentURL(manifestURL), headers)); } } logger.info("Found {} bundles", bundles.size()); return bundles; } private Map<String, String> getHeaders(URL manifestURL) throws Exception { Map<String, String> headers = new HashMap<>(); byte[] bytes = new byte[1024 * 1024 * 2]; // TODO - remove this arbitrary limit try (InputStream input = manifestURL.openStream()) { int size = 0; for (int i = input.read(bytes); i != -1; i = input.read(bytes, size, bytes.length - size)) { size += i; if (size == bytes.length) { byte[] tmp = new byte[size * 2]; System.arraycopy(bytes, 0, tmp, 0, bytes.length); bytes = tmp; } } // Now parse the main attributes. The idea is to do that // without creating new byte arrays. Therefore, we read through // the manifest bytes inside the bytes array and write them back into // the same array unless we don't need them (e.g., \r\n and \n are skipped). // That allows us to create the strings from the bytes array without the skipped // chars. We stop as soon as we see a blank line as that denotes that the main //attributes part is finished. String key = null; int last = 0; int current = 0; for (int i = 0; i < size; i++) { // skip \r and \n if it is follows by another \n // (we catch the blank line case in the next iteration) if (bytes[i] == '\r') { if ((i + 1 < size) && (bytes[i + 1] == '\n')) { continue; } } if (bytes[i] == '\n') { if ((i + 1 < size) && (bytes[i + 1] == ' ')) { i++; continue; } } // If we don't have a key yet and see the first : we parse it as the key // and skip the :<blank> that follows it. if ((key == null) && (bytes[i] == ':')) { key = new String(bytes, last, (current - last), "UTF-8"); if ((i + 1 < size) && (bytes[i + 1] == ' ')) { last = current + 1; continue; } else { throw new Exception( "Manifest error: Missing space separator - " + key); } } // if we are at the end of a line if (bytes[i] == '\n') { // and it is a blank line stop parsing (main attributes are done) if ((last == current) && (key == null)) { break; } // Otherwise, parse the value and add it to the map (we throw an // exception if we don't have a key or the key already exist. String value = new String(bytes, last, (current - last), "UTF-8"); if (key == null) { throw new Exception("Manifest error: Missing attribute name - " + value); } else if (headers.put(key, value) != null) { throw new Exception("Manifest error: Duplicate attribute name - " + key); } last = current; key = null; } else { // write back the byte if it needs to be included in the key or the value. bytes[current++] = bytes[i]; } } } return headers; } private URL getParentURL(URL url) throws Exception { String externalForm = url.toExternalForm(); return new URL(externalForm.substring(0, externalForm.length() - "META-INF/MANIFEST.MF".length())); } }
framework/src/main/java/de/kalpatec/pojosr/framework/launch/ClasspathScanner.java
/* * Copyright 2011 Karl Pauls [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.kalpatec.pojosr.framework.launch; import de.kalpatec.pojosr.framework.felix.framework.util.MapToDictionary; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.net.URL; import java.util.*; public class ClasspathScanner { private static final Logger logger = LoggerFactory.getLogger(ClasspathScanner.class); public List<BundleDescriptor> scanForBundles() throws Exception { return scanForBundles(null, null); } public List<BundleDescriptor> scanForBundles(ClassLoader loader) throws Exception { return scanForBundles(null, loader); } public List<BundleDescriptor> scanForBundles(String filterString) throws Exception { return scanForBundles(filterString, null); } public List<BundleDescriptor> scanForBundles(String filterString, ClassLoader loader) throws Exception { logger.info("Starting classpath scan"); Filter filter = (filterString != null) ? FrameworkUtil.createFilter(filterString) : null; List<BundleDescriptor> bundles = new ArrayList<>(); loader = (loader != null) ? loader : getClass().getClassLoader(); List<URL> manifestUrls = Collections.list(loader.getResources("META-INF/MANIFEST.MF")); for (URL manifestURL : manifestUrls) { Map<String, String> headers = getHeaders(manifestURL); if ((filter == null) || filter.match(new MapToDictionary(headers))) { bundles.add(new BundleDescriptor(loader, getParentURL(manifestURL), headers)); } } logger.info("Found {} bundles", bundles.size()); return bundles; } private Map<String, String> getHeaders(URL manifestURL) throws Exception { Map<String, String> headers = new HashMap<>(); byte[] bytes = new byte[1024 * 1024 * 2]; // TODO - remove this arbitrary limit try (InputStream input = manifestURL.openStream()) { int size = 0; for (int i = input.read(bytes); i != -1; i = input.read(bytes, size, bytes.length - size)) { size += i; if (size == bytes.length) { byte[] tmp = new byte[size * 2]; System.arraycopy(bytes, 0, tmp, 0, bytes.length); bytes = tmp; } } // Now parse the main attributes. The idea is to do that // without creating new byte arrays. Therefore, we read through // the manifest bytes inside the bytes array and write them back into // the same array unless we don't need them (e.g., \r\n and \n are skipped). // That allows us to create the strings from the bytes array without the skipped // chars. We stop as soon as we see a blank line as that denotes that the main //attributes part is finished. String key = null; int last = 0; int current = 0; for (int i = 0; i < size; i++) { // skip \r and \n if it is follows by another \n // (we catch the blank line case in the next iteration) if (bytes[i] == '\r') { if ((i + 1 < size) && (bytes[i + 1] == '\n')) { continue; } } if (bytes[i] == '\n') { if ((i + 1 < size) && (bytes[i + 1] == ' ')) { i++; continue; } } // If we don't have a key yet and see the first : we parse it as the key // and skip the :<blank> that follows it. if ((key == null) && (bytes[i] == ':')) { key = new String(bytes, last, (current - last), "UTF-8"); if ((i + 1 < size) && (bytes[i + 1] == ' ')) { last = current + 1; continue; } else { throw new Exception( "Manifest error: Missing space separator - " + key); } } // if we are at the end of a line if (bytes[i] == '\n') { // and it is a blank line stop parsing (main attributes are done) if ((last == current) && (key == null)) { break; } // Otherwise, parse the value and add it to the map (we throw an // exception if we don't have a key or the key already exist. String value = new String(bytes, last, (current - last), "UTF-8"); if (key == null) { throw new Exception("Manifest error: Missing attribute name - " + value); } else if (headers.put(key, value) != null) { throw new Exception("Manifest error: Duplicate attribute name - " + key); } last = current; key = null; } else { // write back the byte if it needs to be included in the key or the value. bytes[current++] = bytes[i]; } } } return headers; } private URL getParentURL(URL url) throws Exception { String externalForm = url.toExternalForm(); return new URL(externalForm.substring(0, externalForm.length() - "META-INF/MANIFEST.MF".length())); } }
Suppress warning, reformat
framework/src/main/java/de/kalpatec/pojosr/framework/launch/ClasspathScanner.java
Suppress warning, reformat
<ide><path>ramework/src/main/java/de/kalpatec/pojosr/framework/launch/ClasspathScanner.java <ide> return scanForBundles(null, null); <ide> } <ide> <add> @SuppressWarnings("unused") <ide> public List<BundleDescriptor> scanForBundles(ClassLoader loader) throws Exception { <ide> return scanForBundles(null, loader); <ide> } <ide> return scanForBundles(filterString, null); <ide> } <ide> <del> public List<BundleDescriptor> scanForBundles(String filterString, ClassLoader loader) <del> throws Exception { <add> public List<BundleDescriptor> scanForBundles(String filterString, ClassLoader loader) throws Exception { <ide> logger.info("Starting classpath scan"); <ide> Filter filter = (filterString != null) ? FrameworkUtil.createFilter(filterString) : null; <ide> <ide> Map<String, String> headers = getHeaders(manifestURL); <ide> <ide> if ((filter == null) || filter.match(new MapToDictionary(headers))) { <del> bundles.add(new BundleDescriptor(loader, getParentURL(manifestURL), <del> headers)); <add> bundles.add(new BundleDescriptor(loader, getParentURL(manifestURL), headers)); <ide> } <ide> } <ide> logger.info("Found {} bundles", bundles.size());
Java
apache-2.0
8b5a8297fd0336f6cefe9b7b02a2e554445e34fa
0
edwardcapriolo/teknek-core,edwardcapriolo/teknek-core
/* Copyright 2013 Edward Capriolo, Matt Landolf, Lodwin Cueto Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.teknek.daemon; import io.teknek.datalayer.WorkerDao; import io.teknek.datalayer.WorkerDaoException; import io.teknek.graphite.reporter.CommonGraphiteReporter; import io.teknek.graphite.reporter.SimpleJmxReporter; import io.teknek.plan.Plan; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.recipes.lock.LockListener; import org.apache.zookeeper.recipes.lock.WriteLock; import com.codahale.metrics.MetricRegistry; import com.google.common.annotations.VisibleForTesting; public class TeknekDaemon implements Watcher{ private final static Logger logger = Logger.getLogger(TeknekDaemon.class.getName()); public static final String ZK_SERVER_LIST = "teknek.zk.servers"; public static final String MAX_WORKERS = "teknek.max.workers"; public static final String DAEMON_ID = "teknek.daemon.id"; public static final String GRAPHITE_HOST = "teknek.graphite.host"; public static final String GRAPHITE_PORT = "teknek.graphite.port"; public static final String GRAPHITE_CLUSTER = "teknek.graphite.cluster"; private int maxWorkers = 4; private String myId; private Properties properties; private ZooKeeper zk; private long rescanMillis = 5000; ConcurrentHashMap<Plan, List<Worker>> workerThreads; private boolean goOn = true; private String hostname; private CountDownLatch awaitConnection; private MetricRegistry metricRegistry; private SimpleJmxReporter jmxReporter; private CommonGraphiteReporter graphiteReporter; /* * <bean id="graphiteReporter" class="io.teknek.graphite.reporter.CommonGraphiteReporter" init-method="init"> <constructor-arg ref="metricRegistry" /> <constructor-arg value="monitor.use1.huffpo.net" /> <constructor-arg value="2003" /> <constructor-arg value="true" /> <property name="clusterName" value="lighthouse-development" /> </bean> */ public TeknekDaemon(Properties properties){ this.properties = properties; if (properties.containsKey(DAEMON_ID)){ myId = properties.getProperty(DAEMON_ID); } else { myId = UUID.randomUUID().toString(); } workerThreads = new ConcurrentHashMap<Plan,List<Worker>>(); if (properties.containsKey(MAX_WORKERS)){ maxWorkers = Integer.parseInt(properties.getProperty(MAX_WORKERS)); } try { setHostname(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException ex) { setHostname("unknown"); } metricRegistry = new MetricRegistry(); jmxReporter = new SimpleJmxReporter(metricRegistry, "teknek-core"); } public void init() { jmxReporter.init(); if (properties.get(GRAPHITE_HOST) != null){ graphiteReporter = new CommonGraphiteReporter(metricRegistry, properties.getProperty(GRAPHITE_HOST), Integer.parseInt(properties.getProperty(GRAPHITE_PORT)), true); graphiteReporter.setClusterName(properties.getProperty(GRAPHITE_CLUSTER)); graphiteReporter.init(); } logger.info("Daemon id:" + myId); logger.info("Connecting to:" + properties.getProperty(ZK_SERVER_LIST)); awaitConnection = new CountDownLatch(1); try { zk = new ZooKeeper(properties.getProperty(ZK_SERVER_LIST), 1000, this); boolean connected = awaitConnection.await(10, TimeUnit.SECONDS); if (!connected){ throw new RuntimeException("Did not connect before timeout"); } } catch (IOException | InterruptedException e1) { throw new RuntimeException(e1); } try { WorkerDao.createZookeeperBase(zk); WorkerDao.createEphemeralNodeForDaemon(zk, this); } catch (WorkerDaoException e) { throw new RuntimeException(e); } new Thread(){ public void run(){ while (goOn){ try { if (workerThreads.size() < maxWorkers) { List<String> children = WorkerDao.finalAllPlanNames(zk); logger.debug("List of plans: " + children); for (String child: children){ considerStarting(child); } } else { logger.debug("Will not attempt to start worker. Already at max workers " + workerThreads.size()); } } catch (Exception ex){ logger.warn("Exception during scan", ex); } try { Thread.sleep(rescanMillis); } catch (InterruptedException e) { logger.warn(e); } } } }.start(); } @VisibleForTesting public void applyPlan(Plan plan){ try { WorkerDao.createOrUpdatePlan(plan, zk); } catch (WorkerDaoException e) { logger.warn("Failed writing/updating plan", e); } } @VisibleForTesting public void deletePlan(Plan plan){ try { WorkerDao.deletePlan(zk, plan); } catch (WorkerDaoException e) { logger.warn("Failed deleting/updating plan", e); } } /** * Determines if the plan can be run. IE not disabled and not * malformed * @return true if the plan seems reasonable enough to run */ public boolean isPlanSane(Plan plan){ if (plan == null){ logger.warn("did not find plan"); return false; } if (plan.isDisabled()){ logger.debug("disabled "+ plan.getName()); return false; } if (plan.getFeedDesc() == null){ logger.warn("feed was null "+ plan.getName()); return false; } return true; } @VisibleForTesting boolean alreadyAtMaxWorkersPerNode(Plan plan, List<String> workerUuids, List<Worker> workingOnPlan){ if (plan.getMaxWorkersPerNode() == 0){ return false; } int numberOfWorkersRunningInDaemon = 0; if (workingOnPlan == null){ return false; } for (Worker worker: workingOnPlan){ for (String uuid : workerUuids ) { if (worker.getMyId().toString().equals(uuid)){ numberOfWorkersRunningInDaemon++; } } } if (numberOfWorkersRunningInDaemon >= plan.getMaxWorkersPerNode()){ return true; } else { return false; } } private void considerStarting(String child){ Plan plan = null; List<String> workerUuidsWorkingOnPlan = null; try { plan = WorkerDao.findPlanByName(zk, child); if (!child.equals(plan.getName())){ logger.warn(String.format("Node name %s is not the same is the json value %s will not start", child, plan.getName())); return; } workerUuidsWorkingOnPlan = WorkerDao.findWorkersWorkingOnPlan(zk, plan); } catch (WorkerDaoException e) { logger.warn("Problem finding plan or workers for plan ", e); return; } if (alreadyAtMaxWorkersPerNode(plan, workerUuidsWorkingOnPlan, workerThreads.get(plan))){ return; } if (!isPlanSane(plan)){ return; } logger.debug("trying to acqure lock on " + WorkerDao.LOCKS_ZK + "/" + plan.getName()); try { WorkerDao.maybeCreatePlanLockDir(zk, plan); } catch (WorkerDaoException e1) { logger.warn(e1); return; } final CountDownLatch c = new CountDownLatch(1); WriteLock l = new WriteLock(zk, WorkerDao.LOCKS_ZK + "/" + plan.getName(), null); l.setLockListener(new LockListener(){ @Override public void lockAcquired() { logger.debug(myId + " counting down"); c.countDown(); } @Override public void lockReleased() { logger.debug(myId + " released"); } }); try { boolean gotLock = l.lock(); /* if (!gotLock){ logger.debug("did not get lock"); return; }*/ boolean hasLatch = c.await(3000, TimeUnit.MILLISECONDS); if (hasLatch){ /* plan could have been disabled after latch:Maybe editing the plan should lock it as well */ try { plan = WorkerDao.findPlanByName(zk, child); } catch (WorkerDaoException e) { logger.warn(e); return; } if (plan.isDisabled()){ logger.debug("disabled "+ plan.getName()); return; } List<String> workerUuids = WorkerDao.findWorkersWorkingOnPlan(zk, plan); if (workerUuids.size() >= plan.getMaxWorkers()) { logger.debug("already running max children:" + workerUuids.size() + " planmax:" + plan.getMaxWorkers() + " running:" + workerUuids); return; } logger.debug("starting worker"); try { Worker worker = new Worker(plan, workerUuids, this); worker.init(); worker.start(); addWorkerToList(plan, worker); } catch (RuntimeException e){ throw new WorkerStartException(e); } } } catch (KeeperException | InterruptedException | WorkerDaoException | WorkerStartException e) { logger.warn("getting lock", e); } finally { try { l.unlock(); } catch (RuntimeException ex){ logger.warn("Unable to unlock ", ex); } } } private void addWorkerToList(Plan plan, Worker worker) { logger.debug("adding worker " + worker.getMyId() + " to plan "+plan.getName()); List<Worker> list = workerThreads.get(plan); if (list == null) { list = Collections.synchronizedList(new ArrayList<Worker>()); } list.add(worker); workerThreads.put(plan, list); } @Override public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected){ awaitConnection.countDown(); } } public String getMyId() { return myId; } public void setMyId(String myId) { this.myId = myId; } public void stop(){ this.goOn = false; } public Properties getProperties() { return properties; } public long getRescanMillis() { return rescanMillis; } public void setRescanMillis(long rescanMillis) { this.rescanMillis = rescanMillis; } public String getHostname() { return hostname; } @VisibleForTesting void setHostname(String hostname) { this.hostname = hostname; } public MetricRegistry getMetricRegistry() { return metricRegistry; } public void setMetricRegistry(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } public static void main (String [] args){ TeknekDaemon td = new TeknekDaemon(System.getProperties()); td.init(); } }
src/main/java/io/teknek/daemon/TeknekDaemon.java
/* Copyright 2013 Edward Capriolo, Matt Landolf, Lodwin Cueto Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.teknek.daemon; import io.teknek.datalayer.WorkerDao; import io.teknek.datalayer.WorkerDaoException; import io.teknek.graphite.reporter.SimpleJmxReporter; import io.teknek.plan.Plan; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.recipes.lock.LockListener; import org.apache.zookeeper.recipes.lock.WriteLock; import com.codahale.metrics.MetricRegistry; import com.google.common.annotations.VisibleForTesting; public class TeknekDaemon implements Watcher{ private final static Logger logger = Logger.getLogger(TeknekDaemon.class.getName()); public static final String ZK_SERVER_LIST = "teknek.zk.servers"; public static final String MAX_WORKERS = "teknek.max.workers"; public static final String DAEMON_ID = "teknek.daemon.id"; private int maxWorkers = 4; private String myId; private Properties properties; private ZooKeeper zk; private long rescanMillis = 5000; ConcurrentHashMap<Plan, List<Worker>> workerThreads; private boolean goOn = true; private String hostname; private CountDownLatch awaitConnection; private MetricRegistry metricRegistry; private SimpleJmxReporter jmxReporter; public TeknekDaemon(Properties properties){ this.properties = properties; if (properties.containsKey(DAEMON_ID)){ myId = properties.getProperty(DAEMON_ID); } else { myId = UUID.randomUUID().toString(); } workerThreads = new ConcurrentHashMap<Plan,List<Worker>>(); if (properties.containsKey(MAX_WORKERS)){ maxWorkers = Integer.parseInt(properties.getProperty(MAX_WORKERS)); } try { setHostname(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException ex) { setHostname("unknown"); } metricRegistry = new MetricRegistry(); jmxReporter = new SimpleJmxReporter(metricRegistry, "teknek-core"); } public void init() { jmxReporter.init(); logger.info("Daemon id:" + myId); logger.info("Connecting to:" + properties.getProperty(ZK_SERVER_LIST)); awaitConnection = new CountDownLatch(1); try { zk = new ZooKeeper(properties.getProperty(ZK_SERVER_LIST), 1000, this); boolean connected = awaitConnection.await(10, TimeUnit.SECONDS); if (!connected){ throw new RuntimeException("Did not connect before timeout"); } } catch (IOException | InterruptedException e1) { throw new RuntimeException(e1); } try { WorkerDao.createZookeeperBase(zk); WorkerDao.createEphemeralNodeForDaemon(zk, this); } catch (WorkerDaoException e) { throw new RuntimeException(e); } new Thread(){ public void run(){ while (goOn){ try { if (workerThreads.size() < maxWorkers) { List<String> children = WorkerDao.finalAllPlanNames(zk); logger.debug("List of plans: " + children); for (String child: children){ considerStarting(child); } } else { logger.debug("Will not attempt to start worker. Already at max workers " + workerThreads.size()); } } catch (Exception ex){ logger.warn("Exception during scan", ex); } try { Thread.sleep(rescanMillis); } catch (InterruptedException e) { logger.warn(e); } } } }.start(); } @VisibleForTesting public void applyPlan(Plan plan){ try { WorkerDao.createOrUpdatePlan(plan, zk); } catch (WorkerDaoException e) { logger.warn("Failed writing/updating plan", e); } } @VisibleForTesting public void deletePlan(Plan plan){ try { WorkerDao.deletePlan(zk, plan); } catch (WorkerDaoException e) { logger.warn("Failed deleting/updating plan", e); } } /** * Determines if the plan can be run. IE not disabled and not * malformed * @return true if the plan seems reasonable enough to run */ public boolean isPlanSane(Plan plan){ if (plan == null){ logger.warn("did not find plan"); return false; } if (plan.isDisabled()){ logger.debug("disabled "+ plan.getName()); return false; } if (plan.getFeedDesc() == null){ logger.warn("feed was null "+ plan.getName()); return false; } return true; } @VisibleForTesting boolean alreadyAtMaxWorkersPerNode(Plan plan, List<String> workerUuids, List<Worker> workingOnPlan){ if (plan.getMaxWorkersPerNode() == 0){ return false; } int numberOfWorkersRunningInDaemon = 0; if (workingOnPlan == null){ return false; } for (Worker worker: workingOnPlan){ for (String uuid : workerUuids ) { if (worker.getMyId().toString().equals(uuid)){ numberOfWorkersRunningInDaemon++; } } } if (numberOfWorkersRunningInDaemon >= plan.getMaxWorkersPerNode()){ return true; } else { return false; } } private void considerStarting(String child){ Plan plan = null; List<String> workerUuidsWorkingOnPlan = null; try { plan = WorkerDao.findPlanByName(zk, child); if (!child.equals(plan.getName())){ logger.warn(String.format("Node name %s is not the same is the json value %s will not start", child, plan.getName())); return; } workerUuidsWorkingOnPlan = WorkerDao.findWorkersWorkingOnPlan(zk, plan); } catch (WorkerDaoException e) { logger.warn("Problem finding plan or workers for plan ", e); return; } if (alreadyAtMaxWorkersPerNode(plan, workerUuidsWorkingOnPlan, workerThreads.get(plan))){ return; } if (!isPlanSane(plan)){ return; } logger.debug("trying to acqure lock on " + WorkerDao.LOCKS_ZK + "/" + plan.getName()); try { WorkerDao.maybeCreatePlanLockDir(zk, plan); } catch (WorkerDaoException e1) { logger.warn(e1); return; } final CountDownLatch c = new CountDownLatch(1); WriteLock l = new WriteLock(zk, WorkerDao.LOCKS_ZK + "/" + plan.getName(), null); l.setLockListener(new LockListener(){ @Override public void lockAcquired() { logger.debug(myId + " counting down"); c.countDown(); } @Override public void lockReleased() { logger.debug(myId + " released"); } }); try { boolean gotLock = l.lock(); /* if (!gotLock){ logger.debug("did not get lock"); return; }*/ boolean hasLatch = c.await(3000, TimeUnit.MILLISECONDS); if (hasLatch){ /* plan could have been disabled after latch:Maybe editing the plan should lock it as well */ try { plan = WorkerDao.findPlanByName(zk, child); } catch (WorkerDaoException e) { logger.warn(e); return; } if (plan.isDisabled()){ logger.debug("disabled "+ plan.getName()); return; } List<String> workerUuids = WorkerDao.findWorkersWorkingOnPlan(zk, plan); if (workerUuids.size() >= plan.getMaxWorkers()) { logger.debug("already running max children:" + workerUuids.size() + " planmax:" + plan.getMaxWorkers() + " running:" + workerUuids); return; } logger.debug("starting worker"); try { Worker worker = new Worker(plan, workerUuids, this); worker.init(); worker.start(); addWorkerToList(plan, worker); } catch (RuntimeException e){ throw new WorkerStartException(e); } } } catch (KeeperException | InterruptedException | WorkerDaoException | WorkerStartException e) { logger.warn("getting lock", e); } finally { try { l.unlock(); } catch (RuntimeException ex){ logger.warn("Unable to unlock ", ex); } } } private void addWorkerToList(Plan plan, Worker worker) { logger.debug("adding worker " + worker.getMyId() + " to plan "+plan.getName()); List<Worker> list = workerThreads.get(plan); if (list == null) { list = Collections.synchronizedList(new ArrayList<Worker>()); } list.add(worker); workerThreads.put(plan, list); } @Override public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected){ awaitConnection.countDown(); } } public String getMyId() { return myId; } public void setMyId(String myId) { this.myId = myId; } public void stop(){ this.goOn = false; } public Properties getProperties() { return properties; } public long getRescanMillis() { return rescanMillis; } public void setRescanMillis(long rescanMillis) { this.rescanMillis = rescanMillis; } public String getHostname() { return hostname; } @VisibleForTesting void setHostname(String hostname) { this.hostname = hostname; } public MetricRegistry getMetricRegistry() { return metricRegistry; } public void setMetricRegistry(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } public static void main (String [] args){ TeknekDaemon td = new TeknekDaemon(System.getProperties()); td.init(); } }
graphite reporter ftw
src/main/java/io/teknek/daemon/TeknekDaemon.java
graphite reporter ftw
<ide><path>rc/main/java/io/teknek/daemon/TeknekDaemon.java <ide> <ide> import io.teknek.datalayer.WorkerDao; <ide> import io.teknek.datalayer.WorkerDaoException; <add>import io.teknek.graphite.reporter.CommonGraphiteReporter; <ide> import io.teknek.graphite.reporter.SimpleJmxReporter; <ide> import io.teknek.plan.Plan; <ide> <ide> public static final String MAX_WORKERS = "teknek.max.workers"; <ide> public static final String DAEMON_ID = "teknek.daemon.id"; <ide> <add> public static final String GRAPHITE_HOST = "teknek.graphite.host"; <add> public static final String GRAPHITE_PORT = "teknek.graphite.port"; <add> public static final String GRAPHITE_CLUSTER = "teknek.graphite.cluster"; <add> <ide> private int maxWorkers = 4; <ide> private String myId; <ide> private Properties properties; <ide> private CountDownLatch awaitConnection; <ide> private MetricRegistry metricRegistry; <ide> private SimpleJmxReporter jmxReporter; <add> private CommonGraphiteReporter graphiteReporter; <add> <add> /* <add> * <bean id="graphiteReporter" class="io.teknek.graphite.reporter.CommonGraphiteReporter" <add>init-method="init"> <add><constructor-arg ref="metricRegistry" /> <add><constructor-arg value="monitor.use1.huffpo.net" /> <add><constructor-arg value="2003" /> <add><constructor-arg value="true" /> <add><property name="clusterName" value="lighthouse-development" /> <add></bean> <add> */ <ide> <ide> public TeknekDaemon(Properties properties){ <ide> this.properties = properties; <ide> <ide> public void init() { <ide> jmxReporter.init(); <add> if (properties.get(GRAPHITE_HOST) != null){ <add> graphiteReporter = new CommonGraphiteReporter(metricRegistry, <add> properties.getProperty(GRAPHITE_HOST), <add> Integer.parseInt(properties.getProperty(GRAPHITE_PORT)), true); <add> graphiteReporter.setClusterName(properties.getProperty(GRAPHITE_CLUSTER)); <add> graphiteReporter.init(); <add> } <ide> logger.info("Daemon id:" + myId); <ide> logger.info("Connecting to:" + properties.getProperty(ZK_SERVER_LIST)); <ide> awaitConnection = new CountDownLatch(1);
Java
apache-2.0
26d3af9556b4f596fa5deb7019716287fe9848c6
0
apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.kernel.rmi; import java.io.IOException; import java.io.Serializable; import java.net.InetSocketAddress; import java.net.Socket; import java.rmi.server.RMIClientSocketFactory; public class GeronimoRMIClientSocketFactory implements RMIClientSocketFactory, Serializable { private static final long serialVersionUID = 8238444722121747980L; private int connectionTimeout = -1; private int readTimeout = -1; public GeronimoRMIClientSocketFactory(int connectionTimeout, int readTimeout) { this.connectionTimeout = connectionTimeout; this.readTimeout = readTimeout; } public Socket createSocket(String host, int port) throws IOException { Socket socket = new Socket(); socket.bind(null); socket.connect(new InetSocketAddress(host, port), (this.connectionTimeout > 0) ? this.connectionTimeout : 0); if (this.readTimeout >= 0) { socket.setSoTimeout(this.readTimeout); } return socket; } }
framework/modules/geronimo-kernel/src/main/java/org/apache/geronimo/kernel/rmi/GeronimoRMIClientSocketFactory.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.kernel.rmi; import java.io.IOException; import java.io.Serializable; import java.net.InetSocketAddress; import java.net.Socket; import java.rmi.server.RMIClientSocketFactory; public class GeronimoRMIClientSocketFactory implements RMIClientSocketFactory, Serializable { private static final long serialVersionUID = 8238444722121747980L; private int connectionTimeout = -1; private int readTimeout = -1; public GeronimoRMIClientSocketFactory(int connectionTimeout, int readTimeout) { this.connectionTimeout = connectionTimeout; this.readTimeout = readTimeout; } public Socket createSocket(String _host, int port) throws IOException { Socket socket = new Socket(); socket.bind(null); socket.connect(new InetSocketAddress(host, port), (this.connectionTimeout > 0) ? this.connectionTimeout : 0); if (this.readTimeout >= 0) { socket.setSoTimeout(this.readTimeout); } return socket; } }
fix build problem git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@736774 13f79535-47bb-0310-9956-ffa450edef68
framework/modules/geronimo-kernel/src/main/java/org/apache/geronimo/kernel/rmi/GeronimoRMIClientSocketFactory.java
fix build problem
<ide><path>ramework/modules/geronimo-kernel/src/main/java/org/apache/geronimo/kernel/rmi/GeronimoRMIClientSocketFactory.java <ide> this.readTimeout = readTimeout; <ide> } <ide> <del> public Socket createSocket(String _host, int port) throws IOException { <add> public Socket createSocket(String host, int port) throws IOException { <ide> Socket socket = new Socket(); <ide> socket.bind(null); <ide> socket.connect(new InetSocketAddress(host, port), (this.connectionTimeout > 0) ? this.connectionTimeout : 0);