lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 293031d0cf2bc6c222f29ed3b244257680e60a9d | 0 | indeedeng/proctor,indeedeng/proctor | package com.indeed.proctor.common;
import com.indeed.proctor.common.model.Allocation;
import com.indeed.proctor.common.model.Audit;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import com.indeed.proctor.common.model.TestBucket;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySortedMap;
/**
* Return value from {@link Proctor#determineTestGroups(Identifiers, java.util.Map, java.util.Map)}
* @author ketan
*
*/
public class ProctorResult {
public static final ProctorResult EMPTY = new ProctorResult(
Audit.EMPTY_VERSION,
emptySortedMap(),
emptySortedMap(),
emptyMap()
);
private final String matrixVersion;
/**
* maps from testname to bucket
*/
@Nonnull
private final SortedMap<String, TestBucket> buckets;
/**
* maps from testname to allocation
*/
@Nonnull
private final SortedMap<String, Allocation> allocations;
/**
* maps from testname to TestDefinition
*/
@Nonnull
private final Map<String, ConsumableTestDefinition> testDefinitions;
/**
* Create a ProctorResult with copies of the provided collections
* @deprecated this constructor creates copies of all inputs
*/
@Deprecated
public ProctorResult(
@Nonnull final int matrixVersion,
@Nonnull final Map<String, TestBucket> buckets,
// allowing null for historical reasons
@Nullable final Map<String, ConsumableTestDefinition> testDefinitions
) {
this(Integer.toString(matrixVersion), buckets, emptyMap(), testDefinitions);
}
/**
* Create a ProctorResult with copies of the provided collections
* @deprecated this constructor creates copies of all inputs
*/
@Deprecated
public ProctorResult(
@Nonnull final String matrixVersion,
@Nonnull final Map<String, TestBucket> buckets,
// allowing null for historical reasons
@Nullable final Map<String, ConsumableTestDefinition> testDefinitions
) {
this(matrixVersion, buckets, emptyMap(), testDefinitions);
}
/**
* Create a ProctorResult with copies of the provided collections
* @deprecated this constructor creates copies of all input collections
*/
@Deprecated
public ProctorResult(
@Nonnull final String matrixVersion,
@Nonnull final Map<String, TestBucket> buckets,
@Nonnull final Map<String, Allocation> allocations,
// allowing null for historical reasons
@Nullable final Map<String, ConsumableTestDefinition> testDefinitions
) {
// Potentially client applications might need to build ProctorResult instances in each request, and some apis
// have large proctorResult objects, so if teams use this constructor, this may have a noticeable
// impact on latency and GC, so ideally clients should avoid this constructor.
this(
matrixVersion,
new TreeMap<>(buckets),
new TreeMap<>(allocations),
(testDefinitions == null) ? emptyMap() : new HashMap<>(testDefinitions)
);
}
/**
* Plain constructor, not creating TreeMaps as in the deprecated version.
*/
public ProctorResult(
@Nonnull final String matrixVersion,
@Nonnull final SortedMap<String, TestBucket> buckets,
@Nonnull final SortedMap<String, Allocation> allocations,
@Nonnull final Map<String, ConsumableTestDefinition> testDefinitions
) {
this.matrixVersion = matrixVersion;
this.buckets = buckets;
this.allocations = allocations;
this.testDefinitions = testDefinitions;
}
/**
* @return a new Proctor Result, which does not allow modifying the contained collections.
* The result's fields are views of the original fields, to reduce memory allocation effort.
*/
public static ProctorResult unmodifiableView(final ProctorResult proctorResult) {
return new ProctorResult(
proctorResult.matrixVersion,
// using fields directly because methods do not expose SortedMap type
Collections.unmodifiableSortedMap(proctorResult.buckets),
Collections.unmodifiableSortedMap(proctorResult.allocations),
Collections.unmodifiableMap(proctorResult.testDefinitions)
);
}
@SuppressWarnings("UnusedDeclaration")
public String getMatrixVersion() {
return matrixVersion;
}
/**
* @return a SortedMap (should be ordered by testname)
*/
@Nonnull
// returning Map instead of SortedMap for historic reasons (changing breaks compiled libraries)
public Map<String, TestBucket> getBuckets() {
return buckets;
}
/**
* @return a SortedMap (should be ordered by testname)
*/
@Nonnull
// returning Map instead of SortedMap for historic reasons (changing breaks compiled libraries)
public Map<String, Allocation> getAllocations() {
return allocations;
}
@Nonnull
public Map<String, ConsumableTestDefinition> getTestDefinitions() {
return testDefinitions;
}
}
| proctor-common/src/main/java/com/indeed/proctor/common/ProctorResult.java | package com.indeed.proctor.common;
import com.indeed.proctor.common.model.Allocation;
import com.indeed.proctor.common.model.Audit;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import com.indeed.proctor.common.model.TestBucket;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySortedMap;
/**
* Return value from {@link Proctor#determineTestGroups(Identifiers, java.util.Map, java.util.Map)}
* @author ketan
*
*/
public class ProctorResult {
public static final ProctorResult EMPTY = new ProctorResult(
Audit.EMPTY_VERSION,
emptySortedMap(),
emptySortedMap(),
emptyMap()
);
private final String matrixVersion;
/**
* maps from testname to bucket
*/
@Nonnull
private final SortedMap<String, TestBucket> buckets;
/**
* maps from testname to allocation
*/
@Nonnull
private final SortedMap<String, Allocation> allocations;
/**
* maps from testname to TestDefinition
*/
@Nonnull
private final Map<String, ConsumableTestDefinition> testDefinitions;
/**
* Create a ProctorResult with copies of the provided collections
* @deprecated this constructor creates copies of all inputs
*/
@Deprecated
public ProctorResult(
@Nonnull final int matrixVersion,
@Nonnull final Map<String, TestBucket> buckets,
// allowing null for historical reasons
@Nullable final Map<String, ConsumableTestDefinition> testDefinitions
) {
this(Integer.toString(matrixVersion), buckets, emptyMap(), testDefinitions);
}
/**
* Create a ProctorResult with copies of the provided collections
* @deprecated this constructor creates copies of all inputs
*/
@Deprecated
public ProctorResult(
@Nonnull final String matrixVersion,
@Nonnull final Map<String, TestBucket> buckets,
// allowing null for historical reasons
@Nullable final Map<String, ConsumableTestDefinition> testDefinitions
) {
this(matrixVersion, buckets, emptyMap(), testDefinitions);
}
/**
* Create a ProctorResult with copies of the provided collections
* @deprecated this constructor creates copies of all input collections
*/
@Deprecated
public ProctorResult(
@Nonnull final String matrixVersion,
@Nonnull final Map<String, TestBucket> buckets,
@Nonnull final Map<String, Allocation> allocations,
// allowing null for historical reasons
@Nullable final Map<String, ConsumableTestDefinition> testDefinitions
) {
// Potentially client applications might need to build ProctorResult instances in each request, and some apis
// have large proctorResult objects, so if teams use this constructor, this may have a noticeable
// impact on latency and GC, so ideally clients should avoid this constructor.
this(
matrixVersion,
new TreeMap<>(buckets),
new TreeMap<>(allocations),
(testDefinitions == null) ? emptyMap() : new HashMap<>(testDefinitions)
);
}
/**
* Plain constructor, not creating TreeMaps as in the deprecated version.
*/
public ProctorResult(
@Nonnull final String matrixVersion,
@Nonnull final SortedMap<String, TestBucket> buckets,
@Nonnull final SortedMap<String, Allocation> allocations,
@Nonnull final Map<String, ConsumableTestDefinition> testDefinitions
) {
this.matrixVersion = matrixVersion;
this.buckets = buckets;
this.allocations = allocations;
this.testDefinitions = testDefinitions;
}
/**
* @return a new Proctor Result, which does not allow modifying the contained collections.
* The result's fields are views of the original fields, to reduce memory allocation effort.
*/
public static ProctorResult unmodifiableView(final ProctorResult proctorResult) {
return new ProctorResult(
proctorResult.getMatrixVersion(),
Collections.unmodifiableSortedMap((SortedMap<String, TestBucket>) proctorResult.getBuckets()),
Collections.unmodifiableSortedMap((SortedMap<String, Allocation>) proctorResult.getAllocations()),
Collections.unmodifiableMap(proctorResult.getTestDefinitions())
);
}
@SuppressWarnings("UnusedDeclaration")
public String getMatrixVersion() {
return matrixVersion;
}
/**
* @return a SortedMap (should be ordered by testname)
*/
@Nonnull
// returning Map instead of SortedMap for historic reasons (changing breaks compiled libraries)
public Map<String, TestBucket> getBuckets() {
return buckets;
}
/**
* @return a SortedMap (should be ordered by testname)
*/
@Nonnull
// returning Map instead of SortedMap for historic reasons (changing breaks compiled libraries)
public Map<String, Allocation> getAllocations() {
return allocations;
}
@Nonnull
public Map<String, ConsumableTestDefinition> getTestDefinitions() {
return testDefinitions;
}
}
| PROC-897: Use inline call to getter
| proctor-common/src/main/java/com/indeed/proctor/common/ProctorResult.java | PROC-897: Use inline call to getter |
|
Java | apache-2.0 | 3e150b6d6fcbf61c2ab76d0807fd7e936c83c9e8 | 0 | fengshao0907/qfs,chanwit/qfs,chanwit/qfs,chanwit/qfs,fengshao0907/qfs,quantcast/qfs,thebigbrain/qfs,thebigbrain/qfs,thebigbrain/qfs,quantcast/qfs,qnu/qfs,thebigbrain/qfs,fengshao0907/qfs,thebigbrain/qfs,chanwit/qfs,quantcast/qfs,quantcast/qfs,qnu/qfs,qnu/qfs,fengshao0907/qfs,quantcast/qfs,qnu/qfs,qnu/qfs,qnu/qfs,qnu/qfs,chanwit/qfs,fengshao0907/qfs,chanwit/qfs,qnu/qfs,thebigbrain/qfs,quantcast/qfs,chanwit/qfs,thebigbrain/qfs,fengshao0907/qfs,chanwit/qfs,fengshao0907/qfs,fengshao0907/qfs,quantcast/qfs,thebigbrain/qfs,quantcast/qfs | /**
*
* 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.
*
* Implements the Hadoop FS interfaces to allow applications to store files in
* Quantcast File System (QFS). This is an extension of KFS.
*/
package com.quantcast.qfs.hadoop;
import java.io.*;
import java.net.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.fs.BlockLocation;
import com.quantcast.qfs.access.KfsFileAttr;
public class QuantcastFileSystem extends FileSystem {
private FileSystem localFs;
private IFSImpl qfsImpl = null;
private URI uri;
private Path workingDir = new Path("/");
public QuantcastFileSystem() {
}
QuantcastFileSystem(IFSImpl fsimpl) {
this.qfsImpl = fsimpl;
}
public URI getUri() {
return uri;
}
public void initialize(URI uri, Configuration conf) throws IOException {
super.initialize(uri, conf);
try {
if (qfsImpl == null) {
if (uri.getHost() == null) {
qfsImpl = new QFSImpl(conf.get("fs.qfs.metaServerHost", ""),
conf.getInt("fs.qfs.metaServerPort", -1),
statistics);
} else {
qfsImpl = new QFSImpl(uri.getHost(), uri.getPort(), statistics);
}
}
this.localFs = FileSystem.getLocal(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
this.workingDir = new Path("/user", System.getProperty("user.name")
).makeQualified(this);
setConf(conf);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Unable to initialize QFS");
System.exit(-1);
}
}
public Path getWorkingDirectory() {
return workingDir;
}
public void setWorkingDirectory(Path dir) {
workingDir = makeAbsolute(dir);
}
private Path makeAbsolute(Path path) {
if (path.isAbsolute()) {
return path;
}
return new Path(workingDir, path);
}
public boolean mkdirs(Path path, FsPermission permission)
throws IOException {
return qfsImpl.mkdirs(makeAbsolute(path).toUri().getPath(),
permission.toShort()) == 0;
}
@Deprecated
public boolean isDirectory(Path path) throws IOException {
Path absolute = makeAbsolute(path);
String srep = absolute.toUri().getPath();
return qfsImpl.isDirectory(srep);
}
@Deprecated
public boolean isFile(Path path) throws IOException {
Path absolute = makeAbsolute(path);
String srep = absolute.toUri().getPath();
return qfsImpl.isFile(srep);
}
public FileStatus[] listStatus(Path path) throws IOException {
final Path absolute = makeAbsolute(path);
final FileStatus fs = qfsImpl.stat(absolute);
return fs.isDir() ?
qfsImpl.readdirplus(absolute) :
new FileStatus[] { fs };
}
public FileStatus getFileStatus(Path path) throws IOException {
return qfsImpl.stat(makeAbsolute(path));
}
public FSDataOutputStream append(Path path, int bufferSize,
Progressable progress) throws IOException {
return qfsImpl.append(
makeAbsolute(path).toUri().getPath(), (short)-1, bufferSize);
}
public FSDataOutputStream create(Path file, FsPermission permission,
boolean overwrite, int bufferSize,
short replication, long blockSize,
Progressable progress)
throws IOException {
Path parent = file.getParent();
if (parent != null && !mkdirs(parent)) {
throw new IOException("Mkdirs failed to create " + parent);
}
return qfsImpl.create(makeAbsolute(file).toUri().getPath(),
replication, bufferSize, overwrite, permission.toShort());
}
public FSDataOutputStream createNonRecursive(Path file,
FsPermission permission,
boolean overwrite, int bufferSize,
short replication, long blockSize,
Progressable progress)
throws IOException {
Path parent = file.getParent();
if (parent == null || exists(parent)) {
return create(file, permission, overwrite, bufferSize, replication,
blockSize, progress);
} else {
throw new IOException("Parent " + parent + " does not exist");
}
}
public FSDataInputStream open(Path path, int bufferSize) throws IOException {
return qfsImpl.open(makeAbsolute(path).toUri().getPath(), bufferSize);
}
public boolean rename(Path src, Path dst) throws IOException {
Path absoluteS = makeAbsolute(src);
String srepS = absoluteS.toUri().getPath();
Path absoluteD = makeAbsolute(dst);
String srepD = absoluteD.toUri().getPath();
return qfsImpl.rename(srepS, srepD) == 0;
}
// recursively delete the directory and its contents
public boolean delete(Path path, boolean recursive) throws IOException {
Path absolute = makeAbsolute(path);
String srep = absolute.toUri().getPath();
if (qfsImpl.isFile(srep))
return qfsImpl.remove(srep) == 0;
FileStatus[] dirEntries = listStatus(absolute);
if ((!recursive) && (dirEntries != null) && (dirEntries.length != 0)) {
throw new IOException("Directory " + path.toString() + " is not empty.");
}
if (dirEntries != null) {
for (int i = 0; i < dirEntries.length; i++) {
delete(new Path(absolute, dirEntries[i].getPath()), recursive);
}
}
return qfsImpl.rmdir(srep) == 0;
}
@Deprecated
public boolean delete(Path path) throws IOException {
return delete(path, true);
}
public short getDefaultReplication() {
return 3;
}
public boolean setReplication(Path path, short replication)
throws IOException {
Path absolute = makeAbsolute(path);
String srep = absolute.toUri().getPath();
int res = qfsImpl.setReplication(srep, replication);
return res >= 0;
}
// 64MB is the QFS block size
public long getDefaultBlockSize() {
return 1 << 26;
}
/**
* Return null if the file doesn't exist; otherwise, get the
* locations of the various chunks of the file file from QFS.
*/
@Override
public BlockLocation[] getFileBlockLocations(FileStatus file,
long start, long len) throws IOException {
if (file == null) {
return null;
}
String srep = makeAbsolute(file.getPath()).toUri().getPath();
String[][] hints = qfsImpl.getDataLocation(srep, start, len);
if (hints == null) {
return null;
}
BlockLocation[] result = new BlockLocation[hints.length];
long blockSize = getDefaultBlockSize();
long length = len;
long blockStart = start;
for(int i=0; i < result.length; ++i) {
result[i] = new BlockLocation(
null,
hints[i],
blockStart,
length < blockSize ? length : blockSize);
blockStart += blockSize;
length -= blockSize;
}
return result;
}
public void copyFromLocalFile(boolean delSrc, Path src, Path dst)
throws IOException {
FileUtil.copy(localFs, src, this, dst, delSrc, getConf());
}
public void copyToLocalFile(boolean delSrc, Path src, Path dst)
throws IOException {
FileUtil.copy(this, src, localFs, dst, delSrc, getConf());
}
public Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile)
throws IOException {
return tmpLocalFile;
}
public void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile)
throws IOException {
moveFromLocalFile(tmpLocalFile, fsOutputFile);
}
public void setPermission(Path path, FsPermission permission)
throws IOException {
qfsImpl.setPermission(makeAbsolute(path).toUri().getPath(),
permission.toShort());
}
public void setOwner(Path path, String username, String groupname)
throws IOException {
qfsImpl.setOwner(makeAbsolute(path).toUri().getPath(),
username, groupname);
}
// The following is to get du and dus working without implementing file
// and directory counts on in the meta server.
private class ContentSummaryProxy extends ContentSummary
{
private ContentSummary cs;
private final Path path;
private ContentSummaryProxy(Path path, long len) {
super(len, -1, -1);
this.path = path;
}
private ContentSummary get() {
if (cs == null) {
try {
cs = getContentSummarySuper(path);
} catch (IOException ex) {
cs = this;
}
}
return cs;
}
public long getDirectoryCount() {
return get().getDirectoryCount();
}
public long getFileCount() {
return get().getFileCount();
}
public void write(DataOutput out) throws IOException {
get().write(out);
}
public String toString(boolean qOption) {
return get().toString(qOption);
}
}
private ContentSummary getContentSummarySuper(Path path) throws IOException {
return super.getContentSummary(path);
}
public ContentSummary getContentSummary(Path path) throws IOException {
// since QFS stores sizes at each level of the dir tree, we can
// just stat the dir.
final Path absolute = makeAbsolute(path);
final KfsFileAttr stat = qfsImpl.fullStat(absolute);
if (stat.isDirectory) {
final long len = stat.filesize;
if (len < 0) {
return getContentSummarySuper(absolute);
}
if (stat.dirCount < 0) {
return new ContentSummaryProxy(absolute, len);
}
return new ContentSummary(len, stat.fileCount, stat.dirCount + 1);
}
return new ContentSummary(stat.filesize, 1, 0);
}
}
| src/java/hadoop-qfs/src/main/java/com/quantcast/qfs/hadoop/QuantcastFileSystem.java | /**
*
* 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.
*
* Implements the Hadoop FS interfaces to allow applications to store files in
* Quantcast File System (QFS). This is an extension of KFS.
*/
package com.quantcast.qfs.hadoop;
import java.io.*;
import java.net.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.fs.BlockLocation;
import com.quantcast.qfs.access.KfsFileAttr;
public class QuantcastFileSystem extends FileSystem {
private FileSystem localFs;
private IFSImpl qfsImpl = null;
private URI uri;
private Path workingDir = new Path("/");
public QuantcastFileSystem() {
}
QuantcastFileSystem(IFSImpl fsimpl) {
this.qfsImpl = fsimpl;
}
public URI getUri() {
return uri;
}
public void initialize(URI uri, Configuration conf) throws IOException {
super.initialize(uri, conf);
try {
if (qfsImpl == null) {
if (uri.getHost() == null) {
qfsImpl = new QFSImpl(conf.get("fs.qfs.metaServerHost", ""),
conf.getInt("fs.qfs.metaServerPort", -1),
statistics);
} else {
qfsImpl = new QFSImpl(uri.getHost(), uri.getPort(), statistics);
}
}
this.localFs = FileSystem.getLocal(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
this.workingDir = new Path("/user", System.getProperty("user.name")
).makeQualified(this);
setConf(conf);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Unable to initialize QFS");
System.exit(-1);
}
}
public Path getWorkingDirectory() {
return workingDir;
}
public void setWorkingDirectory(Path dir) {
workingDir = makeAbsolute(dir);
}
private Path makeAbsolute(Path path) {
if (path.isAbsolute()) {
return path;
}
return new Path(workingDir, path);
}
public boolean mkdirs(Path path, FsPermission permission)
throws IOException {
return qfsImpl.mkdirs(makeAbsolute(path).toUri().getPath(),
permission.toShort()) == 0;
}
@Deprecated
public boolean isDirectory(Path path) throws IOException {
Path absolute = makeAbsolute(path);
String srep = absolute.toUri().getPath();
return qfsImpl.isDirectory(srep);
}
@Deprecated
public boolean isFile(Path path) throws IOException {
Path absolute = makeAbsolute(path);
String srep = absolute.toUri().getPath();
return qfsImpl.isFile(srep);
}
public FileStatus[] listStatus(Path path) throws IOException {
final Path absolute = makeAbsolute(path);
final FileStatus fs = qfsImpl.stat(absolute);
return fs.isDir() ?
qfsImpl.readdirplus(absolute) :
new FileStatus[] { fs };
}
public FileStatus getFileStatus(Path path) throws IOException {
return qfsImpl.stat(makeAbsolute(path));
}
public FSDataOutputStream append(Path path, int bufferSize,
Progressable progress) throws IOException {
return qfsImpl.append(
makeAbsolute(path).toUri().getPath(), (short)-1, bufferSize);
}
public FSDataOutputStream create(Path file, FsPermission permission,
boolean overwrite, int bufferSize,
short replication, long blockSize,
Progressable progress)
throws IOException {
Path parent = file.getParent();
if (parent != null && !mkdirs(parent)) {
throw new IOException("Mkdirs failed to create " + parent);
}
return qfsImpl.create(makeAbsolute(file).toUri().getPath(),
replication, bufferSize, overwrite, permission.toShort());
}
public FSDataInputStream open(Path path, int bufferSize) throws IOException {
return qfsImpl.open(makeAbsolute(path).toUri().getPath(), bufferSize);
}
public boolean rename(Path src, Path dst) throws IOException {
Path absoluteS = makeAbsolute(src);
String srepS = absoluteS.toUri().getPath();
Path absoluteD = makeAbsolute(dst);
String srepD = absoluteD.toUri().getPath();
return qfsImpl.rename(srepS, srepD) == 0;
}
// recursively delete the directory and its contents
public boolean delete(Path path, boolean recursive) throws IOException {
Path absolute = makeAbsolute(path);
String srep = absolute.toUri().getPath();
if (qfsImpl.isFile(srep))
return qfsImpl.remove(srep) == 0;
FileStatus[] dirEntries = listStatus(absolute);
if ((!recursive) && (dirEntries != null) && (dirEntries.length != 0)) {
throw new IOException("Directory " + path.toString() + " is not empty.");
}
if (dirEntries != null) {
for (int i = 0; i < dirEntries.length; i++) {
delete(new Path(absolute, dirEntries[i].getPath()), recursive);
}
}
return qfsImpl.rmdir(srep) == 0;
}
@Deprecated
public boolean delete(Path path) throws IOException {
return delete(path, true);
}
public short getDefaultReplication() {
return 3;
}
public boolean setReplication(Path path, short replication)
throws IOException {
Path absolute = makeAbsolute(path);
String srep = absolute.toUri().getPath();
int res = qfsImpl.setReplication(srep, replication);
return res >= 0;
}
// 64MB is the QFS block size
public long getDefaultBlockSize() {
return 1 << 26;
}
/**
* Return null if the file doesn't exist; otherwise, get the
* locations of the various chunks of the file file from QFS.
*/
@Override
public BlockLocation[] getFileBlockLocations(FileStatus file,
long start, long len) throws IOException {
if (file == null) {
return null;
}
String srep = makeAbsolute(file.getPath()).toUri().getPath();
String[][] hints = qfsImpl.getDataLocation(srep, start, len);
if (hints == null) {
return null;
}
BlockLocation[] result = new BlockLocation[hints.length];
long blockSize = getDefaultBlockSize();
long length = len;
long blockStart = start;
for(int i=0; i < result.length; ++i) {
result[i] = new BlockLocation(
null,
hints[i],
blockStart,
length < blockSize ? length : blockSize);
blockStart += blockSize;
length -= blockSize;
}
return result;
}
public void copyFromLocalFile(boolean delSrc, Path src, Path dst)
throws IOException {
FileUtil.copy(localFs, src, this, dst, delSrc, getConf());
}
public void copyToLocalFile(boolean delSrc, Path src, Path dst)
throws IOException {
FileUtil.copy(this, src, localFs, dst, delSrc, getConf());
}
public Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile)
throws IOException {
return tmpLocalFile;
}
public void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile)
throws IOException {
moveFromLocalFile(tmpLocalFile, fsOutputFile);
}
public void setPermission(Path path, FsPermission permission)
throws IOException {
qfsImpl.setPermission(makeAbsolute(path).toUri().getPath(),
permission.toShort());
}
public void setOwner(Path path, String username, String groupname)
throws IOException {
qfsImpl.setOwner(makeAbsolute(path).toUri().getPath(),
username, groupname);
}
// The following is to get du and dus working without implementing file
// and directory counts on in the meta server.
private class ContentSummaryProxy extends ContentSummary
{
private ContentSummary cs;
private final Path path;
private ContentSummaryProxy(Path path, long len) {
super(len, -1, -1);
this.path = path;
}
private ContentSummary get() {
if (cs == null) {
try {
cs = getContentSummarySuper(path);
} catch (IOException ex) {
cs = this;
}
}
return cs;
}
public long getDirectoryCount() {
return get().getDirectoryCount();
}
public long getFileCount() {
return get().getFileCount();
}
public void write(DataOutput out) throws IOException {
get().write(out);
}
public String toString(boolean qOption) {
return get().toString(qOption);
}
}
private ContentSummary getContentSummarySuper(Path path) throws IOException {
return super.getContentSummary(path);
}
public ContentSummary getContentSummary(Path path) throws IOException {
// since QFS stores sizes at each level of the dir tree, we can
// just stat the dir.
final Path absolute = makeAbsolute(path);
final KfsFileAttr stat = qfsImpl.fullStat(absolute);
if (stat.isDirectory) {
final long len = stat.filesize;
if (len < 0) {
return getContentSummarySuper(absolute);
}
if (stat.dirCount < 0) {
return new ContentSummaryProxy(absolute, len);
}
return new ContentSummary(len, stat.fileCount, stat.dirCount + 1);
}
return new ContentSummary(stat.filesize, 1, 0);
}
}
| Implementing createNonRecursive method for HBase compatibility.
| src/java/hadoop-qfs/src/main/java/com/quantcast/qfs/hadoop/QuantcastFileSystem.java | Implementing createNonRecursive method for HBase compatibility. |
|
Java | apache-2.0 | fcfec4534d4fd5c9b1f308217b51788b85400507 | 0 | redisson/redisson,mrniko/redisson | /**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.cluster;
import io.netty.resolver.AddressResolver;
import io.netty.util.NetUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.ScheduledFuture;
import org.redisson.api.NatMapper;
import org.redisson.api.NodeType;
import org.redisson.api.RFuture;
import org.redisson.client.*;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.RedisStrictCommand;
import org.redisson.cluster.ClusterNodeInfo.Flag;
import org.redisson.cluster.ClusterPartition.Type;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.MasterSlaveServersConfig;
import org.redisson.config.ReadMode;
import org.redisson.connection.CRC16;
import org.redisson.connection.ClientConnectionsEntry.FreezeReason;
import org.redisson.connection.MasterSlaveConnectionManager;
import org.redisson.connection.MasterSlaveEntry;
import org.redisson.connection.SingleEntry;
import org.redisson.misc.RPromise;
import org.redisson.misc.RedisURI;
import org.redisson.misc.RedissonPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.stream.Collectors;
/**
*
* @author Nikita Koksharov
*
*/
public class ClusterConnectionManager extends MasterSlaveConnectionManager {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ConcurrentMap<Integer, ClusterPartition> lastPartitions = new ConcurrentHashMap<>();
private ScheduledFuture<?> monitorFuture;
private volatile RedisURI lastClusterNode;
private RedisStrictCommand<List<ClusterNodeInfo>> clusterNodesCommand;
private String configEndpointHostName;
private final NatMapper natMapper;
private final AtomicReferenceArray<MasterSlaveEntry> slot2entry = new AtomicReferenceArray<>(MAX_SLOT);
private final Map<RedisClient, MasterSlaveEntry> client2entry = new ConcurrentHashMap<>();
public ClusterConnectionManager(ClusterServersConfig cfg, Config config, UUID id) {
super(config, id);
if (cfg.getNodeAddresses().isEmpty()) {
throw new IllegalArgumentException("At least one cluster node should be defined!");
}
this.natMapper = cfg.getNatMapper();
this.config = create(cfg);
initTimer(this.config);
Throwable lastException = null;
List<String> failedMasters = new ArrayList<String>();
for (String address : cfg.getNodeAddresses()) {
RedisURI addr = new RedisURI(address);
RFuture<RedisConnection> connectionFuture = connectToNode(cfg, addr, null, addr.getHost());
try {
RedisConnection connection = connectionFuture.syncUninterruptibly().getNow();
if (cfg.getNodeAddresses().size() == 1 && NetUtil.createByteArrayFromIpAddressString(addr.getHost()) == null) {
configEndpointHostName = addr.getHost();
}
clusterNodesCommand = RedisCommands.CLUSTER_NODES;
if (addr.isSsl()) {
clusterNodesCommand = RedisCommands.CLUSTER_NODES_SSL;
}
List<ClusterNodeInfo> nodes = connection.sync(clusterNodesCommand);
StringBuilder nodesValue = new StringBuilder();
for (ClusterNodeInfo clusterNodeInfo : nodes) {
nodesValue.append(clusterNodeInfo.getNodeInfo()).append("\n");
}
log.info("Redis cluster nodes configuration got from {}:\n{}", connection.getRedisClient().getAddr(), nodesValue);
lastClusterNode = addr;
Collection<ClusterPartition> partitions = parsePartitions(nodes);
List<RFuture<Void>> masterFutures = new ArrayList<>();
for (ClusterPartition partition : partitions) {
if (partition.isMasterFail()) {
failedMasters.add(partition.getMasterAddress().toString());
continue;
}
if (partition.getMasterAddress() == null) {
throw new IllegalStateException("Master node: " + partition.getNodeId() + " doesn't have address.");
}
RFuture<Void> masterFuture = addMasterEntry(partition, cfg);
masterFutures.add(masterFuture);
}
for (RFuture<Void> masterFuture : masterFutures) {
masterFuture.awaitUninterruptibly();
if (!masterFuture.isSuccess()) {
lastException = masterFuture.cause();
}
}
break;
} catch (Exception e) {
lastException = e;
log.warn(e.getMessage());
}
}
if (lastPartitions.isEmpty()) {
stopThreads();
if (failedMasters.isEmpty()) {
throw new RedisConnectionException("Can't connect to servers!", lastException);
} else {
throw new RedisConnectionException("Can't connect to servers! Failed masters according to cluster status: " + failedMasters, lastException);
}
}
if (cfg.isCheckSlotsCoverage() && lastPartitions.size() != MAX_SLOT) {
stopThreads();
if (failedMasters.isEmpty()) {
throw new RedisConnectionException("Not all slots covered! Only " + lastPartitions.size() + " slots are available. Set checkSlotsCoverage = false to avoid this check.", lastException);
} else {
throw new RedisConnectionException("Not all slots covered! Only " + lastPartitions.size() + " slots are available. Set checkSlotsCoverage = false to avoid this check. Failed masters according to cluster status: " + failedMasters, lastException);
}
}
scheduleClusterChangeCheck(cfg);
}
@Override
public Collection<MasterSlaveEntry> getEntrySet() {
return client2entry.values();
}
protected MasterSlaveEntry getEntry(RedisURI addr) {
for (MasterSlaveEntry entry : client2entry.values()) {
if (RedisURI.compare(entry.getClient().getAddr(), addr)) {
return entry;
}
if (entry.hasSlave(addr)) {
return entry;
}
}
return null;
}
@Override
public MasterSlaveEntry getEntry(RedisClient redisClient) {
MasterSlaveEntry entry = client2entry.get(redisClient);
if (entry != null) {
return entry;
}
for (MasterSlaveEntry mentry : client2entry.values()) {
if (mentry.hasSlave(redisClient)) {
return mentry;
}
}
return null;
}
@Override
public MasterSlaveEntry getEntry(InetSocketAddress address) {
for (MasterSlaveEntry entry : client2entry.values()) {
InetSocketAddress addr = entry.getClient().getAddr();
if (addr.getAddress().equals(address.getAddress()) && addr.getPort() == address.getPort()) {
return entry;
}
}
return null;
}
@Override
protected RFuture<RedisClient> changeMaster(int slot, RedisURI address) {
MasterSlaveEntry entry = getEntry(slot);
RedisClient oldClient = entry.getClient();
RFuture<RedisClient> future = super.changeMaster(slot, address);
future.onComplete((res, e) -> {
if (e == null) {
client2entry.remove(oldClient);
client2entry.put(entry.getClient(), entry);
}
});
return future;
}
@Override
public MasterSlaveEntry getEntry(int slot) {
return slot2entry.get(slot);
}
private void addEntry(Integer slot, MasterSlaveEntry entry) {
MasterSlaveEntry oldEntry = slot2entry.getAndSet(slot, entry);
if (oldEntry != entry) {
entry.incReference();
shutdownEntry(oldEntry);
}
client2entry.put(entry.getClient(), entry);
}
private void removeEntry(Integer slot) {
MasterSlaveEntry entry = slot2entry.getAndSet(slot, null);
shutdownEntry(entry);
}
private void shutdownEntry(MasterSlaveEntry entry) {
if (entry != null && entry.decReference() == 0) {
client2entry.remove(entry.getClient());
entry.getAllEntries().forEach(e -> entry.nodeDown(e));
entry.masterDown();
entry.shutdownAsync();
subscribeService.remove(entry);
String slaves = entry.getAllEntries().stream()
.filter(e -> !e.getClient().getAddr().equals(entry.getClient().getAddr()))
.map(e -> e.getClient().toString())
.collect(Collectors.joining(","));
log.info("{} master and related slaves: {} removed", entry.getClient().getAddr(), slaves);
}
}
@Override
protected RedisClientConfig createRedisConfig(NodeType type, RedisURI address, int timeout, int commandTimeout, String sslHostname) {
RedisClientConfig result = super.createRedisConfig(type, address, timeout, commandTimeout, sslHostname);
result.setReadOnly(type == NodeType.SLAVE && config.getReadMode() != ReadMode.MASTER);
return result;
}
private RFuture<Void> addMasterEntry(ClusterPartition partition, ClusterServersConfig cfg) {
if (partition.isMasterFail()) {
RedisException e = new RedisException("Failed to add master: " +
partition.getMasterAddress() + " for slot ranges: " +
partition.getSlotRanges() + ". Reason - server has FAIL flag");
if (partition.getSlotsAmount() == 0) {
e = new RedisException("Failed to add master: " +
partition.getMasterAddress() + ". Reason - server has FAIL flag");
}
return RedissonPromise.newFailedFuture(e);
}
RPromise<Void> result = new RedissonPromise<>();
RFuture<RedisConnection> connectionFuture = connectToNode(cfg, partition.getMasterAddress(), null, configEndpointHostName);
connectionFuture.onComplete((connection, ex1) -> {
if (ex1 != null) {
log.error("Can't connect to master: {} with slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
result.tryFailure(ex1);
return;
}
MasterSlaveServersConfig config = create(cfg);
config.setMasterAddress(partition.getMasterAddress().toString());
MasterSlaveEntry entry;
if (config.checkSkipSlavesInit()) {
entry = new SingleEntry(ClusterConnectionManager.this, config);
} else {
Set<String> slaveAddresses = partition.getSlaveAddresses().stream().map(r -> r.toString()).collect(Collectors.toSet());
config.setSlaveAddresses(slaveAddresses);
entry = new MasterSlaveEntry(ClusterConnectionManager.this, config);
}
RFuture<RedisClient> f = entry.setupMasterEntry(new RedisURI(config.getMasterAddress()));
f.onComplete((masterClient, ex3) -> {
if (ex3 != null) {
log.error("Can't add master: " + partition.getMasterAddress() + " for slot ranges: " + partition.getSlotRanges(), ex3);
result.tryFailure(ex3);
return;
}
for (Integer slot : partition.getSlots()) {
addEntry(slot, entry);
lastPartitions.put(slot, partition);
}
if (!config.checkSkipSlavesInit()) {
List<RFuture<Void>> fs = entry.initSlaveBalancer(partition.getFailedSlaveAddresses(), masterClient);
AtomicInteger counter = new AtomicInteger(fs.size());
for (RFuture<Void> future : fs) {
future.onComplete((r, ex) -> {
if (ex != null) {
log.error("unable to add slave for: " + partition.getMasterAddress()
+ " slot ranges: " + partition.getSlotRanges(), ex);
}
if (counter.decrementAndGet() == 0) {
if (!partition.getSlaveAddresses().isEmpty()) {
log.info("slaves: {} added for slot ranges: {}", partition.getSlaveAddresses(), partition.getSlotRanges());
if (!partition.getFailedSlaveAddresses().isEmpty()) {
log.warn("slaves: {} are down for slot ranges: {}", partition.getFailedSlaveAddresses(), partition.getSlotRanges());
}
}
if (result.trySuccess(null)) {
log.info("master: {} added for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
} else {
log.error("unable to add master: {} for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
}
}
});
}
} else {
if (result.trySuccess(null)) {
log.info("master: {} added for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
} else {
log.error("unable to add master: {} for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
}
}
});
});
return result;
}
private void scheduleClusterChangeCheck(ClusterServersConfig cfg) {
monitorFuture = group.schedule(new Runnable() {
@Override
public void run() {
if (configEndpointHostName != null) {
String address = cfg.getNodeAddresses().iterator().next();
RedisURI uri = new RedisURI(address);
AddressResolver<InetSocketAddress> resolver = resolverGroup.getResolver(getGroup().next());
Future<List<InetSocketAddress>> allNodes = resolver.resolveAll(InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort()));
allNodes.addListener(new FutureListener<List<InetSocketAddress>>() {
@Override
public void operationComplete(Future<List<InetSocketAddress>> future) throws Exception {
AtomicReference<Throwable> lastException = new AtomicReference<Throwable>(future.cause());
if (!future.isSuccess()) {
checkClusterState(cfg, Collections.emptyIterator(), lastException);
return;
}
List<RedisURI> nodes = new ArrayList<>();
for (InetSocketAddress addr : future.getNow()) {
RedisURI node = new RedisURI(uri.getScheme() + "://" + addr.getAddress().getHostAddress() + ":" + addr.getPort());
RedisURI address = applyNatMap(node);
nodes.add(address);
}
Iterator<RedisURI> nodesIterator = nodes.iterator();
checkClusterState(cfg, nodesIterator, lastException);
}
});
} else {
AtomicReference<Throwable> lastException = new AtomicReference<Throwable>();
List<RedisURI> nodes = new ArrayList<>();
List<RedisURI> slaves = new ArrayList<>();
for (ClusterPartition partition : getLastPartitions()) {
if (!partition.isMasterFail()) {
nodes.add(partition.getMasterAddress());
}
Set<RedisURI> partitionSlaves = new HashSet<>(partition.getSlaveAddresses());
partitionSlaves.removeAll(partition.getFailedSlaveAddresses());
slaves.addAll(partitionSlaves);
}
// master nodes first
nodes.addAll(slaves);
Iterator<RedisURI> nodesIterator = nodes.iterator();
checkClusterState(cfg, nodesIterator, lastException);
}
}
}, cfg.getScanInterval(), TimeUnit.MILLISECONDS);
}
private void checkClusterState(ClusterServersConfig cfg, Iterator<RedisURI> iterator, AtomicReference<Throwable> lastException) {
if (!iterator.hasNext()) {
if (lastException.get() != null) {
log.error("Can't update cluster state", lastException.get());
}
scheduleClusterChangeCheck(cfg);
return;
}
if (!getShutdownLatch().acquire()) {
return;
}
RedisURI uri = iterator.next();
RFuture<RedisConnection> connectionFuture = connectToNode(cfg, uri, null, configEndpointHostName);
connectionFuture.onComplete((connection, e) -> {
if (e != null) {
lastException.set(e);
getShutdownLatch().release();
checkClusterState(cfg, iterator, lastException);
return;
}
updateClusterState(cfg, connection, iterator, uri, lastException);
});
}
private void updateClusterState(ClusterServersConfig cfg, RedisConnection connection,
Iterator<RedisURI> iterator, RedisURI uri, AtomicReference<Throwable> lastException) {
RFuture<List<ClusterNodeInfo>> future = connection.async(clusterNodesCommand);
future.onComplete((nodes, e) -> {
if (e != null) {
log.error("Can't execute CLUSTER_NODES with " + connection.getRedisClient().getAddr(), e);
closeNodeConnection(connection);
lastException.set(e);
getShutdownLatch().release();
checkClusterState(cfg, iterator, lastException);
return;
}
lastClusterNode = uri;
StringBuilder nodesValue = new StringBuilder();
if (log.isDebugEnabled()) {
for (ClusterNodeInfo clusterNodeInfo : nodes) {
nodesValue.append(clusterNodeInfo.getNodeInfo()).append("\n");
}
log.debug("cluster nodes state got from {}:\n{}", connection.getRedisClient().getAddr(), nodesValue);
}
Collection<ClusterPartition> newPartitions = parsePartitions(nodes);
RFuture<Void> masterFuture = checkMasterNodesChange(cfg, newPartitions);
checkSlaveNodesChange(newPartitions);
masterFuture.onComplete((res, ex) -> {
checkSlotsMigration(newPartitions);
checkSlotsChange(newPartitions);
getShutdownLatch().release();
scheduleClusterChangeCheck(cfg);
});
});
}
private void checkSlaveNodesChange(Collection<ClusterPartition> newPartitions) {
Set<ClusterPartition> lastPartitions = getLastPartitions();
for (ClusterPartition newPart : newPartitions) {
for (ClusterPartition currentPart : lastPartitions) {
if (!newPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
continue;
}
MasterSlaveEntry entry = getEntry(currentPart.slots().nextSetBit(0));
// should be invoked first in order to remove stale failedSlaveAddresses
Set<RedisURI> addedSlaves = addRemoveSlaves(entry, currentPart, newPart);
// Do some slaves have changed state from failed to alive?
upDownSlaves(entry, currentPart, newPart, addedSlaves);
break;
}
}
}
private void upDownSlaves(MasterSlaveEntry entry, ClusterPartition currentPart, ClusterPartition newPart, Set<RedisURI> addedSlaves) {
Set<RedisURI> aliveSlaves = new HashSet<>(currentPart.getFailedSlaveAddresses());
aliveSlaves.removeAll(addedSlaves);
aliveSlaves.removeAll(newPart.getFailedSlaveAddresses());
for (RedisURI uri : aliveSlaves) {
currentPart.removeFailedSlaveAddress(uri);
if (entry.hasSlave(uri) && entry.slaveUp(uri, FreezeReason.MANAGER)) {
log.info("slave: {} is up for slot ranges: {}", uri, currentPart.getSlotRanges());
}
}
Set<RedisURI> failedSlaves = new HashSet<>(newPart.getFailedSlaveAddresses());
failedSlaves.removeAll(currentPart.getFailedSlaveAddresses());
for (RedisURI uri : failedSlaves) {
currentPart.addFailedSlaveAddress(uri);
if (entry.slaveDown(uri, FreezeReason.MANAGER)) {
disconnectNode(uri);
log.warn("slave: {} has down for slot ranges: {}", uri, currentPart.getSlotRanges());
}
}
}
private Set<RedisURI> addRemoveSlaves(MasterSlaveEntry entry, ClusterPartition currentPart, ClusterPartition newPart) {
Set<RedisURI> removedSlaves = new HashSet<>(currentPart.getSlaveAddresses());
removedSlaves.removeAll(newPart.getSlaveAddresses());
for (RedisURI uri : removedSlaves) {
currentPart.removeSlaveAddress(uri);
if (entry.slaveDown(uri, FreezeReason.MANAGER)) {
log.info("slave {} removed for slot ranges: {}", uri, currentPart.getSlotRanges());
}
}
Set<RedisURI> addedSlaves = new HashSet<>(newPart.getSlaveAddresses());
addedSlaves.removeAll(currentPart.getSlaveAddresses());
for (RedisURI uri : addedSlaves) {
RFuture<Void> future = entry.addSlave(uri);
future.onComplete((res, ex) -> {
if (ex != null) {
log.error("Can't add slave: " + uri, ex);
return;
}
currentPart.addSlaveAddress(uri);
entry.slaveUp(uri, FreezeReason.MANAGER);
log.info("slave: {} added for slot ranges: {}", uri, currentPart.getSlotRanges());
});
}
return addedSlaves;
}
private int slotsAmount(Collection<ClusterPartition> partitions) {
int result = 0;
for (ClusterPartition clusterPartition : partitions) {
result += clusterPartition.getSlotsAmount();
}
return result;
}
private ClusterPartition find(Collection<ClusterPartition> partitions, Integer slot) {
for (ClusterPartition clusterPartition : partitions) {
if (clusterPartition.hasSlot(slot)) {
return clusterPartition;
}
}
return null;
}
private RFuture<Void> checkMasterNodesChange(ClusterServersConfig cfg, Collection<ClusterPartition> newPartitions) {
Set<ClusterPartition> lastPartitions = getLastPartitions();
Map<RedisURI, ClusterPartition> addedPartitions = new HashMap<>();
Set<RedisURI> mastersElected = new HashSet<>();
for (ClusterPartition newPart : newPartitions) {
boolean masterFound = false;
for (ClusterPartition currentPart : lastPartitions) {
if (!newPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
continue;
}
masterFound = true;
// current master marked as failed
if (!newPart.isMasterFail() || newPart.getSlotsAmount() == 0) {
continue;
}
for (Integer slot : currentPart.getSlots()) {
ClusterPartition newMasterPart = find(newPartitions, slot);
// does partition has a new master?
if (!newMasterPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
RedisURI newUri = newMasterPart.getMasterAddress();
RedisURI oldUri = currentPart.getMasterAddress();
mastersElected.add(newUri);
RFuture<RedisClient> future = changeMaster(slot, newUri);
currentPart.setMasterAddress(newUri);
future.onComplete((res, e) -> {
if (e != null) {
currentPart.setMasterAddress(oldUri);
} else {
disconnectNode(oldUri);
}
});
}
}
break;
}
if (!masterFound && newPart.getSlotsAmount() > 0) {
addedPartitions.put(newPart.getMasterAddress(), newPart);
}
}
addedPartitions.keySet().removeAll(mastersElected);
if (addedPartitions.isEmpty()) {
return RedissonPromise.newSucceededFuture(null);
}
RPromise<Void> result = new RedissonPromise<>();
AtomicInteger masters = new AtomicInteger(addedPartitions.size());
for (ClusterPartition newPart : addedPartitions.values()) {
RFuture<Void> future = addMasterEntry(newPart, cfg);
future.onComplete((res, e) -> {
if (masters.decrementAndGet() == 0) {
result.trySuccess(null);
}
});
}
return result;
}
private void checkSlotsChange(Collection<ClusterPartition> newPartitions) {
int newSlotsAmount = slotsAmount(newPartitions);
if (newSlotsAmount == lastPartitions.size() && lastPartitions.size() == MAX_SLOT) {
return;
}
Set<Integer> removedSlots = new HashSet<>();
for (Integer slot : lastPartitions.keySet()) {
boolean found = false;
for (ClusterPartition clusterPartition : newPartitions) {
if (clusterPartition.hasSlot(slot)) {
found = true;
break;
}
}
if (!found) {
removedSlots.add(slot);
}
}
lastPartitions.keySet().removeAll(removedSlots);
if (!removedSlots.isEmpty()) {
log.info("{} slots found to remove", removedSlots.size());
}
for (Integer slot : removedSlots) {
removeEntry(slot);
}
Integer addedSlots = 0;
for (ClusterPartition clusterPartition : newPartitions) {
MasterSlaveEntry entry = getEntry(clusterPartition.getMasterAddress());
for (Integer slot : clusterPartition.getSlots()) {
if (lastPartitions.containsKey(slot)) {
continue;
}
if (entry != null) {
addEntry(slot, entry);
lastPartitions.put(slot, clusterPartition);
addedSlots++;
}
}
}
if (addedSlots > 0) {
log.info("{} slots found to add", addedSlots);
}
}
private void checkSlotsMigration(Collection<ClusterPartition> newPartitions) {
for (ClusterPartition currentPartition : getLastPartitions()) {
for (ClusterPartition newPartition : newPartitions) {
if (!currentPartition.getNodeId().equals(newPartition.getNodeId())) {
continue;
}
MasterSlaveEntry entry = getEntry(currentPartition.slots().nextSetBit(0));
BitSet addedSlots = newPartition.copySlots();
addedSlots.andNot(currentPartition.slots());
currentPartition.addSlots(addedSlots);
for (Integer slot : (Iterable<Integer>) addedSlots.stream()::iterator) {
addEntry(slot, entry);
lastPartitions.put(slot, currentPartition);
}
if (!addedSlots.isEmpty()) {
log.info("{} slots added to {}", addedSlots.cardinality(), currentPartition.getMasterAddress());
}
BitSet removedSlots = currentPartition.copySlots();
removedSlots.andNot(newPartition.slots());
currentPartition.removeSlots(removedSlots);
for (Integer removeSlot : (Iterable<Integer>) removedSlots.stream()::iterator) {
if (lastPartitions.remove(removeSlot, currentPartition)) {
removeEntry(removeSlot);
}
}
if (!removedSlots.isEmpty()) {
log.info("{} slots removed from {}", removedSlots.cardinality(), currentPartition.getMasterAddress());
}
break;
}
}
}
public String getConfigEndpointHostName() {
return configEndpointHostName;
}
private int indexOf(byte[] array, byte element) {
for (int i = 0; i < array.length; ++i) {
if (array[i] == element) {
return i;
}
}
return -1;
}
@Override
public int calcSlot(byte[] key) {
if (key == null) {
return 0;
}
int start = indexOf(key, (byte) '{');
if (start != -1) {
int end = indexOf(key, (byte) '}');
key = Arrays.copyOfRange(key, start+1, end);
}
int result = CRC16.crc16(key) % MAX_SLOT;
return result;
}
@Override
public int calcSlot(String key) {
if (key == null) {
return 0;
}
int start = key.indexOf('{');
if (start != -1) {
int end = key.indexOf('}');
key = key.substring(start+1, end);
}
int result = CRC16.crc16(key.getBytes()) % MAX_SLOT;
log.debug("slot {} for {}", result, key);
return result;
}
@Override
public RedisURI applyNatMap(RedisURI address) {
return natMapper.map(address);
}
private Collection<ClusterPartition> parsePartitions(List<ClusterNodeInfo> nodes) {
Map<String, ClusterPartition> partitions = new HashMap<String, ClusterPartition>();
for (ClusterNodeInfo clusterNodeInfo : nodes) {
if (clusterNodeInfo.containsFlag(Flag.NOADDR) || clusterNodeInfo.containsFlag(Flag.HANDSHAKE)) {
// skip it
continue;
}
String masterId = clusterNodeInfo.getNodeId();
if (clusterNodeInfo.containsFlag(Flag.SLAVE)) {
masterId = clusterNodeInfo.getSlaveOf();
}
if (masterId == null) {
// skip it
continue;
}
RedisURI address = applyNatMap(clusterNodeInfo.getAddress());
if (clusterNodeInfo.containsFlag(Flag.SLAVE)) {
ClusterPartition masterPartition = getPartition(partitions, masterId);
ClusterPartition slavePartition = getPartition(partitions, clusterNodeInfo.getNodeId());
slavePartition.setType(Type.SLAVE);
slavePartition.setParent(masterPartition);
masterPartition.addSlaveAddress(address);
if (clusterNodeInfo.containsFlag(Flag.FAIL)) {
masterPartition.addFailedSlaveAddress(address);
}
} else if (clusterNodeInfo.containsFlag(Flag.MASTER)) {
ClusterPartition masterPartition = getPartition(partitions, masterId);
masterPartition.addSlotRanges(clusterNodeInfo.getSlotRanges());
masterPartition.setMasterAddress(address);
masterPartition.setType(Type.MASTER);
if (clusterNodeInfo.containsFlag(Flag.FAIL)) {
masterPartition.setMasterFail(true);
}
}
}
addCascadeSlaves(partitions);
return partitions.values();
}
private void addCascadeSlaves(Map<String, ClusterPartition> partitions) {
Iterator<ClusterPartition> iter = partitions.values().iterator();
while (iter.hasNext()) {
ClusterPartition cp = iter.next();
if (cp.getType() != Type.SLAVE) {
continue;
}
if (cp.getParent() != null && cp.getParent().getType() == Type.MASTER) {
ClusterPartition parent = cp.getParent();
for (RedisURI addr : cp.getSlaveAddresses()) {
parent.addSlaveAddress(addr);
}
for (RedisURI addr : cp.getFailedSlaveAddresses()) {
parent.addFailedSlaveAddress(addr);
}
}
iter.remove();
}
}
private ClusterPartition getPartition(Map<String, ClusterPartition> partitions, String id) {
ClusterPartition partition = partitions.get(id);
if (partition == null) {
partition = new ClusterPartition(id);
partitions.put(id, partition);
}
return partition;
}
@Override
public void shutdown() {
if (monitorFuture != null) {
monitorFuture.cancel(true);
}
closeNodeConnections();
super.shutdown();
}
private Set<ClusterPartition> getLastPartitions() {
return new HashSet<>(lastPartitions.values());
}
@Override
public RedisURI getLastClusterNode() {
return lastClusterNode;
}
@Override
public boolean isClusterMode() {
return true;
}
}
| redisson/src/main/java/org/redisson/cluster/ClusterConnectionManager.java | /**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.cluster;
import io.netty.resolver.AddressResolver;
import io.netty.util.NetUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.ScheduledFuture;
import org.redisson.api.NatMapper;
import org.redisson.api.NodeType;
import org.redisson.api.RFuture;
import org.redisson.client.*;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.RedisStrictCommand;
import org.redisson.cluster.ClusterNodeInfo.Flag;
import org.redisson.cluster.ClusterPartition.Type;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.MasterSlaveServersConfig;
import org.redisson.config.ReadMode;
import org.redisson.connection.CRC16;
import org.redisson.connection.ClientConnectionsEntry.FreezeReason;
import org.redisson.connection.MasterSlaveConnectionManager;
import org.redisson.connection.MasterSlaveEntry;
import org.redisson.connection.SingleEntry;
import org.redisson.misc.RPromise;
import org.redisson.misc.RedisURI;
import org.redisson.misc.RedissonPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.stream.Collectors;
/**
*
* @author Nikita Koksharov
*
*/
public class ClusterConnectionManager extends MasterSlaveConnectionManager {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ConcurrentMap<Integer, ClusterPartition> lastPartitions = new ConcurrentHashMap<>();
private ScheduledFuture<?> monitorFuture;
private volatile RedisURI lastClusterNode;
private RedisStrictCommand<List<ClusterNodeInfo>> clusterNodesCommand;
private String configEndpointHostName;
private final NatMapper natMapper;
private final AtomicReferenceArray<MasterSlaveEntry> slot2entry = new AtomicReferenceArray<>(MAX_SLOT);
private final Map<RedisClient, MasterSlaveEntry> client2entry = new ConcurrentHashMap<>();
public ClusterConnectionManager(ClusterServersConfig cfg, Config config, UUID id) {
super(config, id);
if (cfg.getNodeAddresses().isEmpty()) {
throw new IllegalArgumentException("At least one cluster node should be defined!");
}
this.natMapper = cfg.getNatMapper();
this.config = create(cfg);
initTimer(this.config);
Throwable lastException = null;
List<String> failedMasters = new ArrayList<String>();
for (String address : cfg.getNodeAddresses()) {
RedisURI addr = new RedisURI(address);
RFuture<RedisConnection> connectionFuture = connectToNode(cfg, addr, null, addr.getHost());
try {
RedisConnection connection = connectionFuture.syncUninterruptibly().getNow();
if (cfg.getNodeAddresses().size() == 1 && NetUtil.createByteArrayFromIpAddressString(addr.getHost()) == null) {
configEndpointHostName = addr.getHost();
}
clusterNodesCommand = RedisCommands.CLUSTER_NODES;
if (addr.isSsl()) {
clusterNodesCommand = RedisCommands.CLUSTER_NODES_SSL;
}
List<ClusterNodeInfo> nodes = connection.sync(clusterNodesCommand);
StringBuilder nodesValue = new StringBuilder();
for (ClusterNodeInfo clusterNodeInfo : nodes) {
nodesValue.append(clusterNodeInfo.getNodeInfo()).append("\n");
}
log.info("Redis cluster nodes configuration got from {}:\n{}", connection.getRedisClient().getAddr(), nodesValue);
lastClusterNode = addr;
Collection<ClusterPartition> partitions = parsePartitions(nodes);
List<RFuture<Void>> masterFutures = new ArrayList<>();
for (ClusterPartition partition : partitions) {
if (partition.isMasterFail()) {
failedMasters.add(partition.getMasterAddress().toString());
continue;
}
if (partition.getMasterAddress() == null) {
throw new IllegalStateException("Master node: " + partition.getNodeId() + " doesn't have address.");
}
RFuture<Void> masterFuture = addMasterEntry(partition, cfg);
masterFutures.add(masterFuture);
}
for (RFuture<Void> masterFuture : masterFutures) {
masterFuture.awaitUninterruptibly();
if (!masterFuture.isSuccess()) {
lastException = masterFuture.cause();
}
}
break;
} catch (Exception e) {
lastException = e;
log.warn(e.getMessage());
}
}
if (lastPartitions.isEmpty()) {
stopThreads();
if (failedMasters.isEmpty()) {
throw new RedisConnectionException("Can't connect to servers!", lastException);
} else {
throw new RedisConnectionException("Can't connect to servers! Failed masters according to cluster status: " + failedMasters, lastException);
}
}
if (cfg.isCheckSlotsCoverage() && lastPartitions.size() != MAX_SLOT) {
stopThreads();
if (failedMasters.isEmpty()) {
throw new RedisConnectionException("Not all slots covered! Only " + lastPartitions.size() + " slots are available. Set checkSlotsCoverage = false to avoid this check.", lastException);
} else {
throw new RedisConnectionException("Not all slots covered! Only " + lastPartitions.size() + " slots are available. Set checkSlotsCoverage = false to avoid this check. Failed masters according to cluster status: " + failedMasters, lastException);
}
}
scheduleClusterChangeCheck(cfg, null);
}
@Override
public Collection<MasterSlaveEntry> getEntrySet() {
return client2entry.values();
}
protected MasterSlaveEntry getEntry(RedisURI addr) {
for (MasterSlaveEntry entry : client2entry.values()) {
if (RedisURI.compare(entry.getClient().getAddr(), addr)) {
return entry;
}
if (entry.hasSlave(addr)) {
return entry;
}
}
return null;
}
@Override
public MasterSlaveEntry getEntry(RedisClient redisClient) {
MasterSlaveEntry entry = client2entry.get(redisClient);
if (entry != null) {
return entry;
}
for (MasterSlaveEntry mentry : client2entry.values()) {
if (mentry.hasSlave(redisClient)) {
return mentry;
}
}
return null;
}
@Override
public MasterSlaveEntry getEntry(InetSocketAddress address) {
for (MasterSlaveEntry entry : client2entry.values()) {
InetSocketAddress addr = entry.getClient().getAddr();
if (addr.getAddress().equals(address.getAddress()) && addr.getPort() == address.getPort()) {
return entry;
}
}
return null;
}
@Override
protected RFuture<RedisClient> changeMaster(int slot, RedisURI address) {
MasterSlaveEntry entry = getEntry(slot);
RedisClient oldClient = entry.getClient();
RFuture<RedisClient> future = super.changeMaster(slot, address);
future.onComplete((res, e) -> {
if (e == null) {
client2entry.remove(oldClient);
client2entry.put(entry.getClient(), entry);
}
});
return future;
}
@Override
public MasterSlaveEntry getEntry(int slot) {
return slot2entry.get(slot);
}
private void addEntry(Integer slot, MasterSlaveEntry entry) {
MasterSlaveEntry oldEntry = slot2entry.getAndSet(slot, entry);
if (oldEntry != entry) {
entry.incReference();
shutdownEntry(oldEntry);
}
client2entry.put(entry.getClient(), entry);
}
private void removeEntry(Integer slot) {
MasterSlaveEntry entry = slot2entry.getAndSet(slot, null);
shutdownEntry(entry);
}
private void shutdownEntry(MasterSlaveEntry entry) {
if (entry != null && entry.decReference() == 0) {
client2entry.remove(entry.getClient());
entry.getAllEntries().forEach(e -> entry.nodeDown(e));
entry.masterDown();
entry.shutdownAsync();
subscribeService.remove(entry);
String slaves = entry.getAllEntries().stream()
.filter(e -> !e.getClient().getAddr().equals(entry.getClient().getAddr()))
.map(e -> e.getClient().toString())
.collect(Collectors.joining(","));
log.info("{} master and related slaves: {} removed", entry.getClient().getAddr(), slaves);
}
}
@Override
protected RedisClientConfig createRedisConfig(NodeType type, RedisURI address, int timeout, int commandTimeout, String sslHostname) {
RedisClientConfig result = super.createRedisConfig(type, address, timeout, commandTimeout, sslHostname);
result.setReadOnly(type == NodeType.SLAVE && config.getReadMode() != ReadMode.MASTER);
return result;
}
private RFuture<Void> addMasterEntry(ClusterPartition partition, ClusterServersConfig cfg) {
if (partition.isMasterFail()) {
RedisException e = new RedisException("Failed to add master: " +
partition.getMasterAddress() + " for slot ranges: " +
partition.getSlotRanges() + ". Reason - server has FAIL flag");
if (partition.getSlotsAmount() == 0) {
e = new RedisException("Failed to add master: " +
partition.getMasterAddress() + ". Reason - server has FAIL flag");
}
return RedissonPromise.newFailedFuture(e);
}
RPromise<Void> result = new RedissonPromise<>();
RFuture<RedisConnection> connectionFuture = connectToNode(cfg, partition.getMasterAddress(), null, configEndpointHostName);
connectionFuture.onComplete((connection, ex1) -> {
if (ex1 != null) {
log.error("Can't connect to master: {} with slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
result.tryFailure(ex1);
return;
}
MasterSlaveServersConfig config = create(cfg);
config.setMasterAddress(partition.getMasterAddress().toString());
MasterSlaveEntry entry;
if (config.checkSkipSlavesInit()) {
entry = new SingleEntry(ClusterConnectionManager.this, config);
} else {
Set<String> slaveAddresses = partition.getSlaveAddresses().stream().map(r -> r.toString()).collect(Collectors.toSet());
config.setSlaveAddresses(slaveAddresses);
entry = new MasterSlaveEntry(ClusterConnectionManager.this, config);
}
RFuture<RedisClient> f = entry.setupMasterEntry(new RedisURI(config.getMasterAddress()));
f.onComplete((masterClient, ex3) -> {
if (ex3 != null) {
log.error("Can't add master: " + partition.getMasterAddress() + " for slot ranges: " + partition.getSlotRanges(), ex3);
result.tryFailure(ex3);
return;
}
for (Integer slot : partition.getSlots()) {
addEntry(slot, entry);
lastPartitions.put(slot, partition);
}
if (!config.checkSkipSlavesInit()) {
List<RFuture<Void>> fs = entry.initSlaveBalancer(partition.getFailedSlaveAddresses(), masterClient);
AtomicInteger counter = new AtomicInteger(fs.size());
for (RFuture<Void> future : fs) {
future.onComplete((r, ex) -> {
if (ex != null) {
log.error("unable to add slave for: " + partition.getMasterAddress()
+ " slot ranges: " + partition.getSlotRanges(), ex);
}
if (counter.decrementAndGet() == 0) {
if (!partition.getSlaveAddresses().isEmpty()) {
log.info("slaves: {} added for slot ranges: {}", partition.getSlaveAddresses(), partition.getSlotRanges());
if (!partition.getFailedSlaveAddresses().isEmpty()) {
log.warn("slaves: {} are down for slot ranges: {}", partition.getFailedSlaveAddresses(), partition.getSlotRanges());
}
}
if (result.trySuccess(null)) {
log.info("master: {} added for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
} else {
log.error("unable to add master: {} for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
}
}
});
}
} else {
if (result.trySuccess(null)) {
log.info("master: {} added for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
} else {
log.error("unable to add master: {} for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
}
}
});
});
return result;
}
private void scheduleClusterChangeCheck(ClusterServersConfig cfg, Iterator<RedisURI> iterator) {
monitorFuture = group.schedule(new Runnable() {
@Override
public void run() {
if (configEndpointHostName != null) {
String address = cfg.getNodeAddresses().iterator().next();
RedisURI uri = new RedisURI(address);
AddressResolver<InetSocketAddress> resolver = resolverGroup.getResolver(getGroup().next());
Future<List<InetSocketAddress>> allNodes = resolver.resolveAll(InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort()));
allNodes.addListener(new FutureListener<List<InetSocketAddress>>() {
@Override
public void operationComplete(Future<List<InetSocketAddress>> future) throws Exception {
AtomicReference<Throwable> lastException = new AtomicReference<Throwable>(future.cause());
if (!future.isSuccess()) {
checkClusterState(cfg, Collections.<RedisURI>emptyList().iterator(), lastException);
return;
}
List<RedisURI> nodes = new ArrayList<>();
for (InetSocketAddress addr : future.getNow()) {
RedisURI node = new RedisURI(uri.getScheme() + "://" + addr.getAddress().getHostAddress() + ":" + addr.getPort());
RedisURI address = applyNatMap(node);
nodes.add(address);
}
Iterator<RedisURI> nodesIterator = nodes.iterator();
checkClusterState(cfg, nodesIterator, lastException);
}
});
} else {
AtomicReference<Throwable> lastException = new AtomicReference<Throwable>();
Iterator<RedisURI> nodesIterator = iterator;
if (nodesIterator == null) {
List<RedisURI> nodes = new ArrayList<>();
List<RedisURI> slaves = new ArrayList<>();
for (ClusterPartition partition : getLastPartitions()) {
if (!partition.isMasterFail()) {
nodes.add(partition.getMasterAddress());
}
Set<RedisURI> partitionSlaves = new HashSet<>(partition.getSlaveAddresses());
partitionSlaves.removeAll(partition.getFailedSlaveAddresses());
slaves.addAll(partitionSlaves);
}
// master nodes first
nodes.addAll(slaves);
nodesIterator = nodes.iterator();
}
checkClusterState(cfg, nodesIterator, lastException);
}
}
}, cfg.getScanInterval(), TimeUnit.MILLISECONDS);
}
private void checkClusterState(ClusterServersConfig cfg, Iterator<RedisURI> iterator, AtomicReference<Throwable> lastException) {
if (!iterator.hasNext()) {
if (lastException.get() != null) {
log.error("Can't update cluster state", lastException.get());
}
scheduleClusterChangeCheck(cfg, null);
return;
}
if (!getShutdownLatch().acquire()) {
return;
}
RedisURI uri = iterator.next();
RFuture<RedisConnection> connectionFuture = connectToNode(cfg, uri, null, configEndpointHostName);
connectionFuture.onComplete((connection, e) -> {
if (e != null) {
lastException.set(e);
getShutdownLatch().release();
checkClusterState(cfg, iterator, lastException);
return;
}
updateClusterState(cfg, connection, iterator, uri, lastException);
});
}
private void updateClusterState(ClusterServersConfig cfg, RedisConnection connection,
Iterator<RedisURI> iterator, RedisURI uri, AtomicReference<Throwable> lastException) {
RFuture<List<ClusterNodeInfo>> future = connection.async(clusterNodesCommand);
future.onComplete((nodes, e) -> {
if (e != null) {
log.error("Can't execute CLUSTER_NODES with " + connection.getRedisClient().getAddr(), e);
closeNodeConnection(connection);
lastException.set(e);
getShutdownLatch().release();
checkClusterState(cfg, iterator, lastException);
return;
}
lastClusterNode = uri;
StringBuilder nodesValue = new StringBuilder();
if (log.isDebugEnabled()) {
for (ClusterNodeInfo clusterNodeInfo : nodes) {
nodesValue.append(clusterNodeInfo.getNodeInfo()).append("\n");
}
log.debug("cluster nodes state got from {}:\n{}", connection.getRedisClient().getAddr(), nodesValue);
}
Collection<ClusterPartition> newPartitions = parsePartitions(nodes);
RFuture<Void> masterFuture = checkMasterNodesChange(cfg, newPartitions);
checkSlaveNodesChange(newPartitions);
masterFuture.onComplete((res, ex) -> {
checkSlotsMigration(newPartitions);
checkSlotsChange(cfg, newPartitions);
getShutdownLatch().release();
scheduleClusterChangeCheck(cfg, null);
});
});
}
private void checkSlaveNodesChange(Collection<ClusterPartition> newPartitions) {
Set<ClusterPartition> lastPartitions = getLastPartitions();
for (ClusterPartition newPart : newPartitions) {
for (ClusterPartition currentPart : lastPartitions) {
if (!newPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
continue;
}
MasterSlaveEntry entry = getEntry(currentPart.slots().nextSetBit(0));
// should be invoked first in order to remove stale failedSlaveAddresses
Set<RedisURI> addedSlaves = addRemoveSlaves(entry, currentPart, newPart);
// Do some slaves have changed state from failed to alive?
upDownSlaves(entry, currentPart, newPart, addedSlaves);
break;
}
}
}
private void upDownSlaves(MasterSlaveEntry entry, ClusterPartition currentPart, ClusterPartition newPart, Set<RedisURI> addedSlaves) {
Set<RedisURI> aliveSlaves = new HashSet<>(currentPart.getFailedSlaveAddresses());
aliveSlaves.removeAll(addedSlaves);
aliveSlaves.removeAll(newPart.getFailedSlaveAddresses());
for (RedisURI uri : aliveSlaves) {
currentPart.removeFailedSlaveAddress(uri);
if (entry.hasSlave(uri) && entry.slaveUp(uri, FreezeReason.MANAGER)) {
log.info("slave: {} is up for slot ranges: {}", uri, currentPart.getSlotRanges());
}
}
Set<RedisURI> failedSlaves = new HashSet<>(newPart.getFailedSlaveAddresses());
failedSlaves.removeAll(currentPart.getFailedSlaveAddresses());
for (RedisURI uri : failedSlaves) {
currentPart.addFailedSlaveAddress(uri);
if (entry.slaveDown(uri, FreezeReason.MANAGER)) {
disconnectNode(uri);
log.warn("slave: {} has down for slot ranges: {}", uri, currentPart.getSlotRanges());
}
}
}
private Set<RedisURI> addRemoveSlaves(MasterSlaveEntry entry, ClusterPartition currentPart, ClusterPartition newPart) {
Set<RedisURI> removedSlaves = new HashSet<>(currentPart.getSlaveAddresses());
removedSlaves.removeAll(newPart.getSlaveAddresses());
for (RedisURI uri : removedSlaves) {
currentPart.removeSlaveAddress(uri);
if (entry.slaveDown(uri, FreezeReason.MANAGER)) {
log.info("slave {} removed for slot ranges: {}", uri, currentPart.getSlotRanges());
}
}
Set<RedisURI> addedSlaves = new HashSet<>(newPart.getSlaveAddresses());
addedSlaves.removeAll(currentPart.getSlaveAddresses());
for (RedisURI uri : addedSlaves) {
RFuture<Void> future = entry.addSlave(uri);
future.onComplete((res, ex) -> {
if (ex != null) {
log.error("Can't add slave: " + uri, ex);
return;
}
currentPart.addSlaveAddress(uri);
entry.slaveUp(uri, FreezeReason.MANAGER);
log.info("slave: {} added for slot ranges: {}", uri, currentPart.getSlotRanges());
});
}
return addedSlaves;
}
private int slotsAmount(Collection<ClusterPartition> partitions) {
int result = 0;
for (ClusterPartition clusterPartition : partitions) {
result += clusterPartition.getSlotsAmount();
}
return result;
}
private ClusterPartition find(Collection<ClusterPartition> partitions, Integer slot) {
for (ClusterPartition clusterPartition : partitions) {
if (clusterPartition.hasSlot(slot)) {
return clusterPartition;
}
}
return null;
}
private RFuture<Void> checkMasterNodesChange(ClusterServersConfig cfg, Collection<ClusterPartition> newPartitions) {
Set<ClusterPartition> lastPartitions = getLastPartitions();
Map<RedisURI, ClusterPartition> addedPartitions = new HashMap<>();
Set<RedisURI> mastersElected = new HashSet<>();
for (ClusterPartition newPart : newPartitions) {
boolean masterFound = false;
for (ClusterPartition currentPart : lastPartitions) {
if (!newPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
continue;
}
masterFound = true;
// current master marked as failed
if (!newPart.isMasterFail() || newPart.getSlotsAmount() == 0) {
continue;
}
for (Integer slot : currentPart.getSlots()) {
ClusterPartition newMasterPart = find(newPartitions, slot);
// does partition has a new master?
if (!newMasterPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
RedisURI newUri = newMasterPart.getMasterAddress();
RedisURI oldUri = currentPart.getMasterAddress();
mastersElected.add(newUri);
RFuture<RedisClient> future = changeMaster(slot, newUri);
currentPart.setMasterAddress(newUri);
future.onComplete((res, e) -> {
if (e != null) {
currentPart.setMasterAddress(oldUri);
} else {
disconnectNode(oldUri);
}
});
}
}
break;
}
if (!masterFound && newPart.getSlotsAmount() > 0) {
addedPartitions.put(newPart.getMasterAddress(), newPart);
}
}
addedPartitions.keySet().removeAll(mastersElected);
if (addedPartitions.isEmpty()) {
return RedissonPromise.newSucceededFuture(null);
}
RPromise<Void> result = new RedissonPromise<>();
AtomicInteger masters = new AtomicInteger(addedPartitions.size());
for (ClusterPartition newPart : addedPartitions.values()) {
RFuture<Void> future = addMasterEntry(newPart, cfg);
future.onComplete((res, e) -> {
if (masters.decrementAndGet() == 0) {
result.trySuccess(null);
}
});
}
return result;
}
private void checkSlotsChange(ClusterServersConfig cfg, Collection<ClusterPartition> newPartitions) {
int newSlotsAmount = slotsAmount(newPartitions);
if (newSlotsAmount == lastPartitions.size() && lastPartitions.size() == MAX_SLOT) {
return;
}
Set<Integer> removedSlots = new HashSet<>();
for (Integer slot : lastPartitions.keySet()) {
boolean found = false;
for (ClusterPartition clusterPartition : newPartitions) {
if (clusterPartition.hasSlot(slot)) {
found = true;
break;
}
}
if (!found) {
removedSlots.add(slot);
}
}
lastPartitions.keySet().removeAll(removedSlots);
if (!removedSlots.isEmpty()) {
log.info("{} slots found to remove", removedSlots.size());
}
for (Integer slot : removedSlots) {
removeEntry(slot);
}
Integer addedSlots = 0;
for (ClusterPartition clusterPartition : newPartitions) {
MasterSlaveEntry entry = getEntry(clusterPartition.getMasterAddress());
for (Integer slot : clusterPartition.getSlots()) {
if (lastPartitions.containsKey(slot)) {
continue;
}
if (entry != null) {
addEntry(slot, entry);
lastPartitions.put(slot, clusterPartition);
addedSlots++;
}
}
}
if (addedSlots > 0) {
log.info("{} slots found to add", addedSlots);
}
}
private void checkSlotsMigration(Collection<ClusterPartition> newPartitions) {
for (ClusterPartition currentPartition : getLastPartitions()) {
for (ClusterPartition newPartition : newPartitions) {
if (!currentPartition.getNodeId().equals(newPartition.getNodeId())) {
continue;
}
MasterSlaveEntry entry = getEntry(currentPartition.slots().nextSetBit(0));
BitSet addedSlots = newPartition.copySlots();
addedSlots.andNot(currentPartition.slots());
currentPartition.addSlots(addedSlots);
for (Integer slot : (Iterable<Integer>) addedSlots.stream()::iterator) {
addEntry(slot, entry);
lastPartitions.put(slot, currentPartition);
}
if (!addedSlots.isEmpty()) {
log.info("{} slots added to {}", addedSlots.cardinality(), currentPartition.getMasterAddress());
}
BitSet removedSlots = currentPartition.copySlots();
removedSlots.andNot(newPartition.slots());
currentPartition.removeSlots(removedSlots);
for (Integer removeSlot : (Iterable<Integer>) removedSlots.stream()::iterator) {
if (lastPartitions.remove(removeSlot, currentPartition)) {
removeEntry(removeSlot);
}
}
if (!removedSlots.isEmpty()) {
log.info("{} slots removed from {}", removedSlots.cardinality(), currentPartition.getMasterAddress());
}
break;
}
}
}
public String getConfigEndpointHostName() {
return configEndpointHostName;
}
private int indexOf(byte[] array, byte element) {
for (int i = 0; i < array.length; ++i) {
if (array[i] == element) {
return i;
}
}
return -1;
}
@Override
public int calcSlot(byte[] key) {
if (key == null) {
return 0;
}
int start = indexOf(key, (byte) '{');
if (start != -1) {
int end = indexOf(key, (byte) '}');
key = Arrays.copyOfRange(key, start+1, end);
}
int result = CRC16.crc16(key) % MAX_SLOT;
return result;
}
@Override
public int calcSlot(String key) {
if (key == null) {
return 0;
}
int start = key.indexOf('{');
if (start != -1) {
int end = key.indexOf('}');
key = key.substring(start+1, end);
}
int result = CRC16.crc16(key.getBytes()) % MAX_SLOT;
log.debug("slot {} for {}", result, key);
return result;
}
@Override
public RedisURI applyNatMap(RedisURI address) {
return natMapper.map(address);
}
private Collection<ClusterPartition> parsePartitions(List<ClusterNodeInfo> nodes) {
Map<String, ClusterPartition> partitions = new HashMap<String, ClusterPartition>();
for (ClusterNodeInfo clusterNodeInfo : nodes) {
if (clusterNodeInfo.containsFlag(Flag.NOADDR) || clusterNodeInfo.containsFlag(Flag.HANDSHAKE)) {
// skip it
continue;
}
String masterId = clusterNodeInfo.getNodeId();
if (clusterNodeInfo.containsFlag(Flag.SLAVE)) {
masterId = clusterNodeInfo.getSlaveOf();
}
if (masterId == null) {
// skip it
continue;
}
RedisURI address = applyNatMap(clusterNodeInfo.getAddress());
if (clusterNodeInfo.containsFlag(Flag.SLAVE)) {
ClusterPartition masterPartition = getPartition(partitions, masterId);
ClusterPartition slavePartition = getPartition(partitions, clusterNodeInfo.getNodeId());
slavePartition.setType(Type.SLAVE);
slavePartition.setParent(masterPartition);
masterPartition.addSlaveAddress(address);
if (clusterNodeInfo.containsFlag(Flag.FAIL)) {
masterPartition.addFailedSlaveAddress(address);
}
} else if (clusterNodeInfo.containsFlag(Flag.MASTER)) {
ClusterPartition masterPartition = getPartition(partitions, masterId);
masterPartition.addSlotRanges(clusterNodeInfo.getSlotRanges());
masterPartition.setMasterAddress(address);
masterPartition.setType(Type.MASTER);
if (clusterNodeInfo.containsFlag(Flag.FAIL)) {
masterPartition.setMasterFail(true);
}
}
}
addCascadeSlaves(partitions);
return partitions.values();
}
private void addCascadeSlaves(Map<String, ClusterPartition> partitions) {
Iterator<ClusterPartition> iter = partitions.values().iterator();
while (iter.hasNext()) {
ClusterPartition cp = iter.next();
if (cp.getType() != Type.SLAVE) {
continue;
}
if (cp.getParent() != null && cp.getParent().getType() == Type.MASTER) {
ClusterPartition parent = cp.getParent();
for (RedisURI addr : cp.getSlaveAddresses()) {
parent.addSlaveAddress(addr);
}
for (RedisURI addr : cp.getFailedSlaveAddresses()) {
parent.addFailedSlaveAddress(addr);
}
}
iter.remove();
}
}
private ClusterPartition getPartition(Map<String, ClusterPartition> partitions, String id) {
ClusterPartition partition = partitions.get(id);
if (partition == null) {
partition = new ClusterPartition(id);
partitions.put(id, partition);
}
return partition;
}
@Override
public void shutdown() {
if (monitorFuture != null) {
monitorFuture.cancel(true);
}
closeNodeConnections();
super.shutdown();
}
private Set<ClusterPartition> getLastPartitions() {
return new HashSet<>(lastPartitions.values());
}
@Override
public RedisURI getLastClusterNode() {
return lastClusterNode;
}
@Override
public boolean isClusterMode() {
return true;
}
}
| refactoring
| redisson/src/main/java/org/redisson/cluster/ClusterConnectionManager.java | refactoring |
|
Java | apache-2.0 | 5b712e854fcd14d6254c9b42eaefcd80097cf890 | 0 | serge-rider/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2020 DBeaver Corp and others
*
* 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.jkiss.dbeaver.model.impl.jdbc;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPDataSourceTask;
import org.jkiss.dbeaver.model.DBPDataTypeProvider;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSObjectFilter;
import org.jkiss.dbeaver.model.struct.rdb.DBSForeignKeyModifyRule;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* JDBCUtils
*/
public class JDBCUtils {
private static final Log log = Log.getLog(JDBCUtils.class);
private static final Map<String, Integer> badColumnNames = new HashMap<>();
@Nullable
public static String safeGetString(ResultSet dbResult, String columnName)
{
try {
return dbResult.getString(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static String safeGetStringTrimmed(ResultSet dbResult, String columnName)
{
try {
final String value = dbResult.getString(columnName);
if (value != null && !value.isEmpty()) {
return value.trim();
} else {
return value;
}
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static String safeGetString(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getString(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static String safeGetStringTrimmed(ResultSet dbResult, int columnIndex)
{
try {
final String value = dbResult.getString(columnIndex);
if (value != null && !value.isEmpty()) {
return value.trim();
} else {
return value;
}
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
public static int safeGetInt(ResultSet dbResult, String columnName)
{
try {
return dbResult.getInt(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return 0;
}
}
public static int safeGetInt(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getInt(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return 0;
}
}
@Nullable
public static Integer safeGetInteger(ResultSet dbResult, String columnName)
{
try {
final int result = dbResult.getInt(columnName);
if (dbResult.wasNull()) {
return null;
} else {
return result;
}
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Integer safeGetInteger(ResultSet dbResult, int columnIndex)
{
try {
final int result = dbResult.getInt(columnIndex);
if (dbResult.wasNull()) {
return null;
} else {
return result;
}
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
public static long safeGetLong(ResultSet dbResult, String columnName)
{
try {
return dbResult.getLong(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return 0;
}
}
public static long safeGetLong(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getLong(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return 0;
}
}
@Nullable
public static Long safeGetLongNullable(ResultSet dbResult, String columnName)
{
try {
final long result = dbResult.getLong(columnName);
return dbResult.wasNull() ? null : result;
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
public static double safeGetDouble(ResultSet dbResult, String columnName)
{
try {
return dbResult.getDouble(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return 0.0;
}
}
public static double safeGetDouble(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getDouble(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return 0.0;
}
}
public static float safeGetFloat(ResultSet dbResult, String columnName)
{
try {
return dbResult.getFloat(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return 0;
}
}
public static float safeGetFloat(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getFloat(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return 0;
}
}
@Nullable
public static BigDecimal safeGetBigDecimal(ResultSet dbResult, String columnName)
{
try {
return dbResult.getBigDecimal(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static BigDecimal safeGetBigDecimal(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getBigDecimal(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
public static boolean safeGetBoolean(ResultSet dbResult, String columnName)
{
return safeGetBoolean(dbResult, columnName, false);
}
public static boolean safeGetBoolean(ResultSet dbResult, String columnName, boolean defValue)
{
try {
return dbResult.getBoolean(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return defValue;
}
}
public static boolean safeGetBoolean(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getBoolean(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return false;
}
}
public static boolean safeGetBoolean(ResultSet dbResult, String columnName, String trueValue)
{
try {
final String strValue = dbResult.getString(columnName);
return strValue != null && strValue.startsWith(trueValue);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return false;
}
}
@Nullable
public static byte[] safeGetBytes(ResultSet dbResult, String columnName)
{
try {
return dbResult.getBytes(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Timestamp safeGetTimestamp(ResultSet dbResult, String columnName)
{
try {
return dbResult.getTimestamp(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Timestamp safeGetTimestamp(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getTimestamp(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static Date safeGetDate(ResultSet dbResult, String columnName)
{
try {
return dbResult.getDate(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Date safeGetDate(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getDate(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static Time safeGetTime(ResultSet dbResult, String columnName)
{
try {
return dbResult.getTime(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Time safeGetTime(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getTime(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static SQLXML safeGetXML(ResultSet dbResult, String columnName)
{
try {
return dbResult.getSQLXML(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static SQLXML safeGetXML(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getSQLXML(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static Object safeGetObject(ResultSet dbResult, String columnName)
{
try {
return dbResult.getObject(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Object safeGetObject(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getObject(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static <T> T safeGetArray(ResultSet dbResult, String columnName)
{
try {
Array array = dbResult.getArray(columnName);
return array == null ? null : (T) array.getArray();
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Object safeGetArray(ResultSet dbResult, int columnIndex)
{
try {
Array array = dbResult.getArray(columnIndex);
return array == null ? null : array.getArray();
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static String normalizeIdentifier(@Nullable String value)
{
return value == null ? null : value.trim();
}
public static void dumpResultSet(ResultSet dbResult)
{
try {
ResultSetMetaData md = dbResult.getMetaData();
int count = md.getColumnCount();
dumpResultSetMetaData(dbResult);
while (dbResult.next()) {
for (int i = 1; i <= count; i++) {
String colValue = dbResult.getString(i);
System.out.print(colValue + "\t");
}
System.out.println();
}
System.out.println();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void dumpResultSetMetaData(ResultSet dbResult)
{
try {
ResultSetMetaData md = dbResult.getMetaData();
int count = md.getColumnCount();
for (int i = 1; i <= count; i++) {
System.out.print(md.getColumnName(i) + " [" + md.getColumnTypeName(i) + "]\t");
}
System.out.println();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static boolean isConnectionAlive(DBPDataSource dataSource, Connection connection)
{
try {
if (connection == null || connection.isClosed()) {
return false;
}
} catch (SQLException e) {
log.debug(e);
return false;
}
// Check for active tasks. Do not run ping if there is active task
for (DBPDataSourceTask task : dataSource.getContainer().getTasks()) {
if (task.isActiveTask()) {
return true;
}
}
// Run ping query
final String testSQL = dataSource.getSQLDialect().getTestSQL();
int invalidateTimeout = dataSource.getContainer().getPreferenceStore().getInt(ModelPreferences.CONNECTION_VALIDATION_TIMEOUT);
// Invalidate in non-blocking task.
// Timeout is CONNECTION_VALIDATION_TIMEOUT + 2 seconds
final boolean[] isValid = new boolean[1];
RuntimeUtils.runTask(monitor -> {
try {
if (!CommonUtils.isEmpty(testSQL)) {
// Execute test SQL
try (Statement dbStat = connection.createStatement()) {
dbStat.execute(testSQL);
isValid[0] = true;
}
} else {
try {
isValid[0] = connection.isValid(invalidateTimeout);
} catch (Throwable e) {
// isValid may be unsupported by driver
// Let's try to read table list
connection.getMetaData().getTables(null, null, "DBEAVERFAKETABLENAMEFORPING", null);
isValid[0] = true;
}
}
} catch (SQLException e) {
isValid[0] = false;
}
}, "Ping connection " + dataSource.getContainer().getName(), invalidateTimeout + 2000, true);
return isValid[0];
}
public static void scrollResultSet(ResultSet dbResult, long offset, boolean forceFetch) throws SQLException
{
// Scroll to first row
boolean scrolled = false;
if (!forceFetch) {
try {
scrolled = dbResult.absolute((int) offset);
} catch (SQLException | UnsupportedOperationException | IncompatibleClassChangeError e) {
// Seems to be not supported
log.debug(e.getMessage());
}
}
if (!scrolled) {
// Just fetch first 'firstRow' rows
for (long i = 1; i <= offset; i++) {
try {
dbResult.next();
} catch (SQLException e) {
throw new SQLException("Can't scroll result set to row " + offset, e);
}
}
}
}
public static void reportWarnings(JDBCSession session, SQLWarning rootWarning)
{
for (SQLWarning warning = rootWarning; warning != null; warning = warning.getNextWarning()) {
if (warning.getMessage() == null && warning.getErrorCode() == 0) {
// Skip trash [Excel driver]
continue;
}
log.warn("SQL Warning (DataSource: " + session.getDataSource().getContainer().getName() + "; Code: "
+ warning.getErrorCode() + "; State: " + warning.getSQLState() + "): " + warning.getLocalizedMessage());
}
}
@NotNull
public static String limitQueryLength(@NotNull String query, int maxLength)
{
return query.length() <= maxLength ? query : query.substring(0, maxLength);
}
public static DBSForeignKeyModifyRule getCascadeFromNum(int num)
{
switch (num) {
case DatabaseMetaData.importedKeyNoAction:
return DBSForeignKeyModifyRule.NO_ACTION;
case DatabaseMetaData.importedKeyCascade:
return DBSForeignKeyModifyRule.CASCADE;
case DatabaseMetaData.importedKeySetNull:
return DBSForeignKeyModifyRule.SET_NULL;
case DatabaseMetaData.importedKeySetDefault:
return DBSForeignKeyModifyRule.SET_DEFAULT;
case DatabaseMetaData.importedKeyRestrict:
return DBSForeignKeyModifyRule.RESTRICT;
default:
return DBSForeignKeyModifyRule.UNKNOWN;
}
}
public static void executeSQL(Connection session, String sql, Object ... params) throws SQLException
{
try (PreparedStatement dbStat = session.prepareStatement(sql)) {
if (params != null) {
for (int i = 0; i < params.length; i++) {
dbStat.setObject(i + 1, params[i]);
}
}
dbStat.execute();
}
}
public static void executeProcedure(Connection session, String sql) throws SQLException
{
try (PreparedStatement dbStat = session.prepareCall(sql)) {
dbStat.execute();
}
}
public static <T> T executeQuery(Connection session, String sql, Object ... params) throws SQLException
{
try (PreparedStatement dbStat = session.prepareStatement(sql)) {
if (params != null) {
for (int i = 0; i < params.length; i++) {
dbStat.setObject(i + 1, params[i]);
}
}
try (ResultSet resultSet = dbStat.executeQuery()) {
if (resultSet.next()) {
return (T) resultSet.getObject(1);
} else {
return null;
}
}
}
}
public static void executeStatement(Connection session, String sql, Object ... params) throws SQLException {
try (PreparedStatement dbStat = session.prepareStatement(sql)) {
if (params != null) {
for (int i = 0; i < params.length; i++) {
dbStat.setObject(i + 1, params[i]);
}
}
dbStat.execute();
}
}
public static void executeStatement(Connection session, String sql) throws SQLException {
try (Statement dbStat = session.createStatement()) {
dbStat.execute(sql);
}
}
@Nullable
public static String queryString(JDBCSession session, String sql, Object... args) throws SQLException
{
try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) {
if (args != null) {
for (int i = 0; i < args.length; i++) {
dbStat.setObject(i + 1, args[i]);
}
}
try (JDBCResultSet resultSet = dbStat.executeQuery()) {
if (resultSet.next()) {
return resultSet.getString(1);
} else {
return null;
}
}
}
}
@Nullable
public static <T> T queryObject(JDBCSession session, String sql, Object... args) throws SQLException
{
try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) {
if (args != null) {
for (int i = 0; i < args.length; i++) {
dbStat.setObject(i + 1, args[i]);
}
}
try (JDBCResultSet resultSet = dbStat.executeQuery()) {
if (resultSet.next()) {
return (T) resultSet.getObject(1);
} else {
return null;
}
}
}
}
private static void debugColumnRead(ResultSet dbResult, String columnName, SQLException error)
{
String colFullId = columnName;
if (dbResult instanceof JDBCResultSet) {
colFullId += ":" + ((JDBCResultSet) dbResult).getSession().getDataSource().getContainer().getId();
}
synchronized (badColumnNames) {
final Integer errorCount = badColumnNames.get(colFullId);
if (errorCount == null) {
log.debug("Can't get column '" + columnName + "': " + error.getMessage());
}
badColumnNames.put(colFullId, errorCount == null ? 0 : errorCount + 1);
}
}
private static void debugColumnRead(ResultSet dbResult, int columnIndex, SQLException error)
{
debugColumnRead(dbResult, "#" + columnIndex, error);
}
public static void appendFilterClause(StringBuilder sql, DBSObjectFilter filter, String columnAlias, boolean firstClause)
{
if (filter.isNotApplicable()) {
return;
}
if (filter.hasSingleMask()) {
if (columnAlias != null) {
firstClause = SQLUtils.appendFirstClause(sql, firstClause);
sql.append(columnAlias);
}
SQLUtils.appendLikeCondition(sql, filter.getSingleMask(), false);
return;
}
List<String> include = filter.getInclude();
if (!CommonUtils.isEmpty(include)) {
if (columnAlias != null) {
firstClause = SQLUtils.appendFirstClause(sql, firstClause);
}
sql.append("(");
for (int i = 0, includeSize = include.size(); i < includeSize; i++) {
if (i > 0)
sql.append(" OR ");
if (columnAlias != null) {
sql.append(columnAlias);
}
SQLUtils.appendLikeCondition(sql, include.get(i), false);
}
sql.append(")");
}
List<String> exclude = filter.getExclude();
if (!CommonUtils.isEmpty(exclude)) {
if (columnAlias != null) {
SQLUtils.appendFirstClause(sql, firstClause);
}
sql.append("NOT (");
for (int i = 0, excludeSize = exclude.size(); i < excludeSize; i++) {
if (i > 0)
sql.append(" OR ");
if (columnAlias != null) {
sql.append(columnAlias);
}
SQLUtils.appendLikeCondition(sql, exclude.get(i), false);
}
sql.append(")");
}
}
public static void setFilterParameters(PreparedStatement statement, int paramIndex, DBSObjectFilter filter)
throws SQLException
{
if (filter.isNotApplicable()) {
return;
}
for (String inc : CommonUtils.safeCollection(filter.getInclude())) {
statement.setString(paramIndex++, SQLUtils.makeSQLLike(inc));
}
for (String exc : CommonUtils.safeCollection(filter.getExclude())) {
statement.setString(paramIndex++, SQLUtils.makeSQLLike(exc));
}
}
public static void rethrowSQLException(Throwable e) throws SQLException
{
if (e instanceof InvocationTargetException) {
Throwable targetException = ((InvocationTargetException) e).getTargetException();
if (targetException instanceof SQLException) {
throw (SQLException) targetException;
} else {
throw new SQLException(targetException);
}
}
}
public static DBPDataKind resolveDataKind(@Nullable DBPDataSource dataSource, String typeName, int typeID)
{
if (dataSource == null) {
return JDBCDataSource.getDataKind(typeName, typeID);
} else if (dataSource instanceof DBPDataTypeProvider) {
return ((DBPDataTypeProvider) dataSource).resolveDataKind(typeName, typeID);
} else {
return DBPDataKind.UNKNOWN;
}
}
public static String escapeWildCards(JDBCSession session, String string) {
if (string == null || string.isEmpty() || (string.indexOf('%') == -1 && string.indexOf('_') == -1)) {
return string;
}
try {
SQLDialect dialect = SQLUtils.getDialectFromDataSource(session.getDataSource());
String escapeStr = dialect.getSearchStringEscape();
if (CommonUtils.isEmpty(escapeStr) || escapeStr.equals(" ")) {
return string;
}
return string.replace("%", escapeStr + "%").replace("_", escapeStr + "_");
} catch (Throwable e) {
log.debug("Error escaping wildcard string", e);
return string;
}
}
public static boolean queryHasOutputParameters(SQLDialect sqlDialect, String sqlQuery) {
return sqlQuery.contains("?");
}
}
| plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/JDBCUtils.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2020 DBeaver Corp and others
*
* 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.jkiss.dbeaver.model.impl.jdbc;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPDataSourceTask;
import org.jkiss.dbeaver.model.DBPDataTypeProvider;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSObjectFilter;
import org.jkiss.dbeaver.model.struct.rdb.DBSForeignKeyModifyRule;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* JDBCUtils
*/
public class JDBCUtils {
private static final Log log = Log.getLog(JDBCUtils.class);
private static final Map<String, Integer> badColumnNames = new HashMap<>();
@Nullable
public static String safeGetString(ResultSet dbResult, String columnName)
{
try {
return dbResult.getString(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static String safeGetStringTrimmed(ResultSet dbResult, String columnName)
{
try {
final String value = dbResult.getString(columnName);
if (value != null && !value.isEmpty()) {
return value.trim();
} else {
return value;
}
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static String safeGetString(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getString(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static String safeGetStringTrimmed(ResultSet dbResult, int columnIndex)
{
try {
final String value = dbResult.getString(columnIndex);
if (value != null && !value.isEmpty()) {
return value.trim();
} else {
return value;
}
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
public static int safeGetInt(ResultSet dbResult, String columnName)
{
try {
return dbResult.getInt(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return 0;
}
}
public static int safeGetInt(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getInt(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return 0;
}
}
@Nullable
public static Integer safeGetInteger(ResultSet dbResult, String columnName)
{
try {
final int result = dbResult.getInt(columnName);
if (dbResult.wasNull()) {
return null;
} else {
return result;
}
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Integer safeGetInteger(ResultSet dbResult, int columnIndex)
{
try {
final int result = dbResult.getInt(columnIndex);
if (dbResult.wasNull()) {
return null;
} else {
return result;
}
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
public static long safeGetLong(ResultSet dbResult, String columnName)
{
try {
return dbResult.getLong(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return 0;
}
}
public static long safeGetLong(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getLong(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return 0;
}
}
@Nullable
public static Long safeGetLongNullable(ResultSet dbResult, String columnName)
{
try {
final long result = dbResult.getLong(columnName);
return dbResult.wasNull() ? null : result;
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
public static double safeGetDouble(ResultSet dbResult, String columnName)
{
try {
return dbResult.getDouble(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return 0.0;
}
}
public static double safeGetDouble(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getDouble(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return 0.0;
}
}
public static float safeGetFloat(ResultSet dbResult, String columnName)
{
try {
return dbResult.getFloat(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return 0;
}
}
public static float safeGetFloat(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getFloat(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return 0;
}
}
@Nullable
public static BigDecimal safeGetBigDecimal(ResultSet dbResult, String columnName)
{
try {
return dbResult.getBigDecimal(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static BigDecimal safeGetBigDecimal(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getBigDecimal(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
public static boolean safeGetBoolean(ResultSet dbResult, String columnName)
{
return safeGetBoolean(dbResult, columnName, false);
}
public static boolean safeGetBoolean(ResultSet dbResult, String columnName, boolean defValue)
{
try {
return dbResult.getBoolean(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return defValue;
}
}
public static boolean safeGetBoolean(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getBoolean(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return false;
}
}
public static boolean safeGetBoolean(ResultSet dbResult, String columnName, String trueValue)
{
try {
final String strValue = dbResult.getString(columnName);
return strValue != null && strValue.startsWith(trueValue);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return false;
}
}
@Nullable
public static byte[] safeGetBytes(ResultSet dbResult, String columnName)
{
try {
return dbResult.getBytes(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Timestamp safeGetTimestamp(ResultSet dbResult, String columnName)
{
try {
return dbResult.getTimestamp(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Timestamp safeGetTimestamp(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getTimestamp(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static Date safeGetDate(ResultSet dbResult, String columnName)
{
try {
return dbResult.getDate(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Date safeGetDate(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getDate(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static Time safeGetTime(ResultSet dbResult, String columnName)
{
try {
return dbResult.getTime(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Time safeGetTime(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getTime(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static SQLXML safeGetXML(ResultSet dbResult, String columnName)
{
try {
return dbResult.getSQLXML(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static SQLXML safeGetXML(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getSQLXML(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static Object safeGetObject(ResultSet dbResult, String columnName)
{
try {
return dbResult.getObject(columnName);
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Object safeGetObject(ResultSet dbResult, int columnIndex)
{
try {
return dbResult.getObject(columnIndex);
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static <T> T safeGetArray(ResultSet dbResult, String columnName)
{
try {
Array array = dbResult.getArray(columnName);
return array == null ? null : (T) array.getArray();
} catch (SQLException e) {
debugColumnRead(dbResult, columnName, e);
return null;
}
}
@Nullable
public static Object safeGetArray(ResultSet dbResult, int columnIndex)
{
try {
Array array = dbResult.getArray(columnIndex);
return array == null ? null : array.getArray();
} catch (SQLException e) {
debugColumnRead(dbResult, columnIndex, e);
return null;
}
}
@Nullable
public static String normalizeIdentifier(@Nullable String value)
{
return value == null ? null : value.trim();
}
public static void dumpResultSet(ResultSet dbResult)
{
try {
ResultSetMetaData md = dbResult.getMetaData();
int count = md.getColumnCount();
dumpResultSetMetaData(dbResult);
while (dbResult.next()) {
for (int i = 1; i <= count; i++) {
String colValue = dbResult.getString(i);
System.out.print(colValue + "\t");
}
System.out.println();
}
System.out.println();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void dumpResultSetMetaData(ResultSet dbResult)
{
try {
ResultSetMetaData md = dbResult.getMetaData();
int count = md.getColumnCount();
for (int i = 1; i <= count; i++) {
System.out.print(md.getColumnName(i) + " [" + md.getColumnTypeName(i) + "]\t");
}
System.out.println();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static boolean isConnectionAlive(DBPDataSource dataSource, Connection connection)
{
try {
if (connection == null || connection.isClosed()) {
return false;
}
} catch (SQLException e) {
log.debug(e);
return false;
}
// Check for active tasks. Do not run ping if there is active task
for (DBPDataSourceTask task : dataSource.getContainer().getTasks()) {
if (task.isActiveTask()) {
return true;
}
}
// Run ping query
final String testSQL = dataSource.getSQLDialect().getTestSQL();
int invalidateTimeout = dataSource.getContainer().getPreferenceStore().getInt(ModelPreferences.CONNECTION_VALIDATION_TIMEOUT);
// Invalidate in non-blocking task.
// Timeout is CONNECTION_VALIDATION_TIMEOUT + 2 seconds
final boolean[] isValid = new boolean[1];
RuntimeUtils.runTask(monitor -> {
try {
if (!CommonUtils.isEmpty(testSQL)) {
// Execute test SQL
try (Statement dbStat = connection.createStatement()) {
dbStat.execute(testSQL);
isValid[0] = true;
}
} else {
try {
isValid[0] = connection.isValid(invalidateTimeout);
} catch (Throwable e) {
// isValid may be unsupported by driver
// Let's try to read table list
connection.getMetaData().getTables(null, null, "DBEAVERFAKETABLENAMEFORPING", null);
isValid[0] = true;
}
}
} catch (SQLException e) {
isValid[0] = false;
}
}, "Ping connection " + dataSource.getContainer().getName(), invalidateTimeout + 2000, true);
return isValid[0];
}
public static void scrollResultSet(ResultSet dbResult, long offset, boolean forceFetch) throws SQLException
{
// Scroll to first row
boolean scrolled = false;
if (!forceFetch) {
try {
scrolled = dbResult.absolute((int) offset);
} catch (SQLException | UnsupportedOperationException | IncompatibleClassChangeError e) {
// Seems to be not supported
log.debug(e.getMessage());
}
}
if (!scrolled) {
// Just fetch first 'firstRow' rows
for (long i = 1; i <= offset; i++) {
try {
dbResult.next();
} catch (SQLException e) {
throw new SQLException("Can't scroll result set to row " + offset, e);
}
}
}
}
public static void reportWarnings(JDBCSession session, SQLWarning rootWarning)
{
for (SQLWarning warning = rootWarning; warning != null; warning = warning.getNextWarning()) {
if (warning.getMessage() == null && warning.getErrorCode() == 0) {
// Skip trash [Excel driver]
continue;
}
log.warn("SQL Warning (DataSource: " + session.getDataSource().getContainer().getName() + "; Code: "
+ warning.getErrorCode() + "; State: " + warning.getSQLState() + "): " + warning.getLocalizedMessage());
}
}
@NotNull
public static String limitQueryLength(@NotNull String query, int maxLength)
{
return query.length() <= maxLength ? query : query.substring(0, maxLength);
}
public static DBSForeignKeyModifyRule getCascadeFromNum(int num)
{
switch (num) {
case DatabaseMetaData.importedKeyNoAction:
return DBSForeignKeyModifyRule.NO_ACTION;
case DatabaseMetaData.importedKeyCascade:
return DBSForeignKeyModifyRule.CASCADE;
case DatabaseMetaData.importedKeySetNull:
return DBSForeignKeyModifyRule.SET_NULL;
case DatabaseMetaData.importedKeySetDefault:
return DBSForeignKeyModifyRule.SET_DEFAULT;
case DatabaseMetaData.importedKeyRestrict:
return DBSForeignKeyModifyRule.RESTRICT;
default:
return DBSForeignKeyModifyRule.UNKNOWN;
}
}
public static void executeSQL(Connection session, String sql, Object ... params) throws SQLException
{
try (PreparedStatement dbStat = session.prepareStatement(sql)) {
if (params != null) {
for (int i = 0; i < params.length; i++) {
dbStat.setObject(i + 1, params[i]);
}
}
dbStat.execute();
}
}
public static void executeProcedure(Connection session, String sql) throws SQLException
{
try (PreparedStatement dbStat = session.prepareCall(sql)) {
dbStat.execute();
}
}
public static <T> T executeQuery(Connection session, String sql, Object ... params) throws SQLException
{
try (PreparedStatement dbStat = session.prepareStatement(sql)) {
if (params != null) {
for (int i = 0; i < params.length; i++) {
dbStat.setObject(i + 1, params[i]);
}
}
try (ResultSet resultSet = dbStat.executeQuery()) {
if (resultSet.next()) {
return (T) resultSet.getObject(1);
} else {
return null;
}
}
}
}
public static void executeStatement(Connection session, String sql) throws SQLException
{
try (Statement dbStat = session.createStatement()) {
dbStat.execute(sql);
}
}
@Nullable
public static String queryString(JDBCSession session, String sql, Object... args) throws SQLException
{
try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) {
if (args != null) {
for (int i = 0; i < args.length; i++) {
dbStat.setObject(i + 1, args[i]);
}
}
try (JDBCResultSet resultSet = dbStat.executeQuery()) {
if (resultSet.next()) {
return resultSet.getString(1);
} else {
return null;
}
}
}
}
@Nullable
public static <T> T queryObject(JDBCSession session, String sql, Object... args) throws SQLException
{
try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) {
if (args != null) {
for (int i = 0; i < args.length; i++) {
dbStat.setObject(i + 1, args[i]);
}
}
try (JDBCResultSet resultSet = dbStat.executeQuery()) {
if (resultSet.next()) {
return (T) resultSet.getObject(1);
} else {
return null;
}
}
}
}
private static void debugColumnRead(ResultSet dbResult, String columnName, SQLException error)
{
String colFullId = columnName;
if (dbResult instanceof JDBCResultSet) {
colFullId += ":" + ((JDBCResultSet) dbResult).getSession().getDataSource().getContainer().getId();
}
synchronized (badColumnNames) {
final Integer errorCount = badColumnNames.get(colFullId);
if (errorCount == null) {
log.debug("Can't get column '" + columnName + "': " + error.getMessage());
}
badColumnNames.put(colFullId, errorCount == null ? 0 : errorCount + 1);
}
}
private static void debugColumnRead(ResultSet dbResult, int columnIndex, SQLException error)
{
debugColumnRead(dbResult, "#" + columnIndex, error);
}
public static void appendFilterClause(StringBuilder sql, DBSObjectFilter filter, String columnAlias, boolean firstClause)
{
if (filter.isNotApplicable()) {
return;
}
if (filter.hasSingleMask()) {
if (columnAlias != null) {
firstClause = SQLUtils.appendFirstClause(sql, firstClause);
sql.append(columnAlias);
}
SQLUtils.appendLikeCondition(sql, filter.getSingleMask(), false);
return;
}
List<String> include = filter.getInclude();
if (!CommonUtils.isEmpty(include)) {
if (columnAlias != null) {
firstClause = SQLUtils.appendFirstClause(sql, firstClause);
}
sql.append("(");
for (int i = 0, includeSize = include.size(); i < includeSize; i++) {
if (i > 0)
sql.append(" OR ");
if (columnAlias != null) {
sql.append(columnAlias);
}
SQLUtils.appendLikeCondition(sql, include.get(i), false);
}
sql.append(")");
}
List<String> exclude = filter.getExclude();
if (!CommonUtils.isEmpty(exclude)) {
if (columnAlias != null) {
SQLUtils.appendFirstClause(sql, firstClause);
}
sql.append("NOT (");
for (int i = 0, excludeSize = exclude.size(); i < excludeSize; i++) {
if (i > 0)
sql.append(" OR ");
if (columnAlias != null) {
sql.append(columnAlias);
}
SQLUtils.appendLikeCondition(sql, exclude.get(i), false);
}
sql.append(")");
}
}
public static void setFilterParameters(PreparedStatement statement, int paramIndex, DBSObjectFilter filter)
throws SQLException
{
if (filter.isNotApplicable()) {
return;
}
for (String inc : CommonUtils.safeCollection(filter.getInclude())) {
statement.setString(paramIndex++, SQLUtils.makeSQLLike(inc));
}
for (String exc : CommonUtils.safeCollection(filter.getExclude())) {
statement.setString(paramIndex++, SQLUtils.makeSQLLike(exc));
}
}
public static void rethrowSQLException(Throwable e) throws SQLException
{
if (e instanceof InvocationTargetException) {
Throwable targetException = ((InvocationTargetException) e).getTargetException();
if (targetException instanceof SQLException) {
throw (SQLException) targetException;
} else {
throw new SQLException(targetException);
}
}
}
public static DBPDataKind resolveDataKind(@Nullable DBPDataSource dataSource, String typeName, int typeID)
{
if (dataSource == null) {
return JDBCDataSource.getDataKind(typeName, typeID);
} else if (dataSource instanceof DBPDataTypeProvider) {
return ((DBPDataTypeProvider) dataSource).resolveDataKind(typeName, typeID);
} else {
return DBPDataKind.UNKNOWN;
}
}
public static String escapeWildCards(JDBCSession session, String string) {
if (string == null || string.isEmpty() || (string.indexOf('%') == -1 && string.indexOf('_') == -1)) {
return string;
}
try {
SQLDialect dialect = SQLUtils.getDialectFromDataSource(session.getDataSource());
String escapeStr = dialect.getSearchStringEscape();
if (CommonUtils.isEmpty(escapeStr) || escapeStr.equals(" ")) {
return string;
}
return string.replace("%", escapeStr + "%").replace("_", escapeStr + "_");
} catch (Throwable e) {
log.debug("Error escaping wildcard string", e);
return string;
}
}
public static boolean queryHasOutputParameters(SQLDialect sqlDialect, String sqlQuery) {
return sqlQuery.contains("?");
}
}
| JDBC utils
Former-commit-id: 16b10b4ed5514eb95358e70b3cc8f8c79e4daac5 | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/JDBCUtils.java | JDBC utils |
|
Java | apache-2.0 | 2aeefda3fd7364ffb659bca1f09a6c783d3c3375 | 0 | dx-pbuckley/vavr,ummels/vavr,ummels/vavr,amygithub/vavr,amygithub/vavr,dx-pbuckley/vavr | /* / \____ _ _ ____ ______ / \ ____ __ _ _____
* / / \/ \ / \/ \ / /\__\/ // \/ \ / / _ \ Javaslang
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \__/ / Copyright 2014-now Daniel Dietrich
* /___/\_/ \_/\____/\_/ \_/\__\/__/___\_/ \_// \__/_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang;
import javaslang.collection.List;
import javaslang.control.Try;
import javaslang.λModule.ReflectionUtil;
import java.io.Serializable;
import java.lang.invoke.MethodType;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
/**
* This is a general definition of a (checked/unchecked) function of unknown parameters and a return type R.
* <p>
* A checked function may throw an exception. The exception type cannot be expressed as a generic type parameter
* because Java cannot calculate type bounds on function composition.
*
* @param <R> Return type of the function.
* @author Daniel Dietrich
* @since 1.0.0
*/
public interface λ<R> extends Serializable {
/**
* The <a href="https://docs.oracle.com/javase/8/docs/api/index.html">serial version uid</a>.
*/
long serialVersionUID = 1L;
/**
* @return the number of function arguments.
* @see <a href="http://en.wikipedia.org/wiki/Arity">Arity</a>
*/
int arity();
/**
* Returns a curried version of this function.
*
* @return a curried function equivalent to this.
*/
// generic argument count varies
@SuppressWarnings("rawtypes")
λ curried();
/**
* Returns a tupled version of this function.
*
* @return a tupled function equivalent to this.
*/
λ<R> tupled();
/**
* Returns a reversed version of this function. This may be useful in a recursive context.
*
* @return a reversed function equivalent to this.
*/
λ<R> reversed();
/**
* Returns a memoizing version of this function, which computes the return value for given arguments only one time.
* On subsequent calls given the same arguments the memoized value is returned.
* <p>
* Please note that memoizing functions do not permit {@code null} as single argument or return value.
*
* @return a memoizing function equivalent to this.
*/
λ<R> memoized();
/**
* Checks if this function is memoizing (= caching) computed values.
*
* @return true, if this function is memoizing, false otherwise
*/
boolean isMemoized();
/**
* Get reflective type information about lambda parameters and return type.
*
* @return A new instance containing the type information
*/
Type<R> getType();
/**
* Checks if this function is applicable to the given objects,
* i.e. each of the given objects is either null or the object type is assignable to the parameter type.
* <p>
* Please note that it is not checked if this function is defined for the given objects.
* <p>
* A function is applicable to no objects by definition.
*
* @param objects Objects, may be null
* @return true, if {@code 0 < objects.length <= arity()} and this function is applicable to the given objects, false otherwise.
* @throws NullPointerException if {@code objects} is null.
*/
default boolean isApplicableTo(Object... objects) {
Objects.requireNonNull(objects, "objects is null");
if (objects.length == 0 || objects.length > arity()) {
return false;
}
final Class<?>[] paramTypes = getType().parameterTypes();
for (int i = 0; i < objects.length; i++) {
final Object o = objects[i];
if (o != null && !paramTypes[i].isAssignableFrom(o.getClass())) {
return false;
}
}
return true;
}
/**
* Checks if this function is generally applicable to objects of the given types.
* <p>
* A function is applicable to no types by definition.
*
* @param types Argument types
* @return true, if {@code 0 <= types.length <= arity()} and this function is applicable to objects of the given types, false otherwise.
* @throws NullPointerException if {@code types} or one of the elements of {@code types} is null.
*/
default boolean isApplicableToTypes(Class<?>... types) {
Objects.requireNonNull(types, "types is null");
if (types.length == 0 || types.length > arity()) {
return false;
}
final Class<?>[] paramTypes = getType().parameterTypes();
for (int i = 0; i < types.length; i++) {
final Class<?> type = Objects.requireNonNull(types[i], "types[" + i + "] is null");
if (!paramTypes[i].isAssignableFrom(type)) {
return false;
}
}
return true;
}
/**
* Represents the type of a function which consists of <em>parameter types</em> and a <em>return type</em>.
*
* @param <R> the return type of the function
* @since 2.0.0
*/
// DEV-NOTE: implicitly static and therefore not leaking implicit this reference of enclosing instance
abstract class Type<R> implements Serializable {
private static final long serialVersionUID = 1L;
private final Class<R> returnType;
private final Class<?>[] parameterTypes;
/**
* Internal constructor.
*
* @param λ the outer function instance of this type
*/
@SuppressWarnings("unchecked")
protected Type(λ<R> λ) {
final MethodType methodType = ReflectionUtil.getLambdaSignature(λ);
this.returnType = (Class<R>) methodType.returnType();
this.parameterTypes = methodType.parameterArray();
}
public Class<R> returnType() {
return returnType;
}
public Class<?>[] parameterTypes() {
return parameterTypes;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof Type) {
final Type<?> that = (Type<?>) o;
return this.hashCode() == that.hashCode()
&& this.returnType().equals(that.returnType)
&& Arrays.equals(this.parameterTypes, that.parameterTypes);
} else {
return false;
}
}
@Override
public int hashCode() {
return List.of(parameterTypes())
.map(c -> c.getName().hashCode())
.fold(1, (acc, i) -> acc * 31 + i)
* 31 + returnType().getName().hashCode();
}
@Override
public String toString() {
return List.of(parameterTypes).map(Class::getName).mkString("(", ", ", ")") + " -> " + returnType.getName();
}
}
}
interface λModule {
// hiding this functionality
final class ReflectionUtil {
static MethodType getLambdaSignature(Serializable lambda) {
final String signature = getSerializedLambda(lambda).getInstantiatedMethodType();
return MethodType.fromMethodDescriptorString(signature, lambda.getClass().getClassLoader());
}
private static SerializedLambda getSerializedLambda(Serializable lambda) {
return Try.of(() -> {
final Method method = lambda.getClass().getDeclaredMethod("writeReplace");
method.setAccessible(true);
return (SerializedLambda) method.invoke(lambda);
}).get();
}
}
}
| src/main/java/javaslang/λ.java | /* / \____ _ _ ____ ______ / \ ____ __ _ _____
* / / \/ \ / \/ \ / /\__\/ // \/ \ / / _ \ Javaslang
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \__/ / Copyright 2014-now Daniel Dietrich
* /___/\_/ \_/\____/\_/ \_/\__\/__/___\_/ \_// \__/_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang;
import javaslang.collection.List;
import javaslang.control.Try;
import javaslang.λModule.ReflectionUtil;
import java.io.Serializable;
import java.lang.invoke.MethodType;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
/**
* This is a general definition of a (checked/unchecked) function of unknown parameters and a return type R.
* <p>
* A checked function may throw an exception. The exception type cannot be expressed as a generic type parameter
* because Java cannot calculate type bounds on function composition.
*
* @param <R> Return type of the function.
* @author Daniel Dietrich
* @since 1.0.0
*/
public interface λ<R> extends Serializable {
/**
* The <a href="https://docs.oracle.com/javase/8/docs/api/index.html">serial version uid</a>.
*/
long serialVersionUID = 1L;
/**
* @return the number of function arguments.
* @see <a href="http://en.wikipedia.org/wiki/Arity">Arity</a>
*/
int arity();
/**
* Returns a curried version of this function.
*
* @return a curried function equivalent to this.
*/
// generic argument count varies
@SuppressWarnings("rawtypes")
λ curried();
/**
* Returns a tupled version of this function.
*
* @return a tupled function equivalent to this.
*/
λ<R> tupled();
/**
* Returns a reversed version of this function. This may be useful in a recursive context.
*
* @return a reversed function equivalent to this.
*/
λ<R> reversed();
/**
* Returns a memoizing version of this function, which computes the return value for given arguments only one time.
* On subsequent calls given the same arguments the memoized value is returned.
* <p>
* Please note that memoizing functions do not permit {@code null} as single argument or return value.
*
* @return a memoizing function equivalent to this.
*/
λ<R> memoized();
/**
* Checks if this function is memoizing (= caching) computed values.
*
* @return true, if this function is memoizing, false otherwise
*/
boolean isMemoized();
/**
* Get reflective type information about lambda parameters and return type.
*
* @return A new instance containing the type information
*/
Type<R> getType();
/**
* Checks if this function is applicable to the given objects,
* i.e. each of the given objects is either null or the object type is assignable to the parameter type.
* <p>
* Please note that it is not checked if this function is defined for the given objects.
* <p>
* A function is applicable to no objects by definition.
*
* @param objects Objects, may be null
* @return true, if {@code 0 < objects.length <= arity()} and this function is applicable to the given objects, false otherwise.
* @throws NullPointerException if {@code objects} is null.
*/
default boolean isApplicableTo(Object... objects) {
Objects.requireNonNull(objects, "objects is null");
if (objects.length == 0 || objects.length > arity()) {
return false;
}
final Class<?>[] paramTypes = getType().parameterTypes();
for (int i = 0; i < objects.length; i++) {
final Object o = objects[i];
if (o != null && !paramTypes[i].isAssignableFrom(o.getClass())) {
return false;
}
}
return true;
}
/**
* Checks if this function is generally applicable to objects of the given types.
* <p>
* A function is applicable to no types by definition.
*
* @param types Argument types
* @return true, if {@code 0 <= types.length <= arity()} and this function is applicable to objects of the given types, false otherwise.
* @throws NullPointerException if {@code types} or one of the elements of {@code types} is null.
*/
default boolean isApplicableToTypes(Class<?>... types) {
Objects.requireNonNull(types, "types is null");
if (types.length == 0 || types.length > arity()) {
return false;
}
final Class<?>[] paramTypes = getType().parameterTypes();
for (int i = 0; i < types.length; i++) {
final Class<?> type = Objects.requireNonNull(types[i], "types[" + i + "] is null");
if (!paramTypes[i].isAssignableFrom(type)) {
return false;
}
}
return true;
}
/**
* Represents the type of a function which consists of <em>parameter types</em> and a <em>return type</em>.
*
* @param <R> the return type of the function
* @since 2.0.0
*/
// DEV-NOTE: implicitly static and therefore not leaking implicit this reference of enclosing instance
abstract class Type<R> implements Serializable {
private static final long serialVersionUID = 1L;
private final Class<R> returnType;
private final Class<?>[] parameterTypes;
private transient final Lazy<Integer> hashCode = Lazy.of(
() -> List.of(parameterTypes()).map(c -> c.getName().hashCode()).fold(1, (acc, i) -> acc * 31 + i) * 31
+ returnType().getName().hashCode());
/**
* Internal constructor.
*
* @param λ the outer function instance of this type
*/
@SuppressWarnings("unchecked")
protected Type(λ<R> λ) {
final MethodType methodType = ReflectionUtil.getLambdaSignature(λ);
this.returnType = (Class<R>) methodType.returnType();
this.parameterTypes = methodType.parameterArray();
}
public Class<R> returnType() {
return returnType;
}
public Class<?>[] parameterTypes() {
return parameterTypes;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof Type) {
final Type<?> that = (Type<?>) o;
return this.hashCode() == that.hashCode()
&& this.returnType().equals(that.returnType)
&& Arrays.equals(this.parameterTypes, that.parameterTypes);
} else {
return false;
}
}
@Override
public int hashCode() {
return hashCode.get();
}
@Override
public String toString() {
return List.of(parameterTypes).map(Class::getName).mkString("(", ", ", ")") + " -> " + returnType.getName();
}
}
}
interface λModule {
// hiding this functionality
final class ReflectionUtil {
static MethodType getLambdaSignature(Serializable lambda) {
final String signature = getSerializedLambda(lambda).getInstantiatedMethodType();
return MethodType.fromMethodDescriptorString(signature, lambda.getClass().getClassLoader());
}
private static SerializedLambda getSerializedLambda(Serializable lambda) {
return Try.of(() -> {
final Method method = lambda.getClass().getDeclaredMethod("writeReplace");
method.setAccessible(true);
return (SerializedLambda) method.invoke(lambda);
}).get();
}
}
}
| hashcode does not need to be cached on a reflection type
| src/main/java/javaslang/λ.java | hashcode does not need to be cached on a reflection type |
|
Java | apache-2.0 | 87a9cd79920412a5206f2444f0cec036778f6a08 | 0 | gurbuzali/hazelcast-jet,gurbuzali/hazelcast-jet | /*
* Copyright (c) 2008-2020, 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.jet.core;
import com.hazelcast.function.ConsumerEx;
import com.hazelcast.jet.Job;
import com.hazelcast.jet.Observable;
import com.hazelcast.jet.TestInClusterSupport;
import com.hazelcast.jet.function.Observer;
import com.hazelcast.jet.pipeline.BatchSource;
import com.hazelcast.jet.pipeline.BatchStage;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.SourceBuilder;
import com.hazelcast.jet.pipeline.test.SimpleEvent;
import com.hazelcast.jet.pipeline.test.TestSources;
import com.hazelcast.ringbuffer.impl.RingbufferProxy;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ObservableResultsTest extends TestInClusterSupport {
private String observableName;
private TestObserver testObserver;
private Observable<Long> testObservable;
private UUID registrationId;
@Before
public void before() {
observableName = randomName();
testObserver = new TestObserver();
testObservable = jet().getObservable(observableName);
registrationId = testObservable.addObserver(testObserver);
}
@After
@Override
public void after() throws Exception {
jet().getObservables().forEach(Observable::destroy);
super.after();
}
@Test
public void iterable() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
//then
List<Long> items = new ArrayList<>();
for (Long item : testObservable) {
items.add(item);
}
items.sort(Long::compareTo);
assertEquals(Arrays.asList(0L, 1L, 2L, 3L, 4L), items);
}
@Test
public void batchJobCompletesSuccessfully() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(testObserver, 0L, 1L, 2L, 3L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 1);
}
@Test
public void batchJobFails() {
BatchSource<String> errorSource = SourceBuilder
.batch("error-source", x -> null)
.<String>fillBufferFn((in, Void) -> {
throw new Exception("Intentionally thrown!");
})
.destroyFn(ConsumerEx.noop())
.build();
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(errorSource)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
assertTrueEventually(() -> assertEquals(JobStatus.FAILED, job.getStatus()));
//then
assertSortedValues(testObserver);
assertError(testObserver, "Intentionally thrown!");
assertCompletions(testObserver, 0);
}
@Test
public void streamJob() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
//then
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
//when
job.cancel();
//then
assertError(testObserver, "CancellationException");
assertCompletions(testObserver, 0);
}
@Test
public void streamJobRestart() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
//then
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
//when
job.restart();
//then
int resultsSoFar = testObserver.getNoOfValues();
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job.getStatus()));
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > resultsSoFar));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
}
@Test
public void multipleObservables() {
Pipeline pipeline = Pipeline.create();
BatchStage<Long> stage = pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L));
TestObserver otherTestObserver = new TestObserver();
Observable<Long> otherObservable = jet().getObservable("otherObservable");
otherObservable.addObserver(otherTestObserver);
stage.filter(i -> i % 2 == 0).writeTo(Sinks.observable(observableName));
stage.filter(i -> i % 2 != 0).writeTo(Sinks.observable("otherObservable"));
//when
Job job = jet().newJob(pipeline);
job.join();
//then
assertSortedValues(testObserver, 0L, 2L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 1);
//also
assertSortedValues(otherTestObserver, 1L, 3L);
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 1);
}
@Test
public void multipleIdenticalSinks() {
Pipeline pipeline = Pipeline.create();
BatchStage<Long> readStage = pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L));
readStage.writeTo(Sinks.observable(observableName));
readStage.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
job.join();
//then
assertSortedValues(testObserver, 0L, 0L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 1);
}
@Test
public void multipleJobsWithTheSameSink() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.filter(t -> (t % 2 == 0))
.writeTo(Sinks.observable(observableName));
Pipeline pipeline2 = Pipeline.create();
pipeline2.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.filter(t -> (t % 2 != 0))
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
Job job2 = jet().newJob(pipeline2);
//then
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job.getStatus()));
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job2.getStatus()));
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertTrueEventually(() -> {
List<Long> sortedValues = testObserver.getSortedValues();
assertEquals(0, (long) sortedValues.get(0));
assertEquals(1, (long) sortedValues.get(1));
});
assertError(testObserver, null);
assertCompletions(testObserver, 0);
job.cancel();
job2.cancel();
}
@Test
public void multipleJobExecutions() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
jet().newJob(pipeline).join();
//then
assertSortedValues(testObserver, 0L, 0L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 2);
}
@Test
public void observersGetAllEventsStillInRingbuffer() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(testObserver, 0L, 1L, 2L, 3L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 1);
//when
TestObserver otherTestObserver = new TestObserver();
jet().<Long>getObservable(observableName).addObserver(otherTestObserver);
//then
assertSortedValues(otherTestObserver, 0L, 1L, 2L, 3L, 4L);
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 1);
}
@Test
public void observableRegisteredAfterJobFinishedGetAllEventsStillInRingbuffer() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName + "late"));
//when
jet().newJob(pipeline).join();
TestObserver otherTestObserver = new TestObserver();
Observable<Long> lateObservable = jet().getObservable(observableName + "late");
lateObservable.addObserver(otherTestObserver);
//then
assertSortedValues(otherTestObserver, 0L, 1L, 2L, 3L, 4L);
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 1);
}
@Test
public void observableRegisteredAfterJobFailedGetError() {
BatchSource<String> errorSource = SourceBuilder
.batch("error-source", x -> null)
.<String>fillBufferFn((in, Void) -> {
throw new Exception("Intentionally thrown!");
})
.destroyFn(ConsumerEx.noop())
.build();
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(errorSource)
.writeTo(Sinks.observable(observableName));
Job job = jet().newJob(pipeline);
assertTrueEventually(() -> assertEquals(JobStatus.FAILED, job.getStatus()));
//when
TestObserver otherTestObserver = new TestObserver();
Observable<Long> lateObservable = jet().getObservable(observableName);
lateObservable.addObserver(otherTestObserver);
//then
assertSortedValues(testObserver);
assertError(testObserver, "Intentionally thrown!");
assertCompletions(testObserver, 0);
}
@Test
public void errorInOneJobIsNotTerminalForOthers() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
Pipeline pipeline2 = Pipeline.create();
pipeline2.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
Job job2 = jet().newJob(pipeline2);
//then
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job.getStatus()));
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job2.getStatus()));
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
//when
job.cancel();
assertError(testObserver, "CancellationException");
assertCompletions(testObserver, 0);
//then - job2 is still running
int resultsSoFar = testObserver.getNoOfValues();
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > resultsSoFar));
job2.cancel();
}
@Test
public void removedObserverDoesNotGetFurtherEvents() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
//then
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
//when
testObservable.removeObserver(registrationId);
//then
int resultsSoFar = testObserver.getNoOfValues();
assertTrueAllTheTime(() -> assertEquals(resultsSoFar, testObserver.getNoOfValues()), 2);
job.cancel();
}
@Test
public void destroyedObservableDoesNotGetFurtherEvents() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName + "destroyed"));
TestObserver otherTestObserver = new TestObserver();
Observable<Long> destroyedObservable = jet().getObservable(observableName + "destroyed");
destroyedObservable.addObserver(otherTestObserver);
//when
Job job = jet().newJob(pipeline);
//then
assertTrueEventually(() -> assertTrue(otherTestObserver.getNoOfValues() > 10));
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 0);
//when
destroyedObservable.destroy();
//then
int resultsSoFar = otherTestObserver.getNoOfValues();
assertTrueAllTheTime(() -> assertEquals(resultsSoFar, otherTestObserver.getNoOfValues()), 2);
job.cancel();
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 0);
}
@Test
public void fastResultsDoNotGetLost_moreThanBatchSize() {
fastResultsDoNotGetLost(RingbufferProxy.MAX_BATCH_SIZE * 5);
}
@Test
@Ignore //TODO: fast results still can get lost
public void fastResultsDoNotGetLost_moreThanRingbufferCapacity() {
fastResultsDoNotGetLost(250_000);
}
private void fastResultsDoNotGetLost(int noOfResults) {
List<Long> sourceItems = LongStream.range(0, noOfResults)
.boxed()
.collect(Collectors.toList());
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(sourceItems))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(testObserver, sourceItems.toArray(new Long[0]));
assertError(testObserver, null);
assertCompletions(testObserver, 1);
}
@Test
@Ignore //TODO: fast results still can get lost
public void fastResultsDoNotGetLost_whenUsingIterator() throws Exception {
int noOfResults = 250_000;
List<Long> sourceItems = LongStream.range(0, noOfResults)
.boxed()
.collect(Collectors.toList());
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(sourceItems))
.writeTo(Sinks.observable(observableName));
//when
Future<Long> stream = testObservable.toFuture(Stream::count);
jet().newJob(pipeline);
//then
assertEquals(noOfResults, stream.get().longValue());
assertError(testObserver, null);
assertCompletions(testObserver, 1);
}
@Test
public void sinkConsumesThrowables() throws Exception {
Pipeline pipeline = Pipeline.create();
BatchSource<Throwable> input = TestSources.items(
new RuntimeException("runtime_exception"),
new Exception("exception"),
new Error("error"),
new Throwable("throwable")
);
pipeline.readFrom(input)
.writeTo(Sinks.observable("throwables"));
//when
jet().newJob(pipeline).join();
List<Object> results = jet().getObservable("throwables")
.toFuture(s -> {
Comparator<Object> comparator = Comparator.comparing(o -> ((Throwable) o).getMessage());
return s.sorted(comparator).collect(Collectors.toList());
})
.get();
//then
assertEquals(4, results.size());
assertEquals("error", ((Throwable) results.get(0)).getMessage());
assertEquals("exception", ((Throwable) results.get(1)).getMessage());
assertEquals("runtime_exception", ((Throwable) results.get(2)).getMessage());
assertEquals("throwable", ((Throwable) results.get(3)).getMessage());
}
@Test
public void configureCapacity() {
//when
Observable<Object> o = jet().newObservable();
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(o));
//then
o.configureCapacity(20_000); //still possible, pipeline not executing yet
assertThrowsException(o::getConfiguredCapacity, IllegalStateException.class);
//when
Job job = jet().newJob(pipeline);
assertExecutionStarted(job);
//then
assertThrowsException(() -> o.configureCapacity(30_000), IllegalStateException.class);
assertEquals(20_000, o.getConfiguredCapacity());
//when
job.join();
///then
assertThrowsException(() -> o.configureCapacity(30_000), IllegalStateException.class);
assertEquals(20_000, o.getConfiguredCapacity());
}
@Test
public void configureCapacityMultipleTimes() {
Observable<Object> o = jet().newObservable();
o.configureCapacity(10);
assertThrowsException(() -> o.configureCapacity(20), RuntimeException.class);
}
@Test
public void unnamedObservable() {
Observable<Long> unnamedObservable = jet().newObservable();
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(unnamedObservable));
TestObserver observer = new TestObserver();
unnamedObservable.addObserver(observer);
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(observer, 0L, 1L, 2L, 3L, 4L);
assertError(observer, null);
assertCompletions(observer, 1);
}
@Test
public void onlyObservedObservablesGetActivated() {
//when
Observable<Object> a = jet().newObservable();
Observable<Object> b = jet().newObservable();
Observable<Object> c = jet().newObservable();
a.addObserver(Observer.of(ConsumerEx.noop()));
c.addObserver(Observer.of(ConsumerEx.noop()));
//then
Set<String> activeObservables = jet().getObservables().stream().map(Observable::name).collect(Collectors.toSet());
assertTrue(activeObservables.containsAll(Arrays.asList(a.name(), c.name())));
assertFalse(activeObservables.contains(b.name()));
}
@Test
public void createAndDestroyObservableRepeatedly() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable("repeatedObservable"));
for (int i = 0; i < 20; i++) {
TestObserver repeatedTestObserver = new TestObserver();
Observable<Long> repeatedObservable = jet().getObservable("repeatedObservable");
repeatedObservable.addObserver(repeatedTestObserver);
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(repeatedTestObserver, 0L, 1L, 2L, 3L, 4L);
assertError(repeatedTestObserver, null);
assertCompletions(repeatedTestObserver, 1);
repeatedObservable.destroy();
}
}
private void assertExecutionStarted(Job job) {
assertTrueEventually(() -> assertTrue(JobStatus.RUNNING.equals(job.getStatus())
|| JobStatus.COMPLETED.equals(job.getStatus())));
}
private void assertThrowsException(Runnable action, Class<? extends Throwable> exceptionClass) {
//then
try {
action.run();
fail("Expected exception not thrown");
} catch (Throwable t) {
assertEquals(exceptionClass, t.getClass());
}
}
private static void assertSortedValues(TestObserver observer, Long... values) {
assertTrueEventually(() -> assertEquals(Arrays.asList(values), observer.getSortedValues()));
}
private static void assertError(TestObserver observer, String error) {
if (error == null) {
assertNull(observer.getError());
} else {
assertTrueEventually(() -> {
assertNotNull(observer.getError());
assertTrue(observer.getError().toString().contains(error));
});
}
}
private static void assertCompletions(TestObserver observer, int completions) {
assertTrueEventually(() -> assertEquals(completions, observer.getNoOfCompletions()));
}
private static final class TestObserver implements Observer<Long> {
private final List<Long> values = Collections.synchronizedList(new ArrayList<>());
private final AtomicReference<Throwable> error = new AtomicReference<>();
private final AtomicInteger completions = new AtomicInteger();
@Override
public void onNext(@Nonnull Long value) {
values.add(value);
}
@Override
public void onError(@Nonnull Throwable throwable) {
error.set(throwable);
}
@Override
public void onComplete() {
completions.incrementAndGet();
}
int getNoOfValues() {
synchronized (values) {
return values.size();
}
}
@Nonnull
List<Long> getSortedValues() {
List<Long> sortedValues;
synchronized (values) {
sortedValues = new ArrayList<>(values);
}
sortedValues.sort(Long::compare);
return sortedValues;
}
@Nullable
Throwable getError() {
return error.get();
}
int getNoOfCompletions() {
return completions.get();
}
}
}
| hazelcast-jet-core/src/test/java/com/hazelcast/jet/core/ObservableResultsTest.java | /*
* Copyright (c) 2008-2020, 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.jet.core;
import com.hazelcast.function.ConsumerEx;
import com.hazelcast.jet.Job;
import com.hazelcast.jet.Observable;
import com.hazelcast.jet.TestInClusterSupport;
import com.hazelcast.jet.function.Observer;
import com.hazelcast.jet.pipeline.BatchSource;
import com.hazelcast.jet.pipeline.BatchStage;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.SourceBuilder;
import com.hazelcast.jet.pipeline.test.SimpleEvent;
import com.hazelcast.jet.pipeline.test.TestSources;
import com.hazelcast.ringbuffer.impl.RingbufferProxy;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ObservableResultsTest extends TestInClusterSupport {
private String observableName;
private TestObserver testObserver;
private Observable<Long> testObservable;
private UUID registrationId;
private Set<Observable<?>> usedObservables;
@Before
public void before() {
usedObservables = new HashSet<>();
observableName = randomName();
testObserver = new TestObserver();
testObservable = getObservable(observableName);
registrationId = testObservable.addObserver(testObserver);
}
@After
public void after() {
usedObservables.forEach(Observable::destroy);
}
@Test
public void iterable() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
//then
List<Long> items = new ArrayList<>();
for (Long item : testObservable) {
items.add(item);
}
items.sort(Long::compareTo);
assertEquals(Arrays.asList(0L, 1L, 2L, 3L, 4L), items);
}
@Test
public void batchJobCompletesSuccessfully() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(testObserver, 0L, 1L, 2L, 3L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 1);
}
@Test
public void batchJobFails() {
BatchSource<String> errorSource = SourceBuilder
.batch("error-source", x -> null)
.<String>fillBufferFn((in, Void) -> {
throw new Exception("Intentionally thrown!");
})
.destroyFn(ConsumerEx.noop())
.build();
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(errorSource)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
assertTrueEventually(() -> assertEquals(JobStatus.FAILED, job.getStatus()));
//then
assertSortedValues(testObserver);
assertError(testObserver, "Intentionally thrown!");
assertCompletions(testObserver, 0);
}
@Test
public void streamJob() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
//then
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
//when
job.cancel();
//then
assertError(testObserver, "CancellationException");
assertCompletions(testObserver, 0);
}
@Test
public void streamJobRestart() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
//then
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
//when
job.restart();
//then
int resultsSoFar = testObserver.getNoOfValues();
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job.getStatus()));
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > resultsSoFar));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
}
@Test
public void multipleObservables() {
Pipeline pipeline = Pipeline.create();
BatchStage<Long> stage = pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L));
TestObserver otherTestObserver = new TestObserver();
Observable<Long> otherObservable = getObservable("otherObservable");
otherObservable.addObserver(otherTestObserver);
stage.filter(i -> i % 2 == 0).writeTo(Sinks.observable(observableName));
stage.filter(i -> i % 2 != 0).writeTo(Sinks.observable("otherObservable"));
//when
Job job = jet().newJob(pipeline);
job.join();
//then
assertSortedValues(testObserver, 0L, 2L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 1);
//also
assertSortedValues(otherTestObserver, 1L, 3L);
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 1);
}
@Test
public void multipleIdenticalSinks() {
Pipeline pipeline = Pipeline.create();
BatchStage<Long> readStage = pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L));
readStage.writeTo(Sinks.observable(observableName));
readStage.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
job.join();
//then
assertSortedValues(testObserver, 0L, 0L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 1);
}
@Test
public void multipleJobsWithTheSameSink() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.filter(t -> (t % 2 == 0))
.writeTo(Sinks.observable(observableName));
Pipeline pipeline2 = Pipeline.create();
pipeline2.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.filter(t -> (t % 2 != 0))
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
Job job2 = jet().newJob(pipeline2);
//then
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job.getStatus()));
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job2.getStatus()));
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertTrueEventually(() -> {
List<Long> sortedValues = testObserver.getSortedValues();
assertEquals(0, (long) sortedValues.get(0));
assertEquals(1, (long) sortedValues.get(1));
});
assertError(testObserver, null);
assertCompletions(testObserver, 0);
job.cancel();
job2.cancel();
}
@Test
public void multipleJobExecutions() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
jet().newJob(pipeline).join();
//then
assertSortedValues(testObserver, 0L, 0L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 2);
}
@Test
public void observersGetAllEventsStillInRingbuffer() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(testObserver, 0L, 1L, 2L, 3L, 4L);
assertError(testObserver, null);
assertCompletions(testObserver, 1);
//when
TestObserver otherTestObserver = new TestObserver();
this.<Long>getObservable(observableName).addObserver(otherTestObserver);
//then
assertSortedValues(otherTestObserver, 0L, 1L, 2L, 3L, 4L);
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 1);
}
@Test
public void observableRegisteredAfterJobFinishedGetAllEventsStillInRingbuffer() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(observableName + "late"));
//when
jet().newJob(pipeline).join();
TestObserver otherTestObserver = new TestObserver();
Observable<Long> lateObservable = getObservable(observableName + "late");
lateObservable.addObserver(otherTestObserver);
//then
assertSortedValues(otherTestObserver, 0L, 1L, 2L, 3L, 4L);
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 1);
}
@Test
public void observableRegisteredAfterJobFailedGetError() {
BatchSource<String> errorSource = SourceBuilder
.batch("error-source", x -> null)
.<String>fillBufferFn((in, Void) -> {
throw new Exception("Intentionally thrown!");
})
.destroyFn(ConsumerEx.noop())
.build();
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(errorSource)
.writeTo(Sinks.observable(observableName));
Job job = jet().newJob(pipeline);
assertTrueEventually(() -> assertEquals(JobStatus.FAILED, job.getStatus()));
//when
TestObserver otherTestObserver = new TestObserver();
Observable<Long> lateObservable = getObservable(observableName);
lateObservable.addObserver(otherTestObserver);
//then
assertSortedValues(testObserver);
assertError(testObserver, "Intentionally thrown!");
assertCompletions(testObserver, 0);
}
@Test
public void errorInOneJobIsNotTerminalForOthers() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
Pipeline pipeline2 = Pipeline.create();
pipeline2.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
Job job2 = jet().newJob(pipeline2);
//then
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job.getStatus()));
assertTrueEventually(() -> assertEquals(JobStatus.RUNNING, job2.getStatus()));
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
//when
job.cancel();
assertError(testObserver, "CancellationException");
assertCompletions(testObserver, 0);
//then - job2 is still running
int resultsSoFar = testObserver.getNoOfValues();
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > resultsSoFar));
job2.cancel();
}
@Test
public void removedObserverDoesNotGetFurtherEvents() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName));
//when
Job job = jet().newJob(pipeline);
//then
assertTrueEventually(() -> assertTrue(testObserver.getNoOfValues() > 10));
assertError(testObserver, null);
assertCompletions(testObserver, 0);
//when
testObservable.removeObserver(registrationId);
//then
int resultsSoFar = testObserver.getNoOfValues();
assertTrueAllTheTime(() -> assertEquals(resultsSoFar, testObserver.getNoOfValues()), 2);
job.cancel();
}
@Test
public void destroyedObservableDoesNotGetFurtherEvents() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.itemStream(100))
.withoutTimestamps()
.map(SimpleEvent::sequence)
.writeTo(Sinks.observable(observableName + "destroyed"));
TestObserver otherTestObserver = new TestObserver();
Observable<Long> destroyedObservable = jet().getObservable(observableName + "destroyed");
destroyedObservable.addObserver(otherTestObserver);
//when
Job job = jet().newJob(pipeline);
//then
assertTrueEventually(() -> assertTrue(otherTestObserver.getNoOfValues() > 10));
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 0);
//when
destroyedObservable.destroy();
//then
int resultsSoFar = otherTestObserver.getNoOfValues();
assertTrueAllTheTime(() -> assertEquals(resultsSoFar, otherTestObserver.getNoOfValues()), 2);
job.cancel();
assertError(otherTestObserver, null);
assertCompletions(otherTestObserver, 0);
}
@Test
public void fastResultsDoNotGetLost_moreThanBatchSize() {
fastResultsDoNotGetLost(RingbufferProxy.MAX_BATCH_SIZE * 5);
}
@Test
@Ignore //TODO: fast results still can get lost
public void fastResultsDoNotGetLost_moreThanRingbufferCapacity() {
fastResultsDoNotGetLost(250_000);
}
private void fastResultsDoNotGetLost(int noOfResults) {
List<Long> sourceItems = LongStream.range(0, noOfResults)
.boxed()
.collect(Collectors.toList());
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(sourceItems))
.writeTo(Sinks.observable(observableName));
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(testObserver, sourceItems.toArray(new Long[0]));
assertError(testObserver, null);
assertCompletions(testObserver, 1);
}
@Test
@Ignore //TODO: fast results still can get lost
public void fastResultsDoNotGetLost_whenUsingIterator() throws Exception {
int noOfResults = 250_000;
List<Long> sourceItems = LongStream.range(0, noOfResults)
.boxed()
.collect(Collectors.toList());
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(sourceItems))
.writeTo(Sinks.observable(observableName));
//when
Future<Long> stream = testObservable.toFuture(Stream::count);
jet().newJob(pipeline);
//then
assertEquals(noOfResults, stream.get().longValue());
assertError(testObserver, null);
assertCompletions(testObserver, 1);
}
@Test
public void sinkConsumesThrowables() throws Exception {
Pipeline pipeline = Pipeline.create();
BatchSource<Throwable> input = TestSources.items(
new RuntimeException("runtime_exception"),
new Exception("exception"),
new Error("error"),
new Throwable("throwable")
);
pipeline.readFrom(input)
.writeTo(Sinks.observable("throwables"));
//when
jet().newJob(pipeline).join();
List<Object> results = getObservable("throwables")
.toFuture(s -> {
Comparator<Object> comparator = Comparator.comparing(o -> ((Throwable) o).getMessage());
return s.sorted(comparator).collect(Collectors.toList());
})
.get();
//then
assertEquals(4, results.size());
assertEquals("error", ((Throwable) results.get(0)).getMessage());
assertEquals("exception", ((Throwable) results.get(1)).getMessage());
assertEquals("runtime_exception", ((Throwable) results.get(2)).getMessage());
assertEquals("throwable", ((Throwable) results.get(3)).getMessage());
}
@Test
public void configureCapacity() {
//when
Observable<Object> o = newObservable();
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(o));
//then
o.configureCapacity(20_000); //still possible, pipeline not executing yet
assertThrowsException(o::getConfiguredCapacity, IllegalStateException.class);
//when
Job job = jet().newJob(pipeline);
assertExecutionStarted(job);
//then
assertThrowsException(() -> o.configureCapacity(30_000), IllegalStateException.class);
assertEquals(20_000, o.getConfiguredCapacity());
//when
job.join();
///then
assertThrowsException(() -> o.configureCapacity(30_000), IllegalStateException.class);
assertEquals(20_000, o.getConfiguredCapacity());
}
@Test
public void configureCapacityMultipleTimes() {
Observable<Object> o = newObservable();
o.configureCapacity(10);
assertThrowsException(() -> o.configureCapacity(20), RuntimeException.class);
}
@Test
public void unnamedObservable() {
Observable<Long> unnamedObservable = newObservable();
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable(unnamedObservable));
TestObserver observer = new TestObserver();
unnamedObservable.addObserver(observer);
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(observer, 0L, 1L, 2L, 3L, 4L);
assertError(observer, null);
assertCompletions(observer, 1);
}
@Test
public void getObservables() {
//when
getObservable("a").addObserver(Observer.of(ConsumerEx.noop()));
getObservable("b");
getObservable("c").addObserver(Observer.of(ConsumerEx.noop()));
//then
Set<String> activeObservables = jet().getObservables().stream().map(Observable::name).collect(Collectors.toSet());
assertTrue(activeObservables.containsAll(Arrays.asList("a", "c")));
}
@Test
public void createAndDestroyObservableRepeatedly() {
Pipeline pipeline = Pipeline.create();
pipeline.readFrom(TestSources.items(0L, 1L, 2L, 3L, 4L))
.writeTo(Sinks.observable("repeatedObservable"));
for (int i = 0; i < 20; i++) {
TestObserver repeatedTestObserver = new TestObserver();
Observable<Long> repeatedObservable = getObservable("repeatedObservable");
repeatedObservable.addObserver(repeatedTestObserver);
//when
jet().newJob(pipeline).join();
//then
assertSortedValues(repeatedTestObserver, 0L, 1L, 2L, 3L, 4L);
assertError(repeatedTestObserver, null);
assertCompletions(repeatedTestObserver, 1);
repeatedObservable.destroy();
}
}
private void assertExecutionStarted(Job job) {
assertTrueEventually(() -> assertTrue(JobStatus.RUNNING.equals(job.getStatus())
|| JobStatus.COMPLETED.equals(job.getStatus())));
}
private void assertThrowsException(Runnable action, Class<? extends Throwable> exceptionClass) {
//then
try {
action.run();
fail("Expected exception not thrown");
} catch (Throwable t) {
assertEquals(exceptionClass, t.getClass());
}
}
private <T> Observable<T> newObservable() {
Observable<T> observable = jet().newObservable();
usedObservables.add(observable);
return observable;
}
private <T> Observable<T> getObservable(String name) {
Observable<T> observable = jet().getObservable(name);
usedObservables.add(observable);
return observable;
}
private static void assertSortedValues(TestObserver observer, Long... values) {
assertTrueEventually(() -> assertEquals(Arrays.asList(values), observer.getSortedValues()));
}
private static void assertError(TestObserver observer, String error) {
if (error == null) {
assertNull(observer.getError());
} else {
assertTrueEventually(() -> {
assertNotNull(observer.getError());
assertTrue(observer.getError().toString().contains(error));
});
}
}
private static void assertCompletions(TestObserver observer, int completions) {
assertTrueEventually(() -> assertEquals(completions, observer.getNoOfCompletions()));
}
private static final class TestObserver implements Observer<Long> {
private final List<Long> values = Collections.synchronizedList(new ArrayList<>());
private final AtomicReference<Throwable> error = new AtomicReference<>();
private final AtomicInteger completions = new AtomicInteger();
@Override
public void onNext(@Nonnull Long value) {
values.add(value);
}
@Override
public void onError(@Nonnull Throwable throwable) {
error.set(throwable);
}
@Override
public void onComplete() {
completions.incrementAndGet();
}
int getNoOfValues() {
synchronized (values) {
return values.size();
}
}
@Nonnull
List<Long> getSortedValues() {
List<Long> sortedValues;
synchronized (values) {
sortedValues = new ArrayList<>(values);
}
sortedValues.sort(Long::compare);
return sortedValues;
}
@Nullable
Throwable getError() {
return error.get();
}
int getNoOfCompletions() {
return completions.get();
}
}
}
| Attempt to fix Observable tests (#2172)
| hazelcast-jet-core/src/test/java/com/hazelcast/jet/core/ObservableResultsTest.java | Attempt to fix Observable tests (#2172) |
|
Java | apache-2.0 | 74d4988be4ce16b290efb0bce79a1c3ff797147f | 0 | apache/directory-server,drankye/directory-server,darranl/directory-server,apache/directory-server,lucastheisen/apache-directory-server,darranl/directory-server,drankye/directory-server,lucastheisen/apache-directory-server | /*
* 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.directory.server.ldap.support.extended;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
import javax.swing.JFrame;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.interceptor.context.EmptyOperationContext;
import org.apache.directory.server.core.jndi.ServerLdapContext;
import org.apache.directory.server.core.partition.Partition;
import org.apache.directory.server.core.partition.PartitionNexus;
import org.apache.directory.server.core.partition.impl.btree.BTreePartition;
import org.apache.directory.server.core.partition.impl.btree.gui.PartitionFrame;
import org.apache.directory.server.ldap.ExtendedOperationHandler;
import org.apache.directory.server.ldap.LdapProtocolProvider;
import org.apache.directory.server.ldap.SessionRegistry;
import org.apache.directory.server.ldap.gui.SessionsFrame;
import org.apache.directory.shared.ldap.message.ExtendedRequest;
import org.apache.directory.shared.ldap.message.ResultCodeEnum;
import org.apache.directory.shared.ldap.message.extended.LaunchDiagnosticUiRequest;
import org.apache.directory.shared.ldap.message.extended.LaunchDiagnosticUiResponse;
import org.apache.directory.shared.ldap.name.LdapDN;
import org.apache.mina.common.IoSession;
public class LaunchDiagnosticUiHandler implements ExtendedOperationHandler
{
public static final Set EXTENSION_OIDS;
static
{
Set set = new HashSet( 3 );
set.add( LaunchDiagnosticUiRequest.EXTENSION_OID );
set.add( LaunchDiagnosticUiResponse.EXTENSION_OID );
EXTENSION_OIDS = Collections.unmodifiableSet( set );
}
private LdapProtocolProvider ldapProvider;
public String getOid()
{
return LaunchDiagnosticUiRequest.EXTENSION_OID;
}
public void handleExtendedOperation( IoSession requestor, SessionRegistry registry, ExtendedRequest req )
throws NamingException
{
LdapContext ctx = registry.getLdapContext( requestor, null, false );
ctx = ( LdapContext ) ctx.lookup( "" );
if ( ctx instanceof ServerLdapContext )
{
ServerLdapContext slc = ( ServerLdapContext ) ctx;
DirectoryService service = slc.getService();
if ( !slc.getPrincipal().getName().equalsIgnoreCase( PartitionNexus.ADMIN_PRINCIPAL_NORMALIZED ) )
{
requestor.write( new LaunchDiagnosticUiResponse( req.getMessageId(),
ResultCodeEnum.INSUFFICIENT_ACCESS_RIGHTS ) );
return;
}
requestor.write( new LaunchDiagnosticUiResponse( req.getMessageId() ) );
PartitionNexus nexus = service.getConfiguration().getPartitionNexus();
Iterator list = nexus.listSuffixes( new EmptyOperationContext() );
int launchedWindowCount = 0;
while ( list.hasNext() )
{
LdapDN dn = new LdapDN( ( String ) list.next() );
Partition partition = nexus.getPartition( dn );
if ( partition instanceof BTreePartition )
{
BTreePartition btPartition = ( BTreePartition ) partition;
PartitionFrame frame = new PartitionFrame( btPartition, btPartition.getSearchEngine() );
Point pos = getCenteredPosition( frame );
pos.y = launchedWindowCount * 20 + pos.y;
double multiplier = getAspectRatio() * 20.0;
pos.x = ( int ) ( launchedWindowCount * multiplier ) + pos.x;
frame.setLocation( pos );
frame.setVisible( true );
launchedWindowCount++;
}
}
SessionsFrame sessions = new SessionsFrame();
sessions.setRequestor( requestor );
sessions.setLdapProvider( ldapProvider.getHandler() );
Point pos = getCenteredPosition( sessions );
pos.y = launchedWindowCount * 20 + pos.y;
double multiplier = getAspectRatio() * 20.0;
pos.x = ( int ) ( launchedWindowCount * multiplier ) + pos.x;
sessions.setLocation( pos );
sessions.setVisible( true );
return;
}
requestor.write( new LaunchDiagnosticUiResponse( req.getMessageId(), ResultCodeEnum.OPERATIONS_ERROR ) );
}
public double getAspectRatio()
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
return screenSize.getWidth() / screenSize.getHeight();
}
public Point getCenteredPosition( JFrame frame )
{
Point pt = new Point();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
pt.x = ( screenSize.width - frame.getWidth() ) / 2;
pt.y = ( screenSize.height - frame.getHeight() ) / 2;
return pt;
}
public Set getExtensionOids()
{
return EXTENSION_OIDS;
}
public void setLdapProvider( LdapProtocolProvider provider )
{
this.ldapProvider = provider;
}
}
| protocol-ldap/src/main/java/org/apache/directory/server/ldap/support/extended/LaunchDiagnosticUiHandler.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.directory.server.ldap.support.extended;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
import javax.swing.JFrame;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.interceptor.context.EmptyServiceContext;
import org.apache.directory.server.core.jndi.ServerLdapContext;
import org.apache.directory.server.core.partition.Partition;
import org.apache.directory.server.core.partition.PartitionNexus;
import org.apache.directory.server.core.partition.impl.btree.BTreePartition;
import org.apache.directory.server.core.partition.impl.btree.gui.PartitionFrame;
import org.apache.directory.server.ldap.ExtendedOperationHandler;
import org.apache.directory.server.ldap.LdapProtocolProvider;
import org.apache.directory.server.ldap.SessionRegistry;
import org.apache.directory.server.ldap.gui.SessionsFrame;
import org.apache.directory.shared.ldap.message.ExtendedRequest;
import org.apache.directory.shared.ldap.message.ResultCodeEnum;
import org.apache.directory.shared.ldap.message.extended.LaunchDiagnosticUiRequest;
import org.apache.directory.shared.ldap.message.extended.LaunchDiagnosticUiResponse;
import org.apache.directory.shared.ldap.name.LdapDN;
import org.apache.mina.common.IoSession;
public class LaunchDiagnosticUiHandler implements ExtendedOperationHandler
{
public static final Set EXTENSION_OIDS;
static
{
Set set = new HashSet( 3 );
set.add( LaunchDiagnosticUiRequest.EXTENSION_OID );
set.add( LaunchDiagnosticUiResponse.EXTENSION_OID );
EXTENSION_OIDS = Collections.unmodifiableSet( set );
}
private LdapProtocolProvider ldapProvider;
public String getOid()
{
return LaunchDiagnosticUiRequest.EXTENSION_OID;
}
public void handleExtendedOperation( IoSession requestor, SessionRegistry registry, ExtendedRequest req )
throws NamingException
{
LdapContext ctx = registry.getLdapContext( requestor, null, false );
ctx = ( LdapContext ) ctx.lookup( "" );
if ( ctx instanceof ServerLdapContext )
{
ServerLdapContext slc = ( ServerLdapContext ) ctx;
DirectoryService service = slc.getService();
if ( !slc.getPrincipal().getName().equalsIgnoreCase( PartitionNexus.ADMIN_PRINCIPAL_NORMALIZED ) )
{
requestor.write( new LaunchDiagnosticUiResponse( req.getMessageId(),
ResultCodeEnum.INSUFFICIENT_ACCESS_RIGHTS ) );
return;
}
requestor.write( new LaunchDiagnosticUiResponse( req.getMessageId() ) );
PartitionNexus nexus = service.getConfiguration().getPartitionNexus();
Iterator list = nexus.listSuffixes( new EmptyServiceContext() );
int launchedWindowCount = 0;
while ( list.hasNext() )
{
LdapDN dn = new LdapDN( ( String ) list.next() );
Partition partition = nexus.getPartition( dn );
if ( partition instanceof BTreePartition )
{
BTreePartition btPartition = ( BTreePartition ) partition;
PartitionFrame frame = new PartitionFrame( btPartition, btPartition.getSearchEngine() );
Point pos = getCenteredPosition( frame );
pos.y = launchedWindowCount * 20 + pos.y;
double multiplier = getAspectRatio() * 20.0;
pos.x = ( int ) ( launchedWindowCount * multiplier ) + pos.x;
frame.setLocation( pos );
frame.setVisible( true );
launchedWindowCount++;
}
}
SessionsFrame sessions = new SessionsFrame();
sessions.setRequestor( requestor );
sessions.setLdapProvider( ldapProvider.getHandler() );
Point pos = getCenteredPosition( sessions );
pos.y = launchedWindowCount * 20 + pos.y;
double multiplier = getAspectRatio() * 20.0;
pos.x = ( int ) ( launchedWindowCount * multiplier ) + pos.x;
sessions.setLocation( pos );
sessions.setVisible( true );
return;
}
requestor.write( new LaunchDiagnosticUiResponse( req.getMessageId(), ResultCodeEnum.OPERATIONS_ERROR ) );
}
public double getAspectRatio()
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
return screenSize.getWidth() / screenSize.getHeight();
}
public Point getCenteredPosition( JFrame frame )
{
Point pt = new Point();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
pt.x = ( screenSize.width - frame.getWidth() ) / 2;
pt.y = ( screenSize.height - frame.getHeight() ) / 2;
return pt;
}
public Set getExtensionOids()
{
return EXTENSION_OIDS;
}
public void setLdapProvider( LdapProtocolProvider provider )
{
this.ldapProvider = provider;
}
}
| Added a ListOperationContext
Switched from ServiceContext to OperationContext for every contexts, as suggested by Alex
Used opContext in arguments instead of xxxContext like listContext, lookupContext, etc.
git-svn-id: 90776817adfbd895fc5cfa90f675377e0a62e745@529047 13f79535-47bb-0310-9956-ffa450edef68
| protocol-ldap/src/main/java/org/apache/directory/server/ldap/support/extended/LaunchDiagnosticUiHandler.java | Added a ListOperationContext Switched from ServiceContext to OperationContext for every contexts, as suggested by Alex Used opContext in arguments instead of xxxContext like listContext, lookupContext, etc. |
|
Java | apache-2.0 | b953a4b6ff65e4a8f490cbd55c62d81247638499 | 0 | vgaleano1/conversation-discovery-app,vgaleano1/conversation-discovery-app,vgaleano1/conversation-discovery-app,vgaleano1/conversation-discovery-app | /*
* Copyright 2015 IBM Corp. 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.ibm.watson.apis.conversation_with_discovery.rest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.Gson;
import com.ibm.watson.apis.conversation_with_discovery.discovery.DiscoveryClient;
import com.ibm.watson.apis.conversation_with_discovery.payload.DocumentPayload;
import com.ibm.watson.apis.conversation_with_discovery.utils.Constants;
import com.ibm.watson.apis.conversation_with_discovery.utils.Messages;
import com.ibm.watson.developer_cloud.conversation.v1.ConversationService;
import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest;
import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse;
import com.ibm.watson.developer_cloud.service.exception.UnauthorizedException;
import com.ibm.watson.developer_cloud.util.GsonSingleton;
/**
* The Class ProxyResource.
*/
@Path("conversation/api/v1/workspaces")
public class ProxyResource {
private static String API_VERSION;
private static final String ERROR = "error";
private static final Logger logger = LogManager.getLogger(ProxyResource.class.getName());
private DiscoveryClient discoveryClient = new DiscoveryClient();
private String password = System.getenv("CONVERSATION_PASSWORD");
private String url;
private String username = System.getenv("CONVERSATION_USERNAME");
private MessageRequest buildMessageFromPayload(InputStream body) {
StringBuilder sbuilder = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(body, "UTF-8"));
sbuilder = new StringBuilder();
String str = reader.readLine();
while (str != null) {
sbuilder.append(str);
str = reader.readLine();
if (str != null) {
sbuilder.append("\n");
}
}
return GsonSingleton.getGson().fromJson(sbuilder.toString(), MessageRequest.class);
} catch (IOException e) {
logger.error(Messages.getString("ProxyResource.JSON_READ"), e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
logger.error(Messages.getString("ProxyResource.STREAM_CLOSE"), e);
}
}
return null;
}
/**
* This method is responsible for sending the query the user types into the UI to the Watson services. The code
* demonstrates how the conversation service is called, how the response is evaluated, and how the response is then
* sent to the discovery service if necessary.
*
* @param request The full query the user asked of Watson
* @param id The ID of the conversational workspace
* @return The response from Watson. The response will always contain the conversation service's response. If the
* intent confidence is high or the intent is out_of_scope, the response will also contain information from
* the discovery service
*/
private MessageResponse getWatsonResponse(MessageRequest request, String id) throws Exception {
// Configure the Watson Developer Cloud SDK to make a call to the
// appropriate conversation service.
ConversationService service =
new ConversationService(API_VERSION != null ? API_VERSION : ConversationService.VERSION_DATE_2016_09_20);
if ((username != null) || (password != null)) {
service.setUsernameAndPassword(username, password);
}
System.out.println("Url: "+Constants.CONVERSATION_URL );
service.setEndPoint(url == null ? Constants.CONVERSATION_URL : url);
// Use the previously configured service object to make a call to the
// conversational service
MessageResponse response = service.message(id, request).execute();
// Determine if conversation's response is sufficient to answer the
// user's question or if we
// should call the discovery service to obtain better answers
System.out.println("Response "+response.getOutput());
if (response.getOutput().containsKey("action")
&& (response.getOutput().get("action").toString().indexOf("call_discovery") != -1)) {
String query = response.getInputText();
// Extract the user's original query from the conversational
// response
if ((query != null) && !query.isEmpty()) {
// For this app, both the original conversation response and the
// discovery response
// are sent to the UI. Extract and add the conversational
// response to the ultimate response
// we will send to the user. The UI will process this response
// and show the top 3 retrieve
// and rank answers to the user in the main UI. The JSON
// response section of the UI will
// show information from the calls to both services.
Map<String, Object> output = response.getOutput();
if (output == null) {
output = new HashMap<String, Object>();
response.setOutput(output);
}
// Send the user's question to the discovery service
System.out.println("Se conecto con Discovery!");
List<DocumentPayload> docs = discoveryClient.getDocuments("Ford");
// Append the discovery answers to the output object that will
// be sent to the UI
output.put("CEPayload", docs);
response.setOutput(output);
}
}
return response;
}
/**
* Post message.
*
* @param id the id
* @param body the body
* @return the response
*/
@POST
@Path("{id}/message")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postMessage(@PathParam("id") String id, InputStream body) {
HashMap<String, Object> errorsOutput = new HashMap<String, Object>();
MessageRequest request = buildMessageFromPayload(body);
if (request == null) {
throw new IllegalArgumentException(Messages.getString("ProxyResource.NO_REQUEST"));
}
MessageResponse response = null;
try {
response = getWatsonResponse(request, id);
} catch (Exception e) {
if (e instanceof UnauthorizedException) {
errorsOutput.put(ERROR, Messages.getString("ProxyResource.INVALID_CONVERSATION_CREDS"));
} else if (e instanceof IllegalArgumentException) {
errorsOutput.put(ERROR, e.getMessage());
} else if (e instanceof MalformedURLException) {
errorsOutput.put(ERROR, Messages.getString("ProxyResource.MALFORMED_URL"));
} else if (e.getMessage().contains("URL workspaceid parameter is not a valid GUID.")) {
errorsOutput.put(ERROR, Messages.getString("ProxyResource.INVALID_WORKSPACEID"));
} else {
e.printStackTrace();
errorsOutput.put(ERROR, Messages.getString("ProxyResource.GENERIC_ERROR"));
}
logger.error(Messages.getString("ProxyResource.QUERY_EXCEPTION") + e.getMessage());
return Response.ok(new Gson().toJson(errorsOutput, HashMap.class)).type(MediaType.APPLICATION_JSON).build();
}
return Response.ok(new Gson().toJson(response, MessageResponse.class)).type(MediaType.APPLICATION_JSON).build();
}
/**
* Sets the conversation API version.
*
* @param version the new conversation API version
*/
public static void setConversationAPIVersion(String version) {
API_VERSION = version;
}
/**
* Sets the credentials.
*
* @param username the username
* @param password the password
* @param url the url
*/
public void setCredentials(String username, String password, String url) {
this.username = username;
this.password = password;
this.url = url;
}
}
| src/main/java/com/ibm/watson/apis/conversation_with_discovery/rest/ProxyResource.java | /*
* Copyright 2015 IBM Corp. 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.ibm.watson.apis.conversation_with_discovery.rest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.Gson;
import com.ibm.watson.apis.conversation_with_discovery.discovery.DiscoveryClient;
import com.ibm.watson.apis.conversation_with_discovery.payload.DocumentPayload;
import com.ibm.watson.apis.conversation_with_discovery.utils.Constants;
import com.ibm.watson.apis.conversation_with_discovery.utils.Messages;
import com.ibm.watson.developer_cloud.conversation.v1.ConversationService;
import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest;
import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse;
import com.ibm.watson.developer_cloud.service.exception.UnauthorizedException;
import com.ibm.watson.developer_cloud.util.GsonSingleton;
/**
* The Class ProxyResource.
*/
@Path("conversation/api/v1/workspaces")
public class ProxyResource {
private static String API_VERSION;
private static final String ERROR = "error";
private static final Logger logger = LogManager.getLogger(ProxyResource.class.getName());
private DiscoveryClient discoveryClient = new DiscoveryClient();
private String password = System.getenv("CONVERSATION_PASSWORD");
private String url;
private String username = System.getenv("CONVERSATION_USERNAME");
private MessageRequest buildMessageFromPayload(InputStream body) {
StringBuilder sbuilder = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(body, "UTF-8"));
sbuilder = new StringBuilder();
String str = reader.readLine();
while (str != null) {
sbuilder.append(str);
str = reader.readLine();
if (str != null) {
sbuilder.append("\n");
}
}
return GsonSingleton.getGson().fromJson(sbuilder.toString(), MessageRequest.class);
} catch (IOException e) {
logger.error(Messages.getString("ProxyResource.JSON_READ"), e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
logger.error(Messages.getString("ProxyResource.STREAM_CLOSE"), e);
}
}
return null;
}
/**
* This method is responsible for sending the query the user types into the UI to the Watson services. The code
* demonstrates how the conversation service is called, how the response is evaluated, and how the response is then
* sent to the discovery service if necessary.
*
* @param request The full query the user asked of Watson
* @param id The ID of the conversational workspace
* @return The response from Watson. The response will always contain the conversation service's response. If the
* intent confidence is high or the intent is out_of_scope, the response will also contain information from
* the discovery service
*/
private MessageResponse getWatsonResponse(MessageRequest request, String id) throws Exception {
// Configure the Watson Developer Cloud SDK to make a call to the
// appropriate conversation service.
ConversationService service =
new ConversationService(API_VERSION != null ? API_VERSION : ConversationService.VERSION_DATE_2016_09_20);
if ((username != null) || (password != null)) {
service.setUsernameAndPassword(username, password);
}
System.out.println("Url: "+Constants.CONVERSATION_URL );
service.setEndPoint(url == null ? Constants.CONVERSATION_URL : url);
// Use the previously configured service object to make a call to the
// conversational service
MessageResponse response = service.message(id, request).execute();
// Determine if conversation's response is sufficient to answer the
// user's question or if we
// should call the discovery service to obtain better answers
System.out.println("Response "+response.getOutput());
if (response.getOutput().containsKey("action")
&& (response.getOutput().get("action").toString().indexOf("call_discovery") != -1)) {
String query = response.getInputText();
// Extract the user's original query from the conversational
// response
if ((query != null) && !query.isEmpty()) {
// For this app, both the original conversation response and the
// discovery response
// are sent to the UI. Extract and add the conversational
// response to the ultimate response
// we will send to the user. The UI will process this response
// and show the top 3 retrieve
// and rank answers to the user in the main UI. The JSON
// response section of the UI will
// show information from the calls to both services.
Map<String, Object> output = response.getOutput();
if (output == null) {
output = new HashMap<String, Object>();
response.setOutput(output);
}
// Send the user's question to the discovery service
System.out.println("Se conecto con Discovery!");
List<DocumentPayload> docs = discoveryClient.getDocuments("Ford");
// Append the discovery answers to the output object that will
// be sent to the UI
output.put("CEPayload", docs);
}
}
return response;
}
/**
* Post message.
*
* @param id the id
* @param body the body
* @return the response
*/
@POST
@Path("{id}/message")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postMessage(@PathParam("id") String id, InputStream body) {
HashMap<String, Object> errorsOutput = new HashMap<String, Object>();
MessageRequest request = buildMessageFromPayload(body);
if (request == null) {
throw new IllegalArgumentException(Messages.getString("ProxyResource.NO_REQUEST"));
}
MessageResponse response = null;
try {
response = getWatsonResponse(request, id);
} catch (Exception e) {
if (e instanceof UnauthorizedException) {
errorsOutput.put(ERROR, Messages.getString("ProxyResource.INVALID_CONVERSATION_CREDS"));
} else if (e instanceof IllegalArgumentException) {
errorsOutput.put(ERROR, e.getMessage());
} else if (e instanceof MalformedURLException) {
errorsOutput.put(ERROR, Messages.getString("ProxyResource.MALFORMED_URL"));
} else if (e.getMessage().contains("URL workspaceid parameter is not a valid GUID.")) {
errorsOutput.put(ERROR, Messages.getString("ProxyResource.INVALID_WORKSPACEID"));
} else {
e.printStackTrace();
errorsOutput.put(ERROR, Messages.getString("ProxyResource.GENERIC_ERROR"));
}
logger.error(Messages.getString("ProxyResource.QUERY_EXCEPTION") + e.getMessage());
return Response.ok(new Gson().toJson(errorsOutput, HashMap.class)).type(MediaType.APPLICATION_JSON).build();
}
return Response.ok(new Gson().toJson(response, MessageResponse.class)).type(MediaType.APPLICATION_JSON).build();
}
/**
* Sets the conversation API version.
*
* @param version the new conversation API version
*/
public static void setConversationAPIVersion(String version) {
API_VERSION = version;
}
/**
* Sets the credentials.
*
* @param username the username
* @param password the password
* @param url the url
*/
public void setCredentials(String username, String password, String url) {
this.username = username;
this.password = password;
this.url = url;
}
}
| Prueba sin llamar a Discovery
| src/main/java/com/ibm/watson/apis/conversation_with_discovery/rest/ProxyResource.java | Prueba sin llamar a Discovery |
|
Java | apache-2.0 | 71c49f96a76987c0db99109818ce475eb89a8f8a | 0 | ddiroma/pentaho-kettle,wseyler/pentaho-kettle,pentaho/pentaho-kettle,skofra0/pentaho-kettle,skofra0/pentaho-kettle,ddiroma/pentaho-kettle,ddiroma/pentaho-kettle,pentaho/pentaho-kettle,wseyler/pentaho-kettle,pedrofvteixeira/pentaho-kettle,pentaho/pentaho-kettle,wseyler/pentaho-kettle,skofra0/pentaho-kettle,rmansoor/pentaho-kettle,rmansoor/pentaho-kettle,pedrofvteixeira/pentaho-kettle,wseyler/pentaho-kettle,pedrofvteixeira/pentaho-kettle,pentaho/pentaho-kettle,rmansoor/pentaho-kettle,pedrofvteixeira/pentaho-kettle,rmansoor/pentaho-kettle,ddiroma/pentaho-kettle,skofra0/pentaho-kettle | /*!
* HITACHI VANTARA PROPRIETARY AND CONFIDENTIAL
*
* Copyright 2020 Hitachi Vantara. All rights reserved.
*
* NOTICE: All information including source code contained herein is, and
* remains the sole property of Hitachi Vantara and its licensors. The intellectual
* and technical concepts contained herein are proprietary and confidential
* to, and are trade secrets of Hitachi Vantara and may be covered by U.S. and foreign
* patents, or patents in process, and are protected by trade secret and
* copyright laws. The receipt or possession of this source code and/or related
* information does not convey or imply any rights to reproduce, disclose or
* distribute its contents, or to manufacture, use, or sell anything that it
* may describe, in whole or in part. Any reproduction, modification, distribution,
* or public display of this information without the express written authorization
* from Hitachi Vantara is strictly prohibited and in violation of applicable laws and
* international treaties. Access to the source code contained herein is strictly
* prohibited to anyone except those individuals and entities who have executed
* confidentiality and non-disclosure agreements or other agreements with Hitachi Vantara,
* explicitly covering such access.
*/
package org.pentaho.di.ui.core.widget;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.util.StringUtil;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class MultipleSelectionCombo extends Composite {
private Composite topRow = null;
private Text displayText = null;
private Button add = null;
private Button arrow = null;
public Composite getTopRowComposite() {
return topRow;
}
public Text getDisplayText() {
return displayText;
}
public Button getAddButton() {
return add;
}
public Button getArrowButton() {
return arrow;
}
private String[] displayItems;
private int[] comboSelection;
private Shell floatShell = null;
private List list = null;
public String[] getSelectedItemLabels() {
return selectedItemLabels;
}
public void setSelectedItemLabels( String[] selectedItemLabels ) {
this.selectedItemLabels = selectedItemLabels;
}
private String[] selectedItemLabels;
public Composite getBottomRow() {
return bottomRow;
}
public MouseAdapter getExitAction() {
return exitAction;
}
private Composite bottomRow;
private MouseAdapter exitAction;
private static final int MARGIN_OFFSET = 1;
public MultipleSelectionCombo( Composite parent, int style ) {
super( parent, style );
comboSelection = new int[]{};
selectedItemLabels = new String[]{};
displayItems = new String[]{};
init();
}
protected void init() {
GridLayout masterGridLayout = new GridLayout( 1, true );
masterGridLayout.marginBottom = 0;
masterGridLayout.marginTop = 0;
masterGridLayout.verticalSpacing = 0;
setLayout( masterGridLayout );
topRow = new Composite( this, SWT.NONE );
topRow.setLayout( new GridLayout( 4, false ) );
displayText = new Text( topRow, SWT.BORDER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.minimumWidth = 200;
displayText.setLayoutData( gridData );
arrow = new Button( topRow, SWT.ARROW | SWT.DOWN );
arrow.setBackground( Display.getCurrent().getSystemColor( SWT.COLOR_BLUE ) );
arrow.setSize( 25, 25 );
arrow.addMouseListener( new MouseAdapter() {
@Override
public void mouseDown( MouseEvent event ) {
super.mouseDown( event );
if ( floatShell == null || floatShell.isDisposed() ) {
closeOtherFloatShells();
initFloatShell();
} else {
closeShellAndUpdate();
}
}
} );
add = new Button( topRow, SWT.PUSH );
add.setText( "ADD" );
bottomRow = new Composite( this, SWT.NONE );
GridLayout gridLayout = new GridLayout( 2, true );
gridLayout.marginBottom = 0;
gridLayout.marginLeft = 0;
gridLayout.marginRight = 0;
gridLayout.marginTop = 0;
bottomRow.setLayout( gridLayout );
GridData rowGridData = new GridData( SWT.NONE );
rowGridData.widthHint = 297;
rowGridData.minimumWidth = 297;
bottomRow.setLayoutData( rowGridData );
exitAction = new MouseAdapter() {
@Override
public void mouseUp( MouseEvent e ) {
super.mouseUp( e );
String labelText = ((SelectionLabel) ((Label) e.widget).getParent()).getLabelText();
addRemovedTagBackToListUI( labelText );
selectedItemLabels = removeItemFromSelectedList( labelText );
SelectionLabel removedItem = (SelectionLabel) ((Label) e.widget).getParent();
Composite selectionArea = removedItem.getParent();
int decreasedHeight = calculateTotalHeight( removedItem );
removedItem.dispose();
selectionArea.layout( true, true );
int numRemainingItems = selectionArea.getChildren().length;
if ( numRemainingItems % 2 == 0 ) {
updateTagsUI( decreasedHeight );
}
}
};
add.addMouseListener( new MouseAdapter() {
@Override
public void mouseUp( MouseEvent e ) {
super.mouseUp( e );
if ( floatShell != null
&& comboSelection != null
&& comboSelection.length > 0 ) {
Set<String> selectedItems = new HashSet<>( comboSelection.length );
SelectionLabel ref = null;
for ( int i = 0; i < comboSelection.length; i++ ) {
ref = new SelectionLabel( bottomRow, SWT.BORDER, displayItems[comboSelection[i]], exitAction );
selectedItems.add( displayItems[comboSelection[i]] );
}
//remove from display list
displayItems = Arrays.stream( displayItems )
.filter( item -> !selectedItems.contains( item ) )
.toArray( String[]::new );
selectedItemLabels = addToSelectedTags( selectedItems );
if ( ref != null ) {
updateTagsUI( calculateTotalHeight( ref ) );
}
comboSelection = new int[]{};
floatShell.dispose();
}
}
} );
}
private void closeOtherFloatShells() {
Composite parent = this.getParent();
while ( !( parent instanceof Shell ) ) {
Arrays.stream( parent.getChildren() )
.filter( c -> c instanceof MultipleSelectionCombo )
.forEach( c -> ((MultipleSelectionCombo) c).triggerDropdownClose() );
parent = parent.getParent();
}
}
private void addRemovedTagBackToListUI( String labelText ) {
String[] tempItems = new String[displayItems.length + 1];
AtomicInteger idx = new AtomicInteger();
Arrays.stream( displayItems )
.forEach( str -> tempItems[idx.getAndIncrement()] = str );
tempItems[tempItems.length - 1] = labelText;
displayItems = tempItems;
Arrays.sort( displayItems );
}
private String[] removeItemFromSelectedList( String labelText ) {
String[] tempSelectedItems = new String[selectedItemLabels.length - 1];
int tempIdx = 0;
for ( int i = 0; i < selectedItemLabels.length; i++ ) {
if ( !selectedItemLabels[i].equals( labelText ) ) {
tempSelectedItems[tempIdx++] = selectedItemLabels[i];
}
}
return tempSelectedItems;
}
protected int calculateTotalHeight( SelectionLabel label ) {
GridLayout layout = (GridLayout) label.getLayout();
return layout.marginHeight + label.getHeight();
}
protected void updateTagsUI( int height ) {
int numRows = ( selectedItemLabels.length / 2 ) + ( selectedItemLabels.length % 2 );
GridData newData = (GridData) bottomRow.getLayoutData();
newData.minimumHeight = numRows * ( height + MARGIN_OFFSET );
newData.heightHint = numRows * ( height + MARGIN_OFFSET );
bottomRow.setLayoutData( newData );
triggerShellResize();
}
private String[] addToSelectedTags( Set<String> selectedItems ) {
if ( selectedItemLabels.length == 0 ) {
selectedItemLabels = new String[selectedItems.size()];
return selectedItems.toArray( selectedItemLabels );
} else {
String[] tempLabels = new String[selectedItemLabels.length + selectedItems.size()];
int tempIdx = 0;
for ( int i = 0; i < selectedItemLabels.length; i++ ) {
tempLabels[tempIdx++] = selectedItemLabels[i];
}
String[] selectedAry = new String[selectedItems.size()];
selectedItems.toArray( selectedAry );
for ( int i = 0; i < selectedAry.length; i++ ) {
tempLabels[tempIdx++] = selectedAry[i];
}
return tempLabels;
}
}
private void triggerShellResize() {
Composite scrollFinder = findScrollingParent();
if ( scrollFinder != null ) {
scrollFinder.layout( true, true );
Point p = scrollFinder.getSize();
final Point size = scrollFinder.computeSize( p.x, p.y, true );
scrollFinder.setSize( size );
}
}
private Composite findScrollingParent() {
Composite finder = this.getParent();
while ( finder != null && !( finder instanceof ScrolledComposite ) ) {
finder = finder.getParent();
}
return finder;
}
private void initFloatShell() {
Point p = displayText.getParent().toDisplay( displayText.getLocation() );
Point size = displayText.getSize();
Rectangle shellRect = new Rectangle( p.x, p.y + size.y, size.x, 0 );
floatShell = new Shell( MultipleSelectionCombo.this.getShell(),
SWT.NO_TRIM );
GridLayout gl = new GridLayout();
gl.marginBottom = 2;
gl.marginTop = 2;
gl.marginRight = 0;
gl.marginLeft = 0;
gl.marginWidth = 0;
gl.marginHeight = 0;
floatShell.setLayout( gl );
list = new List( floatShell, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL );
for ( String value : displayItems ) {
list.add( value );
}
GridData gd = new GridData( GridData.FILL_BOTH );
list.setLayoutData( gd );
floatShell.setSize( shellRect.width, 100 );
floatShell.setLocation( shellRect.x, shellRect.y );
list.addMouseListener( new MouseAdapter() {
@Override
public void mouseUp( MouseEvent event ) {
super.mouseUp( event );
comboSelection = list.getSelectionIndices();
}
} );
final Listener listener = event -> floatShell.dispose();
Composite scroll = findScrollingParent();
if ( scroll != null ) {
scroll.getVerticalBar().addListener( SWT.Selection, listener );
}
this.getShell().addListener( SWT.Resize, listener );
this.getShell().addListener( SWT.Move, listener );
floatShell.open();
}
private void closeShellAndUpdate() {
if ( floatShell != null && !floatShell.isDisposed() ) {
comboSelection = list.getSelectionIndices();
floatShell.dispose();
}
}
private void bindDataToUI() {
Set<String> selectedSet = new HashSet<>( selectedItemLabels.length );
for ( String label : selectedItemLabels ) {
new SelectionLabel( bottomRow, SWT.BORDER, label, exitAction );
selectedSet.add( label );
}
displayItems = Arrays.stream( displayItems )
.filter( item -> !selectedSet.contains( item ) )
.toArray( String[]::new );
triggerShellResize();
}
public void setItems( String[] items ) {
Arrays.sort( items );
this.displayItems = Arrays.stream( items ).toArray( String[]::new );
}
/**
* Serializes all selected tags in comma separated list to be returned
* and saved in the steps metadata
*
* @return comma separated string of all selected tags
*/
public String getSelectedItems() {
return String.join( ",", selectedItemLabels );
}
/**
* Takes a comma separated string of tags and binds it to the data object
* Then updates the UI for both the tag dropdown and the selected items
*
* @param selectedItems
*/
public void setSelectedItems( String selectedItems ) {
if ( !StringUtil.isEmpty( selectedItems ) ) {
this.selectedItemLabels = selectedItems.split( "," );
bindDataToUI();
}
}
/**
* Public interface for other dropdowns or components
* to trigger open dropdowns to close
*/
public void triggerDropdownClose() {
if ( floatShell != null && !floatShell.isDisposed() ) {
floatShell.dispose();
}
}
/**
* @deprecated
* Simply a convenience interface to keep backward compatibility
*/
@Deprecated
public String getText() {
return this.getSelectedItems();
}
/**
* @deprecated
* Simply a convenience interface to keep backward compatibility
* @param selectedItems
*/
@Deprecated
public void setText( String selectedItems ) {
this.setSelectedItems( selectedItems );
}
}
| ui/src/main/java/org/pentaho/di/ui/core/widget/MultipleSelectionCombo.java | /*!
* HITACHI VANTARA PROPRIETARY AND CONFIDENTIAL
*
* Copyright 2020 Hitachi Vantara. All rights reserved.
*
* NOTICE: All information including source code contained herein is, and
* remains the sole property of Hitachi Vantara and its licensors. The intellectual
* and technical concepts contained herein are proprietary and confidential
* to, and are trade secrets of Hitachi Vantara and may be covered by U.S. and foreign
* patents, or patents in process, and are protected by trade secret and
* copyright laws. The receipt or possession of this source code and/or related
* information does not convey or imply any rights to reproduce, disclose or
* distribute its contents, or to manufacture, use, or sell anything that it
* may describe, in whole or in part. Any reproduction, modification, distribution,
* or public display of this information without the express written authorization
* from Hitachi Vantara is strictly prohibited and in violation of applicable laws and
* international treaties. Access to the source code contained herein is strictly
* prohibited to anyone except those individuals and entities who have executed
* confidentiality and non-disclosure agreements or other agreements with Hitachi Vantara,
* explicitly covering such access.
*/
package org.pentaho.di.ui.core.widget;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.util.StringUtil;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class MultipleSelectionCombo extends Composite {
private Composite topRow = null;
private Text displayText = null;
private Button add = null;
private Button arrow = null;
public Composite getTopRowComposite() {
return topRow;
}
public Text getDisplayText() {
return displayText;
}
public Button getAddButton() {
return add;
}
public Button getArrowButton() {
return arrow;
}
private String[] displayItems;
private int[] comboSelection;
private Shell floatShell = null;
private List list = null;
public String[] getSelectedItemLabels() {
return selectedItemLabels;
}
public void setSelectedItemLabels( String[] selectedItemLabels ) {
this.selectedItemLabels = selectedItemLabels;
}
private String[] selectedItemLabels;
public Composite getBottomRow() {
return bottomRow;
}
public MouseAdapter getExitAction() {
return exitAction;
}
private Composite bottomRow;
private MouseAdapter exitAction;
private static final int MARGIN_OFFSET = 1;
public MultipleSelectionCombo( Composite parent, int style ) {
super( parent, style );
comboSelection = new int[]{};
selectedItemLabels = new String[]{};
displayItems = new String[]{};
init();
}
protected void init() {
GridLayout masterGridLayout = new GridLayout( 1, true );
masterGridLayout.marginBottom = 0;
masterGridLayout.marginTop = 0;
masterGridLayout.verticalSpacing = 0;
setLayout( masterGridLayout );
topRow = new Composite( this, SWT.NONE );
topRow.setLayout( new GridLayout( 4, false ) );
displayText = new Text( topRow, SWT.BORDER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.minimumWidth = 200;
displayText.setLayoutData( gridData );
arrow = new Button( topRow, SWT.ARROW | SWT.DOWN );
arrow.setBackground( Display.getCurrent().getSystemColor( SWT.COLOR_BLUE ) );
arrow.setSize( 25, 25 );
arrow.addMouseListener( new MouseAdapter() {
@Override
public void mouseDown( MouseEvent event ) {
super.mouseDown( event );
if ( floatShell == null || floatShell.isDisposed() ) {
closeOtherFloatShells();
initFloatShell();
} else {
closeShellAndUpdate();
}
}
} );
add = new Button( topRow, SWT.PUSH );
add.setText( "ADD" );
bottomRow = new Composite( this, SWT.NONE );
GridLayout gridLayout = new GridLayout( 2, true );
gridLayout.marginBottom = 0;
gridLayout.marginLeft = 0;
gridLayout.marginRight = 0;
gridLayout.marginTop = 0;
bottomRow.setLayout( gridLayout );
GridData rowGridData = new GridData( SWT.NONE );
rowGridData.widthHint = 297;
rowGridData.minimumWidth = 297;
bottomRow.setLayoutData( rowGridData );
exitAction = new MouseAdapter() {
@Override
public void mouseUp( MouseEvent e ) {
super.mouseUp( e );
String labelText = ((SelectionLabel) ((Label) e.widget).getParent()).getLabelText();
addRemovedTagBackToListUI( labelText );
selectedItemLabels = removeItemFromSelectedList( labelText );
SelectionLabel removedItem = (SelectionLabel) ((Label) e.widget).getParent();
Composite selectionArea = removedItem.getParent();
int decreasedHeight = calculateTotalHeight( removedItem );
removedItem.dispose();
selectionArea.layout( true, true );
int numRemainingItems = selectionArea.getChildren().length;
if ( numRemainingItems % 2 == 0 ) {
updateTagsUI( decreasedHeight );
}
}
};
add.addMouseListener( new MouseAdapter() {
@Override
public void mouseUp( MouseEvent e ) {
super.mouseUp( e );
if ( floatShell != null
&& comboSelection != null
&& comboSelection.length > 0 ) {
Set<String> selectedItems = new HashSet<>( comboSelection.length );
SelectionLabel ref = null;
for ( int i = 0; i < comboSelection.length; i++ ) {
ref = new SelectionLabel( bottomRow, SWT.BORDER, displayItems[comboSelection[i]], exitAction );
selectedItems.add( displayItems[comboSelection[i]] );
}
//remove from display list
displayItems = Arrays.stream( displayItems )
.filter( item -> !selectedItems.contains( item ) )
.toArray( String[]::new );
selectedItemLabels = addToSelectedTags( selectedItems );
if ( ref != null ) {
updateTagsUI( calculateTotalHeight( ref ) );
}
comboSelection = new int[]{};
floatShell.dispose();
}
}
} );
}
private void closeOtherFloatShells() {
Composite parent = this.getParent();
while ( !( parent instanceof Shell ) ) {
Arrays.stream( parent.getChildren() )
.filter( c -> c instanceof MultipleSelectionCombo )
.forEach( c -> ((MultipleSelectionCombo) c).triggerDropdownClose() );
parent = parent.getParent();
}
}
private void addRemovedTagBackToListUI( String labelText ) {
String[] tempItems = new String[displayItems.length + 1];
AtomicInteger idx = new AtomicInteger();
Arrays.stream( displayItems )
.forEach( str -> tempItems[idx.getAndIncrement()] = str );
tempItems[tempItems.length - 1] = labelText;
displayItems = tempItems;
Arrays.sort( displayItems );
}
private String[] removeItemFromSelectedList( String labelText ) {
String[] tempSelectedItems = new String[selectedItemLabels.length - 1];
int tempIdx = 0;
for ( int i = 0; i < selectedItemLabels.length; i++ ) {
if ( !selectedItemLabels[i].equals( labelText ) ) {
tempSelectedItems[tempIdx++] = selectedItemLabels[i];
}
}
return tempSelectedItems;
}
protected int calculateTotalHeight( SelectionLabel label ) {
GridLayout layout = (GridLayout) label.getLayout();
return layout.marginHeight + label.getHeight() + MARGIN_OFFSET;
}
protected void updateTagsUI( int height ) {
int numRows = ( selectedItemLabels.length / 2 ) + ( selectedItemLabels.length % 2 );
GridData newData = (GridData) bottomRow.getLayoutData();
newData.minimumHeight = numRows * height;
newData.heightHint = numRows * height;
bottomRow.setLayoutData( newData );
triggerShellResize();
}
private String[] addToSelectedTags( Set<String> selectedItems ) {
if ( selectedItemLabels.length == 0 ) {
selectedItemLabels = new String[selectedItems.size()];
return selectedItems.toArray( selectedItemLabels );
} else {
String[] tempLabels = new String[selectedItemLabels.length + selectedItems.size()];
int tempIdx = 0;
for ( int i = 0; i < selectedItemLabels.length; i++ ) {
tempLabels[tempIdx++] = selectedItemLabels[i];
}
String[] selectedAry = new String[selectedItems.size()];
selectedItems.toArray( selectedAry );
for ( int i = 0; i < selectedAry.length; i++ ) {
tempLabels[tempIdx++] = selectedAry[i];
}
return tempLabels;
}
}
private void triggerShellResize() {
Composite scrollFinder = findScrollingParent();
if ( scrollFinder != null ) {
scrollFinder.layout( true, true );
Point p = scrollFinder.getSize();
final Point size = scrollFinder.computeSize( p.x, p.y, true );
scrollFinder.setSize( size );
}
}
private Composite findScrollingParent() {
Composite finder = this.getParent();
while ( finder != null && !( finder instanceof ScrolledComposite ) ) {
finder = finder.getParent();
}
return finder;
}
private void initFloatShell() {
Point p = displayText.getParent().toDisplay( displayText.getLocation() );
Point size = displayText.getSize();
Rectangle shellRect = new Rectangle( p.x, p.y + size.y, size.x, 0 );
floatShell = new Shell( MultipleSelectionCombo.this.getShell(),
SWT.NO_TRIM );
GridLayout gl = new GridLayout();
gl.marginBottom = 2;
gl.marginTop = 2;
gl.marginRight = 0;
gl.marginLeft = 0;
gl.marginWidth = 0;
gl.marginHeight = 0;
floatShell.setLayout( gl );
list = new List( floatShell, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL );
for ( String value : displayItems ) {
list.add( value );
}
GridData gd = new GridData( GridData.FILL_BOTH );
list.setLayoutData( gd );
floatShell.setSize( shellRect.width, 100 );
floatShell.setLocation( shellRect.x, shellRect.y );
list.addMouseListener( new MouseAdapter() {
@Override
public void mouseUp( MouseEvent event ) {
super.mouseUp( event );
comboSelection = list.getSelectionIndices();
}
} );
final Listener listener = event -> floatShell.dispose();
Composite scroll = findScrollingParent();
if ( scroll != null ) {
scroll.getVerticalBar().addListener( SWT.Selection, listener );
}
this.getShell().addListener( SWT.Resize, listener );
this.getShell().addListener( SWT.Move, listener );
floatShell.open();
}
private void closeShellAndUpdate() {
if ( floatShell != null && !floatShell.isDisposed() ) {
comboSelection = list.getSelectionIndices();
floatShell.dispose();
}
}
private void bindDataToUI() {
Set<String> selectedSet = new HashSet<>( selectedItemLabels.length );
for ( String label : selectedItemLabels ) {
new SelectionLabel( bottomRow, SWT.BORDER, label, exitAction );
selectedSet.add( label );
}
displayItems = Arrays.stream( displayItems )
.filter( item -> !selectedSet.contains( item ) )
.toArray( String[]::new );
triggerShellResize();
}
public void setItems( String[] items ) {
Arrays.sort( items );
this.displayItems = Arrays.stream( items ).toArray( String[]::new );
}
/**
* Serializes all selected tags in comma separated list to be returned
* and saved in the steps metadata
*
* @return comma separated string of all selected tags
*/
public String getSelectedItems() {
return String.join( ",", selectedItemLabels );
}
/**
* Takes a comma separated string of tags and binds it to the data object
* Then updates the UI for both the tag dropdown and the selected items
*
* @param selectedItems
*/
public void setSelectedItems( String selectedItems ) {
if ( !StringUtil.isEmpty( selectedItems ) ) {
this.selectedItemLabels = selectedItems.split( "," );
bindDataToUI();
}
}
/**
* Public interface for other dropdowns or components
* to trigger open dropdowns to close
*/
public void triggerDropdownClose() {
if ( floatShell != null && !floatShell.isDisposed() ) {
floatShell.dispose();
}
}
/**
* @deprecated
* Simply a convenience interface to keep backward compatibility
*/
@Deprecated
public String getText() {
return this.getSelectedItems();
}
/**
* @deprecated
* Simply a convenience interface to keep backward compatibility
* @param selectedItems
*/
@Deprecated
public void setText( String selectedItems ) {
this.setSelectedItems( selectedItems );
}
}
| [BACKLOG-34349] - Catalog step - Multiselect dropdown list loses lines on ubuntu (#7613)
* Put the additional margin offset in the correct place. | ui/src/main/java/org/pentaho/di/ui/core/widget/MultipleSelectionCombo.java | [BACKLOG-34349] - Catalog step - Multiselect dropdown list loses lines on ubuntu (#7613) |
|
Java | bsd-2-clause | bafebe834fec2d537b6dba44d00b8c0e3c174787 | 0 | happygiraffe/jslint4java-eclipse | package com.googlecode.jslint4java.eclipse.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import com.googlecode.jslint4java.eclipse.JSLintLog;
public class ToggleNatureAction implements IObjectActionDelegate {
private IStructuredSelection selection;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
for (Object obj : selection.toArray()) {
IProject project = projectFromSelectedItem(obj);
if (project != null) {
toggleNature(project);
}
}
}
/** Convert to a project, or return null. */
private IProject projectFromSelectedItem(Object obj) {
if (obj instanceof IProject) {
return (IProject) obj;
} else if (obj instanceof IAdaptable) {
return (IProject) ((IAdaptable) obj).getAdapter(IProject.class);
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
* org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
if (selection instanceof IStructuredSelection) {
this.selection = (IStructuredSelection) selection;
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction,
* org.eclipse.ui.IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
/**
* Toggles sample nature on a project
*
* @param project
* to have sample nature added or removed
*/
private void toggleNature(IProject project) {
try {
IProjectDescription description = project.getDescription();
List<String> natures = new ArrayList<String>(Arrays.asList(description.getNatureIds()));
if (natures.contains(JSLintNature.NATURE_ID)) {
// Remove the nature.
natures.remove(JSLintNature.NATURE_ID);
} else {
// Add the nature.
natures.add(JSLintNature.NATURE_ID);
}
description.setNatureIds(natures.toArray(new String[natures.size()]));
project.setDescription(description, null);
} catch (CoreException e) {
JSLintLog.logError(e);
}
}
}
| com.googlecode.jslint4java.eclipse/src/com/googlecode/jslint4java/eclipse/builder/ToggleNatureAction.java | package com.googlecode.jslint4java.eclipse.builder;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import com.googlecode.jslint4java.eclipse.JSLintLog;
public class ToggleNatureAction implements IObjectActionDelegate {
private ISelection selection;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
if (selection instanceof IStructuredSelection) {
for (Iterator<?> it = ((IStructuredSelection) selection).iterator(); it
.hasNext();) {
Object element = it.next();
IProject project = null;
if (element instanceof IProject) {
project = (IProject) element;
} else if (element instanceof IAdaptable) {
project = (IProject) ((IAdaptable) element)
.getAdapter(IProject.class);
}
if (project != null) {
toggleNature(project);
}
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
* org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction,
* org.eclipse.ui.IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
/**
* Toggles sample nature on a project
*
* @param project
* to have sample nature added or removed
*/
private void toggleNature(IProject project) {
try {
IProjectDescription description = project.getDescription();
List<String> natures = new ArrayList<String>(Arrays.asList(description.getNatureIds()));
if (natures.contains(JSLintNature.NATURE_ID)) {
// Remove the nature.
natures.remove(JSLintNature.NATURE_ID);
} else {
// Add the nature.
natures.add(JSLintNature.NATURE_ID);
}
description.setNatureIds(natures.toArray(new String[natures.size()]));
project.setDescription(description, null);
} catch (CoreException e) {
JSLintLog.logError(e);
}
}
}
| Tidy up run(). | com.googlecode.jslint4java.eclipse/src/com/googlecode/jslint4java/eclipse/builder/ToggleNatureAction.java | Tidy up run(). |
|
Java | bsd-2-clause | bd1ae8a140dd1b67e91c447d94c639d597927fe6 | 0 | mapfish/mapfish-print,mapfish/mapfish-print,mapfish/mapfish-print,marcjansen/mapfish-print,marcjansen/mapfish-print,mapfish/mapfish-print,sbrunner/mapfish-print,marcjansen/mapfish-print,Galigeo/mapfish-print,sbrunner/mapfish-print,mapfish/mapfish-print,sbrunner/mapfish-print,Galigeo/mapfish-print,Galigeo/mapfish-print,marcjansen/mapfish-print | /*
* Copyright (C) 2014 Camptocamp
*
* This file is part of MapFish Print
*
* MapFish Print is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MapFish Print is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MapFish Print. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapfish.print.processor.map;
import com.google.common.base.Predicate;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Files;
import jsr166y.ForkJoinPool;
import org.junit.Test;
import org.mapfish.print.AbstractMapfishSpringTest;
import org.mapfish.print.TestHttpClientFactory;
import org.mapfish.print.URIUtils;
import org.mapfish.print.config.Configuration;
import org.mapfish.print.config.ConfigurationFactory;
import org.mapfish.print.config.Template;
import org.mapfish.print.output.Values;
import org.mapfish.print.parser.MapfishParser;
import org.mapfish.print.test.util.ImageSimilarity;
import org.mapfish.print.wrapper.json.PJsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.annotation.DirtiesContext;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Basic test of the set param to WMS layers processor.
* <p></p>
* Created by Jesse on 3/26/14.
*/
public class SetWmsCustomParamProcessorTest extends AbstractMapfishSpringTest {
public static final String BASE_DIR = "setparamprocessor/";
@Autowired
private ConfigurationFactory configurationFactory;
@Autowired
private TestHttpClientFactory requestFactory;
@Autowired
private MapfishParser parser;
@Autowired
private ForkJoinPool forkJoinPool;
@Test
@DirtiesContext
public void testExecute() throws Exception {
final String host = "setparamprocessor";
requestFactory.registerHandler(
new Predicate<URI>() {
@Override
public boolean apply(URI input) {
return (("" + input.getHost()).contains(host + ".wms")) || input.getAuthority().contains(host + ".wms");
}
}, new TestHttpClientFactory.Handler() {
@Override
public MockClientHttpRequest handleRequest(URI uri, HttpMethod httpMethod) throws Exception {
final Multimap<String, String> uppercaseParams = HashMultimap.create();
for (Map.Entry<String, String> entry : URIUtils.getParameters(uri).entries()) {
uppercaseParams.put(entry.getKey().toUpperCase(), entry.getValue().toUpperCase());
}
assertTrue("SERVICE != WMS: " + uppercaseParams.get("WMS"), uppercaseParams.containsEntry("SERVICE", "WMS"));
assertTrue("FORMAT != IMAGE/TIFF: " + uppercaseParams.get("FORMAT"), uppercaseParams.containsEntry("FORMAT",
"IMAGE/TIFF"));
assertTrue("REQUEST != MAP: " + uppercaseParams.get("REQUEST"), uppercaseParams.containsEntry("REQUEST", "MAP"));
assertTrue("VERSION != 1.0.0: " + uppercaseParams.get("VERSION"), uppercaseParams.containsEntry("VERSION",
"1.0.0"));
assertTrue("LAYERS != TIGER-NY: " + uppercaseParams.get("LAYERS"), uppercaseParams.containsEntry("LAYERS",
"TIGER-NY"));
assertTrue("STYLES != LINE: " + uppercaseParams.get("STYLES"), uppercaseParams.containsEntry("STYLES", "LINE"));
assertTrue("CUSTOMP1 != 1: " + uri, uppercaseParams.containsEntry("CUSTOMP1", "1"));
assertTrue("CUSTOMP2 != 2", uppercaseParams.containsEntry("CUSTOMP2", "2"));
assertTrue("BBOX is missing", uppercaseParams.containsKey("BBOX"));
assertTrue("EXCEPTIONS is missing", uppercaseParams.containsKey("EXCEPTIONS"));
try {
byte[] bytes = Files.toByteArray(getFile("/map-data/tiger-ny.tiff"));
return ok(uri, bytes, httpMethod);
} catch (AssertionError e) {
return error404(uri, httpMethod);
}
}
}
);
requestFactory.registerHandler(
new Predicate<URI>() {
@Override
public boolean apply(URI input) {
return (("" + input.getHost()).contains(host + ".json")) || input.getAuthority().contains(host + ".json");
}
}, new TestHttpClientFactory.Handler() {
@Override
public MockClientHttpRequest handleRequest(URI uri, HttpMethod httpMethod) throws Exception {
try {
byte[] bytes = Files.toByteArray(getFile("/map-data" + uri.getPath()));
return ok(uri, bytes, httpMethod);
} catch (AssertionError e) {
return error404(uri, httpMethod);
}
}
}
);
final Configuration config = configurationFactory.getConfig(getFile(BASE_DIR + "config.yaml"));
final Template template = config.getTemplate("main");
PJsonObject requestData = loadJsonRequestData();
Values values = new Values(requestData, template, this.parser, getTaskDirectory(), this.requestFactory, new File("."));
forkJoinPool.invoke(template.getProcessorGraph().createTask(values));
@SuppressWarnings("unchecked")
List<URI> layerGraphics = (List<URI>) values.getObject("layerGraphics", List.class);
assertEquals(2, layerGraphics.size());
// Files.copy(new File(layerGraphics.get(0)), new File("/tmp/0_"+getClass().getSimpleName()+".tiff"));
// Files.copy(new File(layerGraphics.get(1)), new File("/tmp/1_"+getClass().getSimpleName()+".tiff"));
new ImageSimilarity(ImageSimilarity.mergeImages(layerGraphics, 630, 294), 2)
.assertSimilarity(getFile(BASE_DIR + "expectedSimpleImage.tiff"), 20);
}
private static PJsonObject loadJsonRequestData() throws IOException {
return parseJSONObjectFromFile(CreateMapProcessorFlexibleScaleCenterWms1_0_0Test.class, BASE_DIR + "requestData.json");
}
}
| core/src/test/java/org/mapfish/print/processor/map/SetWmsCustomParamProcessorTest.java | /*
* Copyright (C) 2014 Camptocamp
*
* This file is part of MapFish Print
*
* MapFish Print is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MapFish Print is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MapFish Print. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapfish.print.processor.map;
import com.google.common.base.Predicate;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Files;
import jsr166y.ForkJoinPool;
import org.junit.Test;
import org.mapfish.print.AbstractMapfishSpringTest;
import org.mapfish.print.TestHttpClientFactory;
import org.mapfish.print.URIUtils;
import org.mapfish.print.config.Configuration;
import org.mapfish.print.config.ConfigurationFactory;
import org.mapfish.print.config.Template;
import org.mapfish.print.output.Values;
import org.mapfish.print.parser.MapfishParser;
import org.mapfish.print.test.util.ImageSimilarity;
import org.mapfish.print.wrapper.json.PJsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.annotation.DirtiesContext;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Basic test of the set param to WMS layers processor.
* <p></p>
* Created by Jesse on 3/26/14.
*/
public class SetWmsCustomParamProcessorTest extends AbstractMapfishSpringTest {
public static final String BASE_DIR = "setparamprocessor/";
@Autowired
private ConfigurationFactory configurationFactory;
@Autowired
private TestHttpClientFactory requestFactory;
@Autowired
private MapfishParser parser;
@Autowired
private ForkJoinPool forkJoinPool;
@Test
@DirtiesContext
public void testExecute() throws Exception {
final String host = "setparamprocessor";
requestFactory.registerHandler(
new Predicate<URI>() {
@Override
public boolean apply(URI input) {
return (("" + input.getHost()).contains(host + ".wms")) || input.getAuthority().contains(host + ".wms");
}
}, new TestHttpClientFactory.Handler() {
@Override
public MockClientHttpRequest handleRequest(URI uri, HttpMethod httpMethod) throws Exception {
final Multimap<String, String> uppercaseParams = HashMultimap.create();
for (Map.Entry<String, String> entry : URIUtils.getParameters(uri).entries()) {
uppercaseParams.put(entry.getKey().toUpperCase(), entry.getValue().toUpperCase());
}
assertTrue("SERVICE != WMS: " + uppercaseParams.get("WMS"), uppercaseParams.containsEntry("SERVICE", "WMS"));
assertTrue("FORMAT != IMAGE/TIFF: " + uppercaseParams.get("FORMAT"), uppercaseParams.containsEntry("FORMAT",
"IMAGE/TIFF"));
assertTrue("REQUEST != MAP: " + uppercaseParams.get("REQUEST"), uppercaseParams.containsEntry("REQUEST", "MAP"));
assertTrue("VERSION != 1.0.0: " + uppercaseParams.get("VERSION"), uppercaseParams.containsEntry("VERSION",
"1.0.0"));
assertTrue("LAYERS != TIGER-NY: " + uppercaseParams.get("LAYERS"), uppercaseParams.containsEntry("LAYERS",
"TIGER-NY"));
assertTrue("STYLES != LINE: " + uppercaseParams.get("STYLES"), uppercaseParams.containsEntry("STYLES", "LINE"));
assertTrue("CUSTOMP1 != 1 it equals: " + uppercaseParams.get("CUSTOMP1"),
uppercaseParams.containsEntry("CUSTOMP1", "1"));
assertTrue("CUSTOMP2 != 2", uppercaseParams.containsEntry("CUSTOMP2", "2"));
assertTrue("BBOX is missing", uppercaseParams.containsKey("BBOX"));
assertTrue("EXCEPTIONS is missing", uppercaseParams.containsKey("EXCEPTIONS"));
try {
byte[] bytes = Files.toByteArray(getFile("/map-data/tiger-ny.tiff"));
return ok(uri, bytes, httpMethod);
} catch (AssertionError e) {
return error404(uri, httpMethod);
}
}
}
);
requestFactory.registerHandler(
new Predicate<URI>() {
@Override
public boolean apply(URI input) {
return (("" + input.getHost()).contains(host + ".json")) || input.getAuthority().contains(host + ".json");
}
}, new TestHttpClientFactory.Handler() {
@Override
public MockClientHttpRequest handleRequest(URI uri, HttpMethod httpMethod) throws Exception {
try {
byte[] bytes = Files.toByteArray(getFile("/map-data" + uri.getPath()));
return ok(uri, bytes, httpMethod);
} catch (AssertionError e) {
return error404(uri, httpMethod);
}
}
}
);
final Configuration config = configurationFactory.getConfig(getFile(BASE_DIR + "config.yaml"));
final Template template = config.getTemplate("main");
PJsonObject requestData = loadJsonRequestData();
Values values = new Values(requestData, template, this.parser, getTaskDirectory(), this.requestFactory, new File("."));
forkJoinPool.invoke(template.getProcessorGraph().createTask(values));
@SuppressWarnings("unchecked")
List<URI> layerGraphics = (List<URI>) values.getObject("layerGraphics", List.class);
assertEquals(2, layerGraphics.size());
// Files.copy(new File(layerGraphics.get(0)), new File("/tmp/0_"+getClass().getSimpleName()+".tiff"));
// Files.copy(new File(layerGraphics.get(1)), new File("/tmp/1_"+getClass().getSimpleName()+".tiff"));
new ImageSimilarity(ImageSimilarity.mergeImages(layerGraphics, 630, 294), 2)
.assertSimilarity(getFile(BASE_DIR + "expectedSimpleImage.tiff"), 20);
}
private static PJsonObject loadJsonRequestData() throws IOException {
return parseJSONObjectFromFile(CreateMapProcessorFlexibleScaleCenterWms1_0_0Test.class, BASE_DIR + "requestData.json");
}
}
| a minor debug change for an assertion that is failing about 30% of the time on jdk 8
| core/src/test/java/org/mapfish/print/processor/map/SetWmsCustomParamProcessorTest.java | a minor debug change for an assertion that is failing about 30% of the time on jdk 8 |
|
Java | bsd-3-clause | 0ac32a678504bc34d8170f43c9a11329ff32b97f | 0 | msf-oca-his/dhis-core,jason-p-pickering/dhis2-persian-calendar,vietnguyen/dhis2-core,jason-p-pickering/dhis2-persian-calendar,dhis2/dhis2-core,vmluan/dhis2-core,troyel/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis-core,jason-p-pickering/dhis2-persian-calendar,msf-oca-his/dhis2-core,troyel/dhis2-core,msf-oca-his/dhis-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,jason-p-pickering/dhis2-persian-calendar,msf-oca-his/dhis-core,vietnguyen/dhis2-core,jason-p-pickering/dhis2-core,jason-p-pickering/dhis2-persian-calendar,msf-oca-his/dhis2-core,dhis2/dhis2-core,hispindia/dhis2-Core,msf-oca-his/dhis2-core,hispindia/dhis2-Core,vmluan/dhis2-core,troyel/dhis2-core,vmluan/dhis2-core,msf-oca-his/dhis2-core,hispindia/dhis2-Core,dhis2/dhis2-core,vietnguyen/dhis2-core,jason-p-pickering/dhis2-core,vietnguyen/dhis2-core,vietnguyen/dhis2-core,troyel/dhis2-core,jason-p-pickering/dhis2-core,vmluan/dhis2-core,hispindia/dhis2-Core,jason-p-pickering/dhis2-core,msf-oca-his/dhis-core,hispindia/dhis2-Core,vmluan/dhis2-core,jason-p-pickering/dhis2-core,troyel/dhis2-core | package org.hisp.dhis.webapi.controller.mapping;
/*
* Copyright (c) 2004-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.
*/
import org.hisp.dhis.common.DimensionService;
import org.hisp.dhis.common.cache.CacheStrategy;
import org.hisp.dhis.dxf2.metadata.MetadataImportParams;
import org.hisp.dhis.dxf2.webmessage.WebMessageException;
import org.hisp.dhis.dxf2.webmessage.WebMessageUtils;
import org.hisp.dhis.i18n.I18nFormat;
import org.hisp.dhis.i18n.I18nManager;
import org.hisp.dhis.legend.LegendService;
import org.hisp.dhis.mapgeneration.MapGenerationService;
import org.hisp.dhis.mapping.Map;
import org.hisp.dhis.mapping.MapView;
import org.hisp.dhis.mapping.MappingService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitGroupService;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.program.ProgramStageService;
import org.hisp.dhis.schema.descriptors.MapSchemaDescriptor;
import org.hisp.dhis.user.UserService;
import org.hisp.dhis.webapi.controller.AbstractCrudController;
import org.hisp.dhis.webapi.utils.ContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import static org.hisp.dhis.common.DimensionalObjectUtils.getDimensions;
/**
* @author Morten Olav Hansen <[email protected]>
* @author Lars Helge Overland
*/
@Controller
@RequestMapping( value = MapSchemaDescriptor.API_ENDPOINT )
public class MapController
extends AbstractCrudController<Map>
{
private static final int MAP_MIN_WIDTH = 140;
private static final int MAP_MIN_HEIGHT = 25;
@Autowired
private MappingService mappingService;
@Autowired
private LegendService legendService;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private OrganisationUnitGroupService organisationUnitGroupService;
@Autowired
private ProgramService programService;
@Autowired
private ProgramStageService programStageService;
@Autowired
private I18nManager i18nManager;
@Autowired
private MapGenerationService mapGenerationService;
@Autowired
private DimensionService dimensionService;
@Autowired
private UserService userService;
@Autowired
private ContextUtils contextUtils;
//--------------------------------------------------------------------------
// CRUD
//--------------------------------------------------------------------------
@Override
@RequestMapping( method = RequestMethod.POST, consumes = "application/json" )
@ResponseStatus( HttpStatus.CREATED )
public void postJsonObject( HttpServletRequest request, HttpServletResponse response ) throws Exception
{
Map map = deserializeJsonEntity( request, response );
map.getTranslations().clear();
mappingService.addMap( map );
response.addHeader( "Location", MapSchemaDescriptor.API_ENDPOINT + "/" + map.getUid() );
webMessageService.send( WebMessageUtils.created( "Map created" ), response, request );
}
@Override
@RequestMapping( value = "/{uid}", method = RequestMethod.PUT, consumes = "application/json" )
@ResponseStatus( HttpStatus.NO_CONTENT )
public void putJsonObject( @PathVariable String uid, HttpServletRequest request, HttpServletResponse response ) throws Exception
{
Map map = mappingService.getMap( uid );
if ( map == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "Map does not exist: " + uid ) );
}
MetadataImportParams params = importService.getParamsFromMap( contextService.getParameterValuesMap() );
Map newMap = deserializeJsonEntity( request, response );
map.mergeWith( newMap, params.getMergeMode() );
map.setUid( uid );
mappingService.updateMap( map );
}
@Override
protected void preUpdateEntity( Map map, Map newMap )
{
map.getMapViews().clear();
if ( newMap.getUser() == null )
{
map.setUser( null );
}
}
@Override
protected Map deserializeJsonEntity( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
Map map = super.deserializeJsonEntity( request, response );
mergeMap( map );
return map;
}
//--------------------------------------------------------------------------
// Get data
//--------------------------------------------------------------------------
@RequestMapping( value = { "/{uid}/data", "/{uid}/data.png" }, method = RequestMethod.GET )
public void getMapData( @PathVariable String uid,
@RequestParam( value = "date", required = false ) Date date,
@RequestParam( value = "ou", required = false ) String ou,
@RequestParam( required = false ) Integer width,
@RequestParam( required = false ) Integer height,
@RequestParam( value = "attachment", required = false ) boolean attachment,
HttpServletResponse response ) throws Exception
{
Map map = mappingService.getMapNoAcl( uid );
if ( map == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "Map does not exist: " + uid ) );
}
if ( width != null && width < MAP_MIN_WIDTH )
{
throw new WebMessageException( WebMessageUtils.conflict( "Min map width is " + MAP_MIN_WIDTH + ": " + width ) );
}
if ( height != null && height < MAP_MIN_HEIGHT )
{
throw new WebMessageException( WebMessageUtils.conflict( "Min map height is " + MAP_MIN_HEIGHT + ": " + height ) );
}
OrganisationUnit unit = ou != null ? organisationUnitService.getOrganisationUnit( ou ) : null;
renderMapViewPng( map, date, unit, width, height, attachment, response );
}
//--------------------------------------------------------------------------
// Hooks
//--------------------------------------------------------------------------
@Override
public void postProcessEntity( Map map ) throws Exception
{
I18nFormat format = i18nManager.getI18nFormat();
Set<OrganisationUnit> roots = currentUserService.getCurrentUser().getDataViewOrganisationUnitsWithFallback();
for ( MapView view : map.getMapViews() )
{
view.populateAnalyticalProperties();
for ( OrganisationUnit organisationUnit : view.getOrganisationUnits() )
{
view.getParentGraphMap().put( organisationUnit.getUid(), organisationUnit.getParentGraph( roots ) );
}
if ( view.getPeriods() != null && !view.getPeriods().isEmpty() )
{
for ( Period period : view.getPeriods() )
{
period.setName( format.formatPeriod( period ) );
}
}
}
}
//--------------------------------------------------------------------------
// Supportive methods
//--------------------------------------------------------------------------
private void mergeMap( Map map )
{
if ( map.getUser() != null )
{
map.setUser( userService.getUser( map.getUser().getUid() ) );
}
else
{
map.setUser( currentUserService.getCurrentUser() );
}
map.getMapViews().forEach( this::mergeMapView );
}
private void mergeMapView( MapView view )
{
dimensionService.mergeAnalyticalObject( view );
dimensionService.mergeEventAnalyticalObject( view );
view.getColumnDimensions().clear();
view.getColumnDimensions().addAll( getDimensions( view.getColumns() ) );
if ( view.getLegendSet() != null )
{
view.setLegendSet( legendService.getLegendSet( view.getLegendSet().getUid() ) );
}
if ( view.getOrganisationUnitGroupSet() != null )
{
view.setOrganisationUnitGroupSet( organisationUnitGroupService.getOrganisationUnitGroupSet( view.getOrganisationUnitGroupSet().getUid() ) );
}
if ( view.getProgram() != null )
{
view.setProgram( programService.getProgram( view.getProgram().getUid() ) );
}
if ( view.getProgramStage() != null )
{
view.setProgramStage( programStageService.getProgramStage( view.getProgramStage().getUid() ) );
}
}
private void renderMapViewPng( Map map, Date date, OrganisationUnit unit, Integer width, Integer height, boolean attachment, HttpServletResponse response )
throws Exception
{
BufferedImage image = mapGenerationService.generateMapImage( map, date, unit, width, height );
if ( image != null )
{
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, "map.png", attachment );
ImageIO.write( image, "PNG", response.getOutputStream() );
}
else
{
response.setStatus( HttpServletResponse.SC_NO_CONTENT );
}
}
}
| dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/mapping/MapController.java | package org.hisp.dhis.webapi.controller.mapping;
/*
* Copyright (c) 2004-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.
*/
import org.hisp.dhis.common.DimensionService;
import org.hisp.dhis.common.cache.CacheStrategy;
import org.hisp.dhis.dxf2.metadata.MetadataImportParams;
import org.hisp.dhis.dxf2.webmessage.WebMessageException;
import org.hisp.dhis.i18n.I18nFormat;
import org.hisp.dhis.i18n.I18nManager;
import org.hisp.dhis.legend.LegendService;
import org.hisp.dhis.mapgeneration.MapGenerationService;
import org.hisp.dhis.mapping.Map;
import org.hisp.dhis.mapping.MapView;
import org.hisp.dhis.mapping.MappingService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitGroupService;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.program.ProgramStageService;
import org.hisp.dhis.schema.descriptors.MapSchemaDescriptor;
import org.hisp.dhis.user.UserService;
import org.hisp.dhis.webapi.controller.AbstractCrudController;
import org.hisp.dhis.webapi.utils.ContextUtils;
import org.hisp.dhis.dxf2.webmessage.WebMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import static org.hisp.dhis.common.DimensionalObjectUtils.getDimensions;
/**
* @author Morten Olav Hansen <[email protected]>
* @author Lars Helge Overland
*/
@Controller
@RequestMapping( value = MapSchemaDescriptor.API_ENDPOINT )
public class MapController
extends AbstractCrudController<Map>
{
private static final int MAP_MIN_WIDTH = 140;
private static final int MAP_MIN_HEIGHT = 25;
@Autowired
private MappingService mappingService;
@Autowired
private LegendService legendService;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private OrganisationUnitGroupService organisationUnitGroupService;
@Autowired
private ProgramService programService;
@Autowired
private ProgramStageService programStageService;
@Autowired
private I18nManager i18nManager;
@Autowired
private MapGenerationService mapGenerationService;
@Autowired
private DimensionService dimensionService;
@Autowired
private UserService userService;
@Autowired
private ContextUtils contextUtils;
//--------------------------------------------------------------------------
// CRUD
//--------------------------------------------------------------------------
@Override
@RequestMapping( method = RequestMethod.POST, consumes = "application/json" )
@ResponseStatus( HttpStatus.CREATED )
public void postJsonObject( HttpServletRequest request, HttpServletResponse response ) throws Exception
{
Map map = deserializeJsonEntity( request, response );
map.getTranslations().clear();
mappingService.addMap( map );
response.addHeader( "Location", MapSchemaDescriptor.API_ENDPOINT + "/" + map.getUid() );
webMessageService.send( WebMessageUtils.created( "Map created" ), response, request );
}
@Override
@RequestMapping( value = "/{uid}", method = RequestMethod.PUT, consumes = "application/json" )
@ResponseStatus( HttpStatus.NO_CONTENT )
public void putJsonObject( @PathVariable String uid, HttpServletRequest request, HttpServletResponse response ) throws Exception
{
Map map = mappingService.getMap( uid );
if ( map == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "Map does not exist: " + uid ) );
}
MetadataImportParams params = importService.getParamsFromMap( contextService.getParameterValuesMap() );
Map newMap = deserializeJsonEntity( request, response );
map.mergeWith( newMap, params.getMergeMode() );
mappingService.updateMap( map );
}
@Override
protected void preUpdateEntity( Map map, Map newMap )
{
map.getMapViews().clear();
if ( newMap.getUser() == null )
{
map.setUser( null );
}
}
@Override
protected Map deserializeJsonEntity( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
Map map = super.deserializeJsonEntity( request, response );
mergeMap( map );
return map;
}
//--------------------------------------------------------------------------
// Get data
//--------------------------------------------------------------------------
@RequestMapping( value = { "/{uid}/data", "/{uid}/data.png" }, method = RequestMethod.GET )
public void getMapData( @PathVariable String uid,
@RequestParam( value = "date", required = false ) Date date,
@RequestParam( value = "ou", required = false ) String ou,
@RequestParam( required = false ) Integer width,
@RequestParam( required = false ) Integer height,
@RequestParam( value = "attachment", required = false ) boolean attachment,
HttpServletResponse response ) throws Exception
{
Map map = mappingService.getMapNoAcl( uid );
if ( map == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "Map does not exist: " + uid ) );
}
if ( width != null && width < MAP_MIN_WIDTH )
{
throw new WebMessageException( WebMessageUtils.conflict( "Min map width is " + MAP_MIN_WIDTH + ": " + width ) );
}
if ( height != null && height < MAP_MIN_HEIGHT )
{
throw new WebMessageException( WebMessageUtils.conflict( "Min map height is " + MAP_MIN_HEIGHT + ": " + height ) );
}
OrganisationUnit unit = ou != null ? organisationUnitService.getOrganisationUnit( ou ) : null;
renderMapViewPng( map, date, unit, width, height, attachment, response );
}
//--------------------------------------------------------------------------
// Hooks
//--------------------------------------------------------------------------
@Override
public void postProcessEntity( Map map ) throws Exception
{
I18nFormat format = i18nManager.getI18nFormat();
Set<OrganisationUnit> roots = currentUserService.getCurrentUser().getDataViewOrganisationUnitsWithFallback();
for ( MapView view : map.getMapViews() )
{
view.populateAnalyticalProperties();
for ( OrganisationUnit organisationUnit : view.getOrganisationUnits() )
{
view.getParentGraphMap().put( organisationUnit.getUid(), organisationUnit.getParentGraph( roots ) );
}
if ( view.getPeriods() != null && !view.getPeriods().isEmpty() )
{
for ( Period period : view.getPeriods() )
{
period.setName( format.formatPeriod( period ) );
}
}
}
}
//--------------------------------------------------------------------------
// Supportive methods
//--------------------------------------------------------------------------
private void mergeMap( Map map )
{
if ( map.getUser() != null )
{
map.setUser( userService.getUser( map.getUser().getUid() ) );
}
else
{
map.setUser( currentUserService.getCurrentUser() );
}
map.getMapViews().forEach( this::mergeMapView );
}
private void mergeMapView( MapView view )
{
dimensionService.mergeAnalyticalObject( view );
dimensionService.mergeEventAnalyticalObject( view );
view.getColumnDimensions().clear();
view.getColumnDimensions().addAll( getDimensions( view.getColumns() ) );
if ( view.getLegendSet() != null )
{
view.setLegendSet( legendService.getLegendSet( view.getLegendSet().getUid() ) );
}
if ( view.getOrganisationUnitGroupSet() != null )
{
view.setOrganisationUnitGroupSet( organisationUnitGroupService.getOrganisationUnitGroupSet( view.getOrganisationUnitGroupSet().getUid() ) );
}
if ( view.getProgram() != null )
{
view.setProgram( programService.getProgram( view.getProgram().getUid() ) );
}
if ( view.getProgramStage() != null )
{
view.setProgramStage( programStageService.getProgramStage( view.getProgramStage().getUid() ) );
}
}
private void renderMapViewPng( Map map, Date date, OrganisationUnit unit, Integer width, Integer height, boolean attachment, HttpServletResponse response )
throws Exception
{
BufferedImage image = mapGenerationService.generateMapImage( map, date, unit, width, height );
if ( image != null )
{
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, "map.png", attachment );
ImageIO.write( image, "PNG", response.getOutputStream() );
}
else
{
response.setStatus( HttpServletResponse.SC_NO_CONTENT );
}
}
}
| make sure that map keeps the same UID for map updates
| dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/mapping/MapController.java | make sure that map keeps the same UID for map updates |
|
Java | mit | 0f8fdaa88957a41e39fbc676d9975872502101b7 | 0 | Mashape/unirest-java,Mashape/unirest-java | package com.mashape.unirest.http.exceptions;
public class UnirestException extends RuntimeException {
private static final long serialVersionUID = -3714840499934575734L;
public UnirestException(Exception e) {
super(e);
}
public UnirestException(String msg) {
super(msg);
}
}
| src/main/java/com/mashape/unirest/http/exceptions/UnirestException.java | package com.mashape.unirest.http.exceptions;
public class UnirestException extends Exception {
private static final long serialVersionUID = -3714840499934575734L;
public UnirestException(Exception e) {
super(e);
}
public UnirestException(String msg) {
super(msg);
}
}
| Unirest exception should not be checked. Fixes #5
| src/main/java/com/mashape/unirest/http/exceptions/UnirestException.java | Unirest exception should not be checked. Fixes #5 |
|
Java | mit | 30e61ad8b4512b3077bd44bbecc88a54f793296e | 0 | dmullins78/easybatch-framework,Toilal/easybatch-framework,dmullins78/easybatch-framework,EasyBatch/easybatch-framework,Toilal/easybatch-framework,EasyBatch/easybatch-framework | /*
* The MIT License
*
* Copyright (c) 2012, benas ([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 net.benas.cb4j.core.config;
import net.benas.cb4j.core.api.*;
import net.benas.cb4j.core.impl.*;
import net.benas.cb4j.core.jmx.BatchMonitor;
import net.benas.cb4j.core.jmx.BatchMonitorMBean;
import net.benas.cb4j.core.util.BatchConstants;
import net.benas.cb4j.core.util.LogFormatter;
import net.benas.cb4j.core.util.RecordType;
import net.benas.cb4j.core.util.ReportFormatter;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.charset.Charset;
import java.util.*;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
/**
* Batch configuration class.<br/>
*
* This class should be used to provide all configuration parameters and mandatory implementations to run CB4J engine.
*
* @author benas ([email protected])
*/
public class BatchConfiguration {
/**
* CB4J logger.
*/
protected final Logger logger = Logger.getLogger(BatchConstants.LOGGER_CB4J);
/*
* Configuration parameters.
*/
protected Properties configurationProperties;
/*
* Validators and CB4J services that will be used by the engine.
*/
protected Map<Integer, List<FieldValidator>> fieldValidators;
private RecordReader recordReader;
private RecordParser recordParser;
private RecordValidator recordValidator;
private RecordProcessor recordProcessor;
private RecordMapper recordMapper;
private BatchReporter batchReporter;
/**
* Initialize configuration from a properties file.
* @param configurationFile the configuration file name
* @throws BatchConfigurationException thrown if :
* <ul>
* <li>The configuration file is not found</li>
* <li>The configuration file cannot be read</li>
* </ul>
* This constructor is used only by subclasses to check if configuration file is specified.
*/
protected BatchConfiguration(final String configurationFile) throws BatchConfigurationException {
if (configurationFile == null) {
String error = "Configuration failed : configuration file not specified";
logger.severe(error);
throw new BatchConfigurationException(error);
}
logger.config("Configuration file specified : " + configurationFile);
fieldValidators = new HashMap<Integer, List<FieldValidator>>();
}
/**
* Initialize configuration from a properties object.
* @param properties the properties object to load
*/
public BatchConfiguration(final Properties properties) {
configurationProperties = properties;
fieldValidators = new HashMap<Integer, List<FieldValidator>>();
}
/**
* Configure the batch engine.
* @throws BatchConfigurationException thrown if :
* <ul>
* <li>One of the mandatory parameters is not specified, please refer to the reference documentation for all parameters details</li>
* <li>Log files for ignored and rejected records cannot be used</li>
* <li>One of the mandatory services is not specified, please refer to the reference documentation for all mandatory services implementations</li>
* </ul>
*/
public void configure() throws BatchConfigurationException {
/*
* Configure CB4J logger
*/
configureCB4JLogger();
logger.info("Configuration started at : " + new Date());
/*
* Configure record reader
*/
configureRecordReader();
/*
* Configure record parser
*/
configureRecordParser();
/*
* Configure loggers for ignored/rejected/error records
*/
configureRecordsLoggers();
/*
* Configure batch reporter : if no custom reporter registered, use default implementation
*/
if (batchReporter == null) {
batchReporter = new DefaultBatchReporterImpl();
}
/*
* Configure record validator with provided validators : if no custom validator registered, use default implementation
*/
if (recordValidator == null) {
recordValidator = new DefaultRecordValidatorImpl(fieldValidators);
}
/*
* Check record mapper
*/
if (recordMapper == null) {
String error = "Configuration failed : no record mapper registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Check record processor
*/
if (recordProcessor == null) {
String error = "Configuration failed : no record processor registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* register JMX MBean
*/
configureJmxMBean();
logger.info("Configuration successful");
logger.info("Configuration parameters details : " + configurationProperties);
}
/**
* Configure loggers for ignored/rejected/errors records.
* @throws BatchConfigurationException thrown if loggers for ignored/rejected/errors records are not correctly configured
*/
private void configureRecordsLoggers() throws BatchConfigurationException {
String inputDataProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_PATH);
ReportFormatter reportFormatter = new ReportFormatter();
//ignored records logger
String outputIgnored = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_IGNORED);
if (outputIgnored == null || (outputIgnored.length() == 0)) {
outputIgnored = BatchConfigurationUtil.removeExtension(inputDataProperty) + BatchConstants.DEFAULT_IGNORED_SUFFIX;
logger.warning("No log file specified for ignored records, using default : " + outputIgnored);
}
try {
FileHandler ignoredRecordsHandler = new FileHandler(outputIgnored);
ignoredRecordsHandler.setFormatter(reportFormatter);
Logger ignoredRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_IGNORED);
ignoredRecordsReporter.addHandler(ignoredRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for ignored records : " + outputIgnored;
logger.severe(error);
throw new BatchConfigurationException(error);
}
//rejected errors logger
String outputRejected = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_REJECTED);
if (outputRejected == null || (outputRejected.length() == 0)) {
outputRejected = BatchConfigurationUtil.removeExtension(inputDataProperty) + BatchConstants.DEFAULT_REJECTED_SUFFIX;
logger.warning("No log file specified for rejected records, using default : " + outputRejected);
}
try {
FileHandler rejectedRecordsHandler = new FileHandler(outputRejected);
rejectedRecordsHandler.setFormatter(reportFormatter);
Logger rejectedRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_REJECTED);
rejectedRecordsReporter.addHandler(rejectedRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for rejected records : " + outputRejected;
logger.severe(error);
throw new BatchConfigurationException(error);
}
//errors record logger
String outputErrors = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_ERRORS);
if (outputErrors == null || (outputErrors.length() == 0)) {
outputErrors = BatchConfigurationUtil.removeExtension(inputDataProperty) + BatchConstants.DEFAULT_ERRORS_SUFFIX;
logger.warning("No log file specified for error records, using default : " + outputErrors);
}
try {
FileHandler errorRecordsHandler = new FileHandler(outputErrors);
errorRecordsHandler.setFormatter(reportFormatter);
Logger errorRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_ERRORS);
errorRecordsReporter.addHandler(errorRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for error records : " + outputErrors;
logger.severe(error);
throw new BatchConfigurationException(error);
}
}
/**
* Configure CB4J record parser.
* @throws BatchConfigurationException thrown if record parser is not correctly configured
*/
private void configureRecordParser() throws BatchConfigurationException {
//read record type property and set default value if invalid input
String recordTypeProperty = configurationProperties.getProperty(BatchConstants.INPUT_RECORD_TYPE);
String recordType;
if (recordTypeProperty == null || recordTypeProperty.length() == 0) {
recordType = BatchConstants.DEFAULT_RECORD_TYPE;
logger.warning("Record type property not specified, records will be considered as delimiter-separated values");
} else if (!RecordType.DSV.toString().equalsIgnoreCase(recordTypeProperty) && !RecordType.FLR.toString().equalsIgnoreCase(recordTypeProperty)) {
recordType = BatchConstants.DEFAULT_RECORD_TYPE;
logger.warning("Record type property '" + recordTypeProperty +"' is invalid, records will be considered as delimiter-separated values");
} else {
recordType = recordTypeProperty;
}
// fixed length record configuration
if (RecordType.FLR.toString().equalsIgnoreCase(recordType)) {
String fieldsLengthProperties = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_LENGTHS);
if ( fieldsLengthProperties == null || fieldsLengthProperties.length() == 0) {
String error = "Configuration failed : when using fixed length records, fields length values property '" + BatchConstants.INPUT_FIELD_LENGTHS + "' is mandatory but was not specified.";
logger.severe(error);
throw new BatchConfigurationException(error);
} else {
//parse fields length property and extract numeric values
StringTokenizer stringTokenizer = new StringTokenizer(fieldsLengthProperties,",");
int[] fieldsLength = new int[stringTokenizer.countTokens()];
int index = 0;
while(stringTokenizer.hasMoreTokens()) {
String length = stringTokenizer.nextToken();
try {
fieldsLength[index] = Integer.parseInt(length);
index++;
} catch (NumberFormatException e) {
String error = "Configuration failed : field length '" + length + "' in property " + BatchConstants.INPUT_FIELD_LENGTHS + "=" + fieldsLengthProperties + " is not numeric.";
logger.severe(error);
throw new BatchConfigurationException(error);
}
}
recordParser = new FlrRecordParserImpl(fieldsLength);
}
}
else { //delimited values configuration
String recordSizeProperty = configurationProperties.getProperty(BatchConstants.INPUT_RECORD_SIZE);
try {
if (recordSizeProperty == null || (recordSizeProperty != null && recordSizeProperty.length() == 0)) {
String error = "Record size property is mandatory but was not specified";
logger.severe(error);
throw new BatchConfigurationException(error);
}
int recordSize = Integer.parseInt(recordSizeProperty);
String fieldsDelimiter = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_DELIMITER);
if (fieldsDelimiter == null || (fieldsDelimiter != null && fieldsDelimiter.length() == 0)) {
fieldsDelimiter = BatchConstants.DEFAULT_FIELD_DELIMITER;
logger.warning("No field delimiter specified, using default : '" + fieldsDelimiter + "'");
}
String trimWhitespacesProperty = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_TRIM);
boolean trimWhitespaces;
if (trimWhitespacesProperty != null) {
trimWhitespaces = Boolean.valueOf(trimWhitespacesProperty);
} else {
trimWhitespaces = BatchConstants.DEFAULT_FIELD_TRIM;
logger.warning("Trim whitespaces property not specified, default to true");
}
String dataQualifierCharacterProperty = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_QUALIFIER_CHAR);
String dataQualifierCharacter = BatchConstants.DEFAULT_FIELD_QUALIFIER_CHAR;
if (dataQualifierCharacterProperty != null && dataQualifierCharacterProperty.length() > 0) {
dataQualifierCharacter = dataQualifierCharacterProperty;
}
logger.config("Record size specified : " + recordSize);
logger.config("Fields delimiter specified : '" + fieldsDelimiter + "'");
logger.config("Data qualifier character specified : '" + dataQualifierCharacter + "'");
recordParser = new DsvRecordParserImpl(recordSize, fieldsDelimiter, trimWhitespaces, dataQualifierCharacter);
} catch (NumberFormatException e) {
String error = "Record size property is not recognized as a number : " + recordSizeProperty;
logger.severe(error);
throw new BatchConfigurationException(error);
}
}
}
/**
* Configure CB4J record reader.
* @throws BatchConfigurationException thrown if record reader is not correctly configured
*/
private void configureRecordReader() throws BatchConfigurationException {
String inputDataProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_PATH);
String encodingProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_ENCODING);
String skipHeaderProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_SKIP_HEADER);
//check if input data file is specified
if (inputDataProperty == null) {
String error = "Configuration failed : input data file is mandatory but was not specified";
logger.severe(error);
throw new BatchConfigurationException(error);
}
try {
boolean skipHeader;
if (skipHeaderProperty != null) {
skipHeader = Boolean.valueOf(skipHeaderProperty);
} else {
skipHeader = BatchConstants.DEFAULT_SKIP_HEADER;
logger.warning("Skip header property not specified, default to false");
}
String encoding;
if (encodingProperty == null || (encodingProperty.length() == 0)) {
encoding = BatchConstants.DEFAULT_FILE_ENCODING;
logger.warning("No encoding specified for input data, using system default encoding : " + encoding);
} else {
if (Charset.availableCharsets().get(encodingProperty) == null || !Charset.isSupported(encodingProperty)) {
encoding = BatchConstants.DEFAULT_FILE_ENCODING;
logger.warning("Encoding '" + encodingProperty + "' not supported, using system default encoding : " + encoding);
} else {
encoding = encodingProperty;
logger.config("Using '" + encoding + "' encoding for input file reading");
}
}
recordReader = new RecordReaderImpl(inputDataProperty, encoding, skipHeader);
logger.config("Data input file : " + inputDataProperty);
} catch (FileNotFoundException e) {
String error = "Configuration failed : input data file '" + inputDataProperty + "' could not be opened";
logger.severe(error);
throw new BatchConfigurationException(error);
}
}
/*
* Configure JMX MBean
*/
private void configureJmxMBean() {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name;
try {
name = new ObjectName("net.benas.cb4j.jmx:type=BatchMonitorMBean");
BatchMonitorMBean batchMonitorMBean = new BatchMonitor(batchReporter);
mbs.registerMBean(batchMonitorMBean, name);
logger.info("CB4J JMX MBean registered successfully as: " + name.getCanonicalName());
} catch (Exception e) {
String error = "Unable to register CB4J JMX MBean. Root exception is :" + e.getMessage();
logger.warning(error);
}
}
/**
* Configure CB4J logger.
*/
private void configureCB4JLogger() {
logger.setUseParentHandlers(false);
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setFormatter(new LogFormatter());
if (logger.getHandlers().length == 0) {
logger.addHandler(consoleHandler);
}
}
/*
* methods used to register mandatory implementations
*/
/**
* Register one validator for a field.
* @param index the field index
* @param validator the {@link FieldValidator} of the field
*/
public void registerFieldValidator(final int index, final FieldValidator validator) {
List<FieldValidator> validators = fieldValidators.get(index);
if (validators == null) {
validators = new ArrayList<FieldValidator>();
}
validators.add(validator);
fieldValidators.put(index, validators);
}
/**
* Register multiple validators for a field.
* @param index the field index
* @param validators the list of validators used to validate the field
*/
public void registerFieldValidators(int index, final List<FieldValidator> validators) {
fieldValidators.put(index, validators);
}
/**
* Register an implementation of {@link RecordProcessor} that will be used to process records.
* @param recordProcessor the record processor implementation
*/
public void registerRecordProcessor(RecordProcessor recordProcessor) {
this.recordProcessor = recordProcessor;
}
/**
* Register a custom implementation of {@link RecordValidator} that will be used to validate records.
* @param recordValidator the custom validator implementation
*/
public void registerRecordValidator(RecordValidator recordValidator) {
this.recordValidator = recordValidator;
}
/**
* Register an implementation of {@link RecordMapper} that will be used to map records to objects.
* @param recordMapper the record mapper implementation
*/
public void registerRecordMapper(RecordMapper recordMapper) {
this.recordMapper = recordMapper;
}
/**
* Register a custom implementation of {@link BatchReporter} that will be used to ignore/reject records and generate batch report.
* @param batchReporter the custom batch reporter implementation
*/
public void registerBatchReporter(BatchReporter batchReporter) {
this.batchReporter = batchReporter;
}
/*
* Getters for CB4J services and parameters used by the engine
*/
public RecordProcessor getRecordProcessor() {
return recordProcessor;
}
public RecordReader getRecordReader() {
return recordReader;
}
public RecordParser getRecordParser() {
return recordParser;
}
public RecordValidator getRecordValidator() {
return recordValidator;
}
public BatchReporter getBatchReporter() {
return batchReporter;
}
public RecordMapper getRecordMapper() {
return recordMapper;
}
public boolean getAbortOnFirstReject() {
return Boolean.valueOf(configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_ABORT_ON_FIRST_REJECT));
}
}
| cb4j-core/src/main/java/net/benas/cb4j/core/config/BatchConfiguration.java | /*
* The MIT License
*
* Copyright (c) 2012, benas ([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 net.benas.cb4j.core.config;
import net.benas.cb4j.core.api.*;
import net.benas.cb4j.core.impl.*;
import net.benas.cb4j.core.jmx.BatchMonitor;
import net.benas.cb4j.core.jmx.BatchMonitorMBean;
import net.benas.cb4j.core.util.BatchConstants;
import net.benas.cb4j.core.util.LogFormatter;
import net.benas.cb4j.core.util.RecordType;
import net.benas.cb4j.core.util.ReportFormatter;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.charset.Charset;
import java.util.*;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
/**
* Batch configuration class.<br/>
*
* This class should be used to provide all configuration parameters and mandatory implementations to run CB4J engine.
*
* @author benas ([email protected])
*/
public class BatchConfiguration {
/**
* CB4J logger.
*/
protected final Logger logger = Logger.getLogger(BatchConstants.LOGGER_CB4J);
/*
* Configuration parameters.
*/
protected Properties configurationProperties;
/*
* Validators and CB4J services that will be used by the engine.
*/
protected Map<Integer, List<FieldValidator>> fieldValidators;
private RecordReader recordReader;
private RecordParser recordParser;
private RecordValidator recordValidator;
private RecordProcessor recordProcessor;
private RecordMapper recordMapper;
private BatchReporter batchReporter;
/**
* Initialize configuration from a properties file.
* @param configurationFile the configuration file name
* @throws BatchConfigurationException thrown if :
* <ul>
* <li>The configuration file is not found</li>
* <li>The configuration file cannot be read</li>
* </ul>
* This constructor is used only by subclasses to check if configuration file is specified.
*/
protected BatchConfiguration(final String configurationFile) throws BatchConfigurationException {
if (configurationFile == null) {
String error = "Configuration failed : configuration file not specified";
logger.severe(error);
throw new BatchConfigurationException(error);
}
logger.config("Configuration file specified : " + configurationFile);
fieldValidators = new HashMap<Integer, List<FieldValidator>>();
}
/**
* Initialize configuration from a properties object.
* @param properties the properties object to load
*/
public BatchConfiguration(final Properties properties) {
configurationProperties = properties;
fieldValidators = new HashMap<Integer, List<FieldValidator>>();
}
/**
* Configure the batch engine.
* @throws BatchConfigurationException thrown if :
* <ul>
* <li>One of the mandatory parameters is not specified, please refer to the reference documentation for all parameters details</li>
* <li>Log files for ignored and rejected records cannot be used</li>
* <li>One of the mandatory services is not specified, please refer to the reference documentation for all mandatory services implementations</li>
* </ul>
*/
public void configure() throws BatchConfigurationException {
/*
* Configure CB4J logger
*/
configureCB4JLogger();
logger.info("Configuration started at : " + new Date());
/*
* Configure record reader
*/
configureRecordReader();
/*
* Configure record parser
*/
configureRecordParser();
/*
* Configure loggers for ignored/rejected/error records
*/
configureRecordsLoggers();
/*
* Configure batch reporter : if no custom reporter registered, use default implementation
*/
if (batchReporter == null) {
batchReporter = new DefaultBatchReporterImpl();
}
/*
* Configure record validator with provided validators : if no custom validator registered, use default implementation
*/
if (recordValidator == null) {
recordValidator = new DefaultRecordValidatorImpl(fieldValidators);
}
/*
* Check record mapper
*/
if (recordMapper == null) {
String error = "Configuration failed : no record mapper registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Check record processor
*/
if (recordProcessor == null) {
String error = "Configuration failed : no record processor registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* register JMX MBean
*/
configureJmxMBean();
logger.info("Configuration successful");
logger.info("Configuration parameters details : " + configurationProperties);
}
/**
* Configure loggers for ignored/rejected/errors records.
* @throws BatchConfigurationException thrown if loggers for ignored/rejected/errors records are not correctly configured
*/
private void configureRecordsLoggers() throws BatchConfigurationException {
String inputDataProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_PATH);
ReportFormatter reportFormatter = new ReportFormatter();
//ignored records logger
String outputIgnored = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_IGNORED);
if (outputIgnored == null || (outputIgnored.length() == 0)) {
outputIgnored = BatchConfigurationUtil.removeExtension(inputDataProperty) + BatchConstants.DEFAULT_IGNORED_SUFFIX;
logger.warning("No log file specified for ignored records, using default : " + outputIgnored);
}
try {
FileHandler ignoredRecordsHandler = new FileHandler(outputIgnored);
ignoredRecordsHandler.setFormatter(reportFormatter);
Logger ignoredRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_IGNORED);
ignoredRecordsReporter.addHandler(ignoredRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for ignored records : " + outputIgnored;
logger.severe(error);
throw new BatchConfigurationException(error);
}
//rejected errors logger
String outputRejected = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_REJECTED);
if (outputRejected == null || (outputRejected.length() == 0)) {
outputRejected = BatchConfigurationUtil.removeExtension(inputDataProperty) + BatchConstants.DEFAULT_REJECTED_SUFFIX;
logger.warning("No log file specified for rejected records, using default : " + outputRejected);
}
try {
FileHandler rejectedRecordsHandler = new FileHandler(outputRejected);
rejectedRecordsHandler.setFormatter(reportFormatter);
Logger rejectedRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_REJECTED);
rejectedRecordsReporter.addHandler(rejectedRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for rejected records : " + outputRejected;
logger.severe(error);
throw new BatchConfigurationException(error);
}
//errors record logger
String outputErrors = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_ERRORS);
if (outputErrors == null || (outputErrors.length() == 0)) {
outputErrors = BatchConfigurationUtil.removeExtension(inputDataProperty) + BatchConstants.DEFAULT_ERRORS_SUFFIX;
logger.warning("No log file specified for error records, using default : " + outputErrors);
}
try {
FileHandler errorRecordsHandler = new FileHandler(outputErrors);
errorRecordsHandler.setFormatter(reportFormatter);
Logger errorRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_ERRORS);
errorRecordsReporter.addHandler(errorRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for error records : " + outputErrors;
logger.severe(error);
throw new BatchConfigurationException(error);
}
}
/**
* Configure CB4J record parser.
* @throws BatchConfigurationException thrown if record parser is not correctly configured
*/
private void configureRecordParser() throws BatchConfigurationException {
//read record type property and set default value if invalid input
String recordTypeProperty = configurationProperties.getProperty(BatchConstants.INPUT_RECORD_TYPE);
String recordType;
if (recordTypeProperty == null || recordTypeProperty.length() == 0) {
recordType = BatchConstants.DEFAULT_RECORD_TYPE;
logger.warning("Record type property not specified, records will be considered as delimiter-separated values");
} else if (!RecordType.DSV.toString().equalsIgnoreCase(recordTypeProperty) && !RecordType.FLR.toString().equalsIgnoreCase(recordTypeProperty)) {
recordType = BatchConstants.DEFAULT_RECORD_TYPE;
logger.warning("Record type property '" + recordTypeProperty +"' is invalid, records will be considered as delimiter-separated values");
} else {
recordType = recordTypeProperty;
}
// fixed length record configuration
if (RecordType.FLR.toString().equalsIgnoreCase(recordType)) {
String fieldsLengthProperties = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_LENGTHS);
if ( fieldsLengthProperties == null || fieldsLengthProperties.length() == 0) {
String error = "Configuration failed : when using fixed length records, fields length values property '" + BatchConstants.INPUT_FIELD_LENGTHS + "' is mandatory but was not specified.";
logger.severe(error);
throw new BatchConfigurationException(error);
} else {
//parse fields length property and extract numeric values
StringTokenizer stringTokenizer = new StringTokenizer(fieldsLengthProperties,",");
int[] fieldsLength = new int[stringTokenizer.countTokens()];
int index = 0;
while(stringTokenizer.hasMoreTokens()) {
String length = stringTokenizer.nextToken();
try {
fieldsLength[index] = Integer.parseInt(length);
index++;
} catch (NumberFormatException e) {
String error = "Configuration failed : field length '" + length + "' in property " + BatchConstants.INPUT_FIELD_LENGTHS + "=" + fieldsLengthProperties + " is not numeric.";
logger.severe(error);
throw new BatchConfigurationException(error);
}
}
recordParser = new FlrRecordParserImpl(fieldsLength);
}
}
else { //delimited values configuration
String recordSizeProperty = configurationProperties.getProperty(BatchConstants.INPUT_RECORD_SIZE);
try {
if (recordSizeProperty == null || (recordSizeProperty != null && recordSizeProperty.length() == 0)) {
String error = "Record size property is mandatory but was not specified";
logger.severe(error);
throw new BatchConfigurationException(error);
}
int recordSize = Integer.parseInt(recordSizeProperty);
String fieldsDelimiter = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_DELIMITER);
if (fieldsDelimiter == null || (fieldsDelimiter != null && fieldsDelimiter.length() == 0)) {
fieldsDelimiter = BatchConstants.DEFAULT_FIELD_DELIMITER;
logger.warning("No field delimiter specified, using default : '" + fieldsDelimiter + "'");
}
String trimWhitespacesProperty = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_TRIM);
boolean trimWhitespaces;
if (trimWhitespacesProperty != null) {
trimWhitespaces = Boolean.valueOf(trimWhitespacesProperty);
} else {
trimWhitespaces = BatchConstants.DEFAULT_FIELD_TRIM;
logger.warning("Trim whitespaces property not specified, default to true");
}
String dataQualifierCharacterProperty = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_QUALIFIER_CHAR);
String dataQualifierCharacter = BatchConstants.DEFAULT_FIELD_QUALIFIER_CHAR;
if (dataQualifierCharacterProperty != null && dataQualifierCharacterProperty.length() > 0) {
dataQualifierCharacter = dataQualifierCharacterProperty;
}
logger.config("Record size specified : " + recordSize);
logger.config("Fields delimiter specified : '" + fieldsDelimiter + "'");
logger.config("Data qualifier character specified : '" + dataQualifierCharacter + "'");
recordParser = new DsvRecordParserImpl(recordSize, fieldsDelimiter, trimWhitespaces, dataQualifierCharacter);
} catch (NumberFormatException e) {
String error = "Record size property is not recognized as a number : " + recordSizeProperty;
logger.severe(error);
throw new BatchConfigurationException(error);
}
}
}
/**
* Configure CB4J record reader.
* @throws BatchConfigurationException thrown if record reader is not correctly configured
*/
private void configureRecordReader() throws BatchConfigurationException {
String inputDataProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_PATH);
String encodingProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_ENCODING);
String skipHeaderProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_SKIP_HEADER);
//check if input data file is specified
if (inputDataProperty == null) {
String error = "Configuration failed : input data file is mandatory but was not specified";
logger.severe(error);
throw new BatchConfigurationException(error);
}
try {
boolean skipHeader;
if (skipHeaderProperty != null) {
skipHeader = Boolean.valueOf(skipHeaderProperty);
} else {
skipHeader = BatchConstants.DEFAULT_SKIP_HEADER;
logger.warning("Skip header property not specified, default to false");
}
String encoding;
if (encodingProperty == null || (encodingProperty.length() == 0)) {
encoding = BatchConstants.DEFAULT_FILE_ENCODING;
logger.warning("No encoding specified for input data, using system default encoding : " + encoding);
} else {
if (Charset.availableCharsets().get(encodingProperty) == null || !Charset.isSupported(encodingProperty)) {
encoding = BatchConstants.DEFAULT_FILE_ENCODING;
logger.warning("Encoding '" + encodingProperty + "' not supported, using system default encoding : " + encoding);
} else {
encoding = encodingProperty;
logger.config("Using '" + encoding + "' encoding for input file reading");
}
}
recordReader = new RecordReaderImpl(inputDataProperty, encoding, skipHeader);
logger.config("Data input file : " + inputDataProperty);
} catch (FileNotFoundException e) {
String error = "Configuration failed : input data file '" + inputDataProperty + "' could not be opened";
logger.severe(error);
throw new BatchConfigurationException(error);
}
}
/*
* Configure JMX MBean
*/
private void configureJmxMBean() {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name;
try {
name = new ObjectName("net.benas.cb4j.jmx:type=BatchMonitorMBean");
BatchMonitorMBean batchMonitorMBean = new BatchMonitor(batchReporter);
mbs.registerMBean(batchMonitorMBean, name);
logger.info("CB4J JMX MBean registered successfully as: " + name.getCanonicalName());
} catch (Exception e) {
String error = "Unable to register CB4J JMX MBean. Root exception is :" + e.getMessage();
logger.warning(error);
}
}
/**
* Configure CB4J logger.
*/
private void configureCB4JLogger() {
logger.setUseParentHandlers(false);
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setFormatter(new LogFormatter());
logger.addHandler(consoleHandler);
}
/*
* methods used to register mandatory implementations
*/
/**
* Register one validator for a field.
* @param index the field index
* @param validator the {@link FieldValidator} of the field
*/
public void registerFieldValidator(final int index, final FieldValidator validator) {
List<FieldValidator> validators = fieldValidators.get(index);
if (validators == null) {
validators = new ArrayList<FieldValidator>();
}
validators.add(validator);
fieldValidators.put(index, validators);
}
/**
* Register multiple validators for a field.
* @param index the field index
* @param validators the list of validators used to validate the field
*/
public void registerFieldValidators(int index, final List<FieldValidator> validators) {
fieldValidators.put(index, validators);
}
/**
* Register an implementation of {@link RecordProcessor} that will be used to process records.
* @param recordProcessor the record processor implementation
*/
public void registerRecordProcessor(RecordProcessor recordProcessor) {
this.recordProcessor = recordProcessor;
}
/**
* Register a custom implementation of {@link RecordValidator} that will be used to validate records.
* @param recordValidator the custom validator implementation
*/
public void registerRecordValidator(RecordValidator recordValidator) {
this.recordValidator = recordValidator;
}
/**
* Register an implementation of {@link RecordMapper} that will be used to map records to objects.
* @param recordMapper the record mapper implementation
*/
public void registerRecordMapper(RecordMapper recordMapper) {
this.recordMapper = recordMapper;
}
/**
* Register a custom implementation of {@link BatchReporter} that will be used to ignore/reject records and generate batch report.
* @param batchReporter the custom batch reporter implementation
*/
public void registerBatchReporter(BatchReporter batchReporter) {
this.batchReporter = batchReporter;
}
/*
* Getters for CB4J services and parameters used by the engine
*/
public RecordProcessor getRecordProcessor() {
return recordProcessor;
}
public RecordReader getRecordReader() {
return recordReader;
}
public RecordParser getRecordParser() {
return recordParser;
}
public RecordValidator getRecordValidator() {
return recordValidator;
}
public BatchReporter getBatchReporter() {
return batchReporter;
}
public RecordMapper getRecordMapper() {
return recordMapper;
}
public boolean getAbortOnFirstReject() {
return Boolean.valueOf(configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_ABORT_ON_FIRST_REJECT));
}
}
| fix logger : do not add handler if it already exists
| cb4j-core/src/main/java/net/benas/cb4j/core/config/BatchConfiguration.java | fix logger : do not add handler if it already exists |
|
Java | mit | 8be87460f1c74dd39a932e5532608f0c522cc984 | 0 | beepscore/ShuffleAndroid | package com.beepscore.android.shuffleandroid;
import android.util.Log;
import junit.framework.TestCase;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by stevebaker on 6/12/15.
*/
public class NodeTest extends TestCase {
public final String LOG_TAG = NodeTest.class.getSimpleName();
public void testNodePropertiesNull() {
Node node = new Node();
assertNotNull(node);
assertNull(node.value);
assertNull(node.indexes.get(0));
assertNull(node.indexes.get(1));
assertNull(node.children.get(0));
assertNull(node.children.get(1));
}
public void testNodeToStringPropertiesNull() {
Node node = new Node();
String expected = "{\"value\":null,\"indexes\":\"[null, null]\",\"children\":\"[null, null]\"}";
assertEquals(expected, node.toString());
}
public void testNodeProperties() {
Node joe = new Node();
String testValue = "Joe";
joe.value = testValue;
assertEquals(testValue, joe.value);
String expectedDescription = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[null, null]\"}";
assertEquals(expectedDescription, joe.toString());
Node larry = new Node();
((ArrayList<Node>)joe.children).set(0, larry);
larry.value = "Larry";
assertEquals(larry, joe.children.get(0));
expectedDescription = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[Larry, null]\"}";
assertEquals(expectedDescription, joe.toString());
Node rick = new Node();
((ArrayList<Node>)joe.children).set(1, rick);
assertEquals(rick, joe.children.get(1));
expectedDescription = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[Larry, null]\"}";
assertEquals(expectedDescription, joe.toString());
rick.value = "Rick";
expectedDescription = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[Larry, Rick]\"}";
assertEquals(expectedDescription, joe.toString());
}
public void testConstructor() {
String value = "Joe";
Node larry = new Node();
Node rick = new Node();
ArrayList<Node> children = new ArrayList<Node>();
children.add(larry);
children.add(rick);
Node joe = new Node(value, null, children);
assertNotNull(joe);
assertEquals(value, joe.value);
assertEquals(larry, joe.children.get(0));
assertEquals(rick, joe.children.get(1));
}
public void testToString() {
Node larry = new Node();
larry.value = "Larry";
Node rick = new Node();
rick.value = "Rick";
ArrayList<Node> children = new ArrayList<Node>();
children.add(larry);
children.add(rick);
Node joe = new Node("Joe", null, children);
Log.d(LOG_TAG, joe.toString());
String expected = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[Larry, Rick]\"}";
assertEquals(expected, joe.toString());
ArrayList<Integer> indexes = new ArrayList<Integer>();
indexes.add(6);
indexes.add(3);
joe.indexes = indexes;
expected = "{\"value\":\"Joe\",\"indexes\":\"[6, 3]\",\"children\":\"[Larry, Rick]\"}";
assertEquals(expected, joe.toString());
}
}
| app/src/androidTest/java/com/beepscore/android/shuffleandroid/NodeTest.java | package com.beepscore.android.shuffleandroid;
import android.util.Log;
import junit.framework.TestCase;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by stevebaker on 6/12/15.
*/
public class NodeTest extends TestCase {
public final String LOG_TAG = NodeTest.class.getSimpleName();
public void testNodePropertiesNull() {
Node node = new Node();
assertNotNull(node);
assertNull(node.value);
assertNull(node.indexes.get(0));
assertNull(node.indexes.get(1));
assertNull(node.children.get(0));
assertNull(node.children.get(1));
}
public void testNodeToStringPropertiesNull() {
Node node = new Node();
String expected = "{\"value\":null,\"indexes\":\"[null, null]\",\"children\":\"[null, null]\"}";
assertEquals(expected, node.toString());
}
public void testNodeProperties() {
Node joe = new Node();
String testValue = "Joe";
joe.value = testValue;
assertEquals(testValue, joe.value);
String expectedDescription = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[null, null]\"}";
assertEquals(expectedDescription, joe.toString());
Node larry = new Node();
((ArrayList<Node>)joe.children).set(0, larry);
larry.value = "Larry";
assertEquals(larry, joe.children.get(0));
expectedDescription = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[Larry, null]\"}";
assertEquals(expectedDescription, joe.toString());
Node rick = new Node();
((ArrayList<Node>)joe.children).set(1, rick);
assertEquals(rick, joe.children.get(1));
expectedDescription = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[Larry, null]\"}";
assertEquals(expectedDescription, joe.toString());
rick.value = "Rick";
expectedDescription = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[Larry, Rick]\"}";
assertEquals(expectedDescription, joe.toString());
}
public void testConstructor() {
String value = "Joe";
Node larry = new Node();
Node rick = new Node();
ArrayList<Node> children = new ArrayList<Node>();
children.add(larry);
children.add(rick);
Node joe = new Node(value, null, children);
assertNotNull(joe);
assertEquals(value, joe.value);
assertEquals(larry, joe.children.get(0));
assertEquals(rick, joe.children.get(1));
}
public void testToString() {
Node larry = new Node();
larry.value = "Larry";
Node rick = new Node();
rick.value = "Rick";
ArrayList<Node> children = new ArrayList<Node>();
children.add(larry);
children.add(rick);
Node joe = new Node("Joe", null, children);
Log.d(LOG_TAG, joe.toString());
String expected = "{\"value\":\"Joe\",\"indexes\":\"[null, null]\",\"children\":\"[Larry, Rick]\"}";
assertEquals(expected, joe.toString());
}
}
| In NodeTest test indexes.
| app/src/androidTest/java/com/beepscore/android/shuffleandroid/NodeTest.java | In NodeTest test indexes. |
|
Java | mit | 4e548e17dfda06c6fef2ee6b75dc4fa0b1979104 | 0 | aureliano/achmed | package com.github.aureliano.achmed.resources;
import org.apache.log4j.Logger;
import com.github.aureliano.achmed.AppConfiguration;
import com.github.aureliano.achmed.helper.FileHelper;
import com.github.aureliano.achmed.helper.StringHelper;
import com.github.aureliano.achmed.os.fs.IFileProvider;
import com.github.aureliano.achmed.resources.properties.FileProperties;
import com.github.aureliano.achmed.resources.properties.IResourceProperties;
import com.github.aureliano.achmed.types.EnsureFileStatus;
public class FileResource implements IResource {
private static final Logger logger = Logger.getLogger(FileResource.class);
private FileProperties properties;
public FileResource() {
this.properties = new FileProperties();
}
public FileResource(FileProperties properties) {
this.properties = properties;
}
public void apply() {
this.properties.configureAttributes();
logger.info(" >>> Apply file resource to " + this.properties.getPath());
this.amendPaths();
this.amendTexts();
IFileProvider provider = AppConfiguration.instance().getOperatingSystem().getDefaultFileProvider();
provider.setFileProperties(this.properties);
this.ensure(provider);
this.applyFilePermissions(provider);
}
public void setProperties(IResourceProperties properties) {
this.properties = (FileProperties) properties;
}
public IResourceProperties getProperties() {
return this.properties;
}
public ResourceType type() {
return ResourceType.FILE;
}
private void amendPaths() {
this.properties.setPath(FileHelper.amendFilePath(this.properties.getPath()));
if (!StringHelper.isEmpty(this.properties.getSource())) {
this.properties.setSource(FileHelper.amendFilePath(this.properties.getSource()));
}
if (!StringHelper.isEmpty(this.properties.getTarget())) {
this.properties.setTarget(FileHelper.amendFilePath(this.properties.getTarget()));
}
}
private void amendTexts() {
if (!StringHelper.isEmpty(this.properties.getGroup())) {
this.properties.setGroup(StringHelper.amendEnvVars(this.properties.getGroup()));
}
if (!StringHelper.isEmpty(this.properties.getOwner())) {
this.properties.setOwner(StringHelper.amendEnvVars(this.properties.getOwner()));
}
}
private void applyFilePermissions(IFileProvider provider) {
if (!StringHelper.isEmpty(this.properties.getMode())) {
logger.info("Setting file mode " + this.properties.getMode() + " to " + this.properties.getPath());
provider.setFileMode();
}
if (!((StringHelper.isEmpty(this.properties.getGroup())) && (StringHelper.isEmpty(this.properties.getOwner())))) {
provider.setFileOwner();
}
}
private void ensure(IFileProvider provider) {
if (EnsureFileStatus.ABSENT.equals(this.properties.getEnsure())) {
logger.info("Apply file absence to " + this.properties.getPath());
provider.ensureFileAbsence();
} else {
logger.info("Apply file presence to " + this.properties.getPath());
provider.ensureFilePresence();
}
}
} | src/main/java/com/github/aureliano/achmed/resources/FileResource.java | package com.github.aureliano.achmed.resources;
import org.apache.log4j.Logger;
import com.github.aureliano.achmed.AppConfiguration;
import com.github.aureliano.achmed.helper.FileHelper;
import com.github.aureliano.achmed.helper.StringHelper;
import com.github.aureliano.achmed.os.fs.IFileProvider;
import com.github.aureliano.achmed.resources.properties.FileProperties;
import com.github.aureliano.achmed.resources.properties.IResourceProperties;
import com.github.aureliano.achmed.types.EnsureFileStatus;
public class FileResource implements IResource {
private static final Logger logger = Logger.getLogger(FileResource.class);
private FileProperties properties;
public FileResource() {
this.properties = new FileProperties();
}
public FileResource(FileProperties properties) {
this.properties = properties;
}
public void apply() {
logger.info(" >>> Apply file resource to " + this.properties.getPath());
this.properties.configureAttributes();
this.amendPaths();
this.amendTexts();
IFileProvider provider = AppConfiguration.instance().getOperatingSystem().getDefaultFileProvider();
provider.setFileProperties(this.properties);
this.applyFilePermissions(provider);
this.ensure(provider);
}
public void setProperties(IResourceProperties properties) {
this.properties = (FileProperties) properties;
}
public IResourceProperties getProperties() {
return this.properties;
}
public ResourceType type() {
return ResourceType.FILE;
}
private void amendPaths() {
this.properties.setPath(FileHelper.amendFilePath(this.properties.getPath()));
if (!StringHelper.isEmpty(this.properties.getSource())) {
this.properties.setSource(FileHelper.amendFilePath(this.properties.getSource()));
}
if (!StringHelper.isEmpty(this.properties.getTarget())) {
this.properties.setTarget(FileHelper.amendFilePath(this.properties.getTarget()));
}
}
private void amendTexts() {
if (!StringHelper.isEmpty(this.properties.getGroup())) {
this.properties.setGroup(StringHelper.amendEnvVars(this.properties.getGroup()));
}
if (!StringHelper.isEmpty(this.properties.getOwner())) {
this.properties.setOwner(StringHelper.amendEnvVars(this.properties.getOwner()));
}
}
private void applyFilePermissions(IFileProvider provider) {
if (!StringHelper.isEmpty(this.properties.getMode())) {
logger.info("Setting file mode " + this.properties.getMode() + " to " + this.properties.getPath());
provider.setFileMode();
}
if (!((StringHelper.isEmpty(this.properties.getGroup())) && (StringHelper.isEmpty(this.properties.getOwner())))) {
provider.setFileOwner();
}
}
private void ensure(IFileProvider provider) {
if (EnsureFileStatus.ABSENT.equals(this.properties.getEnsure())) {
logger.info("Apply file absence to " + this.properties.getPath());
provider.ensureFileAbsence();
} else {
logger.info("Apply file presence to " + this.properties.getPath());
provider.ensureFilePresence();
}
}
} | Ensure file before setting permissions.
| src/main/java/com/github/aureliano/achmed/resources/FileResource.java | Ensure file before setting permissions. |
|
Java | mit | c52d214a8a3469e549175a0bbae362cc73ba55ac | 0 | vincentzhang96/VahrhedralBot | package co.phoenixlab.discord.commands.fun;
import co.phoenixlab.discord.Command;
import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.DiscordApiClient;
import co.phoenixlab.discord.api.entities.Channel;
import co.phoenixlab.discord.api.entities.Member;
import co.phoenixlab.discord.api.entities.Server;
import co.phoenixlab.discord.api.entities.User;
import co.phoenixlab.discord.commands.CommandUtil;
import co.phoenixlab.discord.util.RateLimiter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import static com.google.common.base.Strings.isNullOrEmpty;
public class StabCommand implements Command {
public float regularStabChance = 0.90F;
private LoadingCache<String, RateLimiter> rateLimiters;
private Random random;
private boolean globalEnabled = true;
private Set<String> disabledServers;
private List<BiFunction<String, String, String>> alternateStabs;
public StabCommand() {
disabledServers = new HashSet<>();
alternateStabs = new ArrayList<>();
rateLimiters = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(new CacheLoader<String, RateLimiter>() {
@Override
public RateLimiter load(String key) throws Exception {
return new RateLimiter(
key,
TimeUnit.SECONDS.toMillis(30),
3
);
}
});
random = new Random();
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s and %2$s make love! :heart:",
stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s and %2$s kiss passionately! :kissing_heart:", stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s and %2$s glance at each other, blushing. D'aww! :blush:",
stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s passionately plunges their blade into %2$s's soft flesh as %2$s screams in pain :dagger:",
stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s passionately plunges their blade into %2$s's soft flesh as %2$s moans with pleasure :eggplant:",
stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s goes deep into %2$s. ouo3o",
stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s stabs %2$s, but %2$s seems to enjoy it a little too much... :smirk:",
stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s stabs %2$s, but doesn't realize that %2$s penetrated them already. :scream:",
stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> String.format(
"%1$s flips %2$s, but you have to question how with those wimpy arms... :thinking:",
stabber, stabbed));
alternateStabs.add((stabber, stabbed) -> "Takes out camera :smirk:");
alternateStabs.add((stabber, stabbed) -> "You have to pay Vahr 500g for this feature");
}
@Override
public void handleCommand(MessageContext context, String args) {
if (args.isEmpty()) {
return;
}
Server server = context.getServer();
if (server == null || server == DiscordApiClient.NO_SERVER) {
return;
}
if (args.startsWith("$admin")) {
performStabAdmin(context, args);
} else {
performStab(context, args);
}
}
private void performStabAdmin(MessageContext context, String args) {
DiscordApiClient api = context.getApiClient();
Channel channel = context.getChannel();
Server server = context.getServer();
String serverId = server.getId();
args = args.substring("$admin".length()).trim();
if (args.startsWith("gon")) {
globalEnabled = true;
api.sendMessage("[Global] Stabbing enabled", channel);
} else if (args.startsWith("goff")) {
globalEnabled = false;
api.sendMessage("[Global] Stabbing disabled", channel);
} else if (args.startsWith("on")) {
disabledServers.remove(serverId);
api.sendMessage("[Server] Stabbing enabled", channel);
} else if (args.startsWith("off")) {
disabledServers.add(serverId);
api.sendMessage("[Server] Stabbing disabled", channel);
}
}
private void performStab(MessageContext context, String args) {
if (!globalEnabled) {
return;
}
DiscordApiClient api = context.getApiClient();
Server server = context.getServer();
if (disabledServers.contains(server.getId())) {
return;
}
User stabbedUser = CommandUtil.findUser(context, args, false);
if (stabbedUser == DiscordApiClient.NO_USER || stabbedUser == null) {
return;
}
User stabbingUser = context.getAuthor();
// Rate limiting
Channel channel = context.getChannel();
if (checkRateLimit(context, stabbingUser, channel)) {
return;
}
String msg = getStabMessage(context, stabbingUser, stabbedUser);
api.sendMessage("*" + msg + "*", channel);
}
private String getStabMessage(MessageContext context, User stabbingUser, User stabbedUser) {
DiscordApiClient api = context.getApiClient();
Server server = context.getServer();
Member stabbingMember = api.getUserMember(stabbingUser, server);
Member stabbedMember = api.getUserMember(stabbedUser, server);
String stabbingName = getUserDisplayName(stabbingUser, stabbingMember);
String stabbedName = getUserDisplayName(stabbedUser, stabbedMember);
float rand = random.nextFloat();
String msg = "";
if (rand < regularStabChance) {
msg = getRegularStabMessage(context, stabbingUser, stabbedUser, stabbingName, stabbedName);
} else {
msg = getAlternativeStabbingMessage(stabbingName, stabbedName);
}
return msg;
}
private String getAlternativeStabbingMessage(String stabbingName, String stabbedName) {
int randi = random.nextInt(alternateStabs.size());
return alternateStabs.get(randi).apply(stabbingName, stabbedName);
}
private String getRegularStabMessage(MessageContext context, User stabbingUser, User stabbedUser,
String stabbingName, String stabbedName) {
DiscordApiClient api = context.getApiClient();
Server server = context.getServer();
String msg;
if (api.getClientUser().equals(stabbedUser)) {
// Bot stabbing itself
msg = stabbedName + " stabs itself!";
} else if (stabbingUser.equals(stabbedUser) ||
context.getBot().getConfig().isAdmin(stabbedUser.getId())) {
// User attempting to stab themselves or an admin
// They get stabbed by the bot instead
Member selfMember = api.getUserMember(api.getClientUser(), server);
String selfName = getUserDisplayName(api.getClientUser(), selfMember);
msg = selfName + " stabs " + stabbingName + "!";
} else {
msg = stabbedName + " gets stabbed!";
}
return msg;
}
private String getUserDisplayName(User user, Member member) {
return isNullOrEmpty(member.getNick()) ?
user.getUsername() : member.getNick();
}
private boolean checkRateLimit(MessageContext context, User user, Channel channel) {
if (!context.getBot().getConfig().isAdmin(user.getId())) {
RateLimiter limiter = rateLimiters.getUnchecked(channel.getId());
if (limiter.tryMark() > 0) {
return true;
}
}
return false;
}
}
| src/main/java/co/phoenixlab/discord/commands/fun/StabCommand.java | package co.phoenixlab.discord.commands.fun;
import co.phoenixlab.discord.Command;
import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.DiscordApiClient;
import co.phoenixlab.discord.api.entities.Channel;
import co.phoenixlab.discord.api.entities.Member;
import co.phoenixlab.discord.api.entities.Server;
import co.phoenixlab.discord.api.entities.User;
import co.phoenixlab.discord.commands.CommandUtil;
import co.phoenixlab.discord.util.RateLimiter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Strings.isNullOrEmpty;
public class StabCommand implements Command {
public float regularStabChance = 0.95F;
private LoadingCache<String, RateLimiter> rateLimiters;
private Random random;
private boolean globalEnabled = true;
private Set<String> disabledServers;
public StabCommand() {
disabledServers = new HashSet<>();
rateLimiters = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(new CacheLoader<String, RateLimiter>() {
@Override
public RateLimiter load(String key) throws Exception {
return new RateLimiter(
key,
TimeUnit.SECONDS.toMillis(30),
3
);
}
});
random = new Random();
}
@Override
public void handleCommand(MessageContext context, String args) {
if (args.isEmpty()) {
return;
}
Server server = context.getServer();
if (server == null || server == DiscordApiClient.NO_SERVER) {
return;
}
if (args.startsWith("$admin")) {
performStabAdmin(context, args);
} else {
performStab(context, args);
}
}
private void performStabAdmin(MessageContext context, String args) {
DiscordApiClient api = context.getApiClient();
Channel channel = context.getChannel();
Server server = context.getServer();
String serverId = server.getId();
args = args.substring("$admin".length()).trim();
if (args.startsWith("gon")) {
globalEnabled = true;
api.sendMessage("[Global] Stabbing enabled", channel);
} else if (args.startsWith("goff")) {
globalEnabled = false;
api.sendMessage("[Global] Stabbing disabled", channel);
} else if (args.startsWith("on")) {
disabledServers.remove(serverId);
api.sendMessage("[Server] Stabbing enabled", channel);
} else if (args.startsWith("off")) {
disabledServers.add(serverId);
api.sendMessage("[Server] Stabbing disabled", channel);
}
}
private void performStab(MessageContext context, String args) {
if (!globalEnabled) {
return;
}
DiscordApiClient api = context.getApiClient();
Server server = context.getServer();
if (disabledServers.contains(server.getId())) {
return;
}
User stabbedUser = CommandUtil.findUser(context, args, false);
if (stabbedUser == DiscordApiClient.NO_USER || stabbedUser == null) {
return;
}
User stabbingUser = context.getAuthor();
// Rate limiting
Channel channel = context.getChannel();
if (checkRateLimit(context, stabbingUser, channel)) {
return;
}
String msg = getStabMessage(context, stabbingUser, stabbedUser);
api.sendMessage("*" + msg + "*", channel);
}
private String getStabMessage(MessageContext context, User stabbingUser, User stabbedUser) {
DiscordApiClient api = context.getApiClient();
Server server = context.getServer();
Member stabbingMember = api.getUserMember(stabbingUser, server);
Member stabbedMember = api.getUserMember(stabbedUser, server);
String stabbingName = getUserDisplayName(stabbingUser, stabbingMember);
String stabbedName = getUserDisplayName(stabbedUser, stabbedMember);
float rand = random.nextFloat();
String msg = "";
if (rand < regularStabChance) {
msg = getRegularStabMessage(context, stabbingUser, stabbedUser, stabbingName, stabbedName);
} else {
msg = getAlternativeStabbingMessage(stabbingName, stabbedName);
}
return msg;
}
private String getAlternativeStabbingMessage(String stabbingName, String stabbedName) {
int randi = random.nextInt(4);
String msg;
String stabbingAndStabbed = stabbingName + " and " + stabbedName;
switch (randi) {
case 0:
msg = stabbingAndStabbed + " make love! :heart:";
break;
case 1:
msg = stabbingAndStabbed + " kiss passionately! :kissing_heart:";
break;
case 2:
msg = stabbingAndStabbed + " glance at each other, blushing. D'aww! :blush:";
break;
case 3:
msg = "Takes out camera :smirk:";
break;
default:
msg = "Bot is out of order, wtf Vahr you suck at coding.";
break;
}
return msg;
}
private String getRegularStabMessage(MessageContext context, User stabbingUser, User stabbedUser,
String stabbingName, String stabbedName) {
DiscordApiClient api = context.getApiClient();
Server server = context.getServer();
String msg;
if (api.getClientUser().equals(stabbedUser)) {
// Bot stabbing itself
msg = stabbedName + " stabs itself!";
} else if (stabbingUser.equals(stabbedUser) ||
context.getBot().getConfig().isAdmin(stabbedUser.getId())) {
// User attempting to stab themselves or an admin
// They get stabbed by the bot instead
Member selfMember = api.getUserMember(api.getClientUser(), server);
String selfName = getUserDisplayName(api.getClientUser(), selfMember);
msg = selfName + " stabs " + stabbingName + "!";
} else {
msg = stabbedName + " gets stabbed!";
}
return msg;
}
private String getUserDisplayName(User user, Member member) {
return isNullOrEmpty(member.getNick()) ?
user.getUsername() : member.getNick();
}
private boolean checkRateLimit(MessageContext context, User user, Channel channel) {
if (!context.getBot().getConfig().isAdmin(user.getId())) {
RateLimiter limiter = rateLimiters.getUnchecked(channel.getId());
if (limiter.tryMark() > 0) {
return true;
}
}
return false;
}
}
| Revamp stab feature
| src/main/java/co/phoenixlab/discord/commands/fun/StabCommand.java | Revamp stab feature |
|
Java | mit | a974949dfd0d4692afbbb7908a225ac675641777 | 0 | magx2/jSupla | package pl.grzeslowski.jsupla.protocol.common;
import io.github.benas.randombeans.EnhancedRandomBuilder;
import io.github.benas.randombeans.api.EnhancedRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.grzeslowski.jsupla.protocol.api.structs.SuplaDataPacket;
import pl.grzeslowski.jsupla.protocol.api.structs.Timeval;
import pl.grzeslowski.jsupla.protocol.api.structs.cs.SuplaChannelNewValue;
import pl.grzeslowski.jsupla.protocol.api.structs.cs.SuplaRegisterClient;
import pl.grzeslowski.jsupla.protocol.api.structs.cs.SuplaRegisterClientB;
import pl.grzeslowski.jsupla.protocol.api.structs.dcs.SuplaPingServer;
import pl.grzeslowski.jsupla.protocol.api.structs.dcs.SuplaSetActivityTimeout;
import pl.grzeslowski.jsupla.protocol.api.structs.ds.FirmwareUpdateParams;
import pl.grzeslowski.jsupla.protocol.api.structs.ds.SuplaChannelNewValueResult;
import pl.grzeslowski.jsupla.protocol.api.structs.ds.SuplaDeviceChannel;
import pl.grzeslowski.jsupla.protocol.api.structs.ds.SuplaDeviceChannelB;
import pl.grzeslowski.jsupla.protocol.api.structs.ds.SuplaDeviceChannelValue;
import pl.grzeslowski.jsupla.protocol.api.structs.ds.SuplaRegisterDevice;
import pl.grzeslowski.jsupla.protocol.api.structs.ds.SuplaRegisterDeviceB;
import pl.grzeslowski.jsupla.protocol.api.structs.ds.SuplaRegisterDeviceC;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannel;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannelPack;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannelValue;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaEvent;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaLocation;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaLocationPack;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaRegisterClientResult;
import pl.grzeslowski.jsupla.protocol.api.structs.sd.FirmwareUpdateUrl;
import pl.grzeslowski.jsupla.protocol.api.structs.sd.FirmwareUpdateUrlResult;
import pl.grzeslowski.jsupla.protocol.api.structs.sd.SuplaRegisterDeviceResult;
import pl.grzeslowski.jsupla.protocol.api.structs.sdc.SuplaGetVersionResult;
import pl.grzeslowski.jsupla.protocol.api.structs.sdc.SuplaPingServerResultClient;
import pl.grzeslowski.jsupla.protocol.api.structs.sdc.SuplaSetActivityTimeoutResult;
import pl.grzeslowski.jsupla.protocol.api.structs.sdc.SuplaVersionError;
import pl.grzeslowski.jsupla.protocol.common.randomizers.SuplaChannelValueRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.SuplaDataPacketRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.TimevalRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.cs.SuplaChannelNewValueBRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.cs.SuplaChannelNewValueRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.cs.SuplaRegisterClientBRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.cs.SuplaRegisterClientRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.dcs.SuplaPingServerRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.dcs.SuplaSetActivityTimeoutRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.ds.FirmwareUpdateParamsRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.ds.SuplaChannelNewValueResultRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.ds.SuplaDeviceChannelBRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.ds.SuplaDeviceChannelRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.ds.SuplaDeviceChannelValueRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.ds.SuplaRegisterDeviceBRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.ds.SuplaRegisterDeviceCRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.ds.SuplaRegisterDeviceRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sc.SuplaChannelPackRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sc.SuplaChannelRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sc.SuplaEventRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sc.SuplaLocationPackRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sc.SuplaLocationRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sc.SuplaRegisterClientResultRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sd.FirmwareUpdateUrlRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sd.FirmwareUpdateUrlResultRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sd.SuplaRegisterDeviceResultRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sdc.SuplaGetVersionResultRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sdc.SuplaPingServerResultClientRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sdc.SuplaSetActivityTimeoutResultRandomizer;
import pl.grzeslowski.jsupla.protocol.common.randomizers.sdc.SuplaVersionErrorRandomizer;
import java.util.stream.Stream;
public class RandomBean extends EnhancedRandom {
public static final RandomBean RANDOM_BEAN = new RandomBean(1337);
@SuppressWarnings("FieldCanBeLocal") private final Logger logger = LoggerFactory.getLogger(RandomBean.class);
private final EnhancedRandom random;
private RandomBean(final long seed) {
logger.info("Starting RandomBean with seed {}.", seed);
random = EnhancedRandomBuilder.aNewEnhancedRandomBuilder()
.seed(123L)
// cs
.randomize(SuplaChannelNewValue.class, new SuplaChannelNewValueBRandomizer(this))
.randomize(SuplaChannelNewValue.class, new SuplaChannelNewValueRandomizer(this))
.randomize(SuplaRegisterClientB.class, new SuplaRegisterClientBRandomizer(this))
.randomize(SuplaRegisterClient.class, new SuplaRegisterClientRandomizer(this))
// dcs
.randomize(SuplaPingServer.class, new SuplaPingServerRandomizer(this))
.randomize(SuplaSetActivityTimeout.class, new SuplaSetActivityTimeoutRandomizer(this))
// ds
.randomize(FirmwareUpdateParams.class, new FirmwareUpdateParamsRandomizer(this))
.randomize(SuplaChannelNewValueResult.class, new SuplaChannelNewValueResultRandomizer(this))
.randomize(SuplaDeviceChannelB.class, new SuplaDeviceChannelBRandomizer(this))
.randomize(SuplaDeviceChannel.class, new SuplaDeviceChannelRandomizer(this))
.randomize(SuplaDeviceChannelValue.class, new SuplaDeviceChannelValueRandomizer(this))
.randomize(SuplaRegisterDeviceB.class, new SuplaRegisterDeviceBRandomizer(this))
.randomize(SuplaRegisterDeviceC.class, new SuplaRegisterDeviceCRandomizer(this))
.randomize(SuplaRegisterDevice.class, new SuplaRegisterDeviceRandomizer(this))
// sc
.randomize(SuplaChannelPack.class, new SuplaChannelPackRandomizer(this))
.randomize(SuplaChannel.class, new SuplaChannelRandomizer(this))
.randomize(SuplaChannelValue.class, new SuplaChannelValueRandomizer(this))
.randomize(SuplaEvent.class, new SuplaEventRandomizer(this))
.randomize(SuplaLocationPack.class, new SuplaLocationPackRandomizer(this))
.randomize(SuplaLocation.class, new SuplaLocationRandomizer(this))
.randomize(SuplaRegisterClientResult.class, new SuplaRegisterClientResultRandomizer(this))
// sd
.randomize(FirmwareUpdateUrl.class, new FirmwareUpdateUrlRandomizer(this))
.randomize(FirmwareUpdateUrlResult.class, new FirmwareUpdateUrlResultRandomizer(this))
.randomize(SuplaChannelNewValue.class, new SuplaChannelNewValueRandomizer(this))
.randomize(SuplaRegisterDeviceResult.class, new SuplaRegisterDeviceResultRandomizer(this))
// sdc
.randomize(SuplaGetVersionResult.class, new SuplaGetVersionResultRandomizer(this))
.randomize(SuplaPingServerResultClient.class, new SuplaPingServerResultClientRandomizer(this))
.randomize(SuplaSetActivityTimeoutResult.class, new SuplaSetActivityTimeoutResultRandomizer(this))
.randomize(SuplaVersionError.class, new SuplaVersionErrorRandomizer(this))
// common
.randomize(pl.grzeslowski.jsupla.protocol.api.structs.SuplaChannelValue.class,
new pl.grzeslowski.jsupla.protocol.common.randomizers.SuplaChannelValueRandomizer(this))
.randomize(SuplaDataPacket.class, new SuplaDataPacketRandomizer(this))
.randomize(Timeval.class, new TimevalRandomizer(this))
//build
.build();
}
@Override
public <T> T nextObject(final Class<T> type, final String... excludedFields) {
return random.nextObject(type, excludedFields);
}
@Override
public <T> Stream<T> objects(final Class<T> type, final int amount, final String... excludedFields) {
return random.objects(type, amount, excludedFields);
}
public byte[] nextByteArray(int size) {
byte[] bytes = new byte[size];
this.nextBytes(bytes);
return bytes;
}
public byte nextByte() {
return (byte) (nextInt(Byte.MAX_VALUE - Byte.MIN_VALUE) + Byte.MIN_VALUE);
}
public byte nextByte(byte bound) {
return (byte) nextInt(bound);
}
public short nextUnsignedByte() {
return (short) nextInt(255);
}
public short nextUnsignedByte(final short bound) {
return (short) nextInt(bound);
}
public long nextUnsignedInt() {
return random.nextInt(Integer.MAX_VALUE); // This is not max uint but it's OK
}
}
| protocol/src/test/java/pl/grzeslowski/jsupla/protocol/common/RandomBean.java | package pl.grzeslowski.jsupla.protocol.common;
import io.github.benas.randombeans.EnhancedRandomBuilder;
import io.github.benas.randombeans.api.EnhancedRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.grzeslowski.jsupla.protocol.api.structs.cs.SuplaChannelNewValue;
import pl.grzeslowski.jsupla.protocol.common.randomizers.cs.SuplaChannelNewValueRandomizer;
import java.util.stream.Stream;
public class RandomBean extends EnhancedRandom {
public static final RandomBean RANDOM_BEAN = new RandomBean(1337);
@SuppressWarnings("FieldCanBeLocal") private final Logger logger = LoggerFactory.getLogger(RandomBean.class);
private final EnhancedRandom random;
private RandomBean(final long seed) {
logger.info("Starting RandomBean with seed {}.", seed);
random = EnhancedRandomBuilder.aNewEnhancedRandomBuilder()
.seed(123L)
// cs
.randomize(SuplaChannelNewValue.class, new SuplaChannelNewValueRandomizer(this))
// dcs
// ds
// sc
// sd
// sdc
.build();
}
@Override
public <T> T nextObject(final Class<T> type, final String... excludedFields) {
return random.nextObject(type, excludedFields);
}
@Override
public <T> Stream<T> objects(final Class<T> type, final int amount, final String... excludedFields) {
return random.objects(type, amount, excludedFields);
}
public byte[] nextByteArray(int size) {
byte[] bytes = new byte[size];
this.nextBytes(bytes);
return bytes;
}
public byte nextByte() {
return (byte) (nextInt(Byte.MAX_VALUE - Byte.MIN_VALUE) + Byte.MIN_VALUE);
}
public byte nextByte(byte bound) {
return (byte) nextInt(bound);
}
public short nextUnsignedByte() {
return (short) nextInt(255);
}
public short nextUnsignedByte(final short bound) {
return (short) nextInt(bound);
}
public long nextUnsignedInt() {
return random.nextInt(Integer.MAX_VALUE); // This is not max uint but it's OK
}
}
| Setting randomizers
| protocol/src/test/java/pl/grzeslowski/jsupla/protocol/common/RandomBean.java | Setting randomizers |
|
Java | mit | 90e867b23c59ee376aa8e992877fd74d25210f99 | 0 | ashrafeme/ASDProject | package dao;
import java.util.List;
public class RepositoryDaoImpl<T> implements IRepositoryDao<T> {
@Override
public void save(T t) {
}
@Override
public void update(T t) {
}
@Override
public void delete(T t) {
}
@Override
public List<T> getAll() {
return null;
}
@Override
public T get(T t) {
return null;
}
}
| src/dao/RepositoryDaoImpl.java | package dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class RepositoryDaoImpl<T> implements IRepositoryDao<T> {
@Override
public void save(T t) {
}
@Override
public void update(T t) {
}
@Override
public void delete(T t) {
}
@Override
public List<T> getAll() {
return null;
}
@Override
public T get(T t) {
return null;
}
}
| Update this class | src/dao/RepositoryDaoImpl.java | Update this class |
|
Java | epl-1.0 | 5599e1c73250bd719565f37cbcd8564ce414fc41 | 0 | DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base | /*******************************************************************************
* Copyright (c) 2010-2011, G. Weirich, medshare and Elexis
* 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:
* G. Weirich - initial implementation
*******************************************************************************/
package ch.elexis.views;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.part.ViewPart;
import ch.elexis.base.ch.arzttarife.rfe.IReasonForEncounter;
import ch.elexis.base.ch.arzttarife.rfe.ReasonsForEncounter;
import ch.elexis.base.ch.arzttarife.service.ArzttarifeModelServiceHolder;
import ch.elexis.core.model.IEncounter;
import ch.elexis.core.services.IQuery;
import ch.elexis.core.services.IQuery.COMPARATOR;
import ch.elexis.core.ui.UiDesk;
import ch.elexis.core.ui.icons.Images;
import ch.elexis.core.ui.util.SWTHelper;
public class RFEView extends ViewPart {
Table longTable, shortTable, mediumTable;
CTabFolder tabs;
Composite cCalc;
boolean bDaempfung = false;
HashMap<String, Integer> mapCodeToIndex = new HashMap<String, Integer>();
HashMap<Integer, String> mapIndexToCode = new HashMap<Integer, String>();
private IEncounter currentEncounter;
static final int No_More_Valid = 1;
@Inject
void selectedEncounter(@Optional IEncounter encounter){
adjustTable(encounter);
currentEncounter = encounter;
}
private void adjustTable(IEncounter encounter){
List<IReasonForEncounter> rfeForKOns;
if (encounter != null) {
rfeForKOns = getReasonsForEncounter(encounter);
} else {
rfeForKOns = Collections.emptyList();
}
CTabItem top = tabs.getSelection();
if (top != null) {
Control c = top.getControl();
if (c instanceof Table) {
Table table = (Table) c;
table.deselectAll();
for (TableItem it : table.getItems()) {
// it.setBackground(null);
// it.setForeground(null);
it.setImage((Image) null);
}
for (IReasonForEncounter rfe : rfeForKOns) {
int idx = mapCodeToIndex.get(rfe.getCode());
TableItem item = table.getItem(idx);
// item.setBackground(Desk.getColor(Desk.COL_SKYBLUE));
// item.setForeground(Desk.getColor(Desk.COL_RED));
if (item.getChecked())
item.setImage(Images.IMG_TICK.getImage());
// table.select(idx);
}
}
}
}
private List<IReasonForEncounter> getReasonsForEncounter(IEncounter encounter){
IQuery<IReasonForEncounter> query =
ArzttarifeModelServiceHolder.get().getQuery(IReasonForEncounter.class);
query.and("konsID", COMPARATOR.EQUALS, encounter.getId());
return query.execute();
}
private void removeReasonsForEncounter(IEncounter encounter){
List<IReasonForEncounter> existingReasons = getReasonsForEncounter(encounter);
existingReasons.forEach(reason -> ArzttarifeModelServiceHolder.get().remove(reason));
}
@Override
public void createPartControl(Composite parent){
tabs = new CTabFolder(parent, SWT.BOTTOM);
tabs.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
CTabItem ctLong = new CTabItem(tabs, SWT.NONE);
ctLong.setText("lang");
longTable = new Table(tabs, SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK);
ctLong.setControl(longTable);
CTabItem ctMedium = new CTabItem(tabs, SWT.NONE);
ctMedium.setText("kurz");
mediumTable = new Table(tabs, SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK);
ctMedium.setControl(mediumTable);
CTabItem ctStat = new CTabItem(tabs, SWT.NONE);
ctStat.setText("Statistik");
Composite cStat = new Composite(tabs, SWT.NONE);
cStat.setLayout(new GridLayout());
ctStat.setControl(cStat);
Button bRecalc = new Button(cStat, SWT.PUSH);
bRecalc.setText("Berechnen");
bRecalc.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
cCalc = new Composite(cStat, SWT.NONE);
cCalc.setLayout(new GridLayout());
cCalc.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
bRecalc.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e){
for (Control c : cCalc.getChildren()) {
c.dispose();
}
IQuery<IReasonForEncounter> query =
ArzttarifeModelServiceHolder.get().getQuery(IReasonForEncounter.class);
int[] result = new int[ReasonsForEncounter.getCodeToReasonMap().values().size()];
int all = 0;
for (IReasonForEncounter rfe : query.execute()) {
String code = rfe.getCode();
if (code.length() != 2) {
continue;
}
int idx = mapCodeToIndex.get(code);
result[idx]++;
all++;
}
for (int rline = 0; rline < result.length; rline++) {
String code = mapIndexToCode.get(rline);
int num = result[rline];
float percent = num * 100f / all;
int pc = Math.round(percent);
Label lbl = new Label(cCalc, SWT.NONE);
lbl.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
lbl.setText(code + ": " + num + " (=" + pc + "%)");
}
cCalc.layout(true);
}
});
int i = 0;
for (String code : ReasonsForEncounter.getCodeToReasonMap().values()) {
TableItem longItem = new TableItem(longTable, SWT.NONE);
String shortReason = ReasonsForEncounter.getCodeToShortReasonMap().get(code);
if (shortReason == null) {
shortReason = code + "- Unknown";
}
longItem.setText(shortReason);
TableItem mediumItem = new TableItem(mediumTable, SWT.NONE);
mediumItem.setText(ReasonsForEncounter.getCodeToReasonMap().get(code));
mapCodeToIndex.put(code, i);
mapIndexToCode.put(i, code);
if (i == No_More_Valid) {
mediumItem.setBackground(UiDesk.getColor(UiDesk.COL_LIGHTGREY));
mediumItem.setGrayed(true);
longItem.setBackground(UiDesk.getColor(UiDesk.COL_LIGHTGREY));
longItem.setGrayed(true);
}
i++;
}
longTable.addSelectionListener(new ClickListener(longTable));
mediumTable.addSelectionListener(new ClickListener(mediumTable));
}
@Override
public void setFocus(){
// TODO Auto-generated method stub
}
class ClickListener extends SelectionAdapter {
Table table;
ClickListener(Table table){
this.table = table;
}
@Override
public void widgetSelected(SelectionEvent e){
if (currentEncounter != null) {
int[] sel = table.getSelectionIndices();
if (sel.length > 0) {
removeReasonsForEncounter(currentEncounter);
for (int s : sel) {
if (s == No_More_Valid) {
break;
}
String code = mapIndexToCode.get(s);
IReasonForEncounter reason =
ArzttarifeModelServiceHolder.get().create(IReasonForEncounter.class);
reason.setEncounter(currentEncounter);
reason.setCode(code);
ArzttarifeModelServiceHolder.get().save(reason);
}
adjustTable(currentEncounter);
}
}
}
}
}
| bundles/ch.elexis.base.ch.arzttarife/src/ch/elexis/views/RFEView.java | /*******************************************************************************
* Copyright (c) 2010-2011, G. Weirich, medshare and Elexis
* 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:
* G. Weirich - initial implementation
*******************************************************************************/
package ch.elexis.views;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.part.ViewPart;
import ch.elexis.base.ch.arzttarife.rfe.IReasonForEncounter;
import ch.elexis.base.ch.arzttarife.rfe.ReasonsForEncounter;
import ch.elexis.base.ch.arzttarife.service.ArzttarifeModelServiceHolder;
import ch.elexis.core.model.IEncounter;
import ch.elexis.core.services.IQuery;
import ch.elexis.core.services.IQuery.COMPARATOR;
import ch.elexis.core.ui.UiDesk;
import ch.elexis.core.ui.icons.Images;
import ch.elexis.core.ui.util.SWTHelper;
public class RFEView extends ViewPart {
Table longTable, shortTable, mediumTable;
CTabFolder tabs;
Composite cCalc;
boolean bDaempfung = false;
HashMap<String, Integer> mapCodeToIndex = new HashMap<String, Integer>();
HashMap<Integer, String> mapIndexToCode = new HashMap<Integer, String>();
private IEncounter currentEncounter;
static final int No_More_Valid = 1;
@Inject
void selectedEncounter(@Optional IEncounter encounter){
adjustTable(encounter);
currentEncounter = encounter;
}
private void adjustTable(IEncounter encounter){
List<IReasonForEncounter> rfeForKOns;
if (encounter != null) {
rfeForKOns = getReasonsForEncounter(encounter);
} else {
rfeForKOns = Collections.emptyList();
}
CTabItem top = tabs.getSelection();
if (top != null) {
Control c = top.getControl();
if (c instanceof Table) {
Table table = (Table) c;
table.deselectAll();
for (TableItem it : table.getItems()) {
// it.setBackground(null);
// it.setForeground(null);
it.setImage((Image) null);
}
for (IReasonForEncounter rfe : rfeForKOns) {
int idx = mapCodeToIndex.get(rfe.getCode());
TableItem item = table.getItem(idx);
// item.setBackground(Desk.getColor(Desk.COL_SKYBLUE));
// item.setForeground(Desk.getColor(Desk.COL_RED));
if (item.getChecked())
item.setImage(Images.IMG_TICK.getImage());
// table.select(idx);
}
}
}
}
private List<IReasonForEncounter> getReasonsForEncounter(IEncounter encounter){
IQuery<IReasonForEncounter> query =
ArzttarifeModelServiceHolder.get().getQuery(IReasonForEncounter.class);
query.and("konsID", COMPARATOR.EQUALS, encounter.getId());
return query.execute();
}
private void removeReasonsForEncounter(IEncounter encounter){
List<IReasonForEncounter> existingReasons = getReasonsForEncounter(encounter);
existingReasons.forEach(reason -> ArzttarifeModelServiceHolder.get().remove(reason));
}
@Override
public void createPartControl(Composite parent){
tabs = new CTabFolder(parent, SWT.BOTTOM);
tabs.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
CTabItem ctLong = new CTabItem(tabs, SWT.NONE);
ctLong.setText("lang");
longTable = new Table(tabs, SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK);
ctLong.setControl(longTable);
CTabItem ctMedium = new CTabItem(tabs, SWT.NONE);
ctMedium.setText("kurz");
mediumTable = new Table(tabs, SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK);
ctMedium.setControl(mediumTable);
CTabItem ctStat = new CTabItem(tabs, SWT.NONE);
ctStat.setText("Statistik");
Composite cStat = new Composite(tabs, SWT.NONE);
cStat.setLayout(new GridLayout());
ctStat.setControl(cStat);
Button bRecalc = new Button(cStat, SWT.PUSH);
bRecalc.setText("Berechnen");
bRecalc.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
cCalc = new Composite(cStat, SWT.NONE);
cCalc.setLayout(new GridLayout());
cCalc.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
bRecalc.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e){
for (Control c : cCalc.getChildren()) {
c.dispose();
}
IQuery<IReasonForEncounter> query =
ArzttarifeModelServiceHolder.get().getQuery(IReasonForEncounter.class);
int[] result = new int[ReasonsForEncounter.getCodeToReasonMap().values().size()];
int all = 0;
for (IReasonForEncounter rfe : query.execute()) {
String code = rfe.getCode();
if (code.length() != 2) {
continue;
}
int idx = mapCodeToIndex.get(code);
result[idx]++;
all++;
}
for (int rline = 0; rline < result.length; rline++) {
String code = mapIndexToCode.get(rline);
int num = result[rline];
float percent = num * 100f / all;
int pc = Math.round(percent);
Label lbl = new Label(cCalc, SWT.NONE);
lbl.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
lbl.setText(code + ": " + num + " (=" + pc + "%)");
}
cCalc.layout(true);
}
});
int i = 0;
for (String code : ReasonsForEncounter.getCodeToReasonMap().values()) {
TableItem longItem = new TableItem(longTable, SWT.NONE);
longItem.setText(ReasonsForEncounter.getCodeToShortReasonMap().get(code));
TableItem mediumItem = new TableItem(mediumTable, SWT.NONE);
mediumItem.setText(ReasonsForEncounter.getCodeToReasonMap().get(code));
mapCodeToIndex.put(code, i);
mapIndexToCode.put(i, code);
if (i == No_More_Valid) {
mediumItem.setBackground(UiDesk.getColor(UiDesk.COL_LIGHTGREY));
mediumItem.setGrayed(true);
longItem.setBackground(UiDesk.getColor(UiDesk.COL_LIGHTGREY));
longItem.setGrayed(true);
}
i++;
}
longTable.addSelectionListener(new ClickListener(longTable));
mediumTable.addSelectionListener(new ClickListener(mediumTable));
}
@Override
public void setFocus(){
// TODO Auto-generated method stub
}
class ClickListener extends SelectionAdapter {
Table table;
ClickListener(Table table){
this.table = table;
}
@Override
public void widgetSelected(SelectionEvent e){
if (currentEncounter != null) {
int[] sel = table.getSelectionIndices();
if (sel.length > 0) {
removeReasonsForEncounter(currentEncounter);
for (int s : sel) {
if (s == No_More_Valid) {
break;
}
String code = mapIndexToCode.get(s);
IReasonForEncounter reason =
ArzttarifeModelServiceHolder.get().create(IReasonForEncounter.class);
reason.setEncounter(currentEncounter);
reason.setCode(code);
ArzttarifeModelServiceHolder.get().save(reason);
}
adjustTable(currentEncounter);
}
}
}
}
}
| [22634] Invalid/Unknown RF medkey code | bundles/ch.elexis.base.ch.arzttarife/src/ch/elexis/views/RFEView.java | [22634] Invalid/Unknown RF medkey code |
|
Java | lgpl-2.1 | 2c58c3dfd32c98ff09fcb74ceffae094cc7cd464 | 0 | gallardo/opencms-core,gallardo/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.ade.detailpage;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.main.CmsException;
import org.opencms.util.CmsUUID;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.CmsXmlVfsFileValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.List;
import java.util.Locale;
/**
* Class for writing detail page information to an XML configuration file.<p>
*
* @since 8.0.0
*/
public class CmsDetailPageConfigurationWriter {
/** The detail page node. */
public static final String N_DETAIL_PAGE = "DetailPage";
/** The name of the node containing the reference to the actual detail page. */
public static final String N_PAGE = "Page";
/** The name of the node which contains the type which the detail page renders. */
public static final String N_TYPE = "Type";
/** The CMS context. */
private CmsObject m_cms;
/** The content of the configuration file. */
private CmsXmlContent m_document;
/** The configuration file record. */
private CmsFile m_file;
/** The configuration file resource. */
private CmsResource m_resource;
/**
* Creates a new detail page configuration writer.<p>
*
* @param cms the current CMS context
* @param res the configuration file resource
*/
public CmsDetailPageConfigurationWriter(CmsObject cms, CmsResource res) {
m_cms = cms;
m_resource = res;
}
/**
* Writes the new detail page information to the configuration file.<p>
*
* @param infos the new detail page information
* @param newId the id to use for new pages
*
* @throws CmsException if something goes wrong
*/
public void updateAndSave(List<CmsDetailPageInfo> infos, CmsUUID newId) throws CmsException {
if (m_resource != null) {
getDocument();
removeOldValues();
writeDetailPageInfos(infos, newId);
m_document.setAutoCorrectionEnabled(true);
m_document.correctXmlStructure(m_cms);
byte[] content = m_document.marshal();
m_file.setContents(content);
m_cms.writeFile(m_file);
}
}
/**
* Helper method for loading the XML content from the configuration file.<p>
*
* @return the parsed XML document
*
* @throws CmsException if something goes wrong
*/
private I_CmsXmlDocument getDocument() throws CmsException {
if (m_document == null) {
m_file = m_cms.readFile(m_resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, m_file);
m_document = content;
}
return m_document;
}
/**
* Helper method for getting the locale from which to read the configuration data.<p>
*
* @return the locale from which to read the configuration data
*
* @throws CmsException if something goes wrong
*/
private Locale getLocale() throws CmsException {
getDocument();
List<Locale> locales = m_document.getLocales();
if (locales.contains(Locale.ENGLISH) || locales.isEmpty()) {
return Locale.ENGLISH;
}
return locales.get(0);
}
/**
* Removes the old detail page information from the XML content.<p>
*
* @throws CmsException if something goes wrong
*/
private void removeOldValues() throws CmsException {
Locale locale = getLocale();
I_CmsXmlContentValue value = m_document.getValue(N_DETAIL_PAGE, locale);
do {
value = m_document.getValue(N_DETAIL_PAGE, locale);
if (value != null) {
m_document.removeValue(value.getPath(), locale, 0);
}
} while (value != null);
}
/**
* Writes the detail page information to the XML content.<p>
*
* @param infos the list of detail page information bean
* @param newId the id to use for new pages
*/
private void writeDetailPageInfos(List<CmsDetailPageInfo> infos, CmsUUID newId) {
int i = 0;
for (CmsDetailPageInfo info : infos) {
if (info.isInherited()) {
continue;
}
CmsUUID id = info.getId();
if (id == null) {
id = newId;
}
writeValue(info.getType(), id, i);
i += 1;
}
}
/**
* Writes a single item of detail page information to the XML content.<p>
*
* @param type the type which the detail page should render
* @param id the page id of the detail page
* @param index the position at which the detail page info should be added
*/
private void writeValue(String type, CmsUUID id, int index) {
Locale locale = CmsLocaleManager.getLocale("en");
// todo: check actual locale.
m_document.addValue(m_cms, N_DETAIL_PAGE, locale, index);
String typePath = N_DETAIL_PAGE + "[" + (1 + index) + "]/" + N_TYPE;
I_CmsXmlContentValue typeVal = m_document.getValue(typePath, locale);
String pagePath = N_DETAIL_PAGE + "[" + (1 + index) + "]/" + N_PAGE;
CmsXmlVfsFileValue pageVal = (CmsXmlVfsFileValue)m_document.getValue(pagePath, locale);
typeVal.setStringValue(m_cms, type);
pageVal.setIdValue(m_cms, id);
}
}
| src/org/opencms/ade/detailpage/CmsDetailPageConfigurationWriter.java | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.ade.detailpage;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.main.CmsException;
import org.opencms.util.CmsUUID;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.CmsXmlVfsFileValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.List;
import java.util.Locale;
/**
* Class for writing detail page information to an XML configuration file.<p>
*
* @since 8.0.0
*/
public class CmsDetailPageConfigurationWriter {
/** The detail page node. */
public static final String N_DETAIL_PAGE = "DetailPage";
/** The name of the node containing the reference to the actual detail page. */
public static final String N_PAGE = "Page";
/** The name of the node which contains the type which the detail page renders. */
public static final String N_TYPE = "Type";
/** The CMS context. */
private CmsObject m_cms;
/** The content of the configuration file. */
private CmsXmlContent m_document;
/** The configuration file record. */
private CmsFile m_file;
/** The configuration file resource. */
private CmsResource m_resource;
/**
* Creates a new detail page configuration writer.<p>
*
* @param cms the current CMS context
* @param res the configuration file resource
*/
public CmsDetailPageConfigurationWriter(CmsObject cms, CmsResource res) {
m_cms = cms;
m_resource = res;
}
/**
* Writes the new detail page information to the configuration file.<p>
*
* @param infos the new detail page information
* @param newId the id to use for new pages
*
* @throws CmsException if something goes wrong
*/
public void updateAndSave(List<CmsDetailPageInfo> infos, CmsUUID newId) throws CmsException {
//lock(m_cms, m_resource);
getDocument();
removeOldValues();
writeDetailPageInfos(infos, newId);
m_document.setAutoCorrectionEnabled(true);
m_document.correctXmlStructure(m_cms);
byte[] content = m_document.marshal();
m_file.setContents(content);
m_cms.writeFile(m_file);
//m_cms.unlockResource(m_cms.getSitePath(m_resource));
}
/**
* Helper method for loading the XML content from the configuration file.<p>
*
* @return the parsed XML document
*
* @throws CmsException if something goes wrong
*/
private I_CmsXmlDocument getDocument() throws CmsException {
if (m_document == null) {
m_file = m_cms.readFile(m_resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, m_file);
m_document = content;
}
return m_document;
}
/**
* Helper method for getting the locale from which to read the configuration data.<p>
*
* @return the locale from which to read the configuration data
*
* @throws CmsException if something goes wrong
*/
private Locale getLocale() throws CmsException {
getDocument();
List<Locale> locales = m_document.getLocales();
if (locales.contains(Locale.ENGLISH) || locales.isEmpty()) {
return Locale.ENGLISH;
}
return locales.get(0);
}
/**
* Removes the old detail page information from the XML content.<p>
*
* @throws CmsException if something goes wrong
*/
private void removeOldValues() throws CmsException {
Locale locale = getLocale();
I_CmsXmlContentValue value = m_document.getValue(N_DETAIL_PAGE, locale);
do {
value = m_document.getValue(N_DETAIL_PAGE, locale);
if (value != null) {
m_document.removeValue(value.getPath(), locale, 0);
}
} while (value != null);
}
/**
* Writes the detail page information to the XML content.<p>
*
* @param infos the list of detail page information bean
* @param newId the id to use for new pages
*/
private void writeDetailPageInfos(List<CmsDetailPageInfo> infos, CmsUUID newId) {
int i = 0;
for (CmsDetailPageInfo info : infos) {
if (info.isInherited()) {
continue;
}
CmsUUID id = info.getId();
if (id == null) {
id = newId;
}
writeValue(info.getType(), id, i);
i += 1;
}
}
/**
* Writes a single item of detail page information to the XML content.<p>
*
* @param type the type which the detail page should render
* @param id the page id of the detail page
* @param index the position at which the detail page info should be added
*/
private void writeValue(String type, CmsUUID id, int index) {
Locale locale = CmsLocaleManager.getLocale("en");
// todo: check actual locale.
m_document.addValue(m_cms, N_DETAIL_PAGE, locale, index);
String typePath = N_DETAIL_PAGE + "[" + (1 + index) + "]/" + N_TYPE;
I_CmsXmlContentValue typeVal = m_document.getValue(typePath, locale);
String pagePath = N_DETAIL_PAGE + "[" + (1 + index) + "]/" + N_PAGE;
CmsXmlVfsFileValue pageVal = (CmsXmlVfsFileValue)m_document.getValue(pagePath, locale);
typeVal.setStringValue(m_cms, type);
pageVal.setIdValue(m_cms, id);
}
}
| Avoiding null pointers. | src/org/opencms/ade/detailpage/CmsDetailPageConfigurationWriter.java | Avoiding null pointers. |
|
Java | lgpl-2.1 | 5939d2a88ffcef1ed655fc9d8873c56ad9126bfc | 0 | roidelapluie/mariadb-connector-j-travis,roidelapluie/mariadb-connector-j,krummas/DrizzleJDBC,Mikelarg/mariadb-connector-j,MariaDB/mariadb-connector-j,tempbottle/DrizzleJDBC,StephG38/DrizzleJDBC,Mikelarg/mariadb-connector-j,roidelapluie/mariadb-connector-j-travis,roidelapluie/mariadb-connector-j,MariaDB/mariadb-connector-j | /*
* Drizzle JDBC
*
* Copyright (C) 2009 Marcus Eriksson ([email protected])
* All rights reserved.
*
* Copyright (C) 2009 Sun Microsystems
* All rights reserved.
*
* Use and distribution licensed under the BSD license.
*/
package org.drizzle.jdbc.internal.common.packet;
import java.io.IOException;
import java.io.InputStream;
/**
* Class to represent a raw packet as transferred over the wire. First we
* got 3 bytes specifying the actual length, then one byte packet sequence
* number and then n bytes with user data.
*
*/
public class RawPacket {
static final RawPacket IOEXCEPTION_PILL = new RawPacket(null, -1);
private final byte[] rawBytes;
private final int packetSeq;
/**
* Get the next packet from the stream
*
* @param is the input stream to read the next packet from
* @return The next packet from the stream, or NULL if the stream is closed
* @throws java.io.IOException if an error occurs while reading data
*/
static RawPacket nextPacket(InputStream is) throws IOException {
int length = readLength(is);
if (length == -1) {
return null;
}
if (length < 0) {
throw new IOException("Got negative packet size: " + length);
}
int packetSeq = readPacketSeq(is);
byte[] rawBytes = new byte[length];
int nr = safeRead(is, rawBytes, length);
if (nr == -1) {
throw new IOException("EOF. Expected " + length + ", got " + nr);
/* EOF */
}
return new RawPacket(rawBytes, packetSeq);
}
private RawPacket(byte[] rawBytes, int packetSeq) {
this.rawBytes = rawBytes;
this.packetSeq = packetSeq;
}
private static int safeRead(InputStream is, byte[] buffer, int length) throws IOException{
int offset = 0;
int left = length;
do {
int nr = is.read(buffer, offset, left);
if (nr == -1) {
return nr;
}
offset += nr;
left -= nr;
} while (left > 0);
return length;
}
private static byte readPacketSeq(InputStream reader) throws IOException {
int val = reader.read();
if (val == -1) {
throw new IOException("EOF");
}
return (byte) val;
}
private static int readLength(InputStream reader) throws IOException {
byte[] lengthBuffer = new byte[3];
int nr = safeRead(reader, lengthBuffer, 3);
if (nr == -1) {
return -1;
} else if (nr != 3) {
throw new IOException("Incomplete read! Expected 3, got " + nr);
}
return (lengthBuffer[0] & 0xff) + ((lengthBuffer[1] & 0xff) << 8) + ((lengthBuffer[2] & 0xff) << 16);
}
public byte[] getRawBytes() {
return rawBytes;
}
public int getPacketSeq() {
return packetSeq;
}
}
| src/main/java/org/drizzle/jdbc/internal/common/packet/RawPacket.java | /*
* Drizzle JDBC
*
* Copyright (C) 2009 Marcus Eriksson ([email protected])
* All rights reserved.
*
* Copyright (C) 2009 Sun Microsystems
* All rights reserved.
*
* Use and distribution licensed under the BSD license.
*/
package org.drizzle.jdbc.internal.common.packet;
import java.io.IOException;
import java.io.InputStream;
/**
* Class to represent a raw packet as transferred over the wire. First we
* got 3 bytes specifying the actual length, then one byte packet sequence
* number and then n bytes with user data.
*
*/
public class RawPacket {
static final RawPacket IOEXCEPTION_PILL = new RawPacket(null, -1);
private final byte[] rawBytes;
private final int packetSeq;
/**
* Get the next packet from the stream
*
* @param is the input stream to read the next packet from
* @return The next packet from the stream, or NULL if the stream is closed
* @throws java.io.IOException if an error occurs while reading data
*/
static RawPacket nextPacket(InputStream is) throws IOException {
int length = readLength(is);
if (length == -1) {
return null;
}
if (length < 0) {
throw new IOException("Got negative packet size: " + length);
}
int packetSeq = readPacketSeq(is);
byte[] rawBytes = new byte[length];
int offset = 0;
int left = length;
do {
int nr = is.read(rawBytes, offset, left);
if (nr == -1) {
throw new IOException("EOF. Expected " + length + ", got " + offset);
/* EOF */
}
offset += nr;
left -= nr;
} while (left > 0);
return new RawPacket(rawBytes, packetSeq);
}
private RawPacket(byte[] rawBytes, int packetSeq) {
this.rawBytes = rawBytes;
this.packetSeq = packetSeq;
}
private static byte readPacketSeq(InputStream reader) throws IOException {
int val = reader.read();
if (val == -1) {
throw new IOException("EOF");
}
return (byte) val;
}
private static int readLength(InputStream reader) throws IOException {
byte[] lengthBuffer = new byte[3];
int nr = reader.read(lengthBuffer);
if (nr == -1) {
return -1;
} else if (nr != 3) {
throw new IOException("Incomplete read! Expected 3, got " + nr);
}
return (lengthBuffer[0] & 0xff) + ((lengthBuffer[1] & 0xff) << 8) + ((lengthBuffer[2] & 0xff) << 16);
}
public byte[] getRawBytes() {
return rawBytes;
}
public int getPacketSeq() {
return packetSeq;
}
}
| Loop and check for incomplete reads while reading the packet lenght as well | src/main/java/org/drizzle/jdbc/internal/common/packet/RawPacket.java | Loop and check for incomplete reads while reading the packet lenght as well |
|
Java | lgpl-2.1 | d22a9ee3d234a179b1162c28a2b02f951670c6d5 | 0 | jolie/jolie,jolie/jolie,jolie/jolie | /***************************************************************************
* Copyright (C) 2008-2014 by Fabrizio Montesi <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
***************************************************************************/
package joliex.lang;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import jolie.lang.Constants;
import jolie.ExecutionThread;
import jolie.Interpreter;
import jolie.lang.Constants.EmbeddedServiceType;
import jolie.net.CommListener;
import jolie.net.LocalCommChannel;
import jolie.net.ports.OutputPort;
import jolie.runtime.embedding.EmbeddedServiceLoader;
import jolie.runtime.embedding.EmbeddedServiceLoaderCreationException;
import jolie.runtime.embedding.EmbeddedServiceLoadingException;
import jolie.runtime.FaultException;
import jolie.runtime.InvalidIdException;
import jolie.runtime.JavaService;
import jolie.runtime.Value;
import jolie.runtime.ValuePrettyPrinter;
import jolie.runtime.VariablePath;
import jolie.runtime.VariablePathBuilder;
import jolie.runtime.embedding.RequestResponse;
public class RuntimeService extends JavaService
{
private final Interpreter interpreter;
public RuntimeService()
{
this.interpreter = Interpreter.getInstance();
}
public Value getLocalLocation()
{
Value v = Value.create();
v.setValue( interpreter.commCore().getLocalCommChannel() );
return v;
}
@RequestResponse
public void setMonitor( final Value request )
{
final VariablePath locationPath = new VariablePathBuilder( true )
.add( Constants.MONITOR_OUTPUTPORT_NAME, 0 )
.add( Constants.LOCATION_NODE_NAME, 0 ).toVariablePath();
locationPath.setValue( request.getFirstChild( Constants.LOCATION_NODE_NAME ) );
final VariablePath protocolPath = new VariablePathBuilder( true )
.add( Constants.MONITOR_OUTPUTPORT_NAME, 0 )
.add( Constants.PROTOCOL_NODE_NAME, 0 ).toVariablePath();
protocolPath.setValue( request.getFirstChild( Constants.PROTOCOL_NODE_NAME ) );
OutputPort port = new OutputPort(
interpreter(),
Constants.MONITOR_OUTPUTPORT_NAME,
locationPath,
protocolPath,
null,
true );
port.optimizeLocation();
interpreter.setMonitor( port );
}
@RequestResponse
public void setOutputPort( Value request )
{
String name = request.getFirstChild( "name" ).strValue();
Value locationValue = request.getFirstChild( "location" );
Value protocolValue = request.getFirstChild( "protocol" );
OutputPort port =
new OutputPort(
interpreter(),
name );
Value l;
Value r = interpreter.initThread().state().root();
l = r.getFirstChild( name ).getFirstChild( Constants.LOCATION_NODE_NAME );
if ( locationValue.isChannel() ) {
l.setValue( locationValue.channelValue() );
} else {
l.setValue( locationValue.strValue() );
}
r.getFirstChild( name ).getFirstChild( Constants.PROTOCOL_NODE_NAME ).refCopy( protocolValue );
r = ExecutionThread.currentThread().state().root();
l = r.getFirstChild( name ).getFirstChild( Constants.LOCATION_NODE_NAME );
if ( locationValue.isChannel() ) {
l.setValue( locationValue.channelValue() );
} else {
l.setValue( locationValue.strValue() );
}
r.getFirstChild( name ).getFirstChild( Constants.PROTOCOL_NODE_NAME ).deepCopy( protocolValue );
interpreter.register( name, port );
}
@RequestResponse
public Value getOutputPort( Value v ) throws FaultException
{
OutputPort foundOp = null;
Value ret = Value.create();
for ( OutputPort o : interpreter.outputPorts() ) {
if ( o.id().equals( v.getFirstChild( "name" ).strValue() ) ) {
foundOp = o;
}
}
if ( foundOp == null ) {
throw new FaultException( "OuputPortDoesNotExist" );
} else {
ret.getFirstChild( "name" ).setValue( foundOp.id() );
try {
ret.getFirstChild( "protocol" ).setValue( foundOp.getProtocol().name() );
} catch ( Exception e ) {
ret.getFirstChild( "protocol" ).setValue( "" );
}
ret.getFirstChild( "location" ).setValue( foundOp.locationVariablePath().getValue().strValue() );
}
return ret;
}
@RequestResponse
public Value getOutputPorts()
{
Value ret = Value.create();
int counter = 0;
for ( OutputPort o : interpreter.outputPorts() ) {
ret.getChildren( "port" ).get( counter ).getFirstChild( "name" ).setValue( o.id() );
try {
ret.getChildren( "port" ).get( counter ).getFirstChild( "protocol" ).setValue( o.getProtocol().name() );
} catch ( Exception e ) {
ret.getChildren( "port" ).get( counter ).getFirstChild( "protocol" ).setValue( "" );
}
ret.getChildren( "port" ).get( counter ).getFirstChild( "location" ).setValue( o.locationVariablePath().getValue().strValue() );
counter++;
}
return ret;
}
@RequestResponse
public Value getProcessId( Value request ) {
Value response = Value.create();
response.setValue( ExecutionThread.currentThread().getSessionId() );
return response;
}
@RequestResponse
public void removeOutputPort( String outputPortName )
{
interpreter.removeOutputPort( outputPortName );
}
@RequestResponse
public void setRedirection( Value request )
throws FaultException
{
String serviceName = request.getChildren( "inputPortName" ).first().strValue();
CommListener listener =
interpreter.commCore().getListenerByInputPortName( serviceName );
if ( listener == null ) {
throw new FaultException( "RuntimeException", "Unknown inputPort: " + serviceName );
}
String resourceName = request.getChildren( "resourceName" ).first().strValue();
String opName = request.getChildren( "outputPortName" ).first().strValue();
try {
OutputPort port = interpreter.getOutputPort( opName );
listener.inputPort().redirectionMap().put( resourceName, port );
} catch ( InvalidIdException e ) {
throw new FaultException( "RuntimeException", e );
}
}
@RequestResponse
public void removeRedirection( Value request )
throws FaultException
{
String serviceName = request.getChildren( "inputPortName" ).first().strValue();
CommListener listener =
interpreter.commCore().getListenerByInputPortName( serviceName );
if ( listener == null ) {
throw new FaultException( "RuntimeException", "Unknown inputPort: " + serviceName );
}
String resourceName = request.getChildren( "resourceName" ).first().strValue();
listener.inputPort().redirectionMap().remove( resourceName );
}
public Value getRedirection( Value request )
throws FaultException
{
Value ret = null;
String inputPortName = request.getChildren( "inputPortName" ).first().strValue();
CommListener listener =
interpreter.commCore().getListenerByInputPortName( inputPortName );
if ( listener == null ) {
throw new FaultException( "RuntimeException", Value.create( "Invalid input port: " + inputPortName ) );
}
String resourceName = request.getChildren( "resourceName" ).first().strValue();
OutputPort p = listener.inputPort().redirectionMap().get( resourceName );
if ( p == null ) {
ret = Value.create();
} else {
ret = Value.create( p.id() );
}
return ret;
}
public Value getIncludePaths()
{
Value ret = Value.create();
String[] includePaths = interpreter.includePaths();
for ( String path : includePaths ) {
ret.getNewChild( "path" ).setValue( path );
}
return ret;
}
public Value loadEmbeddedService( Value request )
throws FaultException
{
try {
Value channel = Value.create();
String filePath = request.getFirstChild( "filepath" ).strValue();
String typeStr = request.getFirstChild( "type" ).strValue();
EmbeddedServiceType type =
jolie.lang.Constants.stringToEmbeddedServiceType( typeStr );
EmbeddedServiceLoader loader =
EmbeddedServiceLoader.create( interpreter(), type, filePath, channel );
loader.load();
return channel;
} catch ( EmbeddedServiceLoaderCreationException e ) {
e.printStackTrace();
throw new FaultException( "RuntimeException", e );
} catch ( EmbeddedServiceLoadingException e ) {
e.printStackTrace();
throw new FaultException( "RuntimeException", e );
}
}
@RequestResponse
public void loadLibrary( String libraryPath )
throws FaultException
{
try {
interpreter.getClassLoader().addJarResource( libraryPath );
} catch ( IOException e ) {
throw new FaultException( "IOException", e );
} catch ( IllegalArgumentException e ) {
throw new FaultException( "IOException", e );
}
}
@RequestResponse
public void callExit( Value request )
{
Object o = request.valueObject();
if ( o instanceof LocalCommChannel ) {
((LocalCommChannel) o).interpreter().exit();
}
}
public String dumpState()
{
Writer writer = new StringWriter();
ValuePrettyPrinter printer = new ValuePrettyPrinter( Value.createDeepCopy( interpreter.globalValue() ), writer, "Global state" );
try {
printer.run();
printer = new ValuePrettyPrinter( Value.createDeepCopy( ExecutionThread.currentThread().state().root() ), writer, "Session state" );
printer.run();
} catch ( IOException e ) {
} // Should never happen
return writer.toString();
}
public void halt( Value request )
{
final String status_field = "status";
int status = 0;
if ( request.hasChildren( status_field ) ) {
status = request.getFirstChild( status_field ).intValue();
}
Runtime.getRuntime().halt(status);
}
}
| javaServices/coreJavaServices/src/joliex/lang/RuntimeService.java | /**
* *************************************************************************
* Copyright (C) by Fabrizio Montesi * * This program is free software; you can
* redistribute it and/or modify * it under the terms of the GNU Library General
* Public License as * published by the Free Software Foundation; either version
* 2 of the * License, or (at your option) any later version. * * This program
* is distributed in the hope that it will be useful, * but WITHOUT ANY
* WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more
* details. * * You should have received a copy of the GNU Library General
* Public * License along with this program; if not, write to the * Free
* Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA. * * For details about the authors of this software, see the
* AUTHORS file. *
* *************************************************************************
*/
package joliex.lang;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import jolie.lang.Constants;
import jolie.ExecutionThread;
import jolie.Interpreter;
import jolie.lang.Constants.EmbeddedServiceType;
import jolie.net.CommListener;
import jolie.net.LocalCommChannel;
import jolie.net.ports.OutputPort;
import jolie.runtime.embedding.EmbeddedServiceLoader;
import jolie.runtime.embedding.EmbeddedServiceLoaderCreationException;
import jolie.runtime.embedding.EmbeddedServiceLoadingException;
import jolie.runtime.FaultException;
import jolie.runtime.InvalidIdException;
import jolie.runtime.JavaService;
import jolie.runtime.Value;
import jolie.runtime.ValuePrettyPrinter;
import jolie.runtime.VariablePath;
import jolie.runtime.VariablePathBuilder;
import jolie.runtime.embedding.RequestResponse;
public class RuntimeService extends JavaService
{
private final Interpreter interpreter;
public RuntimeService()
{
this.interpreter = Interpreter.getInstance();
}
public Value getLocalLocation()
{
Value v = Value.create();
v.setValue( interpreter.commCore().getLocalCommChannel() );
return v;
}
@RequestResponse
public void setMonitor( final Value request )
{
final VariablePath locationPath = new VariablePathBuilder( true )
.add( Constants.MONITOR_OUTPUTPORT_NAME, 0 )
.add( Constants.LOCATION_NODE_NAME, 0 ).toVariablePath();
locationPath.setValue( request.getFirstChild( Constants.LOCATION_NODE_NAME ) );
final VariablePath protocolPath = new VariablePathBuilder( true )
.add( Constants.MONITOR_OUTPUTPORT_NAME, 0 )
.add( Constants.PROTOCOL_NODE_NAME, 0 ).toVariablePath();
protocolPath.setValue( request.getFirstChild( Constants.PROTOCOL_NODE_NAME ) );
OutputPort port = new OutputPort(
interpreter(),
Constants.MONITOR_OUTPUTPORT_NAME,
locationPath,
protocolPath,
null,
true );
port.optimizeLocation();
interpreter.setMonitor( port );
}
@RequestResponse
public void setOutputPort( Value request )
{
String name = request.getFirstChild( "name" ).strValue();
Value locationValue = request.getFirstChild( "location" );
Value protocolValue = request.getFirstChild( "protocol" );
OutputPort port =
new OutputPort(
interpreter(),
name );
Value l;
Value r = interpreter.initThread().state().root();
l = r.getFirstChild( name ).getFirstChild( Constants.LOCATION_NODE_NAME );
if ( locationValue.isChannel() ) {
l.setValue( locationValue.channelValue() );
} else {
l.setValue( locationValue.strValue() );
}
r.getFirstChild( name ).getFirstChild( Constants.PROTOCOL_NODE_NAME ).refCopy( protocolValue );
r = ExecutionThread.currentThread().state().root();
l = r.getFirstChild( name ).getFirstChild( Constants.LOCATION_NODE_NAME );
if ( locationValue.isChannel() ) {
l.setValue( locationValue.channelValue() );
} else {
l.setValue( locationValue.strValue() );
}
r.getFirstChild( name ).getFirstChild( Constants.PROTOCOL_NODE_NAME ).deepCopy( protocolValue );
interpreter.register( name, port );
}
@RequestResponse
public Value getOutputPort( Value v ) throws FaultException
{
OutputPort foundOp = null;
Value ret = Value.create();
for ( OutputPort o : interpreter.outputPorts() ) {
if ( o.id().equals( v.getFirstChild( "name" ).strValue() ) ) {
foundOp = o;
}
}
if ( foundOp == null ) {
throw new FaultException( "OuputPortDoesNotExist" );
} else {
ret.getFirstChild( "name" ).setValue( foundOp.id() );
try {
ret.getFirstChild( "protocol" ).setValue( foundOp.getProtocol().name() );
} catch ( Exception e ) {
ret.getFirstChild( "protocol" ).setValue( "" );
}
ret.getFirstChild( "location" ).setValue( foundOp.locationVariablePath().getValue().strValue() );
}
return ret;
}
@RequestResponse
public Value getOutputPorts()
{
Value ret = Value.create();
int counter = 0;
for ( OutputPort o : interpreter.outputPorts() ) {
ret.getChildren( "port" ).get( counter ).getFirstChild( "name" ).setValue( o.id() );
try {
ret.getChildren( "port" ).get( counter ).getFirstChild( "protocol" ).setValue( o.getProtocol().name() );
} catch ( Exception e ) {
ret.getChildren( "port" ).get( counter ).getFirstChild( "protocol" ).setValue( "" );
}
ret.getChildren( "port" ).get( counter ).getFirstChild( "location" ).setValue( o.locationVariablePath().getValue().strValue() );
counter++;
}
return ret;
}
@RequestResponse
public Value getProcessId( Value request ) {
Value response = Value.create();
response.setValue( ExecutionThread.currentThread().getSessionId() );
return response;
}
@RequestResponse
public void removeOutputPort( String outputPortName )
{
interpreter.removeOutputPort( outputPortName );
}
@RequestResponse
public void setRedirection( Value request )
throws FaultException
{
String serviceName = request.getChildren( "inputPortName" ).first().strValue();
CommListener listener =
interpreter.commCore().getListenerByInputPortName( serviceName );
if ( listener == null ) {
throw new FaultException( "RuntimeException", "Unknown inputPort: " + serviceName );
}
String resourceName = request.getChildren( "resourceName" ).first().strValue();
String opName = request.getChildren( "outputPortName" ).first().strValue();
try {
OutputPort port = interpreter.getOutputPort( opName );
listener.inputPort().redirectionMap().put( resourceName, port );
} catch ( InvalidIdException e ) {
throw new FaultException( "RuntimeException", e );
}
}
@RequestResponse
public void removeRedirection( Value request )
throws FaultException
{
String serviceName = request.getChildren( "inputPortName" ).first().strValue();
CommListener listener =
interpreter.commCore().getListenerByInputPortName( serviceName );
if ( listener == null ) {
throw new FaultException( "RuntimeException", "Unknown inputPort: " + serviceName );
}
String resourceName = request.getChildren( "resourceName" ).first().strValue();
listener.inputPort().redirectionMap().remove( resourceName );
}
public Value getRedirection( Value request )
throws FaultException
{
Value ret = null;
String inputPortName = request.getChildren( "inputPortName" ).first().strValue();
CommListener listener =
interpreter.commCore().getListenerByInputPortName( inputPortName );
if ( listener == null ) {
throw new FaultException( "RuntimeException", Value.create( "Invalid input port: " + inputPortName ) );
}
String resourceName = request.getChildren( "resourceName" ).first().strValue();
OutputPort p = listener.inputPort().redirectionMap().get( resourceName );
if ( p == null ) {
ret = Value.create();
} else {
ret = Value.create( p.id() );
}
return ret;
}
public Value getIncludePaths()
{
Value ret = Value.create();
String[] includePaths = interpreter.includePaths();
for ( String path : includePaths ) {
ret.getNewChild( "path" ).setValue( path );
}
return ret;
}
public Value loadEmbeddedService( Value request )
throws FaultException
{
try {
Value channel = Value.create();
String filePath = request.getFirstChild( "filepath" ).strValue();
String typeStr = request.getFirstChild( "type" ).strValue();
EmbeddedServiceType type =
jolie.lang.Constants.stringToEmbeddedServiceType( typeStr );
EmbeddedServiceLoader loader =
EmbeddedServiceLoader.create( interpreter(), type, filePath, channel );
loader.load();
return channel;
} catch ( EmbeddedServiceLoaderCreationException e ) {
e.printStackTrace();
throw new FaultException( "RuntimeException", e );
} catch ( EmbeddedServiceLoadingException e ) {
e.printStackTrace();
throw new FaultException( "RuntimeException", e );
}
}
@RequestResponse
public void loadLibrary( String libraryPath )
throws FaultException
{
try {
interpreter.getClassLoader().addJarResource( libraryPath );
} catch ( IOException e ) {
throw new FaultException( "IOException", e );
} catch ( IllegalArgumentException e ) {
throw new FaultException( "IOException", e );
}
}
@RequestResponse
public void callExit( Value request )
{
Object o = request.valueObject();
if ( o instanceof LocalCommChannel ) {
((LocalCommChannel) o).interpreter().exit();
}
}
public String dumpState()
{
Writer writer = new StringWriter();
ValuePrettyPrinter printer = new ValuePrettyPrinter( Value.createDeepCopy( interpreter.globalValue() ), writer, "Global state" );
try {
printer.run();
printer = new ValuePrettyPrinter( Value.createDeepCopy( ExecutionThread.currentThread().state().root() ), writer, "Session state" );
printer.run();
} catch ( IOException e ) {
} // Should never happen
return writer.toString();
}
public void halt( Value request )
{
final String status_field = "status";
int status = 0;
if ( request.hasChildren( status_field ) ) {
status = request.getFirstChild( status_field ).intValue();
}
Runtime.getRuntime().halt(status);
}
}
| License header fix.
Former-commit-id: 7ab6130f275d0d52dde14534a376ed56f4677874 | javaServices/coreJavaServices/src/joliex/lang/RuntimeService.java | License header fix. |
|
Java | lgpl-2.1 | b2c392cb7a07ed8ee8894fd9e2979c9d9fb268cc | 0 | beast-dev/beast-mcmc,maxbiostat/beast-mcmc,codeaudit/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,codeaudit/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,codeaudit/beast-mcmc,codeaudit/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,codeaudit/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,codeaudit/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc | /*
* ScaleOperator.java
*
* Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST 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
* of the License, or (at your option) any later version.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.inference.operators;
import dr.inference.model.Parameter;
import dr.inference.model.Bounds;
import dr.math.MathUtils;
import dr.xml.*;
/**
* A generic scale operator for use with a multi-dimensional parameters.
*
* @author Alexei Drummond
* @author Andrew Rambaut
*
* @version $Id: ScaleOperator.java,v 1.20 2005/06/14 10:40:34 rambaut Exp $
*/
public class ScaleOperator extends SimpleMCMCOperator implements CoercableMCMCOperator {
public static final String SCALE_OPERATOR = "scaleOperator";
public static final String SCALE_ALL = "scaleAll";
public static final String SCALE_FACTOR = "scaleFactor";
private Parameter indicator;
private double indicatorOnProb;
public ScaleOperator(Parameter parameter, boolean scaleAll, double scale, int weight, int mode, Parameter indicator,
double indicatorOnProb) {
this.parameter = parameter;
this.indicator = indicator;
this.indicatorOnProb = indicatorOnProb;
this.scaleAll = scaleAll;
this.scaleFactor = scale;
this.weight = weight;
this.mode = mode;
}
/** @return the parameter this operator acts on. */
public Parameter getParameter() { return parameter; }
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() throws OperatorFailedException {
final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0/scaleFactor) - scaleFactor)));
double logq;
final Bounds bounds = parameter.getBounds();
final int dim = parameter.getDimension();
if (scaleAll) {
// update all dimensions
// hasting ratio is dim-2 times of 1dim case. why?
logq = (dim - 2) * Math.log(scale);
for (int i = 0; i < dim; i++) {
parameter.setParameterValue(i, parameter.getParameterValue(i) * scale);
}
// why after changing? in the 1dim it is doen before?
for (int i = 0; i < dim; i++) {
final double parameterValue = parameter.getParameterValue(i);
if (parameterValue < bounds.getLowerLimit(i) ||
parameterValue > bounds.getUpperLimit(i)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
}
} else {
logq = - Math.log(scale);
int index;
if( indicator != null ) {
final int idim = indicator.getDimension();
final boolean impliedOne = idim == dim - 1;
int[] loc = new int[idim];
int nLoc = 0;
final boolean takeOne = MathUtils.nextDouble() < indicatorOnProb;
if( impliedOne && takeOne ) {
loc[nLoc] = 0;
++nLoc;
}
for (int i = 0; i < idim; i++) {
final double value = indicator.getStatisticValue(i);
if( takeOne == value > 0 ) {
loc[nLoc] = i + (impliedOne ? 1 : 0);
++nLoc;
}
}
if( nLoc > 0 ) {
final int rand = MathUtils.nextInt(nLoc);
index = loc[rand];
} else {
throw new OperatorFailedException("no active indicators");
}
} else {
index = MathUtils.nextInt(dim);
}
final double oldValue = parameter.getParameterValue(index);
final double newValue = scale * oldValue;
if (newValue < bounds.getLowerLimit(index) ||
newValue > bounds.getUpperLimit(index)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
parameter.setParameterValue(index, newValue);
// provides a hook for subclasses
cleanupOperation(newValue, oldValue);
}
return logq;
}
/**
* This method should be overridden by operators that need to do something just before the return of doOperation.
* @param newValue the proposed parameter value
* @param oldValue the old parameter value
*/
void cleanupOperation(double newValue, double oldValue) {
// DO NOTHING
}
//MCMCOperator INTERFACE
public final String getOperatorName() { return parameter.getParameterName(); }
public double getCoercableParameter() {
return Math.log(1.0/scaleFactor - 1.0);
}
public void setCoercableParameter(double value) {
scaleFactor = 1.0/(Math.exp(value) + 1.0);
}
public double getRawParameter() {
return scaleFactor;
}
public int getMode() {
return mode;
}
public double getScaleFactor() { return scaleFactor; }
public double getTargetAcceptanceProbability() { return 0.234; }
public double getMinimumAcceptanceLevel() { return 0.1;}
public double getMaximumAcceptanceLevel() { return 0.4;}
public double getMinimumGoodAcceptanceLevel() { return 0.20; }
public double getMaximumGoodAcceptanceLevel() { return 0.30; }
public int getWeight() { return weight; }
public void setWeight(int w) { weight = w; }
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
double sf = OperatorUtils.optimizeScaleFactor(scaleFactor, prob, targetProb);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else return "";
}
public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
public String getParserName() { return SCALE_OPERATOR; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
boolean scaleAll = false;
int mode = CoercableMCMCOperator.DEFAULT;
if (xo.hasAttribute(SCALE_ALL)) {
scaleAll = xo.getBooleanAttribute(SCALE_ALL);
}
if (xo.hasAttribute(AUTO_OPTIMIZE)) {
if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) {
mode = CoercableMCMCOperator.COERCION_ON;
} else {
mode = CoercableMCMCOperator.COERCION_OFF;
}
}
int weight = xo.getIntegerAttribute(WEIGHT);
double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
if (scaleFactor <= 0.0 || scaleFactor >= 1.0) {
throw new XMLParseException("scaleFactor must be between 0.0 and 1.0");
}
Parameter parameter = (Parameter)xo.getChild(Parameter.class);
Parameter indicator = null;
final XMLObject cxo = (XMLObject) xo.getChild("indicators");
double indicatorOnProb = 1.0;
if( cxo != null ) {
indicator = (Parameter) cxo.getChild(Parameter.class);
if( cxo.hasAttribute("pickoneprob") ) {
indicatorOnProb = cxo.getDoubleAttribute("pickoneprob");
}
}
return new ScaleOperator(parameter, scaleAll, scaleFactor, weight, mode, indicator, indicatorOnProb);
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "This element returns a scale operator on a given parameter.";
}
public Class getReturnType() { return MCMCOperator.class; }
public XMLSyntaxRule[] getSyntaxRules() { return rules; }
private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
AttributeRule.newDoubleRule(SCALE_FACTOR),
AttributeRule.newBooleanRule(SCALE_ALL, true),
AttributeRule.newIntegerRule(WEIGHT),
AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
new ElementRule(Parameter.class)
};
};
public String toString() {
return "scaleOperator(" + parameter.getParameterName() + " [" + scaleFactor + ", " + (1.0/scaleFactor) + "]";
}
//PRIVATE STUFF
private Parameter parameter = null;
private boolean scaleAll = false;
private double scaleFactor = 0.5;
private int mode = CoercableMCMCOperator.DEFAULT;
private int weight = 1;
}
| src/dr/inference/operators/ScaleOperator.java | /*
* ScaleOperator.java
*
* Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST 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
* of the License, or (at your option) any later version.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.inference.operators;
import dr.inference.model.Parameter;
import dr.inference.model.Bounds;
import dr.math.MathUtils;
import dr.xml.*;
/**
* A generic scale operator for use with a multi-dimensional parameters.
*
* @author Alexei Drummond
* @author Andrew Rambaut
*
* @version $Id: ScaleOperator.java,v 1.20 2005/06/14 10:40:34 rambaut Exp $
*/
public class ScaleOperator extends SimpleMCMCOperator implements CoercableMCMCOperator {
public static final String SCALE_OPERATOR = "scaleOperator";
public static final String SCALE_ALL = "scaleAll";
public static final String SCALE_FACTOR = "scaleFactor";
private Parameter indicator;
private double indicatorOnProb;
public ScaleOperator(Parameter parameter, boolean scaleAll, double scale, int weight, int mode, Parameter indicator,
double indicatorOnProb) {
this.parameter = parameter;
this.indicator = indicator;
this.indicatorOnProb = indicatorOnProb;
this.scaleAll = scaleAll;
this.scaleFactor = scale;
this.weight = weight;
this.mode = mode;
}
/** @return the parameter this operator acts on. */
public Parameter getParameter() { return parameter; }
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() throws OperatorFailedException {
final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0/scaleFactor) - scaleFactor)));
double logq;
final Bounds bounds = parameter.getBounds();
final int dim = parameter.getDimension();
if (scaleAll) {
// update all dimensions
// hasting ratio is dim-2 times of 1dim case. why?
logq = (dim - 2) * Math.log(scale);
for (int i = 0; i < dim; i++) {
parameter.setParameterValue(i, parameter.getParameterValue(i) * scale);
}
// why after changing? in the 1dim it is doen before?
for (int i = 0; i < dim; i++) {
final double parameterValue = parameter.getParameterValue(i);
if (parameterValue < bounds.getLowerLimit(i) ||
parameterValue > bounds.getUpperLimit(i)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
}
} else {
// scale is chosen at uniform from an interval of length 1/scaleFactor, so pdf is 1/scaleFactor and
// hastings ratio is lg(1/scale) = -lg(scale)
logq = - Math.log(scale);
int index;
if( indicator != null ) {
final int idim = indicator.getDimension();
final boolean impliedOne = idim == dim - 1;
int[] loc = new int[idim];
int nLoc = 0;
final boolean takeOne = MathUtils.nextDouble() < indicatorOnProb;
if( impliedOne && takeOne ) {
loc[nLoc] = 0;
++nLoc;
}
for (int i = 0; i < idim; i++) {
final double value = indicator.getStatisticValue(i);
if( takeOne == value > 0 ) {
loc[nLoc] = i + (impliedOne ? 1 : 0);
++nLoc;
}
}
if( nLoc > 0 ) {
final int rand = MathUtils.nextInt(nLoc);
index = loc[rand];
} else {
throw new OperatorFailedException("no active indicators");
}
} else {
index = MathUtils.nextInt(dim);
}
final double oldValue = parameter.getParameterValue(index);
final double newValue = scale * oldValue;
if (newValue < bounds.getLowerLimit(index) ||
newValue > bounds.getUpperLimit(index)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
parameter.setParameterValue(index, newValue);
// provides a hook for subclasses
cleanupOperation(newValue, oldValue);
}
return logq;
}
/**
* This method should be overridden by operators that need to do something just before the return of doOperation.
* @param newValue the proposed parameter value
* @param oldValue the old parameter value
*/
void cleanupOperation(double newValue, double oldValue) {
// DO NOTHING
}
//MCMCOperator INTERFACE
public final String getOperatorName() { return parameter.getParameterName(); }
public double getCoercableParameter() {
return Math.log(1.0/scaleFactor - 1.0);
}
public void setCoercableParameter(double value) {
scaleFactor = 1.0/(Math.exp(value) + 1.0);
}
public double getRawParameter() {
return scaleFactor;
}
public int getMode() {
return mode;
}
public double getScaleFactor() { return scaleFactor; }
public double getTargetAcceptanceProbability() { return 0.234; }
public double getMinimumAcceptanceLevel() { return 0.1;}
public double getMaximumAcceptanceLevel() { return 0.4;}
public double getMinimumGoodAcceptanceLevel() { return 0.20; }
public double getMaximumGoodAcceptanceLevel() { return 0.30; }
public int getWeight() { return weight; }
public void setWeight(int w) { weight = w; }
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
double sf = OperatorUtils.optimizeScaleFactor(scaleFactor, prob, targetProb);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else return "";
}
public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
public String getParserName() { return SCALE_OPERATOR; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
boolean scaleAll = false;
int mode = CoercableMCMCOperator.DEFAULT;
if (xo.hasAttribute(SCALE_ALL)) {
scaleAll = xo.getBooleanAttribute(SCALE_ALL);
}
if (xo.hasAttribute(AUTO_OPTIMIZE)) {
if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) {
mode = CoercableMCMCOperator.COERCION_ON;
} else {
mode = CoercableMCMCOperator.COERCION_OFF;
}
}
int weight = xo.getIntegerAttribute(WEIGHT);
double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
if (scaleFactor <= 0.0 || scaleFactor >= 1.0) {
throw new XMLParseException("scaleFactor must be between 0.0 and 1.0");
}
Parameter parameter = (Parameter)xo.getChild(Parameter.class);
Parameter indicator = null;
final XMLObject cxo = (XMLObject) xo.getChild("indicator");
double indicatorOnProb = 1.0;
if( cxo != null ) {
indicator = (Parameter) cxo.getChild(Parameter.class);
if( cxo.hasAttribute("pickoneprob") ) {
indicatorOnProb = cxo.getDoubleAttribute("pickoneprob");
}
}
return new ScaleOperator(parameter, scaleAll, scaleFactor, weight, mode, indicator, indicatorOnProb);
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "This element returns a scale operator on a given parameter.";
}
public Class getReturnType() { return MCMCOperator.class; }
public XMLSyntaxRule[] getSyntaxRules() { return rules; }
private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
AttributeRule.newDoubleRule(SCALE_FACTOR),
AttributeRule.newBooleanRule(SCALE_ALL, true),
AttributeRule.newIntegerRule(WEIGHT),
AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
new ElementRule(Parameter.class)
};
};
public String toString() {
return "scaleOperator(" + parameter.getParameterName() + " [" + scaleFactor + ", " + (1.0/scaleFactor) + "]";
}
//PRIVATE STUFF
private Parameter parameter = null;
private boolean scaleAll = false;
private double scaleFactor = 0.5;
private int mode = CoercableMCMCOperator.DEFAULT;
private int weight = 1;
}
| correct element name | src/dr/inference/operators/ScaleOperator.java | correct element name |
|
Java | apache-2.0 | 473b77cd8e13dc5e44f48549dd5a2f434505afc3 | 0 | martylamb/nailgun,balihoo/nailgun,rhendric/nailgun,nickman/nailgun,balihoo/nailgun,martylamb/nailgun,martylamb/nailgun,bhamiltoncx/nailgun,bhamiltoncx/nailgun,balihoo/nailgun,benhyland/nailgun,benhyland/nailgun,rhendric/nailgun,nickman/nailgun | /*
Copyright 2004-2012, Martian Software, 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.martiansoftware.nailgun;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Properties;
/**
* <p>Provides quite a bit of potentially useful information to classes
* specifically written for NailGun. The <a href="NGServer.html">NailGun server</a> itself, its
* <a href="AliasManager.html">AliasManager</a>, the remote client's environment variables, and other
* information is available via this class. For all intents and purposes,
* the NGContext represents a single connection from a NailGun client.</p>
*
* If a class is written with a
*
* <pre><code>
* public static void nailMain(NGContext context)
* </code></pre>
*
* method, that method will be called by NailGun instead of the traditional
* <code>main(String[])</code> method normally used for programs. A fully populated <code>NGContext</code>
* object will then be provided to <code>nailMain()</code>.
*
* @author <a href="http://www.martiansoftware.com/contact.html">Marty Lamb </a>
*/
public class NGContext {
/**
* The remote host's environment variables
*/
private Properties remoteEnvironment = null;
/**
* The remote host's address
*/
private InetAddress remoteHost = null;
/**
* The port on the remote host that is communicating with NailGun
*/
private int remotePort = 0;
/**
* Command line arguments for the nail
*/
private String[] args = null;
/**
* A stream to which a client exit code can be printed
*/
private PrintStream exitStream = null;
/**
* The NGServer that accepted this connection
*/
private NGServer server = null;
/**
* The command that was issued for this connection
*/
private String command = null;
private String workingDirectory = null;
/**
* The client's stdin
*/
public InputStream in = null;
/**
* The client's stdout
*/
public PrintStream out = null;
/**
* The client's stderr
*/
public PrintStream err = null;
/**
* Creates a new, empty NGContext
*/
public NGContext() {
super();
}
public void setExitStream(PrintStream exitStream) {
this.exitStream = exitStream;
}
public void setPort(int remotePort) {
this.remotePort = remotePort;
}
public void setCommand(String command) {
this.command = command;
}
/**
* Returns the command that was issued by the client (either an alias or the name of a class).
* This allows multiple aliases to point to the same class but result in different behaviors.
* @return the command issued by the client
*/
public String getCommand() {
return (command);
}
void setWorkingDirectory(String workingDirectory) {
this.workingDirectory = workingDirectory;
}
/**
* Returns the current working directory of the client, as reported by the client.
* This is a String that will use the client's <code>File.separator</code> ('/' or '\'),
* which may differ from the separator on the server.
* @return the current working directory of the client
*/
public String getWorkingDirectory() {
return (workingDirectory);
}
void setEnv(Properties remoteEnvironment) {
this.remoteEnvironment = remoteEnvironment;
}
void setInetAddress(InetAddress remoteHost) {
this.remoteHost = remoteHost;
}
public void setArgs(String[] args) {
this.args = args;
}
void setNGServer(NGServer server) {
this.server = server;
}
/**
* Returns a <code>java.util.Properties</code> object containing a copy
* of the client's environment variables
* @see java.util.Properties
* @return a <code>java.util.Properties</code> object containing a copy
* of the client's environment variables
*/
public Properties getEnv() {
return (remoteEnvironment);
}
/**
* Returns the file separator ('/' or '\\') used by the client's os.
* @return the file separator ('/' or '\\') used by the client's os.
*/
public String getFileSeparator() {
return (remoteEnvironment.getProperty("NAILGUN_FILESEPARATOR"));
}
/**
* Returns the path separator (':' or ';') used by the client's os.
* @return the path separator (':' or ';') used by the client's os.
*/
public String getPathSeparator() {
return (remoteEnvironment.getProperty("NAILGUN_PATHSEPARATOR"));
}
/**
* Returns the address of the client at the other side of this connection.
* @return the address of the client at the other side of this connection.
*/
public InetAddress getInetAddress() {
return (remoteHost);
}
/**
* Returns the command line arguments for the command
* implementation (nail) on the server.
* @return the command line arguments for the command
* implementation (nail) on the server.
*/
public String[] getArgs() {
return (args);
}
/**
* Returns the NGServer that accepted this connection
* @return the NGServer that accepted this connection
*/
public NGServer getNGServer() {
return (server);
}
/**
* Sends an exit command with the specified exit code to
* the client. The client will exit immediately with
* the specified exit code; you probably want to return
* from nailMain immediately after calling this.
*
* @param exitCode the exit code with which the client
* should exit
*/
public void exit(int exitCode) {
exitStream.println(exitCode);
}
/**
* Returns the port on the client connected to the NailGun
* server.
* @return the port on the client connected to the NailGun
* server.
*/
public int getPort() {
return (remotePort);
}
/**
* Throws a <code>java.lang.SecurityException</code> if the client is not
* connected via the loopback address.
*/
public void assertLoopbackClient() {
if (!getInetAddress().isLoopbackAddress()) {
throw (new SecurityException("Client is not at loopback address."));
}
}
/**
* Throws a <code>java.lang.SecurityException</code> if the client is not
* connected from the local machine.
*/
public void assertLocalClient() {
NetworkInterface iface = null;
try {
iface = NetworkInterface.getByInetAddress(getInetAddress());
} catch (java.net.SocketException se) {
throw (new SecurityException("Unable to determine if client is local. Assuming he isn't."));
}
if ((iface == null) && (!getInetAddress().isLoopbackAddress())) {
throw (new SecurityException("Client is not local."));
}
}
/**
* @return the {@link NGInputStream} for this session.
*/
private NGInputStream getInputStream() {
return (NGInputStream) this.in;
}
/**
* @return true if client is connected, false if a client exit has been detected.
*/
public boolean isClientConnected() {
return getInputStream().isClientConnected();
}
/**
* @param listener the {@link NGClientListener} to be notified of client events.
*/
public void addClientListener(NGClientListener listener) {
getInputStream().addClientListener(listener);
}
/**
* @param listener the {@link NGClientListener} to no longer be notified of client events.
*/
public void removeClientListener(NGClientListener listener) {
getInputStream().removeClientListener(listener);
}
/**
* @param listener the {@link com.martiansoftware.nailgun.NGHeartbeatListener} to be notified of client events.
*/
public void addHeartbeatListener(NGHeartbeatListener listener) {
getInputStream().addHeartbeatListener(listener);
}
/**
* @param listener the {@link NGHeartbeatListener} to no longer be notified of client events.
*/
public void removeHeartbeatListener(NGHeartbeatListener listener) {
getInputStream().removeHeartbeatListener(listener);
}
}
| nailgun-server/src/main/java/com/martiansoftware/nailgun/NGContext.java | /*
Copyright 2004-2012, Martian Software, 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.martiansoftware.nailgun;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Properties;
/**
* <p>Provides quite a bit of potentially useful information to classes
* specifically written for NailGun. The <a href="NGServer.html">NailGun server</a> itself, its
* <a href="AliasManager.html">AliasManager</a>, the remote client's environment variables, and other
* information is available via this class. For all intents and purposes,
* the NGContext represents a single connection from a NailGun client.</p>
*
* If a class is written with a
*
* <pre><code>
* public static void nailMain(NGContext context)
* </code></pre>
*
* method, that method will be called by NailGun instead of the traditional
* <code>main(String[])</code> method normally used for programs. A fully populated <code>NGContext</code>
* object will then be provided to <code>nailMain()</code>.
*
* @author <a href="http://www.martiansoftware.com/contact.html">Marty Lamb </a>
*/
public class NGContext {
/**
* The remote host's environment variables
*/
private Properties remoteEnvironment = null;
/**
* The remote host's address
*/
private InetAddress remoteHost = null;
/**
* The port on the remote host that is communicating with NailGun
*/
private int remotePort = 0;
/**
* Command line arguments for the nail
*/
private String[] args = null;
/**
* A stream to which a client exit code can be printed
*/
private PrintStream exitStream = null;
/**
* The NGServer that accepted this connection
*/
private NGServer server = null;
/**
* The command that was issued for this connection
*/
private String command = null;
private String workingDirectory = null;
/**
* The client's stdin
*/
public InputStream in = null;
/**
* The client's stdout
*/
public PrintStream out = null;
/**
* The client's stderr
*/
public PrintStream err = null;
/**
* Creates a new, empty NGContext
*/
public NGContext() {
super();
}
void setExitStream(PrintStream exitStream) {
this.exitStream = exitStream;
}
void setPort(int remotePort) {
this.remotePort = remotePort;
}
void setCommand(String command) {
this.command = command;
}
/**
* Returns the command that was issued by the client (either an alias or the name of a class).
* This allows multiple aliases to point to the same class but result in different behaviors.
* @return the command issued by the client
*/
public String getCommand() {
return (command);
}
void setWorkingDirectory(String workingDirectory) {
this.workingDirectory = workingDirectory;
}
/**
* Returns the current working directory of the client, as reported by the client.
* This is a String that will use the client's <code>File.separator</code> ('/' or '\'),
* which may differ from the separator on the server.
* @return the current working directory of the client
*/
public String getWorkingDirectory() {
return (workingDirectory);
}
void setEnv(Properties remoteEnvironment) {
this.remoteEnvironment = remoteEnvironment;
}
void setInetAddress(InetAddress remoteHost) {
this.remoteHost = remoteHost;
}
public void setArgs(String[] args) {
this.args = args;
}
void setNGServer(NGServer server) {
this.server = server;
}
/**
* Returns a <code>java.util.Properties</code> object containing a copy
* of the client's environment variables
* @see java.util.Properties
* @return a <code>java.util.Properties</code> object containing a copy
* of the client's environment variables
*/
public Properties getEnv() {
return (remoteEnvironment);
}
/**
* Returns the file separator ('/' or '\\') used by the client's os.
* @return the file separator ('/' or '\\') used by the client's os.
*/
public String getFileSeparator() {
return (remoteEnvironment.getProperty("NAILGUN_FILESEPARATOR"));
}
/**
* Returns the path separator (':' or ';') used by the client's os.
* @return the path separator (':' or ';') used by the client's os.
*/
public String getPathSeparator() {
return (remoteEnvironment.getProperty("NAILGUN_PATHSEPARATOR"));
}
/**
* Returns the address of the client at the other side of this connection.
* @return the address of the client at the other side of this connection.
*/
public InetAddress getInetAddress() {
return (remoteHost);
}
/**
* Returns the command line arguments for the command
* implementation (nail) on the server.
* @return the command line arguments for the command
* implementation (nail) on the server.
*/
public String[] getArgs() {
return (args);
}
/**
* Returns the NGServer that accepted this connection
* @return the NGServer that accepted this connection
*/
public NGServer getNGServer() {
return (server);
}
/**
* Sends an exit command with the specified exit code to
* the client. The client will exit immediately with
* the specified exit code; you probably want to return
* from nailMain immediately after calling this.
*
* @param exitCode the exit code with which the client
* should exit
*/
public void exit(int exitCode) {
exitStream.println(exitCode);
}
/**
* Returns the port on the client connected to the NailGun
* server.
* @return the port on the client connected to the NailGun
* server.
*/
public int getPort() {
return (remotePort);
}
/**
* Throws a <code>java.lang.SecurityException</code> if the client is not
* connected via the loopback address.
*/
public void assertLoopbackClient() {
if (!getInetAddress().isLoopbackAddress()) {
throw (new SecurityException("Client is not at loopback address."));
}
}
/**
* Throws a <code>java.lang.SecurityException</code> if the client is not
* connected from the local machine.
*/
public void assertLocalClient() {
NetworkInterface iface = null;
try {
iface = NetworkInterface.getByInetAddress(getInetAddress());
} catch (java.net.SocketException se) {
throw (new SecurityException("Unable to determine if client is local. Assuming he isn't."));
}
if ((iface == null) && (!getInetAddress().isLoopbackAddress())) {
throw (new SecurityException("Client is not local."));
}
}
/**
* @return the {@link NGInputStream} for this session.
*/
private NGInputStream getInputStream() {
return (NGInputStream) this.in;
}
/**
* @return true if client is connected, false if a client exit has been detected.
*/
public boolean isClientConnected() {
return getInputStream().isClientConnected();
}
/**
* @param listener the {@link NGClientListener} to be notified of client events.
*/
public void addClientListener(NGClientListener listener) {
getInputStream().addClientListener(listener);
}
/**
* @param listener the {@link NGClientListener} to no longer be notified of client events.
*/
public void removeClientListener(NGClientListener listener) {
getInputStream().removeClientListener(listener);
}
/**
* @param listener the {@link com.martiansoftware.nailgun.NGHeartbeatListener} to be notified of client events.
*/
public void addHeartbeatListener(NGHeartbeatListener listener) {
getInputStream().addHeartbeatListener(listener);
}
/**
* @param listener the {@link NGHeartbeatListener} to no longer be notified of client events.
*/
public void removeHeartbeatListener(NGHeartbeatListener listener) {
getInputStream().removeHeartbeatListener(listener);
}
}
| Increase visibility of NGContext methods to allow integration testing.
| nailgun-server/src/main/java/com/martiansoftware/nailgun/NGContext.java | Increase visibility of NGContext methods to allow integration testing. |
|
Java | apache-2.0 | c819da3b0eca94f1ac11afdca98ae426369a32f0 | 0 | Donnerbart/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,Donnerbart/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,mdogan/hazelcast,tkountis/hazelcast,Donnerbart/hazelcast,tombujok/hazelcast,lmjacksoniii/hazelcast,juanavelez/hazelcast,lmjacksoniii/hazelcast,mesutcelik/hazelcast,emrahkocaman/hazelcast,tufangorel/hazelcast,mdogan/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,mesutcelik/hazelcast,juanavelez/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,emrahkocaman/hazelcast,tombujok/hazelcast,tkountis/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,mdogan/hazelcast | /*
* Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map.impl;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.internal.serialization.SerializationService;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import static com.hazelcast.util.Preconditions.checkNotNull;
/**
* A {@link java.util.Map.Entry Map.Entry} implementation which serializes/de-serializes key and value objects on demand.
* It is beneficial when you need to prevent unneeded serialization/de-serialization
* when creating a {@link java.util.Map.Entry Map.Entry}. Mainly targeted to supply a lazy entry to
* {@link com.hazelcast.map.EntryProcessor#process(Map.Entry)} and
* {@link com.hazelcast.map.EntryBackupProcessor#processBackup(Map.Entry)}} methods.
* <p/>
* <STRONG>Note that this implementation is not synchronized and is not thread-safe.</STRONG>
*
* LazyMapEntry itself is serializable as long as the object representations of both key and value are serializable.
* After serialization objects are resolved using injected SerializationService. De-serialized LazyMapEntry
* does contain object representation only Data representations and SerializationService is set to null. In other
* words: It's as usable just as a regular Map.Entry.
*
* @see com.hazelcast.map.impl.operation.EntryOperation#createMapEntry(Data, Object)
*/
public class LazyMapEntry implements Map.Entry, Serializable {
private static final long serialVersionUID = 0L;
private transient Object keyObject;
private transient Object valueObject;
private transient Data keyData;
private transient Data valueData;
private transient boolean modified;
private transient SerializationService serializationService;
public LazyMapEntry() {
}
public LazyMapEntry(Object key, Object value, SerializationService serializationService) {
init(key, value, serializationService);
}
public void init(Object key, Object value, SerializationService serializationService) {
checkNotNull(key, "key cannot be null");
checkNotNull(serializationService, "SerializationService cannot be null");
keyData = null;
keyObject = null;
if (key instanceof Data) {
this.keyData = (Data) key;
} else {
this.keyObject = key;
}
valueData = null;
valueObject = null;
if (value instanceof Data) {
this.valueData = (Data) value;
} else {
this.valueObject = value;
}
this.serializationService = serializationService;
}
@Override
public Object getKey() {
if (keyObject == null) {
keyObject = serializationService.toObject(keyData);
}
return keyObject;
}
@Override
public Object getValue() {
if (valueObject == null) {
valueObject = serializationService.toObject(valueData);
}
return valueObject;
}
@Override
public Object setValue(Object value) {
modified = true;
Object oldValue = getValue();
this.valueObject = value;
this.valueData = null;
return oldValue;
}
public Object getKeyData() {
if (keyData == null) {
keyData = serializationService.toData(keyObject);
}
return keyData;
}
public Object getValueData() {
if (valueData == null) {
valueData = serializationService.toData(valueObject);
}
return valueData;
}
public boolean isModified() {
return modified;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
return eq(getKey(), e.getKey()) && eq(getValue(), e.getValue());
}
private static boolean eq(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
@Override
public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode())
^ (getValue() == null ? 0 : getValue().hashCode());
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
keyObject = s.readObject();
valueObject = s.readObject();
}
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeObject(getKey());
s.writeObject(getValue());
}
}
| hazelcast/src/main/java/com/hazelcast/map/impl/LazyMapEntry.java | /*
* Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map.impl;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.internal.serialization.SerializationService;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import static com.hazelcast.util.Preconditions.checkNotNull;
/**
* A {@link java.util.Map.Entry Map.Entry} implementation which serializes/de-serializes key and value objects on demand.
* It is beneficial when you need to prevent unneeded serialization/de-serialization
* when creating a {@link java.util.Map.Entry Map.Entry}. Mainly targeted to supply a lazy entry to
* {@link com.hazelcast.map.EntryProcessor#process(Map.Entry)} and
* {@link com.hazelcast.map.EntryBackupProcessor#processBackup(Map.Entry)}} methods.
* <p/>
* <STRONG>Note that this implementation is not synchronized and is not thread-safe.</STRONG>
*
* LazyMapEntry itself is serializable as long as the object representations of both key and value are serializable.
* After serialization objects are resolved using injected SerializationService. De-serialized LazyMapEntry
* does contain object representation only Data representations and SerializationService is set to null. In other
* words: It's as usable just as a regular Map.Entry.
*
* @see com.hazelcast.map.impl.operation.EntryOperation#createMapEntry(Data, Object)
*/
public class LazyMapEntry implements Map.Entry, Serializable {
private static final long serialVersionUID = 0L;
private transient Object keyObject;
private transient Object valueObject;
private transient Data keyData;
private transient Data valueData;
private transient boolean modified;
private transient SerializationService serializationService;
public LazyMapEntry() {
}
public LazyMapEntry(Object key, Object value, SerializationService serializationService) {
init(key, value, serializationService);
}
public void init(Object key, Object value, SerializationService serializationService) {
checkNotNull(key, "key cannot be null");
checkNotNull(serializationService, "SerializationService cannot be null");
keyData = null;
keyObject = null;
if (key instanceof Data) {
this.keyData = (Data) key;
} else {
this.keyObject = key;
}
valueData = null;
valueObject = null;
if (value instanceof Data) {
this.valueData = (Data) value;
} else {
this.valueObject = value;
}
this.serializationService = serializationService;
}
@Override
public Object getKey() {
if (keyObject == null) {
keyObject = serializationService.toObject(keyData);
}
return keyObject;
}
@Override
public Object getValue() {
if (valueObject == null) {
valueObject = serializationService.toObject(valueData);
}
return valueObject;
}
@Override
public Object setValue(Object value) {
modified = true;
Object oldValue = getValue();
this.valueObject = value;
this.valueData = null;
return oldValue;
}
public Object getKeyData() {
if (keyData == null) {
keyData = serializationService.toData(keyObject);
}
return keyData;
}
public Object getValueData() {
if (valueData == null) {
valueData = serializationService.toData(valueObject);
}
return valueData;
}
public boolean isModified() {
return modified;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
return equals(getKey(), e.getKey()) && equals(getValue(), e.getValue());
}
private static boolean equals(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
@Override
public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode())
^ (getValue() == null ? 0 : getValue().hashCode());
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
keyObject = s.readObject();
valueObject = s.readObject();
}
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeObject(getKey());
s.writeObject(getValue());
}
}
| Renamed LazyMapEntry.equals() to eq() as done in ConcurrentReferenceHashMap.SimpleEntry to prevent a critical SonarQube issue (Naming - Suspicious equals method name).
| hazelcast/src/main/java/com/hazelcast/map/impl/LazyMapEntry.java | Renamed LazyMapEntry.equals() to eq() as done in ConcurrentReferenceHashMap.SimpleEntry to prevent a critical SonarQube issue (Naming - Suspicious equals method name). |
|
Java | apache-2.0 | c40ef295314a52ef2bb71b1d1ad61c24deead6eb | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package verification.platu.logicAnalysis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import verification.platu.common.Pair;
import verification.platu.lpn.VarSet;
import verification.platu.main.Options;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
public class CompositionalAnalysis {
public CompositionalAnalysis(){
}
// public CompositeStateGraph compose(StateGraph sg1, StateGraph sg2){
// long start = System.currentTimeMillis();
//
// // check an output drives an input
// boolean compatible = false;
// for(String output : sg1.getOutputs()){
// VarSet inputs = sg2.getInputs();
// if(inputs.contains(output)){
// compatible = true;
// break;
// }
// }
//
// if(!compatible){
// VarSet inputs = sg1.getInputs();
// for(String output : sg2.getOutputs()){
// if(inputs.contains(output)){
// compatible = true;
// break;
// }
// }
// }
//
// if(!compatible){
// System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
// return null;
// }
//
// // create new node with init states
// State[] initStates = new State[2];
// initStates[0] = sg1.getInitialState();
// initStates[1] = sg2.getInitialState();
// CompositeState initNode = new CompositeState(initStates);
//
// HashSet<LPNTran> synchronousTrans = new HashSet<LPNTran>();
// synchronousTrans.addAll(sg1.getInputTranSet());
// synchronousTrans.retainAll(sg2.getOutputTranSet());
//
// HashSet<LPNTran> temp = new HashSet<LPNTran>();
// temp.addAll(sg2.getInputTranSet());
// temp.retainAll(sg1.getOutputTranSet());
// synchronousTrans.addAll(temp);
//
// List<LPNTran> inputTrans1 = new ArrayList<LPNTran>();
// inputTrans1.addAll(sg1.getInputTranSet());
// inputTrans1.removeAll(synchronousTrans);
//
// List<LPNTran> inputTrans2 = new ArrayList<LPNTran>();
// inputTrans2.addAll(sg2.getInputTranSet());
// inputTrans2.removeAll(synchronousTrans);
//
// // create new composite state graph
// StateGraph[] sgArray = new StateGraph[2];
// sgArray[0] = sg1;
// sgArray[1] = sg2;
// CompositeStateGraph compositeSG = new CompositeStateGraph(initNode, sgArray);
//
// // create CompositeState stack
// Stack<CompositeState> compositeStateStack = new Stack<CompositeState>();
//
// // initialize with initial MDD node
// compositeStateStack.push(initNode);
//
// List<LPNTran> tranList1 = new ArrayList<LPNTran>();
// List<State> stateList1 = new ArrayList<State>();
// List<LPNTran> tranList2 = new ArrayList<LPNTran>();
// List<State> stateList2 = new ArrayList<State>();
// List<State> intersect1 = new ArrayList<State>();
// List<State> intersect2 = new ArrayList<State>();
// List<LPNTran> intersectTran = new ArrayList<LPNTran>();
//
// long peakUsed = 0;
// long peakTotal = 0;
//
// //while stack is not empty
// while(!compositeStateStack.isEmpty()){
// //pop stack
// CompositeState currentCompositeState = compositeStateStack.pop();
//
// State[] stateTuple = currentCompositeState.getStateTuple();
// State s1 = stateTuple[0];
// State s2 = stateTuple[1];
//
// // find next state transitions for each state
//// LPNTranSet enabled1 = sg1.getEnabled(s1);
//// LPNTranSet enabled2 = sg2.getEnabled(s2);
// List<LPNTran> enabled1 = sg1.lpnTransitionMap.get(s1);
// List<LPNTran> enabled2 = sg2.lpnTransitionMap.get(s2);
//
// tranList1.clear();
// stateList1.clear();
// tranList2.clear();
// stateList2.clear();
// intersect1.clear();
// intersect2.clear();
// intersectTran.clear();
//
// for(LPNTran lpnTran : enabled1){
// if(lpnTran.local()){
// tranList1.add(lpnTran);
// stateList1.add((State) lpnTran.getNextState(s1));
// }
// else{
// if(synchronousTrans.contains(lpnTran)){
//// State st = lpnTran.constraintTranMap.get(s2);
// State st = lpnTran.getNextState(s2);
// if(st != null){
// intersect1.add((State) lpnTran.getNextState(s1));
// intersect2.add(st);
// intersectTran.add(lpnTran);
// }
// }
// else{
// tranList1.add(lpnTran);
// stateList1.add((State) lpnTran.getNextState(s1));
// }
// }
// }
//
//
// for(LPNTran lpnTran : enabled2){
// if(lpnTran.local()){
// tranList2.add(lpnTran);
// stateList2.add((State) lpnTran.getNextState(s2));
// }
// else{
// if(synchronousTrans.contains(lpnTran)){
//// State st = lpnTran.constraintTranMap.get(s1);
// State st = lpnTran.getNextState(s1);
// if(st != null){
// intersect1.add(st);
// intersect2.add((State) lpnTran.getNextState(s2));
// intersectTran.add(lpnTran);
// }
// }
// else{
// tranList2.add(lpnTran);
// stateList2.add((State) lpnTran.getNextState(s2));
// }
// }
// }
//
// for(LPNTran lpnTran : inputTrans1){
//// State st = lpnTran.constraintTranMap.get(s1);
// State st = lpnTran.getNextState(s1);
// if(st != null){
// tranList1.add(lpnTran);
// stateList1.add(st);
// }
// }
//
// for(LPNTran lpnTran : inputTrans2){
//// State st = lpnTran.constraintTranMap.get(s2);
// State st = lpnTran.getNextState(s2);
// if(st != null){
// tranList2.add(lpnTran);
// stateList2.add(st);
// }
// }
//
//// int size = tranList1.size() + tranList2.size() + intersect1.size();
//// CompositeState[] nextStateArray = new CompositeState[size];
//// LPNTran[] tranArray = new LPNTran[size];
//// size--;
//
// // for each transition
// // create new MDD node and push onto stack
// for(int i = 0; i < tranList1.size(); i++){
// LPNTran lpnTran = tranList1.get(i);
//
// State nextState = stateList1.get(i);
// State[] newStateTuple = new State[2];
// newStateTuple[0] = nextState;
// newStateTuple[1] = s2;
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// compositeStateStack.push(newCompositeState);
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[size] = st;
//// tranArray[size] = lpnTran;
//// size--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
// for(int i = 0; i < tranList2.size(); i++){
// LPNTran lpnTran = tranList2.get(i);
//
// State nextState = stateList2.get(i);
// State[] newStateTuple = new State[2];
// newStateTuple[0] = s1;
// newStateTuple[1] = nextState;
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// compositeStateStack.push(newCompositeState);
// st = newCompositeState;
// }
//
// // create new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[size] = st;
//// tranArray[size] = lpnTran;
//// size--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
// for(int i = 0; i < intersect1.size(); i++){
// LPNTran lpnTran = intersectTran.get(i);
//
// State nextState1 = intersect1.get(i);
// State nextState2 = intersect2.get(i);
//
// State[] newStateTuple = new State[2];
// newStateTuple[0] = nextState1;
// newStateTuple[1] = nextState2;
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// compositeStateStack.push(newCompositeState);
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[size] = st;
//// tranArray[size] = lpnTran;
//// size--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
//// currentCompositeState.setNextStateArray(nextStateArray);
//// currentCompositeState.setTranArray(tranArray);
//
// long curTotalMem = Runtime.getRuntime().totalMemory();
// if(curTotalMem > peakTotal)
// peakTotal = curTotalMem;
//
// long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// if(curUsedMem > peakUsed)
// peakUsed = curUsedMem;
// }
//
// System.out.println("\n " + compositeSG.getLabel() + ": ");
// System.out.println(" --> # states: " + compositeSG.numCompositeStates());
//// System.out.println(" --> # transitions: " + compositeSG.numCompositeStateTrans());
//
// System.out.println(" --> Peak used memory: " + peakUsed/1000000F + " MB");
// System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
// System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
//
// long elapsedTimeMillis = System.currentTimeMillis()-start;
// float elapsedTimeSec = elapsedTimeMillis/1000F;
// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
//
// if(elapsedTimeSec > 60){
// float elapsedTime = elapsedTimeSec;
// elapsedTime = elapsedTimeSec/(float)60;
// System.out.println(" --> Elapsed time: " + elapsedTime + " min");
// }
//
// System.out.println();
//
//// System.out.println();
//// for(CompositeState cState : compositeSG.compositeStateMap){
//// State[] stateTuple = cState.getStateTuple();
//// State s1 = stateTuple[0];
//// State s2 = stateTuple[1];
////
//// System.out.println(s1.getLabel() + ", " + s2.getLabel());
//// }
//
// return compositeSG;
// }
//
// public CompositeStateGraph compose(CompositeStateGraph csg, StateGraph sg){
// if(csg == null || sg == null){
// return csg;
// }
//
// long start = System.currentTimeMillis();
//
// // check an output drives an input
// boolean compatible = false;
// for(String output : sg.getOutputs()){
// for(StateGraph sg2 : csg.stateGraphArray){
// VarSet inputs = sg2.getInputs();
// if(inputs.contains(output)){
// compatible = true;
// break;
// }
// }
//
// if(compatible){
// break;
// }
// }
//
// if(!compatible){
// VarSet inputs = sg.getInputs();
// for(StateGraph sg2 : csg.stateGraphArray){
// for(String output : sg2.getOutputs()){
// if(inputs.contains(output)){
// compatible = true;
// break;
// }
// }
//
// if(compatible){
// break;
// }
// }
//
// }
//
// if(!compatible){
// System.out.println("state graphs " + csg.getLabel() + " and " + sg.getLabel() + " cannot be composed");
// return null;
// }
//
// for(StateGraph sg2 : csg.stateGraphArray){
// if(sg2 == sg){
// return csg;
// }
// }
//
// // create new node with init states
// int size = csg.getSize() + 1;
// State[] initStates = new State[size];
// initStates[0] = sg.getInitialState();
// for(int i = 1; i < size; i++){
// initStates[i] = csg.stateGraphArray[i-1].getInitialState();
// }
//
// CompositeState initNode = new CompositeState(initStates);
//
// HashSet<LPNTran> synchronousTrans = new HashSet<LPNTran>();
//
// for(StateGraph sg2 : csg.stateGraphArray){
// HashSet<LPNTran> inputTrans = new HashSet<LPNTran>();
// inputTrans.addAll(sg.getInputTranSet());
// inputTrans.retainAll(sg2.getOutputTranSet());
//
// HashSet<LPNTran> outputTrans = new HashSet<LPNTran>();
// outputTrans.addAll(sg2.getInputTranSet());
// outputTrans.retainAll(sg.getOutputTranSet());
//
// synchronousTrans.addAll(inputTrans);
// synchronousTrans.addAll(outputTrans);
// }
//
// List<LPNTran> inputTrans = new ArrayList<LPNTran>();
// inputTrans.addAll(sg.getInputTranSet());
// inputTrans.removeAll(synchronousTrans);
//
// // create new composite state graph
// StateGraph[] sgArray = new StateGraph[size];
// sgArray[0] = sg;
// for(int i = 1; i < size; i++){
// sgArray[i] = csg.stateGraphArray[i-1];
// }
//
// CompositeStateGraph compositeSG = new CompositeStateGraph(initNode, sgArray);
//
// // create CompositeState stack
// Stack<State> stateStack = new Stack<State>();
// Stack<CompositeState> compositeStateStack = new Stack<CompositeState>();
// Stack<CompositeState> newStateStack = new Stack<CompositeState>();
//
//// Queue<State> stateQueue = new LinkedList<State>();
//// Queue<CompositeState> compositeStateQueue = new LinkedList<CompositeState>();
//// Queue<CompositeState> newStateQueue = new LinkedList<CompositeState>();
//
// // initialize with initial MDD node
// newStateStack.push(initNode);
// stateStack.push(sg.getInitialState());
// compositeStateStack.push(csg.getInitState());
//
//// stateQueue.offer(sg.init);
//// compositeStateQueue.offer(csg.getInitState());
//// newStateQueue.offer(initNode);
//
//// HashMap<LPNTran, StateTran> tranMap = new HashMap<LPNTran, StateTran>();
//// List<CompositeStateTran> csgStateTranList = new ArrayList<CompositeStateTran>();
//// List<StateTran> sgIntersect = new ArrayList<StateTran>();
//// List<CompositeStateTran> csgIntersect = new ArrayList<CompositeStateTran>();
//
// List<LPNTran> tranList1 = new ArrayList<LPNTran>();
// List<State> stateList1 = new ArrayList<State>();
// List<LPNTran> tranList2 = new ArrayList<LPNTran>();
// List<CompositeState> stateList2 = new ArrayList<CompositeState>();
// List<State> intersect1 = new ArrayList<State>();
// List<CompositeState> intersect2 = new ArrayList<CompositeState>();
// List<LPNTran> intersectTran = new ArrayList<LPNTran>();
//
// long peakUsed = 0;
// long peakTotal = 0;
//
// //while stack is not empty
// while(!newStateStack.isEmpty()){
//// while(!newStateQueue.isEmpty()){
// long s1 = System.currentTimeMillis();
//
// //pop stack
// CompositeState currentCompositeState = newStateStack.pop();
// State subState = stateStack.pop();
// CompositeState subCompositeState = compositeStateStack.pop();
//
//// CompositeState currentCompositeState = newStateQueue.poll();
//// State subState = stateQueue.poll();
//// CompositeState subCompositeState = compositeStateQueue.poll();
//
// State[] subCompositeTuple = subCompositeState.getStateTuple();
//
// tranList1.clear();
// stateList1.clear();
// tranList2.clear();
// stateList2.clear();
// intersect1.clear();
// intersect2.clear();
// intersectTran.clear();
//
// // find next state transitions for each state
// List<LPNTran> enabled1 = sg.lpnTransitionMap.get(subState);
//// List<LPNTran> enabled2 = subCompositeState.getTranList();
//// List<CompositeState> edgeList = subCompositeState.getNextStateList();
//// LPNTran[] enabled2 = subCompositeState.getTranArray();
//// CompositeState[] edgeList = subCompositeState.getNextStateArray();
// List<LPNTran> enabled2 = subCompositeState.enabledTranList;
// List<CompositeState> edgeList = subCompositeState.nextStateList;
//
//// System.out.println(" enabled1: " + enabled1.size());
// for(LPNTran lpnTran : enabled1){
// if(lpnTran.local()){
// tranList1.add(lpnTran);
// stateList1.add((State) lpnTran.getNextState(subState));
// }
// else{
// if(synchronousTrans.contains(lpnTran)){
// boolean synch = false;
// CompositeState st = null;
// for(int i = 0; i < enabled2.size(); i++){
// if(enabled2.get(i) == lpnTran){
// synch = true;
// st = edgeList.get(i);
// break;
// }
// }
//
// if(synch){
// intersect1.add((State) lpnTran.getNextState(subState));
// intersect2.add(st);
// intersectTran.add(lpnTran);
// }
// else{
// System.out.println("ST == NULL1\n");
// }
// }
// else{
// tranList1.add(lpnTran);
// stateList1.add((State) lpnTran.getNextState(subState));
// }
// }
// }
//
//// System.out.println(" enabled2: " + enabled2.size());
// for(int i = 0; i < enabled2.size(); i++){
// LPNTran lpnTran = enabled2.get(i);
//
// if(synchronousTrans.contains(lpnTran)){
//// State st = lpnTran.constraintTranMap.get(subState);
// State st = lpnTran.getNextState(subState);
// if(st != null){
// intersectTran.add(lpnTran);
// intersect1.add(st);
// intersect2.add(edgeList.get(i));
// }
// }
// else{
// tranList2.add(lpnTran);
// stateList2.add(edgeList.get(i));
// }
// }
//
//// System.out.println(" inputTrans: " + inputTrans.size());
// for(LPNTran lpnTran : inputTrans){
//// State st = lpnTran.constraintTranMap.get(subState);
// State st = lpnTran.getNextState(subState);
// if(st != null){
// tranList1.add(lpnTran);
// stateList1.add(st);
// }
// }
//
//// int items = tranList1.size() + tranList2.size() + intersect1.size();
//// CompositeState[] nextStateArray = new CompositeState[items];
//// LPNTran[] tranArray = new LPNTran[items];
//// items--;
//
// long s2 = System.currentTimeMillis();
// // for each transition
// // create new MDD node and push onto stack
// for(int i = 0; i < tranList1.size(); i++){
// LPNTran lpnTran = tranList1.get(i);
// State nextState = stateList1.get(i);
// State[] newStateTuple = new State[size];
// newStateTuple[0] = nextState;
// for(int j = 1; j < size; j++){
// newStateTuple[j] = subCompositeTuple[j-1];
// }
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// newStateStack.push(newCompositeState);
// stateStack.push(nextState);
// compositeStateStack.push(subCompositeState);
//// newStateQueue.offer(newCompositeState);
//// stateQueue.offer(nextState);
//// compositeStateQueue.offer(subCompositeState);
//
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[items] = st;
//// tranArray[items] = lpnTran;
//// items--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
//// System.out.println(" transList2: " + tranList2.size());
// for(int i = 0; i < tranList2.size(); i++){
// LPNTran lpnTran = tranList2.get(i);
// CompositeState nextState = stateList2.get(i);
// State[] nextStateTuple = nextState.getStateTuple();
// State[] newStateTuple = new State[size];
// newStateTuple[0] = subState;
// for(int j = 1; j < size; j++){
// newStateTuple[j] = nextStateTuple[j-1];
// }
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// newStateStack.push(newCompositeState);
// stateStack.push(subState);
// compositeStateStack.push(nextState);
//// newStateQueue.offer(newCompositeState);
//// stateQueue.offer(subState);
//// compositeStateQueue.offer(nextState);
//
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[items] = st;
//// tranArray[items] = lpnTran;
//// items--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
//// System.out.println(" intersect: " + intersect1.size());
// for(int i = 0; i < intersect1.size(); i++){
// LPNTran lpnTran = intersectTran.get(i);
//
// State nextState1 = intersect1.get(i);
// CompositeState nextState2 = intersect2.get(i);
// State[] nextStateTuple = nextState2.getStateTuple();
//
// State[] newStateTuple = new State[size];
// newStateTuple[0] = nextState1;
// for(int j = 1; j < size; j++){
// newStateTuple[j] = nextStateTuple[j-1];
// }
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// newStateStack.push(newCompositeState);
// compositeStateStack.push(nextState2);
// stateStack.push(nextState1);
//// newStateQueue.offer(newCompositeState);
//// stateQueue.offer(nextState1);
//// compositeStateQueue.offer(nextState2);
//
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, stTran1.lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[items] = st;
//// tranArray[items] = lpnTran;
//// items--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
//// currentCompositeState.setNextStateArray(nextStateArray);
//// currentCompositeState.setTranArray(tranArray);
//
// long curTotalMem = Runtime.getRuntime().totalMemory();
// if(curTotalMem > peakTotal)
// peakTotal = curTotalMem;
//
// long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// if(curUsedMem > peakUsed)
// peakUsed = curUsedMem;
// }
//
// System.out.println("\n " + compositeSG.getLabel() + ": ");
// System.out.println(" --> # states: " + compositeSG.numCompositeStates());
//// System.out.println(" --> # transitions: " + compositeSG.numCompositeStateTrans());
//
// System.out.println(" --> Peak used memory: " + peakUsed/1000000F + " MB");
// System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
// System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
//
// long elapsedTimeMillis = System.currentTimeMillis()-start;
// float elapsedTimeSec = elapsedTimeMillis/1000F;
// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
//
// if(elapsedTimeSec > 60){
// float elapsedTime = elapsedTimeSec;
// elapsedTime = elapsedTimeSec/(float)60;
// System.out.println(" --> Elapsed time: " + elapsedTime + " min");
// }
//
// System.out.println();
//
//// System.out.println();
//// for(CompositeState cState : compositeSG.compositeStateMap){
//// State[] stateTuple = cState.getStateTuple();
//// State s1 = stateTuple[0];
//// State s2 = stateTuple[1];
////
//// System.out.println(s1.getLabel() + ", " + s2.getLabel());
//// }
//
// return compositeSG;
// }
public CompositeStateGraph compose2(CompositeStateGraph sg1, CompositeStateGraph sg2){
long start = System.currentTimeMillis();
if(sg1 == null || sg2 == null){
return null;
}
StateGraph[] stateGraphArray1 = sg1.getStateGraphArray();
StateGraph[] stateGraphArray2 = sg2.getStateGraphArray();
// check an output drives an input
boolean compatible = false;
for(StateGraph g : stateGraphArray1){
for(String output : g.getLpn().getAllOutputs().keySet()){
for(StateGraph g2 : stateGraphArray2){
VarSet inputs = (VarSet) g2.getLpn().getAllInputs().keySet();
if(inputs.contains(output)){
compatible = true;
break;
}
}
if(compatible){
break;
}
}
if(compatible){
break;
}
}
if(!compatible){
for(StateGraph g1 : stateGraphArray1){
VarSet inputs = (VarSet) g1.getLpn().getAllInputs().keySet();
for(StateGraph g2 : stateGraphArray2){
for(String output : g2.getLpn().getAllOutputs().keySet()){
if(inputs.contains(output)){
compatible = true;
break;
}
}
if(compatible){
break;
}
}
if(compatible){
break;
}
}
}
if(!compatible){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
HashSet<StateGraph> sgSet = new HashSet<StateGraph>();
for(StateGraph sg : stateGraphArray1){
if(sgSet.add(sg) == false){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
}
for(StateGraph sg : stateGraphArray2){
if(sgSet.add(sg) == false){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
}
// create new node with init states
int size = sg1.getSize() + sg2.getSize();
int sg1Size = sg1.getSize();
int[] initStates = new int[size];
for(int i = 0; i < sg1Size; i++){
initStates[i] = stateGraphArray1[i].getInitialState().getIndex();
}
for(int i = sg1Size; i < size; i++){
initStates[i] = stateGraphArray2[i-sg1Size].getInitialState().getIndex();
}
CompositeState initNode = new CompositeState(initStates);
HashSet<Integer> synchronousTrans = new HashSet<Integer>();
for(StateGraph g1 : stateGraphArray1){
LhpnFile lpn1 = g1.getLpn();
for(StateGraph g2 : stateGraphArray2){
LhpnFile lpn2 = g2.getLpn();
// TOOD: Need to use our LPN
/*
HashSet<LPNTran> inputTrans = new HashSet<LPNTran>();
inputTrans.addAll(lpn1.getInputTranSet());
inputTrans.retainAll(lpn2.getOutputTranSet());
HashSet<LPNTran> outputTrans = new HashSet<LPNTran>();
outputTrans.addAll(lpn2.getInputTranSet());
outputTrans.retainAll(lpn1.getOutputTranSet());
for(LPNTran lpnTran : inputTrans){
synchronousTrans.add(lpnTran.getIndex());
}
for(LPNTran lpnTran : outputTrans){
synchronousTrans.add(lpnTran.getIndex());
}
*/
}
}
// create new composite state graph
StateGraph[] sgArray = new StateGraph[size];
List<LhpnFile> lpnList = new ArrayList<LhpnFile>(size);
for(int i = 0; i < sg1Size; i++){
sgArray[i] = stateGraphArray1[i];
// TOOD: is this needed???
//lpnList.add(stateGraphArray1[i].getLpn());
}
for(int i = sg1Size; i < size; i++){
sgArray[i] = stateGraphArray2[i-sg1Size];
// TOOD: is this needed???
//lpnList.add(stateGraphArray2[i-sg1Size].getLpn());
}
CompositeStateGraph compositeSG = new CompositeStateGraph(initNode, sgArray);
// create CompositeState stack
Stack<CompositeState> newStateStack = new Stack<CompositeState>();
Stack<CompositeState> subStateStack1 = new Stack<CompositeState>();
Stack<CompositeState> subStateStack2 = new Stack<CompositeState>();
// initialize with initial CompositionalState
newStateStack.push(initNode);
subStateStack1.push(sg1.getInitState());
subStateStack2.push(sg2.getInitState());
List<CompositeStateTran> intersectingTrans1 = new LinkedList<CompositeStateTran>();
List<CompositeStateTran> intersectingTrans2 = new LinkedList<CompositeStateTran>();
List<CompositeStateTran> independentTrans1 = new LinkedList<CompositeStateTran>();
List<CompositeStateTran> independentTrans2 = new LinkedList<CompositeStateTran>();
long peakUsed = 0;
long peakTotal = 0;
CompositeState tempState = null;
while(!newStateStack.isEmpty()){
CompositeState currentState = newStateStack.pop();
CompositeState subState1 = subStateStack1.pop();
CompositeState subState2 = subStateStack2.pop();
int[] subState1Tuple = subState1.getStateTuple();
int[] subState2Tuple = subState2.getStateTuple();
List<CompositeStateTran> stateTrans1 = subState1.getOutgoingStateTranList();
List<CompositeStateTran> stateTrans2 = subState2.getOutgoingStateTranList();
// clear reused lists
intersectingTrans1.clear();
intersectingTrans2.clear();
independentTrans1.clear();
independentTrans2.clear();
for(CompositeStateTran stateTran : stateTrans1){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
if(!stateTran.visible()){
independentTrans1.add(stateTran);
}
else{
if(synchronousTrans.contains(lpnTran.getIndex())){
for(CompositeStateTran stateTran2 : stateTrans2){
lpn.parser.Transition lpnTran2 = stateTran2.getLPNTran();
if(lpnTran == lpnTran2){
intersectingTrans1.add(stateTran);
intersectingTrans2.add(stateTran2);
}
}
}
else{
independentTrans1.add(stateTran);
}
}
}
for(CompositeStateTran stateTran : stateTrans2){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
if(!stateTran.visible()){
independentTrans2.add(stateTran);
}
else{
if(!synchronousTrans.contains(lpnTran.getIndex())){
independentTrans2.add(stateTran);
}
}
}
for(CompositeStateTran stateTran : independentTrans1){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
CompositeState nextState = sg1.getState(stateTran.getNextState());
int[] nextStateTuple = nextState.getStateTuple();
int[] newStateTuple = new int[size];
for(int j = 0; j < sg1Size; j++){
newStateTuple[j] = nextStateTuple[j];
}
for(int j = sg1Size; j < size; j++){
newStateTuple[j] = subState2Tuple[j-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(nextState);
subStateStack2.push(subState2);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnTran.isLocal()){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
for(CompositeStateTran stateTran : independentTrans2){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
CompositeState nextState = sg2.getState(stateTran.getNextState());
int[] nextStateTuple = nextState.getStateTuple();
int[] newStateTuple = new int[size];
for(int i = 0; i < sg1Size; i++){
newStateTuple[i] = subState1Tuple[i];
}
for(int i = sg1Size; i < size; i++){
newStateTuple[i] = nextStateTuple[i-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(subState1);
subStateStack2.push(nextState);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnTran.isLocal()){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
Iterator<CompositeStateTran> iter1 = intersectingTrans1.iterator();
Iterator<CompositeStateTran> iter2 = intersectingTrans2.iterator();
while(iter1.hasNext()){
CompositeStateTran stateTran1 = iter1.next();
CompositeStateTran stateTran2 = iter2.next();
lpn.parser.Transition lpnTran = stateTran1.getLPNTran();
CompositeState nextState1 = sg1.getState(stateTran1.getNextState());
int[] nextState1Tuple = nextState1.getStateTuple();
CompositeState nextState2 = sg2.getState(stateTran2.getNextState());
int[] nextState2Tuple = nextState2.getStateTuple();
int[] newStateTuple = new int[size];
for(int i = 0; i < sg1Size; i++){
newStateTuple[i] = nextState1Tuple[i];
}
for(int i = sg1Size; i < size; i++){
newStateTuple[i] = nextState2Tuple[i-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(nextState1);
subStateStack2.push(nextState2);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnList.containsAll(lpnTran.getDstLpnList())){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
System.out.println("\n " + compositeSG.getLabel() + ": ");
System.out.println(" --> # states: " + compositeSG.numStates());
System.out.println(" --> # transitions: " + compositeSG.numStateTrans());
System.out.println(" --> Peak used memory: " + peakUsed/1000000F + " MB");
System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
if(elapsedTimeSec > 60){
float elapsedTime = elapsedTimeSec;
elapsedTime = elapsedTimeSec/(float)60;
System.out.println(" --> Elapsed time: " + elapsedTime + " min");
}
System.out.println();
return compositeSG;
}
public CompositeStateGraph compose(CompositeStateGraph sg1, CompositeStateGraph sg2){
long start = System.currentTimeMillis();
if(sg1 == null || sg2 == null){
return null;
}
StateGraph[] stateGraphArray1 = sg1.getStateGraphArray();
StateGraph[] stateGraphArray2 = sg2.getStateGraphArray();
// check an output drives an input
boolean compatible = false;
for(StateGraph g : stateGraphArray1){
for(String output : g.getLpn().getAllOutputs().keySet()){
for(StateGraph g2 : stateGraphArray2){
VarSet inputs = (VarSet) g2.getLpn().getAllInputs().keySet();
if(inputs.contains(output)){
compatible = true;
break;
}
}
if(compatible){
break;
}
}
if(compatible){
break;
}
}
if(!compatible){
for(StateGraph g1 : stateGraphArray1){
VarSet inputs = (VarSet) g1.getLpn().getAllInputs().keySet();
for(StateGraph g2 : stateGraphArray2){
for(String output : g2.getLpn().getAllOutputs().keySet()){
if(inputs.contains(output)){
compatible = true;
break;
}
}
if(compatible){
break;
}
}
if(compatible){
break;
}
}
}
if(!compatible){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
HashSet<StateGraph> sgSet = new HashSet<StateGraph>();
for(StateGraph sg : stateGraphArray1){
if(sgSet.add(sg) == false){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
}
for(StateGraph sg : stateGraphArray2){
if(sgSet.add(sg) == false){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
}
// create new node with init states
int size = sg1.getSize() + sg2.getSize();
int sg1Size = sg1.getSize();
int[] initStates = new int[size];
for(int i = 0; i < sg1Size; i++){
initStates[i] = stateGraphArray1[i].getInitialState().getIndex();
}
for(int i = sg1Size; i < size; i++){
initStates[i] = stateGraphArray2[i-sg1Size].getInitialState().getIndex();
}
CompositeState initNode = new CompositeState(initStates);
HashSet<Transition> synchronousTrans = new HashSet<Transition>();
for(StateGraph g1 : stateGraphArray1){
LhpnFile lpn1 = g1.getLpn();
for(StateGraph g2 : stateGraphArray2){
LhpnFile lpn2 = g2.getLpn();
// TOOD: need to change to use our LPN
/*
HashSet<LPNTran> inputTrans = new HashSet<LPNTran>();
inputTrans.addAll(lpn1.getInputTranSet());
inputTrans.retainAll(lpn2.getOutputTranSet());
HashSet<LPNTran> outputTrans = new HashSet<LPNTran>();
outputTrans.addAll(lpn2.getInputTranSet());
outputTrans.retainAll(lpn1.getOutputTranSet());
synchronousTrans.addAll(inputTrans);
synchronousTrans.addAll(outputTrans);
*/
}
}
// create new composite state graph
StateGraph[] sgArray = new StateGraph[size];
List<LhpnFile> lpnList = new ArrayList<LhpnFile>(size);
for(int i = 0; i < sg1Size; i++){
sgArray[i] = stateGraphArray1[i];
// TODO: (future) Is this needed??
//lpnList.add(stateGraphArray1[i].getLpn());
}
for(int i = sg1Size; i < size; i++){
sgArray[i] = stateGraphArray2[i-sg1Size];
// TODO: (future) Is this needed??
//lpnList.add(stateGraphArray2[i-sg1Size].getLpn());
}
CompositeStateGraph compositeSG = new CompositeStateGraph(initNode, sgArray);
// create CompositeState stack
Stack<CompositeState> newStateStack = new Stack<CompositeState>();
Stack<CompositeState> subStateStack1 = new Stack<CompositeState>();
Stack<CompositeState> subStateStack2 = new Stack<CompositeState>();
// initialize with initial CompositionalState
newStateStack.push(initNode);
subStateStack1.push(sg1.getInitState());
subStateStack2.push(sg2.getInitState());
List<lpn.parser.Transition> intersectingTrans = new ArrayList<lpn.parser.Transition>();
List<CompositeState> intStateList1 = new ArrayList<CompositeState>();
List<CompositeState> intStateList2 = new ArrayList<CompositeState>();
List<lpn.parser.Transition> independentTrans1 = new ArrayList<lpn.parser.Transition>();
List<CompositeState> indStateList1 = new ArrayList<CompositeState>();
List<lpn.parser.Transition> independentTrans2 = new ArrayList<lpn.parser.Transition>();
List<CompositeState> indStateList2 = new ArrayList<CompositeState>();
long peakUsed = 0;
long peakTotal = 0;
CompositeState tempState = null;
while(!newStateStack.isEmpty()){
CompositeState currentState = newStateStack.pop();
CompositeState subState1 = subStateStack1.pop();
CompositeState subState2 = subStateStack2.pop();
int[] subState1Tuple = subState1.getStateTuple();
int[] subState2Tuple = subState2.getStateTuple();
List<CompositeStateTran> stateTrans1 = subState1.getOutgoingStateTranList();
List<CompositeStateTran> stateTrans2 = subState2.getOutgoingStateTranList();
// clear reused lists
intersectingTrans.clear();
intStateList1.clear();
intStateList2.clear();
independentTrans1.clear();
indStateList1.clear();
independentTrans2.clear();
indStateList2.clear();
for(CompositeStateTran stateTran : stateTrans1){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
CompositeState nextState = sg1.getState(stateTran.getNextState());
if(!stateTran.visible()){
independentTrans1.add(lpnTran);
indStateList1.add(nextState);
}
else{
if(synchronousTrans.contains(lpnTran)){
for(CompositeStateTran stateTran2 : stateTrans2){
lpn.parser.Transition lpnTran2 = stateTran2.getLPNTran();
CompositeState nextState2 = sg2.getState(stateTran2.getNextState());
if(lpnTran == lpnTran2){
intersectingTrans.add(lpnTran);
intStateList1.add(nextState);
intStateList2.add(nextState2);
}
}
}
else{
independentTrans1.add(lpnTran);
indStateList1.add(nextState);
}
}
}
for(CompositeStateTran stateTran : stateTrans2){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
CompositeState nextState = sg2.getState(stateTran.getNextState());
if(!stateTran.visible()){
independentTrans2.add(lpnTran);
indStateList2.add(nextState);
}
else{
if(!synchronousTrans.contains(lpnTran)){
independentTrans2.add(lpnTran);
indStateList2.add(nextState);
}
}
}
for(int i = 0; i < independentTrans1.size(); i++){
lpn.parser.Transition lpnTran = independentTrans1.get(i);
CompositeState nextState = indStateList1.get(i);
int[] nextStateTuple = nextState.getStateTuple();
int[] newStateTuple = new int[size];
for(int j = 0; j < sg1Size; j++){
newStateTuple[j] = nextStateTuple[j];
}
for(int j = sg1Size; j < size; j++){
newStateTuple[j] = subState2Tuple[j-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(nextState);
subStateStack2.push(subState2);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnTran.isLocal()){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
for(int j = 0; j < independentTrans2.size(); j++){
lpn.parser.Transition lpnTran = independentTrans2.get(j);
CompositeState nextState = indStateList2.get(j);
int[] nextStateTuple = nextState.getStateTuple();
int[] newStateTuple = new int[size];
for(int i = 0; i < sg1Size; i++){
newStateTuple[i] = subState1Tuple[i];
}
for(int i = sg1Size; i < size; i++){
newStateTuple[i] = nextStateTuple[i-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(subState1);
subStateStack2.push(nextState);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnTran.isLocal()){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
for(int j = 0; j < intersectingTrans.size(); j++){
Transition lpnTran = intersectingTrans.get(j);
CompositeState nextState1 = intStateList1.get(j);
int[] nextState1Tuple = nextState1.getStateTuple();
CompositeState nextState2 = intStateList2.get(j);
int[] nextState2Tuple = nextState2.getStateTuple();
int[] newStateTuple = new int[size];
for(int i = 0; i < sg1Size; i++){
newStateTuple[i] = nextState1Tuple[i];
}
for(int i = sg1Size; i < size; i++){
newStateTuple[i] = nextState2Tuple[i-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(nextState1);
subStateStack2.push(nextState2);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnList.containsAll(lpnTran.getDstLpnList())){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
System.out.println("\n " + compositeSG.getLabel() + ": ");
System.out.println(" --> # states: " + compositeSG.numStates());
System.out.println(" --> # transitions: " + compositeSG.numStateTrans());
System.out.println(" --> Peak used memory: " + peakUsed/1000000F + " MB");
System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
if(elapsedTimeSec > 60){
float elapsedTime = elapsedTimeSec;
elapsedTime = elapsedTimeSec/(float)60;
System.out.println(" --> Elapsed time: " + elapsedTime + " min");
}
System.out.println();
return compositeSG;
}
public void compositionalAnalsysis(List<StateGraph> designUnitSet) {
// System.out.println("\n****** Compositional Analysis ******");
// long start = System.currentTimeMillis();
//
// if(Options.getParallelFlag()){
// parallelCompositionalFindSG(designUnitSet);
// }
// else{
// compositionalFindSG(designUnitSet);
// }
findReducedSG(designUnitSet);
// long totalMillis = System.currentTimeMillis()-start;
// float totalSec = totalMillis/1000F;
// System.out.println("\n***** Total Elapsed Time: " + totalSec + " sec *****");
//
// if(totalSec > 60){
// float totalTime = totalSec/(float)60;
// System.out.println("***** Total Elapsed Time: " + totalTime + " min *****");
// }
//
// System.out.println();
}
public void findReducedSG(List<StateGraph> designUnitSet) {
System.out.println("\n****** Compositional Analysis ******");
long start = System.currentTimeMillis();
StateGraph[] sgArray = (StateGraph[]) designUnitSet.toArray();
compositionalFindSG(sgArray);
List<CompositeStateGraph> sgList = new ArrayList<CompositeStateGraph>();
System.out.println();
long peakTotal = 0;
long peakUsed = 0;
int largestSG = 0;
for(StateGraph sg : designUnitSet){
CompositeStateGraph csg = new CompositeStateGraph(sg);
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
// csg.draw();
if(Options.getCompositionalMinimization().equals("reduction")){
// reduce(csg);
}
else if(Options.getCompositionalMinimization().equals("abstraction")){
System.out.println(csg.getLabel() + ": transitionBasedAbstraction");
transitionBasedAbstraction(csg);
// csg.draw();
System.out.println(csg.getLabel() + ": mergeOutgoing");
mergeOutgoing(csg);
// csg.draw();
System.out.println(csg.getLabel() + ": mergeIncoming");
mergeIncoming(csg);
System.out.println();
// csg.draw();
}
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
sgList.add(csg);
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
CompositeStateGraph csg = null;
if(sgList.size() > 0){
csg = sgList.get(0);
sgList.remove(0);
}
while(sgList.size() > 1){
CompositeStateGraph tmpSG = null;
for(CompositeStateGraph sg2 : sgList){
tmpSG = compose(csg, sg2);
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
if(tmpSG != null){
sgList.remove(sg2);
// tmpSG.draw();
System.out.println();
if(Options.getCompositionalMinimization().equals("reduction")){
// reduce(tmpSG);
}
else if(Options.getCompositionalMinimization().equals("abstraction")){
System.out.println(tmpSG.getLabel() + ": transitionBasedAbstraction");
transitionBasedAbstraction(tmpSG);
// tmpSG.draw();
System.out.println(tmpSG.getLabel() + ": mergeOutgoing");
mergeOutgoing(tmpSG);
// tmpSG.draw();
System.out.println(tmpSG.getLabel() + ": mergeIncoming");
mergeIncoming(tmpSG);
System.out.println();
// tmpSG.draw();
}
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
break;
}
}
csg = tmpSG;
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
if(sgList.size() == 1){
csg = compose(csg, sgList.get(0));
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
// csg.draw();
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
long totalMillis = System.currentTimeMillis()-start;
float totalSec = totalMillis/1000F;
System.out.println("\n****** Total Elapsed Time: " + totalSec + " sec ******");
if(totalSec > 60){
float totalTime = totalSec/(float)60;
System.out.println("****** Total Elapsed Time: " + totalTime + " min ******");
}
System.out.println("****** Peak Memory Used: " + peakUsed/1000000F + " MB ******");
System.out.println("****** Peak Memory Total: " + peakTotal/1000000F + " MB ******");
System.out.println("****** Lastest SG: " + largestSG + " states ******");
System.out.println();
}
// public void reduce(CompositeStateGraph sg){
// long startTime = System.currentTimeMillis();
// int initNumTrans = sg.numTransitions;
// int initNumStates = sg.compositeStateMap.size();
// int totalReducedTrans = sg.numTransitions;
//
// int case2StateMin = 0;
// int case3StateMin = 0;
// int case2TranMin = 0;
// int case3TranMin = 0;
//
// int iter = 0;
// while(totalReducedTrans > 0){
// totalReducedTrans = 0;
//
// int numStates = sg.compositeStateMap.size();
// int numTrans = sg.numTransitions;
// int tranDiff = 0;
//
// case2(sg);
//
// case2TranMin += numTrans - sg.numTransitions;
// tranDiff = numStates - sg.compositeStateMap.size();
// case2StateMin += tranDiff;
// totalReducedTrans += tranDiff;
//
// numTrans = sg.numTransitions;
// numStates = sg.compositeStateMap.size();
//
// case3(sg);
//
// case3TranMin += numTrans - sg.numTransitions;
// tranDiff = numStates - sg.compositeStateMap.size();
// case3StateMin += tranDiff;
// totalReducedTrans += tranDiff;
//
// iter++;
// }
//
// System.out.println(" Reduce " + sg.getLabel() + ": ");
// System.out.println(" --> case2: -" + case2StateMin + " states");
// System.out.println(" --> case2: -" + case2TranMin + " transitions");
// System.out.println(" --> case3: -" + case3StateMin + " states");
// System.out.println(" --> case3: -" + case3TranMin + " transitions");
// System.out.println(" --> # states: " + sg.compositeStateMap.size());
// System.out.println(" --> # transitions: " + sg.numTransitions);
// System.out.println(" --> # iterations: " + iter);
// long elapsedTimeMillis = System.currentTimeMillis()-startTime;
// float elapsedTimeSec = elapsedTimeMillis/1000F;
// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec\n");
// }
public void transitionBasedAbstraction(CompositeStateGraph sg){
HashSet<Integer> stateSet = new HashSet<Integer>();
HashSet<CompositeStateTran> tranSet = new HashSet<CompositeStateTran>();
CompositeState initialState = sg.getInitState();
Stack<CompositeStateTran> stateTranStack = new Stack<CompositeStateTran>();
HashSet<Integer> loopSet = new HashSet<Integer>(); // set used to detect loops
HashSet<Integer> traversalSet = new HashSet<Integer>(); // set used to avoid duplicate work
// int count = 0;
for(CompositeStateTran nonlocalStateTran : sg.getStateTranSet()){
// count++;
// System.out.println(count + "/" + sg.getStateTranSet().size());
// if(!sg.containsStateTran(nonlocalStateTran)) continue;
lpn.parser.Transition lpnTran = nonlocalStateTran.getLPNTran();
if(!nonlocalStateTran.visible()){
continue;
}
else if(nonlocalStateTran.getNextState() == sg.getInitState().getIndex()){
// add current state transition
tranSet.add(nonlocalStateTran);
stateSet.add(nonlocalStateTran.getCurrentState());
stateSet.add(nonlocalStateTran.getNextState());
continue;
}
// state transition stack for dfs traversal
stateTranStack.clear();
// set used to detect loops
loopSet.clear();
loopSet.add(nonlocalStateTran.getNextState());
// set used to avoid duplicate work
traversalSet.clear();
traversalSet.add(nonlocalStateTran.getNextState());
boolean flag = false;
CompositeState nextState = sg.getState(nonlocalStateTran.getNextState());
for(CompositeStateTran outgoingTran : nextState.getOutgoingStateTranList()){
if(!outgoingTran.visible()){
stateTranStack.push(outgoingTran);
loopSet.add(outgoingTran.getNextState());
// traversalSet.add(outgoingTran.getNextState());
}
else{
flag = true;
}
}
// keep nonlocal state transition if a visible successor state transition exists
if(flag){
tranSet.add(nonlocalStateTran);
stateSet.add(nonlocalStateTran.getCurrentState());
stateSet.add(nonlocalStateTran.getNextState());
}
// System.out.println(nonlocalStateTran);
while(!stateTranStack.empty()){
CompositeStateTran currentStateTran = stateTranStack.pop();
CompositeState currentNextState = sg.getState(currentStateTran.getNextState());
// // if state has already been encountered skip
if(!traversalSet.add(currentStateTran.getNextState())){
// System.out.println(" " + currentStateTran);
// System.out.println("skip");
continue;
}
if(currentNextState == initialState){
CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getCurrentState(),
currentStateTran.getNextState(), lpnTran);
System.out.println(newStateTran.getCurrentState() + " -> " + newStateTran.getNextState());
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(newStateTran.getCurrentState());
stateSet.add(newStateTran.getCurrentState());
continue;
}
// if the state transition does not have successor transitions create a state transition to last state in path
if(currentNextState.numOutgoingTrans() == 0){
CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getCurrentState(),
currentStateTran.getNextState(), lpnTran);
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(newStateTran.getCurrentState());
stateSet.add(newStateTran.getNextState());
}
// add local outgoing state trans to stack
// for each nonlocal state tran create a state transition from nonlocalStateTran.currentState to stateTran.currentState
for(CompositeStateTran stateTran : currentNextState.getOutgoingStateTranList()){
if(stateTran.visible()){
CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getCurrentState(),
stateTran.getCurrentState(), lpnTran);
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(nonlocalStateTran.getCurrentState());
stateSet.add(stateTran.getCurrentState());
}
else{
// if(!loopSet.add(stateTran.getNextState())){
// // create self loop after visible state transition
// if(flag){
// CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getNextState(),
// nonlocalStateTran.getNextState(), currentStateTran.getLPNTran());
//
// tranSet.add(newStateTran);
// }
// else{
// tranSet.add(nonlocalStateTran);
// stateSet.add(nonlocalStateTran.getCurrentState());
// stateSet.add(nonlocalStateTran.getNextState());
// flag = true;
//
// CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getNextState(),
// nonlocalStateTran.getNextState(), currentStateTran.getLPNTran());
//
// tranSet.add(newStateTran);
// }
//
//// traversalSet.add(stateTran.getNextState());
// continue;
// }
// else if(!traversalSet.add(stateTran.getNextState())){
// continue;
// }
stateTranStack.push(stateTran);
}
}
loopSet.remove(currentNextState.getIndex());
}
}
System.out.println(stateSet.size());
System.out.println(tranSet.size());
// System.out.println("INITIAL STATE");
// handle initial state
loopSet.clear();
loopSet.add(initialState.getIndex());
traversalSet.clear();
traversalSet.add(initialState.getIndex());
for(CompositeStateTran stateTran : initialState.getOutgoingStateTranList()){
if(!stateTran.visible()){
stateTranStack.push(stateTran);
loopSet.add(stateTran.getNextState());
// traversalSet.add(stateTran.getNextState());
}
}
stateSet.add(initialState.getIndex());
while(!stateTranStack.empty()){
CompositeStateTran stateTran = stateTranStack.pop();
// // if state has already been encountered skip
if(!traversalSet.add(stateTran.getNextState())){
continue;
}
CompositeState nextState = sg.getState(stateTran.getNextState());
// if the state transition does not have successor transitions create a state transition to last state in path
if(nextState.numOutgoingTrans() == 0){
CompositeStateTran newStateTran = new CompositeStateTran(initialState, sg.getState(stateTran.getNextState()),
stateTran.getLPNTran());
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(stateTran.getNextState());
}
for(CompositeStateTran succStateTran : nextState.getOutgoingStateTranList()){
lpn.parser.Transition lpnTran = succStateTran.getLPNTran();
if(succStateTran.visible()){
// create a state tran from initial state to succStateTran.currentState
CompositeStateTran newStateTran = new CompositeStateTran(initialState, sg.getState(succStateTran.getNextState()), lpnTran);
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(succStateTran.getNextState());
}
else{
// if(!loopSet.add(succStateTran.getNextState())){
// CompositeStateTran newStateTran = new CompositeStateTran(initialState, initialState, lpnTran);
// tranSet.add(newStateTran);
//
//// traversalSet.add(succStateTran.getNextState());
// continue;
// }
// else if(!traversalSet.add(succStateTran.getNextState())){
// continue;
// }
// add to stack
stateTranStack.push(succStateTran);
}
}
loopSet.remove(stateTran.getNextState());
}
// System.out.println();
// for(CompositeStateTran stateTran : tranSet){
// System.out.println(stateTran);
// }
// System.out.println();
//
// System.out.println();
// for(Integer state : stateSet){
// System.out.println(state);
// }
// System.out.println();
// System.out.println("COMPOSITE STATE SET");
HashMap<CompositeState, CompositeState> stateMap = new HashMap<CompositeState, CompositeState>();
HashMap<Integer, CompositeState> indexStateMap = new HashMap<Integer, CompositeState>();
for(Integer stateIndex : stateSet){
CompositeState currentState = sg.getState(stateIndex);
currentState.clear();
stateMap.put(currentState, currentState);
indexStateMap.put(stateIndex, currentState);
}
sg.indexStateMap = indexStateMap;
sg.stateMap = stateMap;
sg.stateTranMap = new HashMap<CompositeStateTran, CompositeStateTran>();
for(CompositeStateTran stateTran : tranSet){
sg.addStateTran(stateTran);
}
System.out.println(" --> # states: " + stateSet.size());
System.out.println(" --> # transitions: " + tranSet.size());
}
private void removeUnreachableState(CompositeStateGraph sg, CompositeState currentState){
if(currentState == sg.getInitState()){
return;
}
else if(currentState.numIncomingTrans() != 0){
return;
}
boolean rc = sg.containsState(currentState.getIndex());
if(rc == false){
return;
}
for(CompositeStateTran stateTran : currentState.getOutgoingStateTranList().toArray(new CompositeStateTran[currentState.numOutgoingTrans()])){
sg.removeStateTran(stateTran);
CompositeState nextState = sg.getState(stateTran.getNextState());
if(nextState.numIncomingTrans() == 0){
removeUnreachableState(sg, nextState);
}
}
sg.removeState(currentState);
}
private void removeDanglingState(CompositeStateGraph sg, CompositeState currentState){
if(currentState == sg.getInitState()){
return;
}
else if(currentState.numOutgoingTrans() != 0){
return;
}
boolean rc = sg.containsState(currentState.getIndex());
if(rc == false){
return;
}
for(CompositeStateTran stateTran : currentState.getIncomingStateTranList().toArray(new CompositeStateTran[currentState.numIncomingTrans()])){
sg.removeStateTran(stateTran);
CompositeState previousState = sg.getState(stateTran.getCurrentState());
if(previousState.numOutgoingTrans() == 0){
removeDanglingState(sg, previousState);
}
}
sg.removeState(currentState);
}
public void redundantStateRemoval(CompositeStateGraph sg){
this.mergeOutgoing(sg);
this.mergeIncoming(sg);
}
public void mergeOutgoing(CompositeStateGraph sg){
// System.out.println("FIND EQUIVALENT PAIRS");
HashSet<Pair<Integer, Integer>> equivalentPairSet = findInitialEquivalentPairs(sg);
// System.out.println("REMOVE STATES");
// remove states that are not equivalent
for(Pair<Integer, Integer> eqPair : equivalentPairSet.toArray(new Pair[equivalentPairSet.size()])){
CompositeState state1 = sg.getState(eqPair.getLeft());
CompositeState state2 = sg.getState(eqPair.getRight());
List<CompositeStateTran> stateTranList1 = state1.getOutgoingStateTranList();
List<CompositeStateTran> stateTranList2 = state2.getOutgoingStateTranList();
boolean eq = true;
for(CompositeStateTran stateTran1 : stateTranList1){
boolean succEq = false;
for(CompositeStateTran stateTran2 : stateTranList2){
int nextState1 = stateTran1.getNextState();
int nextState2 = stateTran2.getNextState();
if(nextState1 == nextState2){
succEq = true;
continue;
}
if(nextState2 < nextState1){
int tmp = nextState2;
nextState2 = nextState1;
nextState1 = tmp;
}
Pair<Integer, Integer> statePair = new Pair<Integer, Integer>(nextState1, nextState2);
if(equivalentPairSet.contains(statePair)){
succEq = true;
continue;
}
}
if(!succEq){
eq = false;
break;
}
}
if(!eq){
equivalentPairSet.remove(eqPair);
}
}
for(Pair<Integer, Integer> statePair : equivalentPairSet){
int stateIndex1 = statePair.getLeft();
int stateIndex2 = statePair.getRight();
if(!sg.containsState(stateIndex1) || !sg.containsState(stateIndex2))
continue;
System.out.println(stateIndex1 + " - " + stateIndex2);
CompositeState state2 = sg.getState(stateIndex2);
// merge
for(CompositeStateTran incomingStateTran : state2.getIncomingStateTranList().toArray(new CompositeStateTran[state2.numIncomingTrans()])){
sg.removeStateTran(incomingStateTran);
incomingStateTran.setNextState(stateIndex1);
sg.addStateTran(incomingStateTran);
}
this.removeUnreachableState(sg, state2);
}
System.out.println(" --> # states: " + sg.numStates());
System.out.println(" --> # transitions: " + sg.numStateTrans());
}
public void mergeIncoming(CompositeStateGraph sg){
HashSet<Pair<Integer, Integer>> equivalentPairSet = findInitialEquivalentPairs2(sg);
for(Pair<Integer, Integer> statePair : equivalentPairSet){
int stateIndex1 = statePair.getLeft();
int stateIndex2 = statePair.getRight();
System.out.println(stateIndex1 + " - " + stateIndex2);
if(!sg.containsState(stateIndex1) || !sg.containsState(stateIndex2))
continue;
CompositeState state2 = sg.getState(stateIndex2);
// merge outgoing state transitions
for(CompositeStateTran outgoingStateTran : state2.getOutgoingStateTranList().toArray(new CompositeStateTran[state2.numOutgoingTrans()])){
sg.removeStateTran(outgoingStateTran);
outgoingStateTran.setCurrentState(stateIndex1);
sg.addStateTran(outgoingStateTran);
}
this.removeDanglingState(sg, state2);
}
System.out.println(" --> # states: " + sg.numStates());
System.out.println(" --> # transitions: " + sg.numStateTrans());
}
private HashSet<Pair<Integer, Integer>> findInitialEquivalentPairs(CompositeStateGraph sg){
HashSet<Pair<Integer, Integer>> equivalentSet = new HashSet<Pair<Integer, Integer>>();
CompositeState[] stateArray = sg.getStateSet().toArray(new CompositeState[sg.numStates()]);
for(int i = 0; i < stateArray.length; i++){
// System.out.println(" " + i + "/" + stateArray.length);
CompositeState state1 = stateArray[i];
List<Transition> enabled1 = sg.getEnabled(state1);
// HashSet<LPNTran> enabled1Set = new HashSet<LPNTran>();
// enabled1Set.addAll(enabled1);
for(int j = i + 1; j < stateArray.length; j++){
// System.out.println(" " + j + "/" + stateArray.length);
CompositeState state2 = stateArray[j];
CompositeState state = state1;
List<Transition> enabled2 = sg.getEnabled(state2);
if(enabled1.containsAll(enabled2) && enabled2.containsAll(enabled1)){
if(state2.getIndex() < state.getIndex()){
CompositeState temp = state;
state = state2;
state2 = temp;
}
equivalentSet.add(new Pair<Integer, Integer>(state.getIndex(), state2.getIndex()));
}
}
}
return equivalentSet;
}
private boolean equivalentOutgoing(Set<Transition> enabled1, List<Transition> enabled2){
// enabled2.containsAll(enabled1) && enabled1.containsAll(enabled2)
HashSet<Transition> enabled2Set = new HashSet<Transition>();
enabled2Set.addAll(enabled2);
if(enabled2Set.size() == enabled1.size() && enabled1.containsAll(enabled2Set))
return true;
return false;
}
private HashSet<Pair<Integer, Integer>> findInitialEquivalentPairs2(CompositeStateGraph sg){
HashSet<Pair<Integer, Integer>> equivalentSet = new HashSet<Pair<Integer, Integer>>();
CompositeState[] stateArray = sg.getStateSet().toArray(new CompositeState[sg.numStates()]);
for(int i = 0; i < stateArray.length; i++){
CompositeState state1 = stateArray[i];
List<Transition> enabled1 = this.getIncomingLpnTrans(state1);
for(int j = i + 1; j < stateArray.length; j++){
CompositeState state2 = stateArray[j];
CompositeState state = state1;
List<Transition> enabled2 = this.getIncomingLpnTrans(state2);
if(enabled2.containsAll(enabled1) && enabled1.containsAll(enabled2)){
if(state2.getIndex() < state.getIndex()){
CompositeState temp = state;
state = state2;
state2 = temp;
}
equivalentSet.add(new Pair<Integer, Integer>(state.getIndex(), state2.getIndex()));
}
}
}
return equivalentSet;
}
private List<Transition> getIncomingLpnTrans(CompositeState currentState){
Set<Transition> lpnTranSet = new HashSet<Transition>(currentState.numOutgoingTrans());
List<Transition> enabled = new ArrayList<Transition>(currentState.numOutgoingTrans());
for(CompositeStateTran stTran : currentState.getIncomingStateTranList()){
Transition lpnTran = stTran.getLPNTran();
if(lpnTranSet.add(lpnTran))
enabled.add(lpnTran);
}
return enabled;
}
// public void case2(CompositeStateGraph sg){
// long start = System.currentTimeMillis();
// int trans = sg.numTransitions;
// int states = sg.numCompositeStates();
//
// List<LPNTran> localTrans = new ArrayList<LPNTran>();
// List<CompositeState> localStates = new ArrayList<CompositeState>();
// List<LPNTran> nonLocalTrans = new ArrayList<LPNTran>();
// List<CompositeState> nonLocalStates = new ArrayList<CompositeState>();
//
// for(Object o : sg.getStateMap().values().toArray()){
// CompositeState currentState = (CompositeState) o;
//
// List<LPNTran> enabledTrans = currentState.enabledTranList;
// List<CompositeState> nextStates = currentState.nextStateList;
//
// localTrans.clear();
// localStates.clear();
// nonLocalTrans.clear();
// nonLocalStates.clear();
//
// for(int i = 0; i < enabledTrans.size(); i++){
// LPNTran lpnTran = enabledTrans.get(i);
// CompositeState nextState = (nextStates.get(i));
// if(lpnTran.local()){
// localTrans.add(lpnTran);
// localStates.add(nextState);
// }
//// else{
// nonLocalTrans.add(lpnTran);
// nonLocalStates.add(nextState);
//// }
// }
//
// if(nonLocalTrans.isEmpty()){
// continue;
// }
//
// for(int i = 0; i < nonLocalTrans.size(); i++){
// LPNTran nonLocalTran = nonLocalTrans.get(i);
// CompositeState s2 = nonLocalStates.get(i);
//
// List<LPNTran> s2Enabled = s2.enabledTranList;
// if(s2Enabled.size() > 1 || s2Enabled.size() < 1){
// continue;
// }
//// else if(s2 == sg.getInitState()){
//// continue;
//// }
//
// List<CompositeState> s2NextState = s2.nextStateList;
// for(int j = 0; j < s2Enabled.size(); j++){
// LPNTran invTran2 = s2Enabled.get(j);
// if(invTran2.local()){
// CompositeState s4 = s2NextState.get(j);
//
// for(int k = 0; k < localTrans.size(); k++){
// LPNTran invTran = localTrans.get(k);
// if(invTran == nonLocalTran) continue;
//
// CompositeState s3 = localStates.get(k);
//
// List<LPNTran> s3Enabled = s3.enabledTranList;
// List<CompositeState> s3NextState = s3.nextStateList;
// for(int n = 0; n < s3Enabled.size(); n++){
// LPNTran nonLocalTran2 = s3Enabled.get(n);
// CompositeState nextState = s3NextState.get(n);
//
// if(nonLocalTran2 == nonLocalTran && nextState == s4){
// currentState.enabledTranList.remove(nonLocalTran);
// currentState.nextStateList.remove(s2);
// sg.numTransitions --;
//
// List<CompositeState> incomingStates = s2.incomingStateList;
// for(int m = 0; m < incomingStates.size(); m++){
// CompositeState curr = incomingStates.get(m);
// List<CompositeState> incomingNextStateList = curr.nextStateList;
//
// for(int idx = 0; idx < incomingNextStateList.size(); idx++){
// CompositeState tmpState = incomingNextStateList.get(idx);
// if(tmpState == s2){
// incomingNextStateList.set(idx, s4);
// s4.incomingStateList.add(curr);
// break;
// }
// }
// }
//
// s2.nextStateList.clear();
// s2.incomingStateList.clear();
// s2.enabledTranList.clear();
//
// sg.compositeStateMap.remove(s2);
// if(sg.getInitState() == s2){
// sg.setInitState(s4);
// }
// sg.numTransitions --;
// }
// }
// }
// }
// }
// }
// }
//
//// System.out.println(sg.getLabel() + " case2 transitions: " + trans + " - " + sg.numTransitions);
//// System.out.println(sg.getLabel() + " case2 states: " + states + " - " + sg.numCompositeStates());
//// long elapsedTimeMillis = System.currentTimeMillis()-start;
//// float elapsedTimeSec = elapsedTimeMillis/1000F;
//// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
// }
//
// public void case3(CompositeStateGraph sg){
// long start = System.currentTimeMillis();
// int trans = sg.numTransitions;
// int states = sg.numCompositeStates();
//
// List<LPNTran> localTrans = new ArrayList<LPNTran>();
// List<CompositeState> localStates = new ArrayList<CompositeState>();
// List<LPNTran> nonLocalTrans = new ArrayList<LPNTran>();
// List<CompositeState> nonLocalStates = new ArrayList<CompositeState>();
//
// for(Object o : sg.getStateMap().values().toArray()){
// CompositeState currentState = (CompositeState) o;
//
// List<LPNTran> enabledTrans = currentState.enabledTranList;
// List<CompositeState> nextStates = currentState.nextStateList;
//
// localTrans.clear();
// localStates.clear();
// nonLocalTrans.clear();
// nonLocalStates.clear();
//
// for(int i = 0; i < enabledTrans.size(); i++){
// LPNTran lpnTran = enabledTrans.get(i);
// CompositeState nextState = (nextStates.get(i));
// if(lpnTran.local()){
// localTrans.add(lpnTran);
// localStates.add(nextState);
// }
//// else{
// nonLocalTrans.add(lpnTran);
// nonLocalStates.add(nextState);
//// }
// }
//
// if(nonLocalTrans.isEmpty()){
// continue;
// }
//
// for(int i = 0; i < localTrans.size(); i++){
// LPNTran localTran = localTrans.get(i);
// CompositeState s3 = localStates.get(i);
// if(s3.incomingStateList.size() != 1){
// continue;
// }
//// else if(s3 == sg.getInitState()){
//// continue;
//// }
//
// List<LPNTran> s3Enabled = s3.enabledTranList;
// List<CompositeState> s3NextState = s3.nextStateList;
//
// boolean remove = false;
// List<LPNTran> removeTran = new ArrayList<LPNTran>();
//
// for(int j = 0; j < s3Enabled.size(); j++){
// LPNTran nonLocalTran2 = s3Enabled.get(j);
// if(!nonLocalTran2.local()){
// CompositeState s4 = s3NextState.get(j);
//
// for(int k = 0; k < nonLocalTrans.size(); k++){
// LPNTran nonLocalTran = nonLocalTrans.get(k);
// if(localTran == nonLocalTran) continue;
//
// CompositeState s2 = nonLocalStates.get(k);
//
// List<LPNTran> s2Enabled = s2.enabledTranList;
// List<CompositeState> s2NextState = s2.nextStateList;
// for(int n = 0; n < s2Enabled.size(); n++){
// LPNTran invTran2 = s2Enabled.get(n);
// if(invTran2.local()){
// CompositeState nextState = s2NextState.get(n);
//
// if(nonLocalTran2 == nonLocalTran && nextState == s4){
// removeTran.add(nonLocalTran2);
// remove = true;
// }
// }
// }
// }
// }
// }
//
// if(remove){
// currentState.enabledTranList.remove(localTran);
// currentState.nextStateList.remove(s3);
// sg.numTransitions--;
//
// for(int m = 0; m < s3Enabled.size(); m++){
// CompositeState currState = s3NextState.get(m);
// LPNTran currTran = s3Enabled.get(m);
//
// if(removeTran.contains(currTran)){
// removeTran.remove(currTran);
// sg.numTransitions--;
// continue;
// }
//
// currentState.enabledTranList.add(currTran);
// currentState.nextStateList.add(currState);
//
// List<CompositeState> currIncomingList = currState.incomingStateList;
// for(int idx = 0; idx < currIncomingList.size(); idx++){
// if(currIncomingList.get(idx) == s3){
// currIncomingList.set(idx, currState);
// }
// }
// }
//
// sg.compositeStateMap.remove(s3);
// if(sg.getInitState() == s3){
// sg.setInitState(currentState);
// }
//
// s3.nextStateList.clear();
// s3.enabledTranList.clear();
// s3.incomingStateList.clear();
// }
// }
// }
//
//// System.out.println(sg.getLabel() + " case3 transitions: " + trans + " - " + sg.numTransitions);
//// System.out.println(sg.getLabel() + " case3 states: " + states + " - " + sg.numCompositeStates());
//// long elapsedTimeMillis = System.currentTimeMillis()-start;
//// float elapsedTimeSec = elapsedTimeMillis/1000F;
//// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
// }
/**
* Constructs the compositional state graphs.
*/
public void compositionalFindSG(StateGraph[] sgArray){
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// try {
// br.readLine();
// } catch (IOException e) {
// e.printStackTrace();
// }
int iter = 0;
int newTransitions = 0;
long start = System.currentTimeMillis();
HashMap<StateGraph, List<StateGraph>> inputSrcMap = new HashMap<StateGraph, List<StateGraph>>();
for (StateGraph sg : sgArray) {
LhpnFile lpn = sg.getLpn();
// Add initial state to state graph
State init = sg.genInitialState();
sg.setInitialState(init);
sg.addState(init);
sg.addFrontierState(init);
Set<String> inputSet = lpn.getAllInputs().keySet();
Set<String> outputSet = lpn.getAllOutputs().keySet();
int numSrc = 0;
// Find lpn interfaces
for(StateGraph sg2 : sgArray){
if(sg == sg2)
continue;
LhpnFile lpn2 = sg2.getLpn();
Set<String> outputs = lpn2.getAllOutputs().keySet();
for(String output : outputs){
if (inputSet.contains(output)){
numSrc++;
break;
}
}
for(String output : outputs){
if (outputSet.contains(output)){
numSrc++;
break;
}
}
}
List<int[]> thisInterfaceList = new ArrayList<int[]>(sgArray.length);
List<int[]> otherInterfaceList = new ArrayList<int[]>(sgArray.length);
// TODO: Why designUnitSet.size() + 1 ?
// for(int i = 0; i < designUnitSet.size() + 1; i++){
for(int i = 0; i < sgArray.length; i++){
thisInterfaceList.add(null);
otherInterfaceList.add(null);
}
List<StateGraph> srcArray = new ArrayList<StateGraph>(numSrc);
if(numSrc > 0){
// int index = 0;
for(StateGraph sg2 : sgArray){
if(sg == sg2)
continue;
LhpnFile lpn2 = sg2.getLpn();
int interfaceSize = 0;
Set<String> outputs = lpn2.getAllOutputs().keySet();
Set<String> inputs = lpn2.getAllInputs().keySet();
for(String output : outputs){
if (inputSet.contains(output)){
interfaceSize++;
}
}
for(String input : inputs){
if(outputSet.contains(input)){
interfaceSize++;
}
}
for(String output : outputs){
if (outputSet.contains(output)){
interfaceSize++;
}
}
for(String input : inputs){
if (inputSet.contains(input)){
interfaceSize++;
}
}
if(interfaceSize > 0){
int[] thisIndexList = new int[interfaceSize];
int[] otherIndexList = new int[interfaceSize];
lpn.genIndexLists(thisIndexList, otherIndexList, lpn2);
thisInterfaceList.set(lpn2.getLpnIndex(), thisIndexList);
otherInterfaceList.set(lpn2.getLpnIndex(), otherIndexList);
// Hao's LPN starting index is 1, whereas ours starts from 0.
// thisInterfaceList.set(lpn2.ID-1, thisIndexList);
// otherInterfaceList.set(lpn2.ID-1, otherIndexList);
srcArray.add(sg2);
// index++;
}
}
}
lpn.setThisIndexList(thisInterfaceList);
lpn.setOtherIndexList(otherInterfaceList);
inputSrcMap.put(sg, srcArray);
}
// TODO: (temp) designUnitSet has been created already at this point.
// LhpnFile[] lpnList = new LhpnFile[designUnitSet.size()];
// int idx = 0;
// for (StateGraph sg : designUnitSet) {
// lpnList[idx++] = sg.getLpn();
// }
constructDstLpnList(sgArray);
// Run initial findSG
for (StateGraph sg : sgArray) {
int result = 0;
if(Options.getStickySemantics()){
// result = sg.constrStickyFindSG(sg.getInitialState(), emptyTranList);
}
else{
result = sg.constrFindSG(sg.getInitialState());
}
newTransitions += result;
}
long peakUsed = 0;
long peakTotal = 0;
List<Constraint> newConstraintSet = new ArrayList<Constraint>();
List<Constraint> oldConstraintSet = new ArrayList<Constraint>();
while(newTransitions > 0){
iter++;
newTransitions = 0;
for(StateGraph sg : sgArray){
sg.genConstraints();
sg.genFrontier();
}
// Extract and apply constraints generated from srcSG to sg.
for(StateGraph sg : sgArray){
for(StateGraph srcSG : inputSrcMap.get(sg)){
extractConstraints(sg, srcSG, newConstraintSet, oldConstraintSet);
newTransitions += applyConstraintSet(sg, srcSG, newConstraintSet, oldConstraintSet);
}
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
System.out.println();
int numStates = 0;
// int numTrans = 0;
int numConstr = 0;
for (StateGraph sg : sgArray) {
sg.genConstraints();
sg.genFrontier();
System.out.print(" ");
sg.printStates();
// sg.clear();
numStates += sg.reachSize();
// numTrans += sg.numTransitions();
numConstr += sg.numConstraints();
}
System.out.println("\n --> # states: " + numStates);
// System.out.println(" --> # transitions: " + numTrans);
System.out.println(" --> # constraints: " + numConstr);
System.out.println(" --> # iterations: " + iter);
System.out.println("\n --> Peak used memory: " + peakUsed/1000000F + " MB");
System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
if(elapsedTimeSec > 60){
float elapsedTime = elapsedTimeSec/(float)60;
System.out.println(" --> Elapsed time: " + elapsedTime + " min");
}
}
/**
* Constructs the compositional state graphs.
*/
public void parallelCompositionalFindSG(List<StateGraph> designUnitSet){
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// try {
// br.readLine();
// } catch (IOException e) {
// e.printStackTrace();
// }
int iter = 0;
int newTransitions = 0;
long start = System.currentTimeMillis();
HashMap<StateGraph, StateGraph[]> inputSrcMap = new HashMap<StateGraph, StateGraph[]>();
for (StateGraph sg : designUnitSet) {
LhpnFile lpn = sg.getLpn();
// Add initial state to state graph
State init = sg.genInitialState();
sg.setInitialState(init);
sg.addState(init);
sg.addFrontierState(init);
Set<String> inputSet = lpn.getAllInputs().keySet();
Set<String> outputSet = lpn.getAllOutputs().keySet();
int size = 0;
// Find lpn interfaces
for(StateGraph sg2 : designUnitSet){
if(sg == sg2) continue;
Set<String> outputs = sg2.getLpn().getAllOutputs().keySet();
for(String output : outputs){
if (inputSet.contains(output)){
size++;
break;
}
}
}
List<int[]> thisInterfaceList = new ArrayList<int[]>(designUnitSet.size() + 1);
List<int[]> otherInterfaceList = new ArrayList<int[]>(designUnitSet.size() + 1);
for(int i = 0; i < designUnitSet.size() + 1; i++){
thisInterfaceList.add(null);
otherInterfaceList.add(null);
}
StateGraph[] srcArray = new StateGraph[size];
if(size > 0){
int index = 0;
for(StateGraph sg2 : designUnitSet){
LhpnFile lpn2 = sg2.getLpn();
if(sg == sg2) continue;
boolean src = false;
int interfaceSize = 0;
Set<String> outputs = lpn2.getAllOutputs().keySet();
for(String output : outputs){
if (inputSet.contains(output)){
interfaceSize++;
src = true;
}
}
if(src){
Set<String> inputs = lpn2.getAllInputs().keySet();
for(String input : inputs){
if (outputSet.contains(input)){
interfaceSize++;
}
}
for(String input : inputs){
if (inputSet.contains(input)){
interfaceSize++;
}
}
for(String output : outputs){
if (outputSet.contains(output)){
interfaceSize++;
}
}
int[] thisIndexList = new int[interfaceSize];
int[] otherIndexList = new int[interfaceSize];
// TODO: (future) need to add getThisIndexArray in LhpnFile
/*
lpn.genIndexLists(thisIndexList, otherIndexList, lpn2);
thisInterfaceList.set(lpn2.ID, thisIndexList);
otherInterfaceList.set(lpn2.ID, otherIndexList);
*/
srcArray[index] = sg2;
index++;
}
}
}
lpn.setThisIndexList(thisInterfaceList);
lpn.setOtherIndexList(otherInterfaceList);
inputSrcMap.put(sg, srcArray);
}
LhpnFile[] lpnList = new LhpnFile[designUnitSet.size()];
int idx = 0;
for (StateGraph sg : designUnitSet) {
lpnList[idx] = sg.getLpn();
idx++;
}
// Run initial findSG
for (StateGraph sg : designUnitSet) {
int result = sg.constrFindSG(sg.getInitialState());
newTransitions += result;
}
long peakUsed = 0;
long peakTotal = 0;
CompositionalThread[] threadArray = new CompositionalThread[designUnitSet.size()];
while(newTransitions > 0){
iter++;
newTransitions = 0;
for(StateGraph sg : designUnitSet){
sg.genConstraints();
sg.genFrontier();
}
int t = 0;
for(StateGraph sg : designUnitSet){
CompositionalThread newThread = new CompositionalThread(sg, inputSrcMap.get(sg), iter);
newThread.start();
threadArray[t++] = newThread;
}
for(CompositionalThread p : threadArray){
try {
p.join();
newTransitions += p.getNewTransitions();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
System.out.println();
int numStates = 0;
int numTrans = 0;
int numConstr = 0;
for (StateGraph sg : designUnitSet) {
System.out.print(" ");
sg.printStates();
numStates += sg.reachSize();
//numTrans += sg.numTransitions();
numConstr += sg.numConstraints();
}
System.out.println("\n --> # states: " + numStates);
System.out.println(" --> # transitions: " + numTrans);
System.out.println(" --> # constraints: " + numConstr);
System.out.println(" --> # iterations: " + iter);
System.out.println("\n --> Peak used memory: " + peakUsed/1000000F + " MB");
System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
if(elapsedTimeSec > 60){
float elapsedTime = elapsedTimeSec/(float)60;
System.out.println(" --> Elapsed time: " + elapsedTime + " min");
}
}
/**
* Applies new constraints to the entire state set, and applies old constraints to the frontier state set.
* @return Number of new transitions.
*/
private int applyConstraintSet(StateGraph sg, StateGraph srcSG, List<Constraint> newConstraintSet, List<Constraint> oldConstraintSet){
int newTransitions = 0;
LhpnFile srcLpn = srcSG.getLpn();
LhpnFile lpn = sg.getLpn();
int[] thisIndexList = lpn.getThisIndexArray(srcLpn.getLpnIndex());
int[] otherIndexList = lpn.getOtherIndexArray(srcLpn.getLpnIndex());
// int[] thisIndexList = lpn.getThisIndexArray(srcLpn.ID - 1);
// int[] otherIndexList = lpn.getOtherIndexArray(srcLpn.ID - 1);
if(newConstraintSet.size() > 0){
for(State currentState : sg.getStateSet()){
for(Constraint c : newConstraintSet){
if(compatible(currentState, c, thisIndexList, otherIndexList)){
newTransitions += createNewState(sg, currentState, c);
}
}
}
for(State currentState : sg.getFrontierStateSet()){
for(Constraint c : newConstraintSet){
if(compatible(currentState, c, thisIndexList, otherIndexList)){
newTransitions += createNewState(sg, currentState, c);
}
}
}
}
if(oldConstraintSet.size() > 0){
for(State currentState : sg.getFrontierStateSet()){
for(Constraint c : oldConstraintSet){
if(compatible(currentState, c, thisIndexList, otherIndexList)){
newTransitions += createNewState(sg, currentState, c);
}
}
}
}
return newTransitions;
}
/**
* Extracts applicable constraints from a StateGraph.
* @param sg - The state graph the constraints are to be applied.
* @param srcSG - The state graph the constraint are extracted from.
*/
private void extractConstraints(StateGraph sg, StateGraph srcSG, List<Constraint> newConstraintSet, List<Constraint> oldConstraintSet){
newConstraintSet.clear();
oldConstraintSet.clear();
LhpnFile srcLpn = srcSG.getLpn();
for(Constraint newConstraint : sg.getNewConstraintSet()){
if(newConstraint.getLpn() != srcLpn)
continue;
newConstraintSet.add(newConstraint);
}
for(Constraint oldConstraint : sg.getOldConstraintSet()){
if(oldConstraint.getLpn() != srcLpn)
continue;
oldConstraintSet.add(oldConstraint);
}
}
/**
* Determines whether a constraint is compatible with a state.
* @return True if compatible, otherwise False.
*/
private boolean compatible(State currentState, Constraint constr, int[] thisIndexList, int[] otherIndexList){
int[] constraintVector = constr.getVector();
int[] currentVector = currentState.getVariableVector();
for(int i = 0; i < thisIndexList.length; i++){
int thisIndex = thisIndexList[i];
int otherIndex = otherIndexList[i];
if(currentVector[thisIndex] != constraintVector[otherIndex]){
return false;
}
}
return true;
}
/**
* Creates a state from a given constraint and compatible state and insert into state graph. If the state is new, then findSG is called.
* @return Number of new transitions.
*/
private int createNewState(StateGraph sg, State compatibleState, Constraint c){
int newTransitions = 0;
State newState = new State(compatibleState);
int[] newVector = newState.getVariableVector();
//List<VarNode> variableList = c.getVariableList();
List<Integer> variableList = c.getVariableList();
List<Integer> valueList = c.getValueList();
//int[] compatibleVector = compatibleState.getVector();
// TODO: Need to update tranVector here?
for(int i = 0; i < variableList.size(); i++){
//int index = variableList.get(i).getIndex(compatibleVector);
int index = variableList.get(i);
newVector[index] = valueList.get(i);
}
updateTranVectorByConstraint(newState.getLpn(), newState.getTranVector(), newState.getMarking(), newVector);
State nextState = sg.addState(newState);
if(nextState == newState){
int result = 0;
sg.addFrontierState(nextState);
// TODO: Need to consider the "Sticky sematics"
// if(Options.getStickySemantics()){
// result = sg.constrStickyFindSG(nextState, sg.getEnabled(compatibleState));
// }
// else{
result = sg.constrFindSG(nextState);
// }
if(result < 0)
return newTransitions;
newTransitions += result;
}
Transition constraintTran = c.getLpnTransition();
sg.addStateTran(compatibleState, constraintTran, nextState);
newTransitions++;
return newTransitions;
}
private String printTranVecotr(boolean[] tranVector) {
String tranVecStr = "[";
for (boolean i : tranVector) {
tranVecStr = tranVecStr + "," + i;
}
tranVecStr = tranVecStr + "]";
return tranVecStr;
}
/**
* Update tranVector due to application of a constraint. Only vector of a state can change due to a constraint, and
* therefore the tranVector can potentially change.
* @param lpn
* @param enabledTranBeforeConstr
* @param marking
* @param newVector
* @return
*/
public void updateTranVectorByConstraint(LhpnFile lpn, boolean[] enabledTran,
int[] marking, int[] newVector) {
// find newly enabled transition(s) based on the updated variables vector.
for (Transition tran : lpn.getAllTransitions()) {
boolean needToUpdate = true;
String tranName = tran.getLabel();
int tranIndex = tran.getIndex();
if (Options.getDebugMode()) {
// System.out.println("Checking " + tranName);
}
if (lpn.getEnablingTree(tranName) != null
&& lpn.getEnablingTree(tranName).evaluateExpr(lpn.getAllVarsWithValuesAsString(newVector)) == 0.0) {
if (Options.getDebugMode()) {
System.out.println(tran.getLabel() + " " + "Enabling condition is false");
}
if (enabledTran[tranIndex] && !tran.isPersistent())
enabledTran[tranIndex] = false;
continue;
}
if (lpn.getTransitionRateTree(tranName) != null
&& lpn.getTransitionRateTree(tranName).evaluateExpr(lpn.getAllVarsWithValuesAsString(newVector)) == 0.0) {
if (Options.getDebugMode()) {
System.out.println("Rate is zero");
}
continue;
}
if (lpn.getPreset(tranName) != null && lpn.getPreset(tranName).length != 0) {
for (int place : lpn.getPresetIndex(tranName)) {
if (marking[place]==0) {
if (Options.getDebugMode()) {
System.out.println(tran.getLabel() + " " + "Missing a preset token");
}
needToUpdate = false;
break;
}
}
}
if (needToUpdate) {
enabledTran[tranIndex] = true;
if (Options.getDebugMode()) {
System.out.println(tran.getLabel() + " is Enabled.");
}
}
}
}
private void constructDstLpnList(StateGraph[] sgArray) {
for (int i=0; i<sgArray.length; i++) {
LhpnFile curLPN = sgArray[i].getLpn();
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j<allTrans.length; j++) {
Transition curTran = allTrans[j];
for (int k=0; k<sgArray.length; k++) {
curTran.setDstLpnList(sgArray[k].getLpn());
}
}
}
}
}
| gui/src/verification/platu/logicAnalysis/CompositionalAnalysis.java | package verification.platu.logicAnalysis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import verification.platu.common.Pair;
import verification.platu.lpn.VarSet;
import verification.platu.main.Options;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
public class CompositionalAnalysis {
public CompositionalAnalysis(){
}
// public CompositeStateGraph compose(StateGraph sg1, StateGraph sg2){
// long start = System.currentTimeMillis();
//
// // check an output drives an input
// boolean compatible = false;
// for(String output : sg1.getOutputs()){
// VarSet inputs = sg2.getInputs();
// if(inputs.contains(output)){
// compatible = true;
// break;
// }
// }
//
// if(!compatible){
// VarSet inputs = sg1.getInputs();
// for(String output : sg2.getOutputs()){
// if(inputs.contains(output)){
// compatible = true;
// break;
// }
// }
// }
//
// if(!compatible){
// System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
// return null;
// }
//
// // create new node with init states
// State[] initStates = new State[2];
// initStates[0] = sg1.getInitialState();
// initStates[1] = sg2.getInitialState();
// CompositeState initNode = new CompositeState(initStates);
//
// HashSet<LPNTran> synchronousTrans = new HashSet<LPNTran>();
// synchronousTrans.addAll(sg1.getInputTranSet());
// synchronousTrans.retainAll(sg2.getOutputTranSet());
//
// HashSet<LPNTran> temp = new HashSet<LPNTran>();
// temp.addAll(sg2.getInputTranSet());
// temp.retainAll(sg1.getOutputTranSet());
// synchronousTrans.addAll(temp);
//
// List<LPNTran> inputTrans1 = new ArrayList<LPNTran>();
// inputTrans1.addAll(sg1.getInputTranSet());
// inputTrans1.removeAll(synchronousTrans);
//
// List<LPNTran> inputTrans2 = new ArrayList<LPNTran>();
// inputTrans2.addAll(sg2.getInputTranSet());
// inputTrans2.removeAll(synchronousTrans);
//
// // create new composite state graph
// StateGraph[] sgArray = new StateGraph[2];
// sgArray[0] = sg1;
// sgArray[1] = sg2;
// CompositeStateGraph compositeSG = new CompositeStateGraph(initNode, sgArray);
//
// // create CompositeState stack
// Stack<CompositeState> compositeStateStack = new Stack<CompositeState>();
//
// // initialize with initial MDD node
// compositeStateStack.push(initNode);
//
// List<LPNTran> tranList1 = new ArrayList<LPNTran>();
// List<State> stateList1 = new ArrayList<State>();
// List<LPNTran> tranList2 = new ArrayList<LPNTran>();
// List<State> stateList2 = new ArrayList<State>();
// List<State> intersect1 = new ArrayList<State>();
// List<State> intersect2 = new ArrayList<State>();
// List<LPNTran> intersectTran = new ArrayList<LPNTran>();
//
// long peakUsed = 0;
// long peakTotal = 0;
//
// //while stack is not empty
// while(!compositeStateStack.isEmpty()){
// //pop stack
// CompositeState currentCompositeState = compositeStateStack.pop();
//
// State[] stateTuple = currentCompositeState.getStateTuple();
// State s1 = stateTuple[0];
// State s2 = stateTuple[1];
//
// // find next state transitions for each state
//// LPNTranSet enabled1 = sg1.getEnabled(s1);
//// LPNTranSet enabled2 = sg2.getEnabled(s2);
// List<LPNTran> enabled1 = sg1.lpnTransitionMap.get(s1);
// List<LPNTran> enabled2 = sg2.lpnTransitionMap.get(s2);
//
// tranList1.clear();
// stateList1.clear();
// tranList2.clear();
// stateList2.clear();
// intersect1.clear();
// intersect2.clear();
// intersectTran.clear();
//
// for(LPNTran lpnTran : enabled1){
// if(lpnTran.local()){
// tranList1.add(lpnTran);
// stateList1.add((State) lpnTran.getNextState(s1));
// }
// else{
// if(synchronousTrans.contains(lpnTran)){
//// State st = lpnTran.constraintTranMap.get(s2);
// State st = lpnTran.getNextState(s2);
// if(st != null){
// intersect1.add((State) lpnTran.getNextState(s1));
// intersect2.add(st);
// intersectTran.add(lpnTran);
// }
// }
// else{
// tranList1.add(lpnTran);
// stateList1.add((State) lpnTran.getNextState(s1));
// }
// }
// }
//
//
// for(LPNTran lpnTran : enabled2){
// if(lpnTran.local()){
// tranList2.add(lpnTran);
// stateList2.add((State) lpnTran.getNextState(s2));
// }
// else{
// if(synchronousTrans.contains(lpnTran)){
//// State st = lpnTran.constraintTranMap.get(s1);
// State st = lpnTran.getNextState(s1);
// if(st != null){
// intersect1.add(st);
// intersect2.add((State) lpnTran.getNextState(s2));
// intersectTran.add(lpnTran);
// }
// }
// else{
// tranList2.add(lpnTran);
// stateList2.add((State) lpnTran.getNextState(s2));
// }
// }
// }
//
// for(LPNTran lpnTran : inputTrans1){
//// State st = lpnTran.constraintTranMap.get(s1);
// State st = lpnTran.getNextState(s1);
// if(st != null){
// tranList1.add(lpnTran);
// stateList1.add(st);
// }
// }
//
// for(LPNTran lpnTran : inputTrans2){
//// State st = lpnTran.constraintTranMap.get(s2);
// State st = lpnTran.getNextState(s2);
// if(st != null){
// tranList2.add(lpnTran);
// stateList2.add(st);
// }
// }
//
//// int size = tranList1.size() + tranList2.size() + intersect1.size();
//// CompositeState[] nextStateArray = new CompositeState[size];
//// LPNTran[] tranArray = new LPNTran[size];
//// size--;
//
// // for each transition
// // create new MDD node and push onto stack
// for(int i = 0; i < tranList1.size(); i++){
// LPNTran lpnTran = tranList1.get(i);
//
// State nextState = stateList1.get(i);
// State[] newStateTuple = new State[2];
// newStateTuple[0] = nextState;
// newStateTuple[1] = s2;
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// compositeStateStack.push(newCompositeState);
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[size] = st;
//// tranArray[size] = lpnTran;
//// size--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
// for(int i = 0; i < tranList2.size(); i++){
// LPNTran lpnTran = tranList2.get(i);
//
// State nextState = stateList2.get(i);
// State[] newStateTuple = new State[2];
// newStateTuple[0] = s1;
// newStateTuple[1] = nextState;
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// compositeStateStack.push(newCompositeState);
// st = newCompositeState;
// }
//
// // create new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[size] = st;
//// tranArray[size] = lpnTran;
//// size--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
// for(int i = 0; i < intersect1.size(); i++){
// LPNTran lpnTran = intersectTran.get(i);
//
// State nextState1 = intersect1.get(i);
// State nextState2 = intersect2.get(i);
//
// State[] newStateTuple = new State[2];
// newStateTuple[0] = nextState1;
// newStateTuple[1] = nextState2;
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// compositeStateStack.push(newCompositeState);
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[size] = st;
//// tranArray[size] = lpnTran;
//// size--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
//// currentCompositeState.setNextStateArray(nextStateArray);
//// currentCompositeState.setTranArray(tranArray);
//
// long curTotalMem = Runtime.getRuntime().totalMemory();
// if(curTotalMem > peakTotal)
// peakTotal = curTotalMem;
//
// long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// if(curUsedMem > peakUsed)
// peakUsed = curUsedMem;
// }
//
// System.out.println("\n " + compositeSG.getLabel() + ": ");
// System.out.println(" --> # states: " + compositeSG.numCompositeStates());
//// System.out.println(" --> # transitions: " + compositeSG.numCompositeStateTrans());
//
// System.out.println(" --> Peak used memory: " + peakUsed/1000000F + " MB");
// System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
// System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
//
// long elapsedTimeMillis = System.currentTimeMillis()-start;
// float elapsedTimeSec = elapsedTimeMillis/1000F;
// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
//
// if(elapsedTimeSec > 60){
// float elapsedTime = elapsedTimeSec;
// elapsedTime = elapsedTimeSec/(float)60;
// System.out.println(" --> Elapsed time: " + elapsedTime + " min");
// }
//
// System.out.println();
//
//// System.out.println();
//// for(CompositeState cState : compositeSG.compositeStateMap){
//// State[] stateTuple = cState.getStateTuple();
//// State s1 = stateTuple[0];
//// State s2 = stateTuple[1];
////
//// System.out.println(s1.getLabel() + ", " + s2.getLabel());
//// }
//
// return compositeSG;
// }
//
// public CompositeStateGraph compose(CompositeStateGraph csg, StateGraph sg){
// if(csg == null || sg == null){
// return csg;
// }
//
// long start = System.currentTimeMillis();
//
// // check an output drives an input
// boolean compatible = false;
// for(String output : sg.getOutputs()){
// for(StateGraph sg2 : csg.stateGraphArray){
// VarSet inputs = sg2.getInputs();
// if(inputs.contains(output)){
// compatible = true;
// break;
// }
// }
//
// if(compatible){
// break;
// }
// }
//
// if(!compatible){
// VarSet inputs = sg.getInputs();
// for(StateGraph sg2 : csg.stateGraphArray){
// for(String output : sg2.getOutputs()){
// if(inputs.contains(output)){
// compatible = true;
// break;
// }
// }
//
// if(compatible){
// break;
// }
// }
//
// }
//
// if(!compatible){
// System.out.println("state graphs " + csg.getLabel() + " and " + sg.getLabel() + " cannot be composed");
// return null;
// }
//
// for(StateGraph sg2 : csg.stateGraphArray){
// if(sg2 == sg){
// return csg;
// }
// }
//
// // create new node with init states
// int size = csg.getSize() + 1;
// State[] initStates = new State[size];
// initStates[0] = sg.getInitialState();
// for(int i = 1; i < size; i++){
// initStates[i] = csg.stateGraphArray[i-1].getInitialState();
// }
//
// CompositeState initNode = new CompositeState(initStates);
//
// HashSet<LPNTran> synchronousTrans = new HashSet<LPNTran>();
//
// for(StateGraph sg2 : csg.stateGraphArray){
// HashSet<LPNTran> inputTrans = new HashSet<LPNTran>();
// inputTrans.addAll(sg.getInputTranSet());
// inputTrans.retainAll(sg2.getOutputTranSet());
//
// HashSet<LPNTran> outputTrans = new HashSet<LPNTran>();
// outputTrans.addAll(sg2.getInputTranSet());
// outputTrans.retainAll(sg.getOutputTranSet());
//
// synchronousTrans.addAll(inputTrans);
// synchronousTrans.addAll(outputTrans);
// }
//
// List<LPNTran> inputTrans = new ArrayList<LPNTran>();
// inputTrans.addAll(sg.getInputTranSet());
// inputTrans.removeAll(synchronousTrans);
//
// // create new composite state graph
// StateGraph[] sgArray = new StateGraph[size];
// sgArray[0] = sg;
// for(int i = 1; i < size; i++){
// sgArray[i] = csg.stateGraphArray[i-1];
// }
//
// CompositeStateGraph compositeSG = new CompositeStateGraph(initNode, sgArray);
//
// // create CompositeState stack
// Stack<State> stateStack = new Stack<State>();
// Stack<CompositeState> compositeStateStack = new Stack<CompositeState>();
// Stack<CompositeState> newStateStack = new Stack<CompositeState>();
//
//// Queue<State> stateQueue = new LinkedList<State>();
//// Queue<CompositeState> compositeStateQueue = new LinkedList<CompositeState>();
//// Queue<CompositeState> newStateQueue = new LinkedList<CompositeState>();
//
// // initialize with initial MDD node
// newStateStack.push(initNode);
// stateStack.push(sg.getInitialState());
// compositeStateStack.push(csg.getInitState());
//
//// stateQueue.offer(sg.init);
//// compositeStateQueue.offer(csg.getInitState());
//// newStateQueue.offer(initNode);
//
//// HashMap<LPNTran, StateTran> tranMap = new HashMap<LPNTran, StateTran>();
//// List<CompositeStateTran> csgStateTranList = new ArrayList<CompositeStateTran>();
//// List<StateTran> sgIntersect = new ArrayList<StateTran>();
//// List<CompositeStateTran> csgIntersect = new ArrayList<CompositeStateTran>();
//
// List<LPNTran> tranList1 = new ArrayList<LPNTran>();
// List<State> stateList1 = new ArrayList<State>();
// List<LPNTran> tranList2 = new ArrayList<LPNTran>();
// List<CompositeState> stateList2 = new ArrayList<CompositeState>();
// List<State> intersect1 = new ArrayList<State>();
// List<CompositeState> intersect2 = new ArrayList<CompositeState>();
// List<LPNTran> intersectTran = new ArrayList<LPNTran>();
//
// long peakUsed = 0;
// long peakTotal = 0;
//
// //while stack is not empty
// while(!newStateStack.isEmpty()){
//// while(!newStateQueue.isEmpty()){
// long s1 = System.currentTimeMillis();
//
// //pop stack
// CompositeState currentCompositeState = newStateStack.pop();
// State subState = stateStack.pop();
// CompositeState subCompositeState = compositeStateStack.pop();
//
//// CompositeState currentCompositeState = newStateQueue.poll();
//// State subState = stateQueue.poll();
//// CompositeState subCompositeState = compositeStateQueue.poll();
//
// State[] subCompositeTuple = subCompositeState.getStateTuple();
//
// tranList1.clear();
// stateList1.clear();
// tranList2.clear();
// stateList2.clear();
// intersect1.clear();
// intersect2.clear();
// intersectTran.clear();
//
// // find next state transitions for each state
// List<LPNTran> enabled1 = sg.lpnTransitionMap.get(subState);
//// List<LPNTran> enabled2 = subCompositeState.getTranList();
//// List<CompositeState> edgeList = subCompositeState.getNextStateList();
//// LPNTran[] enabled2 = subCompositeState.getTranArray();
//// CompositeState[] edgeList = subCompositeState.getNextStateArray();
// List<LPNTran> enabled2 = subCompositeState.enabledTranList;
// List<CompositeState> edgeList = subCompositeState.nextStateList;
//
//// System.out.println(" enabled1: " + enabled1.size());
// for(LPNTran lpnTran : enabled1){
// if(lpnTran.local()){
// tranList1.add(lpnTran);
// stateList1.add((State) lpnTran.getNextState(subState));
// }
// else{
// if(synchronousTrans.contains(lpnTran)){
// boolean synch = false;
// CompositeState st = null;
// for(int i = 0; i < enabled2.size(); i++){
// if(enabled2.get(i) == lpnTran){
// synch = true;
// st = edgeList.get(i);
// break;
// }
// }
//
// if(synch){
// intersect1.add((State) lpnTran.getNextState(subState));
// intersect2.add(st);
// intersectTran.add(lpnTran);
// }
// else{
// System.out.println("ST == NULL1\n");
// }
// }
// else{
// tranList1.add(lpnTran);
// stateList1.add((State) lpnTran.getNextState(subState));
// }
// }
// }
//
//// System.out.println(" enabled2: " + enabled2.size());
// for(int i = 0; i < enabled2.size(); i++){
// LPNTran lpnTran = enabled2.get(i);
//
// if(synchronousTrans.contains(lpnTran)){
//// State st = lpnTran.constraintTranMap.get(subState);
// State st = lpnTran.getNextState(subState);
// if(st != null){
// intersectTran.add(lpnTran);
// intersect1.add(st);
// intersect2.add(edgeList.get(i));
// }
// }
// else{
// tranList2.add(lpnTran);
// stateList2.add(edgeList.get(i));
// }
// }
//
//// System.out.println(" inputTrans: " + inputTrans.size());
// for(LPNTran lpnTran : inputTrans){
//// State st = lpnTran.constraintTranMap.get(subState);
// State st = lpnTran.getNextState(subState);
// if(st != null){
// tranList1.add(lpnTran);
// stateList1.add(st);
// }
// }
//
//// int items = tranList1.size() + tranList2.size() + intersect1.size();
//// CompositeState[] nextStateArray = new CompositeState[items];
//// LPNTran[] tranArray = new LPNTran[items];
//// items--;
//
// long s2 = System.currentTimeMillis();
// // for each transition
// // create new MDD node and push onto stack
// for(int i = 0; i < tranList1.size(); i++){
// LPNTran lpnTran = tranList1.get(i);
// State nextState = stateList1.get(i);
// State[] newStateTuple = new State[size];
// newStateTuple[0] = nextState;
// for(int j = 1; j < size; j++){
// newStateTuple[j] = subCompositeTuple[j-1];
// }
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// newStateStack.push(newCompositeState);
// stateStack.push(nextState);
// compositeStateStack.push(subCompositeState);
//// newStateQueue.offer(newCompositeState);
//// stateQueue.offer(nextState);
//// compositeStateQueue.offer(subCompositeState);
//
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[items] = st;
//// tranArray[items] = lpnTran;
//// items--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
//// System.out.println(" transList2: " + tranList2.size());
// for(int i = 0; i < tranList2.size(); i++){
// LPNTran lpnTran = tranList2.get(i);
// CompositeState nextState = stateList2.get(i);
// State[] nextStateTuple = nextState.getStateTuple();
// State[] newStateTuple = new State[size];
// newStateTuple[0] = subState;
// for(int j = 1; j < size; j++){
// newStateTuple[j] = nextStateTuple[j-1];
// }
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// newStateStack.push(newCompositeState);
// stateStack.push(subState);
// compositeStateStack.push(nextState);
//// newStateQueue.offer(newCompositeState);
//// stateQueue.offer(subState);
//// compositeStateQueue.offer(nextState);
//
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[items] = st;
//// tranArray[items] = lpnTran;
//// items--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
//// System.out.println(" intersect: " + intersect1.size());
// for(int i = 0; i < intersect1.size(); i++){
// LPNTran lpnTran = intersectTran.get(i);
//
// State nextState1 = intersect1.get(i);
// CompositeState nextState2 = intersect2.get(i);
// State[] nextStateTuple = nextState2.getStateTuple();
//
// State[] newStateTuple = new State[size];
// newStateTuple[0] = nextState1;
// for(int j = 1; j < size; j++){
// newStateTuple[j] = nextStateTuple[j-1];
// }
//
// CompositeState newCompositeState = new CompositeState(newStateTuple);
// CompositeState st = compositeSG.addState(newCompositeState);
// if(st == null){
// newStateStack.push(newCompositeState);
// compositeStateStack.push(nextState2);
// stateStack.push(nextState1);
//// newStateQueue.offer(newCompositeState);
//// stateQueue.offer(nextState1);
//// compositeStateQueue.offer(nextState2);
//
// st = newCompositeState;
// }
//
// // create a new CompositeStateTran
//// CompositeStateTran newCompositeStateTran = new CompositeStateTran(currentCompositeState, st, stTran1.lpnTran);
//// if(compositeSG.addStateTran(newCompositeStateTran)){
// // add an edge between the current and new state
//// currentCompositeState.addEdge(newCompositeStateTran);
//// }
//
//// nextStateArray[items] = st;
//// tranArray[items] = lpnTran;
//// items--;
//
//// currentCompositeState.addNextState(st);
//// currentCompositeState.addTran(lpnTran);
//
// currentCompositeState.nextStateList.add(st);
// currentCompositeState.enabledTranList.add(lpnTran);
// st.incomingStateList.add(currentCompositeState);
// }
//
//// currentCompositeState.setNextStateArray(nextStateArray);
//// currentCompositeState.setTranArray(tranArray);
//
// long curTotalMem = Runtime.getRuntime().totalMemory();
// if(curTotalMem > peakTotal)
// peakTotal = curTotalMem;
//
// long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// if(curUsedMem > peakUsed)
// peakUsed = curUsedMem;
// }
//
// System.out.println("\n " + compositeSG.getLabel() + ": ");
// System.out.println(" --> # states: " + compositeSG.numCompositeStates());
//// System.out.println(" --> # transitions: " + compositeSG.numCompositeStateTrans());
//
// System.out.println(" --> Peak used memory: " + peakUsed/1000000F + " MB");
// System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
// System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
//
// long elapsedTimeMillis = System.currentTimeMillis()-start;
// float elapsedTimeSec = elapsedTimeMillis/1000F;
// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
//
// if(elapsedTimeSec > 60){
// float elapsedTime = elapsedTimeSec;
// elapsedTime = elapsedTimeSec/(float)60;
// System.out.println(" --> Elapsed time: " + elapsedTime + " min");
// }
//
// System.out.println();
//
//// System.out.println();
//// for(CompositeState cState : compositeSG.compositeStateMap){
//// State[] stateTuple = cState.getStateTuple();
//// State s1 = stateTuple[0];
//// State s2 = stateTuple[1];
////
//// System.out.println(s1.getLabel() + ", " + s2.getLabel());
//// }
//
// return compositeSG;
// }
public CompositeStateGraph compose2(CompositeStateGraph sg1, CompositeStateGraph sg2){
long start = System.currentTimeMillis();
if(sg1 == null || sg2 == null){
return null;
}
StateGraph[] stateGraphArray1 = sg1.getStateGraphArray();
StateGraph[] stateGraphArray2 = sg2.getStateGraphArray();
// check an output drives an input
boolean compatible = false;
for(StateGraph g : stateGraphArray1){
for(String output : g.getLpn().getAllOutputs().keySet()){
for(StateGraph g2 : stateGraphArray2){
VarSet inputs = (VarSet) g2.getLpn().getAllInputs().keySet();
if(inputs.contains(output)){
compatible = true;
break;
}
}
if(compatible){
break;
}
}
if(compatible){
break;
}
}
if(!compatible){
for(StateGraph g1 : stateGraphArray1){
VarSet inputs = (VarSet) g1.getLpn().getAllInputs().keySet();
for(StateGraph g2 : stateGraphArray2){
for(String output : g2.getLpn().getAllOutputs().keySet()){
if(inputs.contains(output)){
compatible = true;
break;
}
}
if(compatible){
break;
}
}
if(compatible){
break;
}
}
}
if(!compatible){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
HashSet<StateGraph> sgSet = new HashSet<StateGraph>();
for(StateGraph sg : stateGraphArray1){
if(sgSet.add(sg) == false){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
}
for(StateGraph sg : stateGraphArray2){
if(sgSet.add(sg) == false){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
}
// create new node with init states
int size = sg1.getSize() + sg2.getSize();
int sg1Size = sg1.getSize();
int[] initStates = new int[size];
for(int i = 0; i < sg1Size; i++){
initStates[i] = stateGraphArray1[i].getInitialState().getIndex();
}
for(int i = sg1Size; i < size; i++){
initStates[i] = stateGraphArray2[i-sg1Size].getInitialState().getIndex();
}
CompositeState initNode = new CompositeState(initStates);
HashSet<Integer> synchronousTrans = new HashSet<Integer>();
for(StateGraph g1 : stateGraphArray1){
LhpnFile lpn1 = g1.getLpn();
for(StateGraph g2 : stateGraphArray2){
LhpnFile lpn2 = g2.getLpn();
// TOOD: Need to use our LPN
/*
HashSet<LPNTran> inputTrans = new HashSet<LPNTran>();
inputTrans.addAll(lpn1.getInputTranSet());
inputTrans.retainAll(lpn2.getOutputTranSet());
HashSet<LPNTran> outputTrans = new HashSet<LPNTran>();
outputTrans.addAll(lpn2.getInputTranSet());
outputTrans.retainAll(lpn1.getOutputTranSet());
for(LPNTran lpnTran : inputTrans){
synchronousTrans.add(lpnTran.getIndex());
}
for(LPNTran lpnTran : outputTrans){
synchronousTrans.add(lpnTran.getIndex());
}
*/
}
}
// create new composite state graph
StateGraph[] sgArray = new StateGraph[size];
List<LhpnFile> lpnList = new ArrayList<LhpnFile>(size);
for(int i = 0; i < sg1Size; i++){
sgArray[i] = stateGraphArray1[i];
// TOOD: is this needed???
//lpnList.add(stateGraphArray1[i].getLpn());
}
for(int i = sg1Size; i < size; i++){
sgArray[i] = stateGraphArray2[i-sg1Size];
// TOOD: is this needed???
//lpnList.add(stateGraphArray2[i-sg1Size].getLpn());
}
CompositeStateGraph compositeSG = new CompositeStateGraph(initNode, sgArray);
// create CompositeState stack
Stack<CompositeState> newStateStack = new Stack<CompositeState>();
Stack<CompositeState> subStateStack1 = new Stack<CompositeState>();
Stack<CompositeState> subStateStack2 = new Stack<CompositeState>();
// initialize with initial CompositionalState
newStateStack.push(initNode);
subStateStack1.push(sg1.getInitState());
subStateStack2.push(sg2.getInitState());
List<CompositeStateTran> intersectingTrans1 = new LinkedList<CompositeStateTran>();
List<CompositeStateTran> intersectingTrans2 = new LinkedList<CompositeStateTran>();
List<CompositeStateTran> independentTrans1 = new LinkedList<CompositeStateTran>();
List<CompositeStateTran> independentTrans2 = new LinkedList<CompositeStateTran>();
long peakUsed = 0;
long peakTotal = 0;
CompositeState tempState = null;
while(!newStateStack.isEmpty()){
CompositeState currentState = newStateStack.pop();
CompositeState subState1 = subStateStack1.pop();
CompositeState subState2 = subStateStack2.pop();
int[] subState1Tuple = subState1.getStateTuple();
int[] subState2Tuple = subState2.getStateTuple();
List<CompositeStateTran> stateTrans1 = subState1.getOutgoingStateTranList();
List<CompositeStateTran> stateTrans2 = subState2.getOutgoingStateTranList();
// clear reused lists
intersectingTrans1.clear();
intersectingTrans2.clear();
independentTrans1.clear();
independentTrans2.clear();
for(CompositeStateTran stateTran : stateTrans1){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
if(!stateTran.visible()){
independentTrans1.add(stateTran);
}
else{
if(synchronousTrans.contains(lpnTran.getIndex())){
for(CompositeStateTran stateTran2 : stateTrans2){
lpn.parser.Transition lpnTran2 = stateTran2.getLPNTran();
if(lpnTran == lpnTran2){
intersectingTrans1.add(stateTran);
intersectingTrans2.add(stateTran2);
}
}
}
else{
independentTrans1.add(stateTran);
}
}
}
for(CompositeStateTran stateTran : stateTrans2){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
if(!stateTran.visible()){
independentTrans2.add(stateTran);
}
else{
if(!synchronousTrans.contains(lpnTran.getIndex())){
independentTrans2.add(stateTran);
}
}
}
for(CompositeStateTran stateTran : independentTrans1){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
CompositeState nextState = sg1.getState(stateTran.getNextState());
int[] nextStateTuple = nextState.getStateTuple();
int[] newStateTuple = new int[size];
for(int j = 0; j < sg1Size; j++){
newStateTuple[j] = nextStateTuple[j];
}
for(int j = sg1Size; j < size; j++){
newStateTuple[j] = subState2Tuple[j-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(nextState);
subStateStack2.push(subState2);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnTran.isLocal()){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
for(CompositeStateTran stateTran : independentTrans2){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
CompositeState nextState = sg2.getState(stateTran.getNextState());
int[] nextStateTuple = nextState.getStateTuple();
int[] newStateTuple = new int[size];
for(int i = 0; i < sg1Size; i++){
newStateTuple[i] = subState1Tuple[i];
}
for(int i = sg1Size; i < size; i++){
newStateTuple[i] = nextStateTuple[i-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(subState1);
subStateStack2.push(nextState);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnTran.isLocal()){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
Iterator<CompositeStateTran> iter1 = intersectingTrans1.iterator();
Iterator<CompositeStateTran> iter2 = intersectingTrans2.iterator();
while(iter1.hasNext()){
CompositeStateTran stateTran1 = iter1.next();
CompositeStateTran stateTran2 = iter2.next();
lpn.parser.Transition lpnTran = stateTran1.getLPNTran();
CompositeState nextState1 = sg1.getState(stateTran1.getNextState());
int[] nextState1Tuple = nextState1.getStateTuple();
CompositeState nextState2 = sg2.getState(stateTran2.getNextState());
int[] nextState2Tuple = nextState2.getStateTuple();
int[] newStateTuple = new int[size];
for(int i = 0; i < sg1Size; i++){
newStateTuple[i] = nextState1Tuple[i];
}
for(int i = sg1Size; i < size; i++){
newStateTuple[i] = nextState2Tuple[i-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(nextState1);
subStateStack2.push(nextState2);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnList.containsAll(lpnTran.getDstLpnList())){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
System.out.println("\n " + compositeSG.getLabel() + ": ");
System.out.println(" --> # states: " + compositeSG.numStates());
System.out.println(" --> # transitions: " + compositeSG.numStateTrans());
System.out.println(" --> Peak used memory: " + peakUsed/1000000F + " MB");
System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
if(elapsedTimeSec > 60){
float elapsedTime = elapsedTimeSec;
elapsedTime = elapsedTimeSec/(float)60;
System.out.println(" --> Elapsed time: " + elapsedTime + " min");
}
System.out.println();
return compositeSG;
}
public CompositeStateGraph compose(CompositeStateGraph sg1, CompositeStateGraph sg2){
long start = System.currentTimeMillis();
if(sg1 == null || sg2 == null){
return null;
}
StateGraph[] stateGraphArray1 = sg1.getStateGraphArray();
StateGraph[] stateGraphArray2 = sg2.getStateGraphArray();
// check an output drives an input
boolean compatible = false;
for(StateGraph g : stateGraphArray1){
for(String output : g.getLpn().getAllOutputs().keySet()){
for(StateGraph g2 : stateGraphArray2){
VarSet inputs = (VarSet) g2.getLpn().getAllInputs().keySet();
if(inputs.contains(output)){
compatible = true;
break;
}
}
if(compatible){
break;
}
}
if(compatible){
break;
}
}
if(!compatible){
for(StateGraph g1 : stateGraphArray1){
VarSet inputs = (VarSet) g1.getLpn().getAllInputs().keySet();
for(StateGraph g2 : stateGraphArray2){
for(String output : g2.getLpn().getAllOutputs().keySet()){
if(inputs.contains(output)){
compatible = true;
break;
}
}
if(compatible){
break;
}
}
if(compatible){
break;
}
}
}
if(!compatible){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
HashSet<StateGraph> sgSet = new HashSet<StateGraph>();
for(StateGraph sg : stateGraphArray1){
if(sgSet.add(sg) == false){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
}
for(StateGraph sg : stateGraphArray2){
if(sgSet.add(sg) == false){
System.out.println("state graphs " + sg1.getLabel() + " and " + sg2.getLabel() + " cannot be composed\n");
return null;
}
}
// create new node with init states
int size = sg1.getSize() + sg2.getSize();
int sg1Size = sg1.getSize();
int[] initStates = new int[size];
for(int i = 0; i < sg1Size; i++){
initStates[i] = stateGraphArray1[i].getInitialState().getIndex();
}
for(int i = sg1Size; i < size; i++){
initStates[i] = stateGraphArray2[i-sg1Size].getInitialState().getIndex();
}
CompositeState initNode = new CompositeState(initStates);
HashSet<Transition> synchronousTrans = new HashSet<Transition>();
for(StateGraph g1 : stateGraphArray1){
LhpnFile lpn1 = g1.getLpn();
for(StateGraph g2 : stateGraphArray2){
LhpnFile lpn2 = g2.getLpn();
// TOOD: need to change to use our LPN
/*
HashSet<LPNTran> inputTrans = new HashSet<LPNTran>();
inputTrans.addAll(lpn1.getInputTranSet());
inputTrans.retainAll(lpn2.getOutputTranSet());
HashSet<LPNTran> outputTrans = new HashSet<LPNTran>();
outputTrans.addAll(lpn2.getInputTranSet());
outputTrans.retainAll(lpn1.getOutputTranSet());
synchronousTrans.addAll(inputTrans);
synchronousTrans.addAll(outputTrans);
*/
}
}
// create new composite state graph
StateGraph[] sgArray = new StateGraph[size];
List<LhpnFile> lpnList = new ArrayList<LhpnFile>(size);
for(int i = 0; i < sg1Size; i++){
sgArray[i] = stateGraphArray1[i];
// TODO: (future) Is this needed??
//lpnList.add(stateGraphArray1[i].getLpn());
}
for(int i = sg1Size; i < size; i++){
sgArray[i] = stateGraphArray2[i-sg1Size];
// TODO: (future) Is this needed??
//lpnList.add(stateGraphArray2[i-sg1Size].getLpn());
}
CompositeStateGraph compositeSG = new CompositeStateGraph(initNode, sgArray);
// create CompositeState stack
Stack<CompositeState> newStateStack = new Stack<CompositeState>();
Stack<CompositeState> subStateStack1 = new Stack<CompositeState>();
Stack<CompositeState> subStateStack2 = new Stack<CompositeState>();
// initialize with initial CompositionalState
newStateStack.push(initNode);
subStateStack1.push(sg1.getInitState());
subStateStack2.push(sg2.getInitState());
List<lpn.parser.Transition> intersectingTrans = new ArrayList<lpn.parser.Transition>();
List<CompositeState> intStateList1 = new ArrayList<CompositeState>();
List<CompositeState> intStateList2 = new ArrayList<CompositeState>();
List<lpn.parser.Transition> independentTrans1 = new ArrayList<lpn.parser.Transition>();
List<CompositeState> indStateList1 = new ArrayList<CompositeState>();
List<lpn.parser.Transition> independentTrans2 = new ArrayList<lpn.parser.Transition>();
List<CompositeState> indStateList2 = new ArrayList<CompositeState>();
long peakUsed = 0;
long peakTotal = 0;
CompositeState tempState = null;
while(!newStateStack.isEmpty()){
CompositeState currentState = newStateStack.pop();
CompositeState subState1 = subStateStack1.pop();
CompositeState subState2 = subStateStack2.pop();
int[] subState1Tuple = subState1.getStateTuple();
int[] subState2Tuple = subState2.getStateTuple();
List<CompositeStateTran> stateTrans1 = subState1.getOutgoingStateTranList();
List<CompositeStateTran> stateTrans2 = subState2.getOutgoingStateTranList();
// clear reused lists
intersectingTrans.clear();
intStateList1.clear();
intStateList2.clear();
independentTrans1.clear();
indStateList1.clear();
independentTrans2.clear();
indStateList2.clear();
for(CompositeStateTran stateTran : stateTrans1){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
CompositeState nextState = sg1.getState(stateTran.getNextState());
if(!stateTran.visible()){
independentTrans1.add(lpnTran);
indStateList1.add(nextState);
}
else{
if(synchronousTrans.contains(lpnTran)){
for(CompositeStateTran stateTran2 : stateTrans2){
lpn.parser.Transition lpnTran2 = stateTran2.getLPNTran();
CompositeState nextState2 = sg2.getState(stateTran2.getNextState());
if(lpnTran == lpnTran2){
intersectingTrans.add(lpnTran);
intStateList1.add(nextState);
intStateList2.add(nextState2);
}
}
}
else{
independentTrans1.add(lpnTran);
indStateList1.add(nextState);
}
}
}
for(CompositeStateTran stateTran : stateTrans2){
lpn.parser.Transition lpnTran = stateTran.getLPNTran();
CompositeState nextState = sg2.getState(stateTran.getNextState());
if(!stateTran.visible()){
independentTrans2.add(lpnTran);
indStateList2.add(nextState);
}
else{
if(!synchronousTrans.contains(lpnTran)){
independentTrans2.add(lpnTran);
indStateList2.add(nextState);
}
}
}
for(int i = 0; i < independentTrans1.size(); i++){
lpn.parser.Transition lpnTran = independentTrans1.get(i);
CompositeState nextState = indStateList1.get(i);
int[] nextStateTuple = nextState.getStateTuple();
int[] newStateTuple = new int[size];
for(int j = 0; j < sg1Size; j++){
newStateTuple[j] = nextStateTuple[j];
}
for(int j = sg1Size; j < size; j++){
newStateTuple[j] = subState2Tuple[j-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(nextState);
subStateStack2.push(subState2);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnTran.isLocal()){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
for(int j = 0; j < independentTrans2.size(); j++){
lpn.parser.Transition lpnTran = independentTrans2.get(j);
CompositeState nextState = indStateList2.get(j);
int[] nextStateTuple = nextState.getStateTuple();
int[] newStateTuple = new int[size];
for(int i = 0; i < sg1Size; i++){
newStateTuple[i] = subState1Tuple[i];
}
for(int i = sg1Size; i < size; i++){
newStateTuple[i] = nextStateTuple[i-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(subState1);
subStateStack2.push(nextState);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnTran.isLocal()){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
for(int j = 0; j < intersectingTrans.size(); j++){
Transition lpnTran = intersectingTrans.get(j);
CompositeState nextState1 = intStateList1.get(j);
int[] nextState1Tuple = nextState1.getStateTuple();
CompositeState nextState2 = intStateList2.get(j);
int[] nextState2Tuple = nextState2.getStateTuple();
int[] newStateTuple = new int[size];
for(int i = 0; i < sg1Size; i++){
newStateTuple[i] = nextState1Tuple[i];
}
for(int i = sg1Size; i < size; i++){
newStateTuple[i] = nextState2Tuple[i-sg1Size];
}
CompositeState newCompositeState = new CompositeState(newStateTuple);
tempState = compositeSG.addState(newCompositeState);
if(tempState == newCompositeState){
newStateStack.push(newCompositeState);
subStateStack1.push(nextState1);
subStateStack2.push(nextState2);
}
else{
newCompositeState = tempState;
}
CompositeStateTran newStateTran = compositeSG.addStateTran(currentState, newCompositeState, lpnTran);
if(!lpnList.containsAll(lpnTran.getDstLpnList())){
newStateTran.setVisibility();
// System.out.println(newStateTran);
}
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
System.out.println("\n " + compositeSG.getLabel() + ": ");
System.out.println(" --> # states: " + compositeSG.numStates());
System.out.println(" --> # transitions: " + compositeSG.numStateTrans());
System.out.println(" --> Peak used memory: " + peakUsed/1000000F + " MB");
System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
if(elapsedTimeSec > 60){
float elapsedTime = elapsedTimeSec;
elapsedTime = elapsedTimeSec/(float)60;
System.out.println(" --> Elapsed time: " + elapsedTime + " min");
}
System.out.println();
return compositeSG;
}
public void compositionalAnalsysis(List<StateGraph> designUnitSet) {
// System.out.println("\n****** Compositional Analysis ******");
// long start = System.currentTimeMillis();
//
// if(Options.getParallelFlag()){
// parallelCompositionalFindSG(designUnitSet);
// }
// else{
// compositionalFindSG(designUnitSet);
// }
findReducedSG(designUnitSet);
// long totalMillis = System.currentTimeMillis()-start;
// float totalSec = totalMillis/1000F;
// System.out.println("\n***** Total Elapsed Time: " + totalSec + " sec *****");
//
// if(totalSec > 60){
// float totalTime = totalSec/(float)60;
// System.out.println("***** Total Elapsed Time: " + totalTime + " min *****");
// }
//
// System.out.println();
}
public void findReducedSG(List<StateGraph> designUnitSet) {
System.out.println("\n****** Compositional Analysis ******");
long start = System.currentTimeMillis();
StateGraph[] sgArray = (StateGraph[]) designUnitSet.toArray();
compositionalFindSG(sgArray);
List<CompositeStateGraph> sgList = new ArrayList<CompositeStateGraph>();
System.out.println();
long peakTotal = 0;
long peakUsed = 0;
int largestSG = 0;
for(StateGraph sg : designUnitSet){
CompositeStateGraph csg = new CompositeStateGraph(sg);
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
// csg.draw();
if(Options.getCompositionalMinimization().equals("reduction")){
// reduce(csg);
}
else if(Options.getCompositionalMinimization().equals("abstraction")){
System.out.println(csg.getLabel() + ": transitionBasedAbstraction");
transitionBasedAbstraction(csg);
// csg.draw();
System.out.println(csg.getLabel() + ": mergeOutgoing");
mergeOutgoing(csg);
// csg.draw();
System.out.println(csg.getLabel() + ": mergeIncoming");
mergeIncoming(csg);
System.out.println();
// csg.draw();
}
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
sgList.add(csg);
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
CompositeStateGraph csg = null;
if(sgList.size() > 0){
csg = sgList.get(0);
sgList.remove(0);
}
while(sgList.size() > 1){
CompositeStateGraph tmpSG = null;
for(CompositeStateGraph sg2 : sgList){
tmpSG = compose(csg, sg2);
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
if(tmpSG != null){
sgList.remove(sg2);
// tmpSG.draw();
System.out.println();
if(Options.getCompositionalMinimization().equals("reduction")){
// reduce(tmpSG);
}
else if(Options.getCompositionalMinimization().equals("abstraction")){
System.out.println(tmpSG.getLabel() + ": transitionBasedAbstraction");
transitionBasedAbstraction(tmpSG);
// tmpSG.draw();
System.out.println(tmpSG.getLabel() + ": mergeOutgoing");
mergeOutgoing(tmpSG);
// tmpSG.draw();
System.out.println(tmpSG.getLabel() + ": mergeIncoming");
mergeIncoming(tmpSG);
System.out.println();
// tmpSG.draw();
}
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
break;
}
}
csg = tmpSG;
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
if(sgList.size() == 1){
csg = compose(csg, sgList.get(0));
if(csg.numStates() > largestSG){
largestSG = csg.numStates();
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
// csg.draw();
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
long totalMillis = System.currentTimeMillis()-start;
float totalSec = totalMillis/1000F;
System.out.println("\n****** Total Elapsed Time: " + totalSec + " sec ******");
if(totalSec > 60){
float totalTime = totalSec/(float)60;
System.out.println("****** Total Elapsed Time: " + totalTime + " min ******");
}
System.out.println("****** Peak Memory Used: " + peakUsed/1000000F + " MB ******");
System.out.println("****** Peak Memory Total: " + peakTotal/1000000F + " MB ******");
System.out.println("****** Lastest SG: " + largestSG + " states ******");
System.out.println();
}
// public void reduce(CompositeStateGraph sg){
// long startTime = System.currentTimeMillis();
// int initNumTrans = sg.numTransitions;
// int initNumStates = sg.compositeStateMap.size();
// int totalReducedTrans = sg.numTransitions;
//
// int case2StateMin = 0;
// int case3StateMin = 0;
// int case2TranMin = 0;
// int case3TranMin = 0;
//
// int iter = 0;
// while(totalReducedTrans > 0){
// totalReducedTrans = 0;
//
// int numStates = sg.compositeStateMap.size();
// int numTrans = sg.numTransitions;
// int tranDiff = 0;
//
// case2(sg);
//
// case2TranMin += numTrans - sg.numTransitions;
// tranDiff = numStates - sg.compositeStateMap.size();
// case2StateMin += tranDiff;
// totalReducedTrans += tranDiff;
//
// numTrans = sg.numTransitions;
// numStates = sg.compositeStateMap.size();
//
// case3(sg);
//
// case3TranMin += numTrans - sg.numTransitions;
// tranDiff = numStates - sg.compositeStateMap.size();
// case3StateMin += tranDiff;
// totalReducedTrans += tranDiff;
//
// iter++;
// }
//
// System.out.println(" Reduce " + sg.getLabel() + ": ");
// System.out.println(" --> case2: -" + case2StateMin + " states");
// System.out.println(" --> case2: -" + case2TranMin + " transitions");
// System.out.println(" --> case3: -" + case3StateMin + " states");
// System.out.println(" --> case3: -" + case3TranMin + " transitions");
// System.out.println(" --> # states: " + sg.compositeStateMap.size());
// System.out.println(" --> # transitions: " + sg.numTransitions);
// System.out.println(" --> # iterations: " + iter);
// long elapsedTimeMillis = System.currentTimeMillis()-startTime;
// float elapsedTimeSec = elapsedTimeMillis/1000F;
// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec\n");
// }
public void transitionBasedAbstraction(CompositeStateGraph sg){
HashSet<Integer> stateSet = new HashSet<Integer>();
HashSet<CompositeStateTran> tranSet = new HashSet<CompositeStateTran>();
CompositeState initialState = sg.getInitState();
Stack<CompositeStateTran> stateTranStack = new Stack<CompositeStateTran>();
HashSet<Integer> loopSet = new HashSet<Integer>(); // set used to detect loops
HashSet<Integer> traversalSet = new HashSet<Integer>(); // set used to avoid duplicate work
// int count = 0;
for(CompositeStateTran nonlocalStateTran : sg.getStateTranSet()){
// count++;
// System.out.println(count + "/" + sg.getStateTranSet().size());
// if(!sg.containsStateTran(nonlocalStateTran)) continue;
lpn.parser.Transition lpnTran = nonlocalStateTran.getLPNTran();
if(!nonlocalStateTran.visible()){
continue;
}
else if(nonlocalStateTran.getNextState() == sg.getInitState().getIndex()){
// add current state transition
tranSet.add(nonlocalStateTran);
stateSet.add(nonlocalStateTran.getCurrentState());
stateSet.add(nonlocalStateTran.getNextState());
continue;
}
// state transition stack for dfs traversal
stateTranStack.clear();
// set used to detect loops
loopSet.clear();
loopSet.add(nonlocalStateTran.getNextState());
// set used to avoid duplicate work
traversalSet.clear();
traversalSet.add(nonlocalStateTran.getNextState());
boolean flag = false;
CompositeState nextState = sg.getState(nonlocalStateTran.getNextState());
for(CompositeStateTran outgoingTran : nextState.getOutgoingStateTranList()){
if(!outgoingTran.visible()){
stateTranStack.push(outgoingTran);
loopSet.add(outgoingTran.getNextState());
// traversalSet.add(outgoingTran.getNextState());
}
else{
flag = true;
}
}
// keep nonlocal state transition if a visible successor state transition exists
if(flag){
tranSet.add(nonlocalStateTran);
stateSet.add(nonlocalStateTran.getCurrentState());
stateSet.add(nonlocalStateTran.getNextState());
}
// System.out.println(nonlocalStateTran);
while(!stateTranStack.empty()){
CompositeStateTran currentStateTran = stateTranStack.pop();
CompositeState currentNextState = sg.getState(currentStateTran.getNextState());
// // if state has already been encountered skip
if(!traversalSet.add(currentStateTran.getNextState())){
// System.out.println(" " + currentStateTran);
// System.out.println("skip");
continue;
}
if(currentNextState == initialState){
CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getCurrentState(),
currentStateTran.getNextState(), lpnTran);
System.out.println(newStateTran.getCurrentState() + " -> " + newStateTran.getNextState());
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(newStateTran.getCurrentState());
stateSet.add(newStateTran.getCurrentState());
continue;
}
// if the state transition does not have successor transitions create a state transition to last state in path
if(currentNextState.numOutgoingTrans() == 0){
CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getCurrentState(),
currentStateTran.getNextState(), lpnTran);
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(newStateTran.getCurrentState());
stateSet.add(newStateTran.getNextState());
}
// add local outgoing state trans to stack
// for each nonlocal state tran create a state transition from nonlocalStateTran.currentState to stateTran.currentState
for(CompositeStateTran stateTran : currentNextState.getOutgoingStateTranList()){
if(stateTran.visible()){
CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getCurrentState(),
stateTran.getCurrentState(), lpnTran);
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(nonlocalStateTran.getCurrentState());
stateSet.add(stateTran.getCurrentState());
}
else{
// if(!loopSet.add(stateTran.getNextState())){
// // create self loop after visible state transition
// if(flag){
// CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getNextState(),
// nonlocalStateTran.getNextState(), currentStateTran.getLPNTran());
//
// tranSet.add(newStateTran);
// }
// else{
// tranSet.add(nonlocalStateTran);
// stateSet.add(nonlocalStateTran.getCurrentState());
// stateSet.add(nonlocalStateTran.getNextState());
// flag = true;
//
// CompositeStateTran newStateTran = new CompositeStateTran(nonlocalStateTran.getNextState(),
// nonlocalStateTran.getNextState(), currentStateTran.getLPNTran());
//
// tranSet.add(newStateTran);
// }
//
//// traversalSet.add(stateTran.getNextState());
// continue;
// }
// else if(!traversalSet.add(stateTran.getNextState())){
// continue;
// }
stateTranStack.push(stateTran);
}
}
loopSet.remove(currentNextState.getIndex());
}
}
System.out.println(stateSet.size());
System.out.println(tranSet.size());
// System.out.println("INITIAL STATE");
// handle initial state
loopSet.clear();
loopSet.add(initialState.getIndex());
traversalSet.clear();
traversalSet.add(initialState.getIndex());
for(CompositeStateTran stateTran : initialState.getOutgoingStateTranList()){
if(!stateTran.visible()){
stateTranStack.push(stateTran);
loopSet.add(stateTran.getNextState());
// traversalSet.add(stateTran.getNextState());
}
}
stateSet.add(initialState.getIndex());
while(!stateTranStack.empty()){
CompositeStateTran stateTran = stateTranStack.pop();
// // if state has already been encountered skip
if(!traversalSet.add(stateTran.getNextState())){
continue;
}
CompositeState nextState = sg.getState(stateTran.getNextState());
// if the state transition does not have successor transitions create a state transition to last state in path
if(nextState.numOutgoingTrans() == 0){
CompositeStateTran newStateTran = new CompositeStateTran(initialState, sg.getState(stateTran.getNextState()),
stateTran.getLPNTran());
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(stateTran.getNextState());
}
for(CompositeStateTran succStateTran : nextState.getOutgoingStateTranList()){
lpn.parser.Transition lpnTran = succStateTran.getLPNTran();
if(succStateTran.visible()){
// create a state tran from initial state to succStateTran.currentState
CompositeStateTran newStateTran = new CompositeStateTran(initialState, sg.getState(succStateTran.getNextState()), lpnTran);
newStateTran.setVisibility();
tranSet.add(newStateTran);
stateSet.add(succStateTran.getNextState());
}
else{
// if(!loopSet.add(succStateTran.getNextState())){
// CompositeStateTran newStateTran = new CompositeStateTran(initialState, initialState, lpnTran);
// tranSet.add(newStateTran);
//
//// traversalSet.add(succStateTran.getNextState());
// continue;
// }
// else if(!traversalSet.add(succStateTran.getNextState())){
// continue;
// }
// add to stack
stateTranStack.push(succStateTran);
}
}
loopSet.remove(stateTran.getNextState());
}
// System.out.println();
// for(CompositeStateTran stateTran : tranSet){
// System.out.println(stateTran);
// }
// System.out.println();
//
// System.out.println();
// for(Integer state : stateSet){
// System.out.println(state);
// }
// System.out.println();
// System.out.println("COMPOSITE STATE SET");
HashMap<CompositeState, CompositeState> stateMap = new HashMap<CompositeState, CompositeState>();
HashMap<Integer, CompositeState> indexStateMap = new HashMap<Integer, CompositeState>();
for(Integer stateIndex : stateSet){
CompositeState currentState = sg.getState(stateIndex);
currentState.clear();
stateMap.put(currentState, currentState);
indexStateMap.put(stateIndex, currentState);
}
sg.indexStateMap = indexStateMap;
sg.stateMap = stateMap;
sg.stateTranMap = new HashMap<CompositeStateTran, CompositeStateTran>();
for(CompositeStateTran stateTran : tranSet){
sg.addStateTran(stateTran);
}
System.out.println(" --> # states: " + stateSet.size());
System.out.println(" --> # transitions: " + tranSet.size());
}
private void removeUnreachableState(CompositeStateGraph sg, CompositeState currentState){
if(currentState == sg.getInitState()){
return;
}
else if(currentState.numIncomingTrans() != 0){
return;
}
boolean rc = sg.containsState(currentState.getIndex());
if(rc == false){
return;
}
for(CompositeStateTran stateTran : currentState.getOutgoingStateTranList().toArray(new CompositeStateTran[currentState.numOutgoingTrans()])){
sg.removeStateTran(stateTran);
CompositeState nextState = sg.getState(stateTran.getNextState());
if(nextState.numIncomingTrans() == 0){
removeUnreachableState(sg, nextState);
}
}
sg.removeState(currentState);
}
private void removeDanglingState(CompositeStateGraph sg, CompositeState currentState){
if(currentState == sg.getInitState()){
return;
}
else if(currentState.numOutgoingTrans() != 0){
return;
}
boolean rc = sg.containsState(currentState.getIndex());
if(rc == false){
return;
}
for(CompositeStateTran stateTran : currentState.getIncomingStateTranList().toArray(new CompositeStateTran[currentState.numIncomingTrans()])){
sg.removeStateTran(stateTran);
CompositeState previousState = sg.getState(stateTran.getCurrentState());
if(previousState.numOutgoingTrans() == 0){
removeDanglingState(sg, previousState);
}
}
sg.removeState(currentState);
}
public void redundantStateRemoval(CompositeStateGraph sg){
this.mergeOutgoing(sg);
this.mergeIncoming(sg);
}
public void mergeOutgoing(CompositeStateGraph sg){
// System.out.println("FIND EQUIVALENT PAIRS");
HashSet<Pair<Integer, Integer>> equivalentPairSet = findInitialEquivalentPairs(sg);
// System.out.println("REMOVE STATES");
// remove states that are not equivalent
for(Pair<Integer, Integer> eqPair : equivalentPairSet.toArray(new Pair[equivalentPairSet.size()])){
CompositeState state1 = sg.getState(eqPair.getLeft());
CompositeState state2 = sg.getState(eqPair.getRight());
List<CompositeStateTran> stateTranList1 = state1.getOutgoingStateTranList();
List<CompositeStateTran> stateTranList2 = state2.getOutgoingStateTranList();
boolean eq = true;
for(CompositeStateTran stateTran1 : stateTranList1){
boolean succEq = false;
for(CompositeStateTran stateTran2 : stateTranList2){
int nextState1 = stateTran1.getNextState();
int nextState2 = stateTran2.getNextState();
if(nextState1 == nextState2){
succEq = true;
continue;
}
if(nextState2 < nextState1){
int tmp = nextState2;
nextState2 = nextState1;
nextState1 = tmp;
}
Pair<Integer, Integer> statePair = new Pair<Integer, Integer>(nextState1, nextState2);
if(equivalentPairSet.contains(statePair)){
succEq = true;
continue;
}
}
if(!succEq){
eq = false;
break;
}
}
if(!eq){
equivalentPairSet.remove(eqPair);
}
}
for(Pair<Integer, Integer> statePair : equivalentPairSet){
int stateIndex1 = statePair.getLeft();
int stateIndex2 = statePair.getRight();
if(!sg.containsState(stateIndex1) || !sg.containsState(stateIndex2))
continue;
System.out.println(stateIndex1 + " - " + stateIndex2);
CompositeState state2 = sg.getState(stateIndex2);
// merge
for(CompositeStateTran incomingStateTran : state2.getIncomingStateTranList().toArray(new CompositeStateTran[state2.numIncomingTrans()])){
sg.removeStateTran(incomingStateTran);
incomingStateTran.setNextState(stateIndex1);
sg.addStateTran(incomingStateTran);
}
this.removeUnreachableState(sg, state2);
}
System.out.println(" --> # states: " + sg.numStates());
System.out.println(" --> # transitions: " + sg.numStateTrans());
}
public void mergeIncoming(CompositeStateGraph sg){
HashSet<Pair<Integer, Integer>> equivalentPairSet = findInitialEquivalentPairs2(sg);
for(Pair<Integer, Integer> statePair : equivalentPairSet){
int stateIndex1 = statePair.getLeft();
int stateIndex2 = statePair.getRight();
System.out.println(stateIndex1 + " - " + stateIndex2);
if(!sg.containsState(stateIndex1) || !sg.containsState(stateIndex2))
continue;
CompositeState state2 = sg.getState(stateIndex2);
// merge outgoing state transitions
for(CompositeStateTran outgoingStateTran : state2.getOutgoingStateTranList().toArray(new CompositeStateTran[state2.numOutgoingTrans()])){
sg.removeStateTran(outgoingStateTran);
outgoingStateTran.setCurrentState(stateIndex1);
sg.addStateTran(outgoingStateTran);
}
this.removeDanglingState(sg, state2);
}
System.out.println(" --> # states: " + sg.numStates());
System.out.println(" --> # transitions: " + sg.numStateTrans());
}
private HashSet<Pair<Integer, Integer>> findInitialEquivalentPairs(CompositeStateGraph sg){
HashSet<Pair<Integer, Integer>> equivalentSet = new HashSet<Pair<Integer, Integer>>();
CompositeState[] stateArray = sg.getStateSet().toArray(new CompositeState[sg.numStates()]);
for(int i = 0; i < stateArray.length; i++){
// System.out.println(" " + i + "/" + stateArray.length);
CompositeState state1 = stateArray[i];
List<Transition> enabled1 = sg.getEnabled(state1);
// HashSet<LPNTran> enabled1Set = new HashSet<LPNTran>();
// enabled1Set.addAll(enabled1);
for(int j = i + 1; j < stateArray.length; j++){
// System.out.println(" " + j + "/" + stateArray.length);
CompositeState state2 = stateArray[j];
CompositeState state = state1;
List<Transition> enabled2 = sg.getEnabled(state2);
if(enabled1.containsAll(enabled2) && enabled2.containsAll(enabled1)){
if(state2.getIndex() < state.getIndex()){
CompositeState temp = state;
state = state2;
state2 = temp;
}
equivalentSet.add(new Pair<Integer, Integer>(state.getIndex(), state2.getIndex()));
}
}
}
return equivalentSet;
}
private boolean equivalentOutgoing(Set<Transition> enabled1, List<Transition> enabled2){
// enabled2.containsAll(enabled1) && enabled1.containsAll(enabled2)
HashSet<Transition> enabled2Set = new HashSet<Transition>();
enabled2Set.addAll(enabled2);
if(enabled2Set.size() == enabled1.size() && enabled1.containsAll(enabled2Set))
return true;
return false;
}
private HashSet<Pair<Integer, Integer>> findInitialEquivalentPairs2(CompositeStateGraph sg){
HashSet<Pair<Integer, Integer>> equivalentSet = new HashSet<Pair<Integer, Integer>>();
CompositeState[] stateArray = sg.getStateSet().toArray(new CompositeState[sg.numStates()]);
for(int i = 0; i < stateArray.length; i++){
CompositeState state1 = stateArray[i];
List<Transition> enabled1 = this.getIncomingLpnTrans(state1);
for(int j = i + 1; j < stateArray.length; j++){
CompositeState state2 = stateArray[j];
CompositeState state = state1;
List<Transition> enabled2 = this.getIncomingLpnTrans(state2);
if(enabled2.containsAll(enabled1) && enabled1.containsAll(enabled2)){
if(state2.getIndex() < state.getIndex()){
CompositeState temp = state;
state = state2;
state2 = temp;
}
equivalentSet.add(new Pair<Integer, Integer>(state.getIndex(), state2.getIndex()));
}
}
}
return equivalentSet;
}
private List<Transition> getIncomingLpnTrans(CompositeState currentState){
Set<Transition> lpnTranSet = new HashSet<Transition>(currentState.numOutgoingTrans());
List<Transition> enabled = new ArrayList<Transition>(currentState.numOutgoingTrans());
for(CompositeStateTran stTran : currentState.getIncomingStateTranList()){
Transition lpnTran = stTran.getLPNTran();
if(lpnTranSet.add(lpnTran))
enabled.add(lpnTran);
}
return enabled;
}
// public void case2(CompositeStateGraph sg){
// long start = System.currentTimeMillis();
// int trans = sg.numTransitions;
// int states = sg.numCompositeStates();
//
// List<LPNTran> localTrans = new ArrayList<LPNTran>();
// List<CompositeState> localStates = new ArrayList<CompositeState>();
// List<LPNTran> nonLocalTrans = new ArrayList<LPNTran>();
// List<CompositeState> nonLocalStates = new ArrayList<CompositeState>();
//
// for(Object o : sg.getStateMap().values().toArray()){
// CompositeState currentState = (CompositeState) o;
//
// List<LPNTran> enabledTrans = currentState.enabledTranList;
// List<CompositeState> nextStates = currentState.nextStateList;
//
// localTrans.clear();
// localStates.clear();
// nonLocalTrans.clear();
// nonLocalStates.clear();
//
// for(int i = 0; i < enabledTrans.size(); i++){
// LPNTran lpnTran = enabledTrans.get(i);
// CompositeState nextState = (nextStates.get(i));
// if(lpnTran.local()){
// localTrans.add(lpnTran);
// localStates.add(nextState);
// }
//// else{
// nonLocalTrans.add(lpnTran);
// nonLocalStates.add(nextState);
//// }
// }
//
// if(nonLocalTrans.isEmpty()){
// continue;
// }
//
// for(int i = 0; i < nonLocalTrans.size(); i++){
// LPNTran nonLocalTran = nonLocalTrans.get(i);
// CompositeState s2 = nonLocalStates.get(i);
//
// List<LPNTran> s2Enabled = s2.enabledTranList;
// if(s2Enabled.size() > 1 || s2Enabled.size() < 1){
// continue;
// }
//// else if(s2 == sg.getInitState()){
//// continue;
//// }
//
// List<CompositeState> s2NextState = s2.nextStateList;
// for(int j = 0; j < s2Enabled.size(); j++){
// LPNTran invTran2 = s2Enabled.get(j);
// if(invTran2.local()){
// CompositeState s4 = s2NextState.get(j);
//
// for(int k = 0; k < localTrans.size(); k++){
// LPNTran invTran = localTrans.get(k);
// if(invTran == nonLocalTran) continue;
//
// CompositeState s3 = localStates.get(k);
//
// List<LPNTran> s3Enabled = s3.enabledTranList;
// List<CompositeState> s3NextState = s3.nextStateList;
// for(int n = 0; n < s3Enabled.size(); n++){
// LPNTran nonLocalTran2 = s3Enabled.get(n);
// CompositeState nextState = s3NextState.get(n);
//
// if(nonLocalTran2 == nonLocalTran && nextState == s4){
// currentState.enabledTranList.remove(nonLocalTran);
// currentState.nextStateList.remove(s2);
// sg.numTransitions --;
//
// List<CompositeState> incomingStates = s2.incomingStateList;
// for(int m = 0; m < incomingStates.size(); m++){
// CompositeState curr = incomingStates.get(m);
// List<CompositeState> incomingNextStateList = curr.nextStateList;
//
// for(int idx = 0; idx < incomingNextStateList.size(); idx++){
// CompositeState tmpState = incomingNextStateList.get(idx);
// if(tmpState == s2){
// incomingNextStateList.set(idx, s4);
// s4.incomingStateList.add(curr);
// break;
// }
// }
// }
//
// s2.nextStateList.clear();
// s2.incomingStateList.clear();
// s2.enabledTranList.clear();
//
// sg.compositeStateMap.remove(s2);
// if(sg.getInitState() == s2){
// sg.setInitState(s4);
// }
// sg.numTransitions --;
// }
// }
// }
// }
// }
// }
// }
//
//// System.out.println(sg.getLabel() + " case2 transitions: " + trans + " - " + sg.numTransitions);
//// System.out.println(sg.getLabel() + " case2 states: " + states + " - " + sg.numCompositeStates());
//// long elapsedTimeMillis = System.currentTimeMillis()-start;
//// float elapsedTimeSec = elapsedTimeMillis/1000F;
//// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
// }
//
// public void case3(CompositeStateGraph sg){
// long start = System.currentTimeMillis();
// int trans = sg.numTransitions;
// int states = sg.numCompositeStates();
//
// List<LPNTran> localTrans = new ArrayList<LPNTran>();
// List<CompositeState> localStates = new ArrayList<CompositeState>();
// List<LPNTran> nonLocalTrans = new ArrayList<LPNTran>();
// List<CompositeState> nonLocalStates = new ArrayList<CompositeState>();
//
// for(Object o : sg.getStateMap().values().toArray()){
// CompositeState currentState = (CompositeState) o;
//
// List<LPNTran> enabledTrans = currentState.enabledTranList;
// List<CompositeState> nextStates = currentState.nextStateList;
//
// localTrans.clear();
// localStates.clear();
// nonLocalTrans.clear();
// nonLocalStates.clear();
//
// for(int i = 0; i < enabledTrans.size(); i++){
// LPNTran lpnTran = enabledTrans.get(i);
// CompositeState nextState = (nextStates.get(i));
// if(lpnTran.local()){
// localTrans.add(lpnTran);
// localStates.add(nextState);
// }
//// else{
// nonLocalTrans.add(lpnTran);
// nonLocalStates.add(nextState);
//// }
// }
//
// if(nonLocalTrans.isEmpty()){
// continue;
// }
//
// for(int i = 0; i < localTrans.size(); i++){
// LPNTran localTran = localTrans.get(i);
// CompositeState s3 = localStates.get(i);
// if(s3.incomingStateList.size() != 1){
// continue;
// }
//// else if(s3 == sg.getInitState()){
//// continue;
//// }
//
// List<LPNTran> s3Enabled = s3.enabledTranList;
// List<CompositeState> s3NextState = s3.nextStateList;
//
// boolean remove = false;
// List<LPNTran> removeTran = new ArrayList<LPNTran>();
//
// for(int j = 0; j < s3Enabled.size(); j++){
// LPNTran nonLocalTran2 = s3Enabled.get(j);
// if(!nonLocalTran2.local()){
// CompositeState s4 = s3NextState.get(j);
//
// for(int k = 0; k < nonLocalTrans.size(); k++){
// LPNTran nonLocalTran = nonLocalTrans.get(k);
// if(localTran == nonLocalTran) continue;
//
// CompositeState s2 = nonLocalStates.get(k);
//
// List<LPNTran> s2Enabled = s2.enabledTranList;
// List<CompositeState> s2NextState = s2.nextStateList;
// for(int n = 0; n < s2Enabled.size(); n++){
// LPNTran invTran2 = s2Enabled.get(n);
// if(invTran2.local()){
// CompositeState nextState = s2NextState.get(n);
//
// if(nonLocalTran2 == nonLocalTran && nextState == s4){
// removeTran.add(nonLocalTran2);
// remove = true;
// }
// }
// }
// }
// }
// }
//
// if(remove){
// currentState.enabledTranList.remove(localTran);
// currentState.nextStateList.remove(s3);
// sg.numTransitions--;
//
// for(int m = 0; m < s3Enabled.size(); m++){
// CompositeState currState = s3NextState.get(m);
// LPNTran currTran = s3Enabled.get(m);
//
// if(removeTran.contains(currTran)){
// removeTran.remove(currTran);
// sg.numTransitions--;
// continue;
// }
//
// currentState.enabledTranList.add(currTran);
// currentState.nextStateList.add(currState);
//
// List<CompositeState> currIncomingList = currState.incomingStateList;
// for(int idx = 0; idx < currIncomingList.size(); idx++){
// if(currIncomingList.get(idx) == s3){
// currIncomingList.set(idx, currState);
// }
// }
// }
//
// sg.compositeStateMap.remove(s3);
// if(sg.getInitState() == s3){
// sg.setInitState(currentState);
// }
//
// s3.nextStateList.clear();
// s3.enabledTranList.clear();
// s3.incomingStateList.clear();
// }
// }
// }
//
//// System.out.println(sg.getLabel() + " case3 transitions: " + trans + " - " + sg.numTransitions);
//// System.out.println(sg.getLabel() + " case3 states: " + states + " - " + sg.numCompositeStates());
//// long elapsedTimeMillis = System.currentTimeMillis()-start;
//// float elapsedTimeSec = elapsedTimeMillis/1000F;
//// System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
// }
/**
* Constructs the compositional state graphs.
*/
public void compositionalFindSG(StateGraph[] sgArray){
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// try {
// br.readLine();
// } catch (IOException e) {
// e.printStackTrace();
// }
int iter = 0;
int newTransitions = 0;
long start = System.currentTimeMillis();
HashMap<StateGraph, List<StateGraph>> inputSrcMap = new HashMap<StateGraph, List<StateGraph>>();
for (StateGraph sg : sgArray) {
LhpnFile lpn = sg.getLpn();
// Add initial state to state graph
State init = sg.genInitialState();
sg.setInitialState(init);
sg.addState(init);
sg.addFrontierState(init);
Set<String> inputSet = lpn.getAllInputs().keySet();
Set<String> outputSet = lpn.getAllOutputs().keySet();
int numSrc = 0;
// Find lpn interfaces
for(StateGraph sg2 : sgArray){
if(sg == sg2)
continue;
LhpnFile lpn2 = sg2.getLpn();
Set<String> outputs = lpn2.getAllOutputs().keySet();
for(String output : outputs){
if (inputSet.contains(output)){
numSrc++;
break;
}
}
for(String output : outputs){
if (outputSet.contains(output)){
numSrc++;
break;
}
}
}
List<int[]> thisInterfaceList = new ArrayList<int[]>(sgArray.length);
List<int[]> otherInterfaceList = new ArrayList<int[]>(sgArray.length);
// TODO: Why designUnitSet.size() + 1 ?
// for(int i = 0; i < designUnitSet.size() + 1; i++){
for(int i = 0; i < sgArray.length; i++){
thisInterfaceList.add(null);
otherInterfaceList.add(null);
}
List<StateGraph> srcArray = new ArrayList<StateGraph>(numSrc);
if(numSrc > 0){
// int index = 0;
for(StateGraph sg2 : sgArray){
if(sg == sg2)
continue;
LhpnFile lpn2 = sg2.getLpn();
int interfaceSize = 0;
Set<String> outputs = lpn2.getAllOutputs().keySet();
Set<String> inputs = lpn2.getAllInputs().keySet();
for(String output : outputs){
if (inputSet.contains(output)){
interfaceSize++;
}
}
for(String input : inputs){
if(outputSet.contains(input)){
interfaceSize++;
}
}
for(String output : outputs){
if (outputSet.contains(output)){
interfaceSize++;
}
}
for(String input : inputs){
if (inputSet.contains(input)){
interfaceSize++;
}
}
if(interfaceSize > 0){
int[] thisIndexList = new int[interfaceSize];
int[] otherIndexList = new int[interfaceSize];
lpn.genIndexLists(thisIndexList, otherIndexList, lpn2);
thisInterfaceList.set(lpn2.getLpnIndex(), thisIndexList);
otherInterfaceList.set(lpn2.getLpnIndex(), otherIndexList);
// Hao's LPN starting index is 1, whereas ours starts from 0.
// thisInterfaceList.set(lpn2.ID-1, thisIndexList);
// otherInterfaceList.set(lpn2.ID-1, otherIndexList);
srcArray.add(sg2);
// index++;
}
}
}
lpn.setThisIndexList(thisInterfaceList);
lpn.setOtherIndexList(otherInterfaceList);
inputSrcMap.put(sg, srcArray);
}
// TODO: (temp) designUnitSet has been created already at this point.
// LhpnFile[] lpnList = new LhpnFile[designUnitSet.size()];
// int idx = 0;
// for (StateGraph sg : designUnitSet) {
// lpnList[idx++] = sg.getLpn();
// }
constructDstLpnList(sgArray);
// Run initial findSG
for (StateGraph sg : sgArray) {
int result = 0;
if(Options.getStickySemantics()){
// result = sg.constrStickyFindSG(sg.getInitialState(), emptyTranList);
}
else{
result = sg.constrFindSG(sg.getInitialState());
}
newTransitions += result;
}
long peakUsed = 0;
long peakTotal = 0;
List<Constraint> newConstraintSet = new ArrayList<Constraint>();
List<Constraint> oldConstraintSet = new ArrayList<Constraint>();
while(newTransitions > 0){
iter++;
newTransitions = 0;
for(StateGraph sg : sgArray){
sg.genConstraints();
sg.genFrontier();
}
// Extract and apply constraints generated from srcSG to sg.
for(StateGraph sg : sgArray){
for(StateGraph srcSG : inputSrcMap.get(sg)){
extractConstraints(sg, srcSG, newConstraintSet, oldConstraintSet);
newTransitions += applyConstraintSet(sg, srcSG, newConstraintSet, oldConstraintSet);
}
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
System.out.println();
int numStates = 0;
int numTrans = 0;
int numConstr = 0;
for (StateGraph sg : sgArray) {
sg.genConstraints();
sg.genFrontier();
System.out.print(" ");
sg.printStates();
// sg.clear();
numStates += sg.reachSize();
// numTrans += sg.numTransitions();
numConstr += sg.numConstraints();
}
System.out.println("\n --> # states: " + numStates);
System.out.println(" --> # transitions: " + numTrans);
System.out.println(" --> # constraints: " + numConstr);
System.out.println(" --> # iterations: " + iter);
System.out.println("\n --> Peak used memory: " + peakUsed/1000000F + " MB");
System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
if(elapsedTimeSec > 60){
float elapsedTime = elapsedTimeSec/(float)60;
System.out.println(" --> Elapsed time: " + elapsedTime + " min");
}
}
/**
* Constructs the compositional state graphs.
*/
public void parallelCompositionalFindSG(List<StateGraph> designUnitSet){
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// try {
// br.readLine();
// } catch (IOException e) {
// e.printStackTrace();
// }
int iter = 0;
int newTransitions = 0;
long start = System.currentTimeMillis();
HashMap<StateGraph, StateGraph[]> inputSrcMap = new HashMap<StateGraph, StateGraph[]>();
for (StateGraph sg : designUnitSet) {
LhpnFile lpn = sg.getLpn();
// Add initial state to state graph
State init = sg.genInitialState();
sg.setInitialState(init);
sg.addState(init);
sg.addFrontierState(init);
Set<String> inputSet = lpn.getAllInputs().keySet();
Set<String> outputSet = lpn.getAllOutputs().keySet();
int size = 0;
// Find lpn interfaces
for(StateGraph sg2 : designUnitSet){
if(sg == sg2) continue;
Set<String> outputs = sg2.getLpn().getAllOutputs().keySet();
for(String output : outputs){
if (inputSet.contains(output)){
size++;
break;
}
}
}
List<int[]> thisInterfaceList = new ArrayList<int[]>(designUnitSet.size() + 1);
List<int[]> otherInterfaceList = new ArrayList<int[]>(designUnitSet.size() + 1);
for(int i = 0; i < designUnitSet.size() + 1; i++){
thisInterfaceList.add(null);
otherInterfaceList.add(null);
}
StateGraph[] srcArray = new StateGraph[size];
if(size > 0){
int index = 0;
for(StateGraph sg2 : designUnitSet){
LhpnFile lpn2 = sg2.getLpn();
if(sg == sg2) continue;
boolean src = false;
int interfaceSize = 0;
Set<String> outputs = lpn2.getAllOutputs().keySet();
for(String output : outputs){
if (inputSet.contains(output)){
interfaceSize++;
src = true;
}
}
if(src){
Set<String> inputs = lpn2.getAllInputs().keySet();
for(String input : inputs){
if (outputSet.contains(input)){
interfaceSize++;
}
}
for(String input : inputs){
if (inputSet.contains(input)){
interfaceSize++;
}
}
for(String output : outputs){
if (outputSet.contains(output)){
interfaceSize++;
}
}
int[] thisIndexList = new int[interfaceSize];
int[] otherIndexList = new int[interfaceSize];
// TODO: (future) need to add getThisIndexArray in LhpnFile
/*
lpn.genIndexLists(thisIndexList, otherIndexList, lpn2);
thisInterfaceList.set(lpn2.ID, thisIndexList);
otherInterfaceList.set(lpn2.ID, otherIndexList);
*/
srcArray[index] = sg2;
index++;
}
}
}
lpn.setThisIndexList(thisInterfaceList);
lpn.setOtherIndexList(otherInterfaceList);
inputSrcMap.put(sg, srcArray);
}
LhpnFile[] lpnList = new LhpnFile[designUnitSet.size()];
int idx = 0;
for (StateGraph sg : designUnitSet) {
lpnList[idx] = sg.getLpn();
idx++;
}
// Run initial findSG
for (StateGraph sg : designUnitSet) {
int result = sg.constrFindSG(sg.getInitialState());
newTransitions += result;
}
long peakUsed = 0;
long peakTotal = 0;
CompositionalThread[] threadArray = new CompositionalThread[designUnitSet.size()];
while(newTransitions > 0){
iter++;
newTransitions = 0;
for(StateGraph sg : designUnitSet){
sg.genConstraints();
sg.genFrontier();
}
int t = 0;
for(StateGraph sg : designUnitSet){
CompositionalThread newThread = new CompositionalThread(sg, inputSrcMap.get(sg), iter);
newThread.start();
threadArray[t++] = newThread;
}
for(CompositionalThread p : threadArray){
try {
p.join();
newTransitions += p.getNewTransitions();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long curTotalMem = Runtime.getRuntime().totalMemory();
if(curTotalMem > peakTotal)
peakTotal = curTotalMem;
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if(curUsedMem > peakUsed)
peakUsed = curUsedMem;
}
System.out.println();
int numStates = 0;
int numTrans = 0;
int numConstr = 0;
for (StateGraph sg : designUnitSet) {
System.out.print(" ");
sg.printStates();
numStates += sg.reachSize();
//numTrans += sg.numTransitions();
numConstr += sg.numConstraints();
}
System.out.println("\n --> # states: " + numStates);
System.out.println(" --> # transitions: " + numTrans);
System.out.println(" --> # constraints: " + numConstr);
System.out.println(" --> # iterations: " + iter);
System.out.println("\n --> Peak used memory: " + peakUsed/1000000F + " MB");
System.out.println(" --> Peak total memory: " + peakTotal/1000000F + " MB");
System.out.println(" --> Final used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1000000F + " MB");
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(" --> Elapsed time: " + elapsedTimeSec + " sec");
if(elapsedTimeSec > 60){
float elapsedTime = elapsedTimeSec/(float)60;
System.out.println(" --> Elapsed time: " + elapsedTime + " min");
}
}
/**
* Applies new constraints to the entire state set, and applies old constraints to the frontier state set.
* @return Number of new transitions.
*/
private int applyConstraintSet(StateGraph sg, StateGraph srcSG, List<Constraint> newConstraintSet, List<Constraint> oldConstraintSet){
int newTransitions = 0;
LhpnFile srcLpn = srcSG.getLpn();
LhpnFile lpn = sg.getLpn();
int[] thisIndexList = lpn.getThisIndexArray(srcLpn.getLpnIndex());
int[] otherIndexList = lpn.getOtherIndexArray(srcLpn.getLpnIndex());
// int[] thisIndexList = lpn.getThisIndexArray(srcLpn.ID - 1);
// int[] otherIndexList = lpn.getOtherIndexArray(srcLpn.ID - 1);
if(newConstraintSet.size() > 0){
for(State currentState : sg.getStateSet()){
for(Constraint c : newConstraintSet){
if(compatible(currentState, c, thisIndexList, otherIndexList)){
newTransitions += createNewState(sg, currentState, c);
}
}
}
for(State currentState : sg.getFrontierStateSet()){
for(Constraint c : newConstraintSet){
if(compatible(currentState, c, thisIndexList, otherIndexList)){
newTransitions += createNewState(sg, currentState, c);
}
}
}
}
if(oldConstraintSet.size() > 0){
for(State currentState : sg.getFrontierStateSet()){
for(Constraint c : oldConstraintSet){
if(compatible(currentState, c, thisIndexList, otherIndexList)){
newTransitions += createNewState(sg, currentState, c);
}
}
}
}
return newTransitions;
}
/**
* Extracts applicable constraints from a StateGraph.
* @param sg - The state graph the constraints are to be applied.
* @param srcSG - The state graph the constraint are extracted from.
*/
private void extractConstraints(StateGraph sg, StateGraph srcSG, List<Constraint> newConstraintSet, List<Constraint> oldConstraintSet){
newConstraintSet.clear();
oldConstraintSet.clear();
LhpnFile srcLpn = srcSG.getLpn();
for(Constraint newConstraint : sg.getNewConstraintSet()){
if(newConstraint.getLpn() != srcLpn)
continue;
newConstraintSet.add(newConstraint);
}
for(Constraint oldConstraint : sg.getOldConstraintSet()){
if(oldConstraint.getLpn() != srcLpn)
continue;
oldConstraintSet.add(oldConstraint);
}
}
/**
* Determines whether a constraint is compatible with a state.
* @return True if compatible, otherwise False.
*/
private boolean compatible(State currentState, Constraint constr, int[] thisIndexList, int[] otherIndexList){
int[] constraintVector = constr.getVector();
int[] currentVector = currentState.getVariableVector();
for(int i = 0; i < thisIndexList.length; i++){
int thisIndex = thisIndexList[i];
int otherIndex = otherIndexList[i];
if(currentVector[thisIndex] != constraintVector[otherIndex]){
return false;
}
}
return true;
}
/**
* Creates a state from a given constraint and compatible state and insert into state graph. If the state is new, then findSG is called.
* @return Number of new transitions.
*/
private int createNewState(StateGraph sg, State compatibleState, Constraint c){
int newTransitions = 0;
State newState = new State(compatibleState);
int[] newVector = newState.getVariableVector();
//List<VarNode> variableList = c.getVariableList();
List<Integer> variableList = c.getVariableList();
List<Integer> valueList = c.getValueList();
//int[] compatibleVector = compatibleState.getVector();
// TODO: Need to update tranVector here?
for(int i = 0; i < variableList.size(); i++){
//int index = variableList.get(i).getIndex(compatibleVector);
int index = variableList.get(i);
newVector[index] = valueList.get(i);
}
updateTranVectorByConstraint(newState.getLpn(), newState.getTranVector(), newState.getMarking(), newVector);
State nextState = sg.addState(newState);
if(nextState == newState){
int result = 0;
sg.addFrontierState(nextState);
// TODO: Need to consider the "Sticky sematics"
// if(Options.getStickySemantics()){
// result = sg.constrStickyFindSG(nextState, sg.getEnabled(compatibleState));
// }
// else{
result = sg.constrFindSG(nextState);
// }
if(result < 0)
return newTransitions;
newTransitions += result;
}
Transition constraintTran = c.getLpnTransition();
sg.addStateTran(compatibleState, constraintTran, nextState);
newTransitions++;
return newTransitions;
}
private String printTranVecotr(boolean[] tranVector) {
String tranVecStr = "[";
for (boolean i : tranVector) {
tranVecStr = tranVecStr + "," + i;
}
tranVecStr = tranVecStr + "]";
return tranVecStr;
}
/**
* Update tranVector due to application of a constraint. Only vector of a state can change due to a constraint, and
* therefore the tranVector can potentially change.
* @param lpn
* @param enabledTranBeforeConstr
* @param marking
* @param newVector
* @return
*/
public void updateTranVectorByConstraint(LhpnFile lpn, boolean[] enabledTran,
int[] marking, int[] newVector) {
// find newly enabled transition(s) based on the updated variables vector.
for (Transition tran : lpn.getAllTransitions()) {
boolean needToUpdate = true;
String tranName = tran.getLabel();
int tranIndex = tran.getIndex();
if (Options.getDebugMode()) {
// System.out.println("Checking " + tranName);
}
if (lpn.getEnablingTree(tranName) != null
&& lpn.getEnablingTree(tranName).evaluateExpr(lpn.getAllVarsWithValuesAsString(newVector)) == 0.0) {
if (Options.getDebugMode()) {
System.out.println(tran.getLabel() + " " + "Enabling condition is false");
}
if (enabledTran[tranIndex] && !tran.isPersistent())
enabledTran[tranIndex] = false;
continue;
}
if (lpn.getTransitionRateTree(tranName) != null
&& lpn.getTransitionRateTree(tranName).evaluateExpr(lpn.getAllVarsWithValuesAsString(newVector)) == 0.0) {
if (Options.getDebugMode()) {
System.out.println("Rate is zero");
}
continue;
}
if (lpn.getPreset(tranName) != null && lpn.getPreset(tranName).length != 0) {
for (int place : lpn.getPresetIndex(tranName)) {
if (marking[place]==0) {
if (Options.getDebugMode()) {
System.out.println(tran.getLabel() + " " + "Missing a preset token");
}
needToUpdate = false;
break;
}
}
}
if (needToUpdate) {
enabledTran[tranIndex] = true;
if (Options.getDebugMode()) {
System.out.println(tran.getLabel() + " is Enabled.");
}
}
}
}
private void constructDstLpnList(StateGraph[] sgArray) {
for (int i=0; i<sgArray.length; i++) {
LhpnFile curLPN = sgArray[i].getLpn();
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j<allTrans.length; j++) {
Transition curTran = allTrans[j];
for (int k=0; k<sgArray.length; k++) {
curTran.setDstLpnList(sgArray[k].getLpn());
}
}
}
}
}
| In compositionalFindSG method, commented out the numTrans in the final printout.
| gui/src/verification/platu/logicAnalysis/CompositionalAnalysis.java | In compositionalFindSG method, commented out the numTrans in the final printout. |
|
Java | apache-2.0 | 4ea0d348921c135a5932a20847aca097a18c5537 | 0 | jamesdbloom/mockserver,jamesdbloom/mockserver,jamesdbloom/mockserver,jamesdbloom/mockserver,jamesdbloom/mockserver | package org.mockserver.socket;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.mockserver.configuration.ConfigurationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
/**
* @author jamesdbloom
*/
public class SSLFactory {
public static final String KEY_STORE_PASSWORD = "changeit";
public static final String CERTIFICATE_DOMAIN = "localhost";
public static final String KEY_STORE_CERT_ALIAS = "mockserver-client-cert";
public static final String KEY_STORE_CA_ALIAS = "mockserver-ca-cert";
private static final Logger logger = LoggerFactory.getLogger(SSLFactory.class);
private static final SSLFactory SSL_FACTORY = new SSLFactory();
private KeyStore keystore;
private SSLFactory() {
}
public static String defaultKeyStoreFileName() {
if ("jks".equalsIgnoreCase(ConfigurationProperties.javaKeyStoreType())) {
return "mockserver_keystore.jks";
} else if ("pkcs12".equalsIgnoreCase(ConfigurationProperties.javaKeyStoreType())) {
return "mockserver_keystore.p12";
} else if ("jceks".equalsIgnoreCase(ConfigurationProperties.javaKeyStoreType())) {
return "mockserver_keystore.jceks";
} else {
throw new IllegalArgumentException(ConfigurationProperties.javaKeyStoreType() + " is not a supported keystore type");
}
}
public static SSLFactory getInstance() {
return SSL_FACTORY;
}
public static SSLEngine createClientSSLEngine() {
SSLEngine engine = SSLFactory.getInstance().sslContext().createSSLEngine();
engine.setUseClientMode(true);
return engine;
}
public static SSLEngine createServerSSLEngine() {
SSLEngine engine = SSLFactory.getInstance().sslContext().createSSLEngine();
engine.setUseClientMode(false);
return engine;
}
public static void addSubjectAlternativeName(String host) {
if (host != null) {
String hostWithoutPort = StringUtils.substringBefore(host, ":");
try {
// resolve host name for subject alternative name in case host name is ip address
InetAddress addr = InetAddress.getByName(hostWithoutPort);
ConfigurationProperties.addSslSubjectAlternativeNameDomains(addr.getHostName());
ConfigurationProperties.addSslSubjectAlternativeNameDomains(addr.getCanonicalHostName());
} catch (UnknownHostException uhe) {
ConfigurationProperties.addSslSubjectAlternativeNameDomains(hostWithoutPort);
}
}
}
public SSLSocket wrapSocket(Socket socket) throws Exception {
// ssl socket factory
SSLSocketFactory sslSocketFactory = sslContext().getSocketFactory();
// ssl socket
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
sslSocket.setUseClientMode(true);
sslSocket.startHandshake();
return sslSocket;
}
public synchronized SSLContext sslContext() {
try {
// key manager
KeyManagerFactory keyManagerFactory = getKeyManagerFactoryInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(buildKeyStore(), ConfigurationProperties.javaKeyStorePassword().toCharArray());
// ssl context
SSLContext sslContext = getSSLContextInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
return sslContext;
} catch (Exception e) {
throw new RuntimeException("Failed to initialize the SSLContext", e);
}
}
public synchronized KeyStore buildKeyStore() {
return buildKeyStore(ConfigurationProperties.rebuildKeyStore());
}
public synchronized KeyStore buildKeyStore(boolean forceRebuild) {
if (keystore == null || forceRebuild) {
File keyStoreFile = new File(ConfigurationProperties.javaKeyStoreFilePath());
System.setProperty("javax.net.ssl.trustStore", keyStoreFile.getAbsolutePath());
if (keyStoreFile.exists()) {
keystore = updateExistingKeyStore(keyStoreFile);
} else {
createNewKeyStore();
}
// don't rebuild again and again and again
ConfigurationProperties.rebuildKeyStore(false);
}
return keystore;
}
private SSLContext getSSLContextInstance(String protocol) throws NoSuchAlgorithmException {
return SSLContext.getInstance(protocol);
}
private KeyManagerFactory getKeyManagerFactoryInstance(String algorithm) throws NoSuchAlgorithmException {
return KeyManagerFactory.getInstance(algorithm);
}
private void createNewKeyStore() {
try {
keystore = new KeyStoreFactory().generateCertificate(
null,
KEY_STORE_CERT_ALIAS,
KEY_STORE_CA_ALIAS,
ConfigurationProperties.javaKeyStorePassword().toCharArray(),
ConfigurationProperties.sslCertificateDomainName(),
ConfigurationProperties.sslSubjectAlternativeNameDomains(),
ConfigurationProperties.sslSubjectAlternativeNameIps()
);
} catch (Exception e) {
throw new RuntimeException("Exception while building KeyStore dynamically", e);
}
}
private synchronized KeyStore updateExistingKeyStore(File keyStoreFile) {
try {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(ConfigurationProperties.javaKeyStoreFilePath());
logger.trace("Loading key store from file [" + keyStoreFile + "]");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(fileInputStream, ConfigurationProperties.javaKeyStorePassword().toCharArray());
new KeyStoreFactory().generateCertificate(
keystore,
KEY_STORE_CERT_ALIAS,
KEY_STORE_CA_ALIAS,
ConfigurationProperties.javaKeyStorePassword().toCharArray(),
ConfigurationProperties.sslCertificateDomainName(),
ConfigurationProperties.sslSubjectAlternativeNameDomains(),
ConfigurationProperties.sslSubjectAlternativeNameIps()
);
return keystore;
} finally {
IOUtils.closeQuietly(fileInputStream);
}
} catch (Exception e) {
throw new RuntimeException("Exception while loading KeyStore from " + keyStoreFile.getAbsolutePath(), e);
}
}
}
| mockserver-core/src/main/java/org/mockserver/socket/SSLFactory.java | package org.mockserver.socket;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.mockserver.configuration.ConfigurationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
/**
* @author jamesdbloom
*/
public class SSLFactory {
public static final String KEY_STORE_PASSWORD = "changeit";
public static final String CERTIFICATE_DOMAIN = "localhost";
public static final String KEY_STORE_CERT_ALIAS = "mockserver-client-cert";
public static final String KEY_STORE_CA_ALIAS = "mockserver-ca-cert";
private static final Logger logger = LoggerFactory.getLogger(SSLFactory.class);
private static final SSLFactory SSL_FACTORY = new SSLFactory();
private KeyStore keystore;
private SSLFactory() {
}
public static String defaultKeyStoreFileName() {
if ("jks".equalsIgnoreCase(ConfigurationProperties.javaKeyStoreType())) {
return "mockserver_keystore.jks";
} else if ("pkcs12".equalsIgnoreCase(ConfigurationProperties.javaKeyStoreType())) {
return "mockserver_keystore.p12";
} else if ("jceks".equalsIgnoreCase(ConfigurationProperties.javaKeyStoreType())) {
return "mockserver_keystore.jceks";
} else {
throw new IllegalArgumentException(ConfigurationProperties.javaKeyStoreType() + " is not a supported keystore type");
}
}
public synchronized static SSLFactory getInstance() {
return SSL_FACTORY;
}
public synchronized static SSLEngine createClientSSLEngine() {
SSLEngine engine = SSLFactory.getInstance().sslContext().createSSLEngine();
engine.setUseClientMode(true);
return engine;
}
public synchronized static SSLEngine createServerSSLEngine() {
SSLEngine engine = SSLFactory.getInstance().sslContext().createSSLEngine();
engine.setUseClientMode(false);
return engine;
}
public synchronized static void addSubjectAlternativeName(String host) {
if (host != null) {
String hostWithoutPort = StringUtils.substringBefore(host, ":");
try {
// resolve host name for subject alternative name in case host name is ip address
InetAddress addr = InetAddress.getByName(hostWithoutPort);
ConfigurationProperties.addSslSubjectAlternativeNameDomains(addr.getHostName());
ConfigurationProperties.addSslSubjectAlternativeNameDomains(addr.getCanonicalHostName());
} catch (UnknownHostException uhe) {
ConfigurationProperties.addSslSubjectAlternativeNameDomains(hostWithoutPort);
}
}
}
public synchronized SSLContext sslContext() {
try {
// key manager
KeyManagerFactory keyManagerFactory = getKeyManagerFactoryInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(buildKeyStore(), ConfigurationProperties.javaKeyStorePassword().toCharArray());
// ssl context
SSLContext sslContext = getSSLContextInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
return sslContext;
} catch (Exception e) {
throw new RuntimeException("Failed to initialize the SSLContext", e);
}
}
public synchronized SSLSocket wrapSocket(Socket socket) throws Exception {
// ssl socket factory
SSLSocketFactory sslSocketFactory = sslContext().getSocketFactory();
// ssl socket
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
sslSocket.setUseClientMode(true);
sslSocket.startHandshake();
return sslSocket;
}
public synchronized KeyStore buildKeyStore() {
return buildKeyStore(ConfigurationProperties.rebuildKeyStore());
}
public synchronized KeyStore buildKeyStore(boolean forceRebuild) {
if (keystore == null || forceRebuild) {
File keyStoreFile = new File(ConfigurationProperties.javaKeyStoreFilePath());
System.setProperty("javax.net.ssl.trustStore", keyStoreFile.getAbsolutePath());
if (keyStoreFile.exists()) {
keystore = updateExistingKeyStore(keyStoreFile);
} else {
createNewKeyStore();
}
// don't rebuild again and again and again
ConfigurationProperties.rebuildKeyStore(false);
}
return keystore;
}
private SSLContext getSSLContextInstance(String protocol) throws NoSuchAlgorithmException {
return SSLContext.getInstance(protocol);
}
private KeyManagerFactory getKeyManagerFactoryInstance(String algorithm) throws NoSuchAlgorithmException {
return KeyManagerFactory.getInstance(algorithm);
}
private void createNewKeyStore() {
try {
keystore = new KeyStoreFactory().generateCertificate(
null,
KEY_STORE_CERT_ALIAS,
KEY_STORE_CA_ALIAS,
ConfigurationProperties.javaKeyStorePassword().toCharArray(),
ConfigurationProperties.sslCertificateDomainName(),
ConfigurationProperties.sslSubjectAlternativeNameDomains(),
ConfigurationProperties.sslSubjectAlternativeNameIps()
);
} catch (Exception e) {
throw new RuntimeException("Exception while building KeyStore dynamically", e);
}
}
private KeyStore updateExistingKeyStore(File keyStoreFile) {
try {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(ConfigurationProperties.javaKeyStoreFilePath());
logger.trace("Loading key store from file [" + keyStoreFile + "]");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(fileInputStream, ConfigurationProperties.javaKeyStorePassword().toCharArray());
new KeyStoreFactory().generateCertificate(
keystore,
KEY_STORE_CERT_ALIAS,
KEY_STORE_CA_ALIAS,
ConfigurationProperties.javaKeyStorePassword().toCharArray(),
ConfigurationProperties.sslCertificateDomainName(),
ConfigurationProperties.sslSubjectAlternativeNameDomains(),
ConfigurationProperties.sslSubjectAlternativeNameIps()
);
return keystore;
} finally {
IOUtils.closeQuietly(fileInputStream);
}
} catch (Exception e) {
throw new RuntimeException("Exception while loading KeyStore from " + keyStoreFile.getAbsolutePath(), e);
}
}
}
| fixing the build - trying to fix issues with proxy throw keystore error when handling lots or parallel request for new domains
| mockserver-core/src/main/java/org/mockserver/socket/SSLFactory.java | fixing the build - trying to fix issues with proxy throw keystore error when handling lots or parallel request for new domains |
|
Java | apache-2.0 | 64c3d90ad0317f1a7c1abc0ac56ca32254dd67ff | 0 | guzike/Sunshine | package com.example.android.sunshine.app;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class ForecastFragment extends Fragment {
public static final String LOG_TAG = ForecastFragment.class.getSimpleName();
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
new FetchWeatherTask().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Weds - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
"Sun - Sunny - 80/68"
};
List<String> weekForecast = new ArrayList<>(Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
ListView forecastList = (ListView) rootView.findViewById(R.id.listview_forecast);
forecastList.setAdapter(mForecastAdapter);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<Void, Void, Void>{
int mPostCode = 94043;
@Override
protected Void doInBackground(Void... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
//https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("forecast")
.appendPath("daily")
.appendQueryParameter("q", mPostCode + "")
.appendQueryParameter("mode", "json")
.appendQueryParameter("units", "metric")
.appendQueryParameter("cnt", "7");
String myUrl = builder.build().toString();
URL url = new URL(myUrl);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
forecastJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
Log.v(LOG_TAG, myUrl);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
forecastJsonStr = null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
}
}
| app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java | package com.example.android.sunshine.app;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class ForecastFragment extends Fragment {
public static final String LOG_TAG = ForecastFragment.class.getSimpleName();
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
new FetchWeatherTask().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Weds - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
"Sun - Sunny - 80/68"
};
List<String> weekForecast = new ArrayList<>(Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
ListView forecastList = (ListView) rootView.findViewById(R.id.listview_forecast);
forecastList.setAdapter(mForecastAdapter);
new FetchWeatherTask().execute();
return rootView;
}
public class FetchWeatherTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
forecastJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
forecastJsonStr = null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
}
}
| ed refresh function
| app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java | ed refresh function |
|
Java | apache-2.0 | 7f5344158372106855476c525f2c9bab532f6ba8 | 0 | apache/jackrabbit,apache/jackrabbit,apache/jackrabbit | /*
* 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.jackrabbit.core;
import org.apache.jackrabbit.test.ConcurrentTestSuite;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Test suite that includes all testcases for the Core module.
*/
public class TestAll extends TestCase {
/**
* @return a <code>Test</code> suite that executes all tests inside this
* package, except the multi-threading related ones.
*/
public static Test suite() {
TestSuite suite = new ConcurrentTestSuite("Core tests");
suite.addTestSuite(CachingHierarchyManagerTest.class);
suite.addTestSuite(ShareableNodeTest.class);
suite.addTestSuite(TransientRepositoryTest.class);
suite.addTestSuite(XATest.class);
suite.addTestSuite(RestoreAndCheckoutTest.class);
suite.addTestSuite(NodeImplTest.class);
suite.addTestSuite(RetentionRegistryImplTest.class);
suite.addTestSuite(InvalidDateTest.class);
suite.addTestSuite(SessionGarbageCollectedTest.class);
suite.addTestSuite(ReferencesTest.class);
// test related to NodeStateMerger
// temporarily disabled see JCR-2272 and JCR-2295
// suite.addTestSuite(ConcurrentImportTest.class);
suite.addTestSuite(ConcurrentAddRemoveMoveTest.class);
suite.addTestSuite(ConcurrentAddRemovePropertyTest.class);
suite.addTestSuite(ConcurrentMixinModificationTest.class);
suite.addTestSuite(ConcurrentModificationWithSNSTest.class);
suite.addTestSuite(ConcurrentMoveTest.class);
suite.addTestSuite(ConcurrentReorderTest.class);
return suite;
}
}
| jackrabbit-core/src/test/java/org/apache/jackrabbit/core/TestAll.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.jackrabbit.core;
import org.apache.jackrabbit.test.ConcurrentTestSuite;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Test suite that includes all testcases for the Core module.
*/
public class TestAll extends TestCase {
/**
* @return a <code>Test</code> suite that executes all tests inside this
* package, except the multi-threading related ones.
*/
public static Test suite() {
TestSuite suite = new ConcurrentTestSuite("Core tests");
suite.addTestSuite(CachingHierarchyManagerTest.class);
suite.addTestSuite(ShareableNodeTest.class);
suite.addTestSuite(TransientRepositoryTest.class);
suite.addTestSuite(XATest.class);
suite.addTestSuite(RestoreAndCheckoutTest.class);
suite.addTestSuite(NodeImplTest.class);
suite.addTestSuite(RetentionRegistryImplTest.class);
suite.addTestSuite(InvalidDateTest.class);
suite.addTestSuite(SessionGarbageCollectedTest.class);
suite.addTestSuite(ReferencesTest.class);
// test related to NodeStateMerger
suite.addTestSuite(ConcurrentImportTest.class);
suite.addTestSuite(ConcurrentAddRemoveMoveTest.class);
suite.addTestSuite(ConcurrentAddRemovePropertyTest.class);
suite.addTestSuite(ConcurrentMixinModificationTest.class);
suite.addTestSuite(ConcurrentModificationWithSNSTest.class);
suite.addTestSuite(ConcurrentMoveTest.class);
suite.addTestSuite(ConcurrentReorderTest.class);
return suite;
}
}
| JCR-2272: Errors during concurrent session import of nodes with same UUIDs
- temporarily disable test until issue is fixed
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@812032 13f79535-47bb-0310-9956-ffa450edef68
| jackrabbit-core/src/test/java/org/apache/jackrabbit/core/TestAll.java | JCR-2272: Errors during concurrent session import of nodes with same UUIDs - temporarily disable test until issue is fixed |
|
Java | apache-2.0 | cad1a7c1bfc930f10bf819a060686bcccab347b6 | 0 | lsitu/fcrepo4-client,mikedurbin/fcrepo4-client,keeps/fcrepo4-client,fcrepo4-labs/fcrepo4-client | /**
* Copyright 2014 DuraSpace, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fcrepo.client.utils;
import static java.lang.Integer.MAX_VALUE;
import static org.apache.http.HttpStatus.SC_BAD_REQUEST;
import static org.apache.http.HttpStatus.SC_FORBIDDEN;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.jena.riot.WebContent.contentTypeSPARQLUpdate;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.fcrepo.client.BadRequestException;
import org.fcrepo.client.ForbiddenException;
import org.fcrepo.client.NotFoundException;
import com.hp.hpl.jena.graph.Node;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.riot.RiotReader;
import org.apache.jena.riot.lang.CollectorStreamTriples;
import org.fcrepo.client.FedoraContent;
import org.fcrepo.client.FedoraException;
import org.fcrepo.client.ReadOnlyException;
import org.fcrepo.client.impl.FedoraResourceImpl;
import org.slf4j.Logger;
/**
* HTTP utilities
* @author escowles
* @since 2014-08-26
**/
public class HttpHelper {
private static final Logger LOGGER = getLogger(HttpHelper.class);
private final String repositoryURL;
private final HttpClient httpClient;
private final boolean readOnly;
/**
* Create an HTTP helper with a pre-configured HttpClient instance.
* @param repositoryURL Fedora base URL.
* @param httpClient Pre-configured HttpClient instance.
* @param readOnly If true, throw an exception when an update is attempted.
**/
public HttpHelper(final String repositoryURL, final HttpClient httpClient, final boolean readOnly) {
this.repositoryURL = repositoryURL;
this.httpClient = httpClient;
this.readOnly = readOnly;
}
/**
* Create an HTTP helper for the specified repository. If fedoraUsername and fedoraPassword are not null, then
* they will be used to connect to the repository.
* @param repositoryURL Fedora base URL.
* @param fedoraUsername Fedora username
* @param fedoraPassword Fedora password
* @param readOnly If true, throw an exception when an update is attempted.
**/
public HttpHelper(final String repositoryURL, final String fedoraUsername, final String fedoraPassword,
final boolean readOnly) {
this.repositoryURL = repositoryURL;
this.readOnly = readOnly;
final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager();
connMann.setMaxTotal(MAX_VALUE);
connMann.setDefaultMaxPerRoute(MAX_VALUE);
final DefaultHttpClient httpClient = new DefaultHttpClient(connMann);
httpClient.setRedirectStrategy(new DefaultRedirectStrategy());
httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false));
// If the Fedora instance requires authentication, set it up here
if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) {
LOGGER.debug("Adding BASIC credentials to client for repo requests.");
final URI fedoraUri = URI.create(repositoryURL);
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()),
new UsernamePasswordCredentials(fedoraUsername, fedoraPassword));
httpClient.setCredentialsProvider(credsProvider);
}
this.httpClient = httpClient;
}
/**
* Execute a request for a subclass.
**/
public HttpResponse execute( final HttpUriRequest request ) throws IOException, ReadOnlyException {
if ( readOnly ) {
switch ( request.getMethod().toLowerCase() ) {
case "copy": case "delete": case "move": case "patch": case "post": case "put":
throw new ReadOnlyException();
default:
break;
}
}
return httpClient.execute(request);
}
/**
* Encode URL parameters as a query string.
* @param params Query parameters
**/
private static String queryString( final Map<String, List<String>> params ) {
final StringBuilder builder = new StringBuilder();
if (params != null && params.size() > 0) {
for (final Iterator<String> it = params.keySet().iterator(); it.hasNext(); ) {
final String key = it.next();
final List<String> values = params.get(key);
for (final String value : values) {
try {
builder.append(key + "=" + URLEncoder.encode(value, "UTF-8") + "&");
} catch (final UnsupportedEncodingException e) {
builder.append(key + "=" + value + "&");
}
}
}
return builder.length() > 0 ? "?" + builder.substring(0, builder.length() - 1) : "";
}
return "";
}
/**
* Create HEAD method
* @param path Resource path, relative to repository baseURL
* @return HEAD method
**/
public HttpHead createHeadMethod(final String path) {
return new HttpHead(repositoryURL + path);
}
/**
* Create GET method with list of parameters
* @param path Resource path, relative to repository baseURL
* @param params Query parameters
* @return GET method
**/
public HttpGet createGetMethod(final String path, final Map<String, List<String>> params) {
return new HttpGet(repositoryURL + path + queryString(params));
}
/**
* Create a request to update triples with SPARQL Update.
* @param path The datastream path.
* @param sparqlUpdate SPARQL Update command.
**/
public HttpPatch createPatchMethod(final String path, final String sparqlUpdate) throws FedoraException {
if ( isBlank(sparqlUpdate) ) {
throw new FedoraException("SPARQL Update command must not be blank");
}
final HttpPatch patch = new HttpPatch(repositoryURL + path);
patch.setEntity( new ByteArrayEntity(sparqlUpdate.getBytes()) );
patch.setHeader("Content-Type", contentTypeSPARQLUpdate);
return patch;
}
/**
* Create POST method with list of parameters
* @param path Resource path, relative to repository baseURL
* @param params Query parameters
* @return PUT method
**/
public HttpPost createPostMethod(final String path, final Map<String, List<String>> params) {
return new HttpPost(repositoryURL + path + queryString(params));
}
/**
* Create PUT method with list of parameters
* @param path Resource path, relative to repository baseURL
* @param params Query parameters
* @return PUT method
**/
public HttpPut createPutMethod(final String path, final Map<String, List<String>> params) {
return new HttpPut(repositoryURL + path + queryString(params));
}
/**
* Create a request to create/update content.
* @param path The datastream path.
* @param content Content parameters.
**/
public HttpPut createContentPutMethod(final String path, final Map<String, List<String>> params,
final FedoraContent content ) {
String contentPath = path + "/fcr:content";
if ( content != null && content.getChecksum() != null ) {
contentPath += "?checksum=" + content.getChecksum();
}
final HttpPut put = createPutMethod( contentPath, params );
// content stream
if ( content != null ) {
put.setEntity( new InputStreamEntity(content.getContent()) );
}
// filename
if ( content != null && content.getFilename() != null ) {
put.setHeader("Content-Disposition", "attachment; filename=\"" + content.getFilename() + "\"" );
}
// content type
if ( content != null && content.getContentType() != null ) {
put.setHeader("Content-Type", content.getContentType() );
}
return put;
}
/**
* Create a request to update triples.
* @param path The datastream path.
* @param updatedProperties InputStream containing RDF.
* @param contentType Content type of the RDF in updatedProperties (e.g., "text/rdf+n3" or
* "application/rdf+xml").
**/
public HttpPut createTriplesPutMethod(final String path, final InputStream updatedProperties,
final String contentType) throws FedoraException {
if ( updatedProperties == null ) {
throw new FedoraException("updatedProperties must not be null");
} else if ( isBlank(contentType) ) {
throw new FedoraException("contentType must not be blank");
}
final HttpPut put = new HttpPut(repositoryURL + path);
put.setEntity( new InputStreamEntity(updatedProperties) );
put.setHeader("Content-Type", contentType);
return put;
}
/**
* Retrieve RDF from the repository and update the properties of a resource
* @param resource The resource to update
* @return the updated resource
**/
public FedoraResourceImpl loadProperties( final FedoraResourceImpl resource ) throws FedoraException {
final HttpGet get = createGetMethod(resource.getPath(), null);
try {
get.setHeader("accept", "application/rdf+xml");
final HttpResponse response = execute(get);
final String uri = get.getURI().toString();
final StatusLine status = response.getStatusLine();
if (status.getStatusCode() == SC_OK) {
LOGGER.debug("Updated properties for resource {}", uri);
// header processing
final Header[] etagHeader = response.getHeaders("ETag");
if (etagHeader != null && etagHeader.length > 0) {
resource.setEtagValue( etagHeader[0].getValue() );
}
// StreamRdf
final HttpEntity entity = response.getEntity();
final Lang lang = RDFLanguages.contentTypeToLang(entity.getContentType().getValue().split(":")[0]);
final CollectorStreamTriples streamTriples = new CollectorStreamTriples();
RiotReader.parse(entity.getContent(), lang, uri, streamTriples);
resource.setGraph( RDFSinkFilter.filterTriples(streamTriples.getCollected().iterator(), Node.ANY) );
return resource;
} else if (status.getStatusCode() == SC_FORBIDDEN) {
LOGGER.info("request for resource {} is not authorized.", uri);
throw new ForbiddenException("request for resource " + uri + " is not authorized.");
} else if (status.getStatusCode() == SC_BAD_REQUEST) {
LOGGER.info("server does not support metadata type application/rdf+xml for resource {} " +
" cannot retrieve", uri);
throw new BadRequestException("server does not support the request metadata type for resource " + uri);
} else if (status.getStatusCode() == SC_NOT_FOUND) {
LOGGER.info("resource {} does not exist, cannot retrieve", uri);
throw new NotFoundException("resource " + uri + " does not exist, cannot retrieve");
} else {
LOGGER.info("unexpected status code ({}) when retrieving resource {}", status.getStatusCode(), uri);
throw new FedoraException("error retrieving resource " + uri + ": " + status.getStatusCode() + " "
+ status.getReasonPhrase());
}
} catch (final FedoraException e) {
throw e;
} catch (final Exception e) {
LOGGER.info("could not encode URI parameter", e);
throw new FedoraException(e);
} finally {
get.releaseConnection();
}
}
}
| fcrepo-client-impl/src/main/java/org/fcrepo/client/utils/HttpHelper.java | /**
* Copyright 2014 DuraSpace, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fcrepo.client.utils;
import static java.lang.Integer.MAX_VALUE;
import static org.apache.http.HttpStatus.SC_BAD_REQUEST;
import static org.apache.http.HttpStatus.SC_FORBIDDEN;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.jena.riot.WebContent.contentTypeSPARQLUpdate;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.fcrepo.client.BadRequestException;
import org.fcrepo.client.ForbiddenException;
import org.fcrepo.client.NotFoundException;
import com.hp.hpl.jena.graph.Node;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.riot.RiotReader;
import org.apache.jena.riot.lang.CollectorStreamTriples;
import org.fcrepo.client.FedoraContent;
import org.fcrepo.client.FedoraException;
import org.fcrepo.client.ReadOnlyException;
import org.fcrepo.client.impl.FedoraResourceImpl;
import org.slf4j.Logger;
/**
* HTTP utilities
* @author escowles
* @since 2014-08-26
**/
public class HttpHelper {
private static final Logger LOGGER = getLogger(HttpHelper.class);
private final String repositoryURL;
private final HttpClient httpClient;
private final boolean readOnly;
/**
* Create an HTTP helper with a pre-configured HttpClient instance.
* @param repositoryURL Fedora base URL.
* @param httpClient Pre-configured HttpClient instance.
* @param readOnly If true, throw an exception when an update is attempted.
**/
public HttpHelper(final String repositoryURL, final HttpClient httpClient, final boolean readOnly) {
this.repositoryURL = repositoryURL;
this.httpClient = httpClient;
this.readOnly = readOnly;
}
/**
* Create an HTTP helper for the specified repository. If fedoraUsername and fedoraPassword are not null, then
* they will be used to connect to the repository.
* @param repositoryURL Fedora base URL.
* @param fedoraUsername Fedora username
* @param fedoraPassword Fedora password
* @param readOnly If true, throw an exception when an update is attempted.
**/
public HttpHelper(final String repositoryURL, final String fedoraUsername, final String fedoraPassword,
final boolean readOnly) {
this.repositoryURL = repositoryURL;
this.readOnly = readOnly;
final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager();
connMann.setMaxTotal(MAX_VALUE);
connMann.setDefaultMaxPerRoute(MAX_VALUE);
final DefaultHttpClient httpClient = new DefaultHttpClient(connMann);
httpClient.setRedirectStrategy(new DefaultRedirectStrategy());
httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false));
// If the Fedora instance requires authentication, set it up here
if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) {
LOGGER.debug("Adding BASIC credentials to client for repo requests.");
final URI fedoraUri = URI.create(repositoryURL);
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()),
new UsernamePasswordCredentials(fedoraUsername, fedoraPassword));
httpClient.setCredentialsProvider(credsProvider);
}
this.httpClient = httpClient;
}
/**
* Execute a request for a subclass.
**/
public HttpResponse execute( final HttpUriRequest request ) throws IOException, ReadOnlyException {
if ( readOnly ) {
switch ( request.getMethod().toLowerCase() ) {
case "copy": case "delete": case "move": case "patch": case "post": case "put":
throw new ReadOnlyException();
default:
break;
}
}
return httpClient.execute(request);
}
/**
* Encode URL parameters as a query string.
* @param params Query parameters
**/
private static String queryString( final Map<String, List<String>> params ) {
final StringBuilder builder = new StringBuilder();
if (params != null && params.size() > 0) {
for (final Iterator<String> it = params.keySet().iterator(); it.hasNext(); ) {
final String key = it.next();
final List<String> values = params.get(key);
for (final String value : values) {
try {
builder.append(key + "=" + URLEncoder.encode(value, "UTF-8") + "&");
} catch (final UnsupportedEncodingException e) {
builder.append(key + "=" + value + "&");
}
}
}
return builder.length() > 0 ? "?" + builder.substring(0, builder.length() - 1) : "";
}
return "";
}
/**
* Create HEAD method
* @param path Resource path, relative to repository baseURL
* @return HEAD method
**/
public HttpHead createHeadMethod(final String path) {
return new HttpHead(repositoryURL + path);
}
/**
* Create GET method with list of parameters
* @param path Resource path, relative to repository baseURL
* @param params Query parameters
* @return GET method
**/
public HttpGet createGetMethod(final String path, final Map<String, List<String>> params) {
return new HttpGet(repositoryURL + path + queryString(params));
}
/**
* Create a request to update triples with SPARQL Update.
* @param path The datastream path.
* @param sparqlUpdate SPARQL Update command.
**/
public HttpPatch createPatchMethod(final String path, final String sparqlUpdate) throws FedoraException {
if ( isBlank(sparqlUpdate) ) {
throw new FedoraException("SPARQL Update command must not be blank");
}
final HttpPatch patch = new HttpPatch(repositoryURL + path);
patch.setEntity( new ByteArrayEntity(sparqlUpdate.getBytes()) );
patch.setHeader("Content-Type", contentTypeSPARQLUpdate);
return patch;
}
/**
* Create POST method with list of parameters
* @param path Resource path, relative to repository baseURL
* @param params Query parameters
* @return PUT method
**/
public HttpPost createPostMethod(final String path, final Map<String, List<String>> params) {
return new HttpPost(repositoryURL + path + queryString(params));
}
/**
* Create PUT method with list of parameters
* @param path Resource path, relative to repository baseURL
* @param params Query parameters
* @return PUT method
**/
public HttpPut createPutMethod(final String path, final Map<String, List<String>> params) {
return new HttpPut(repositoryURL + path + queryString(params));
}
/**
* Create a request to create/update content.
* @param path The datastream path.
* @param content Content parameters.
**/
public HttpPut createContentPutMethod(final String path, final Map<String, List<String>> params,
final FedoraContent content ) {
String contentPath = path + "/fcr:content";
if ( content != null && content.getChecksum() != null ) {
contentPath += "?checksum=" + content.getChecksum();
}
final HttpPut put = createPutMethod( contentPath, params );
// content stream
if ( content != null ) {
put.setEntity( new InputStreamEntity(content.getContent()) );
}
// filename
if ( content != null && content.getFilename() != null ) {
put.setHeader("Content-Disposition", "attachment; filename=\"" + content.getFilename() + "\"" );
}
// content type
if ( content != null && content.getContentType() != null ) {
put.setHeader("Content-Type", content.getContentType() );
}
return put;
}
/**
* Create a request to update triples.
* @param path The datastream path.
* @param updatedProperties InputStream containing RDF.
* @param contentType Content type of the RDF in updatedProperties (e.g., "text/rdf+n3" or
* "application/rdf+xml").
**/
public HttpPut createTriplesPutMethod(final String path, final InputStream updatedProperties,
final String contentType) throws FedoraException {
if ( updatedProperties == null ) {
throw new FedoraException("updatedProperties must not be null");
} else if ( isBlank(contentType) ) {
throw new FedoraException("contentType must not be blank");
}
final HttpPut put = new HttpPut(repositoryURL + path);
put.setEntity( new InputStreamEntity(updatedProperties) );
put.setHeader("Content-Type", contentType);
return put;
}
/**
* Retrieve RDF from the repository and update the properties of a resource
* @param resource The resource to update
* @return the updated resource
**/
public FedoraResourceImpl loadProperties( final FedoraResourceImpl resource ) throws FedoraException {
final HttpGet get = createGetMethod(resource.getPath(), null);
try {
get.setHeader("accept", "application/rdf+xml");
final HttpResponse response = execute(get);
final String uri = get.getURI().toString();
final StatusLine status = response.getStatusLine();
if (status.getStatusCode() == SC_OK) {
LOGGER.debug("Updated properties for resource {}", uri);
// header processing
final Header[] etagHeader = response.getHeaders("ETag");
if (etagHeader != null && etagHeader.length > 0) {
resource.setEtagValue( etagHeader[0].getValue() );
}
// StreamRdf
final HttpEntity entity = response.getEntity();
final Lang lang = RDFLanguages.contentTypeToLang(entity.getContentType().getValue().split(":")[0]);
final CollectorStreamTriples streamTriples = new CollectorStreamTriples();
RiotReader.parse(entity.getContent(), lang, uri, streamTriples);
resource.setGraph( RDFSinkFilter.filterTriples(streamTriples.getCollected().iterator(), Node.ANY) );
return resource;
} else if (status.getStatusCode() == SC_FORBIDDEN) {
LOGGER.error("request for resource {} is not authorized.", uri);
throw new ForbiddenException("request for resource " + uri + " is not authorized.");
} else if (status.getStatusCode() == SC_BAD_REQUEST) {
LOGGER.error("server does not support metadata type application/rdf+xml for resource {} " +
" cannot retrieve", uri);
throw new BadRequestException("server does not support the request metadata type for resource " + uri);
} else if (status.getStatusCode() == SC_NOT_FOUND) {
LOGGER.error("resource {} does not exist, cannot retrieve", uri);
throw new NotFoundException("resource " + uri + " does not exist, cannot retrieve");
} else {
throw new FedoraException("error retrieving resource " + uri + ": " + status.getStatusCode() + " "
+ status.getReasonPhrase());
}
} catch (final FedoraException e) {
throw e;
} catch (final Exception e) {
LOGGER.error("could not encode URI parameter", e);
throw new FedoraException(e);
} finally {
get.releaseConnection();
}
}
}
| Reduce logging on client errors
| fcrepo-client-impl/src/main/java/org/fcrepo/client/utils/HttpHelper.java | Reduce logging on client errors |
|
Java | apache-2.0 | 3e36989636203ed9ae0a41d7f9716d537b8d82dd | 0 | norcalrdf/Tenuki | package com.oreilly.rdf.tenuki.jaxrs;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.openjena.atlas.lib.Sink;
import org.openjena.riot.RiotReader;
import org.openjena.riot.lang.LangNQuads;
import com.hp.hpl.jena.sdb.store.StoreLoaderPlus;
import com.hp.hpl.jena.sparql.core.DatasetGraph;
import com.hp.hpl.jena.sparql.core.Quad;
@Path("/bulk")
public class BulkLoadResource extends DatasetAccessResource {
public class SDBBulkSink implements Sink<Quad> {
private StoreLoaderPlus loader;
public SDBBulkSink(StoreLoaderPlus loader){
this.loader = loader;
loader.setChunkSize(100000);
loader.startBulkUpdate();
}
@Override
public void flush() {
}
@Override
public void send(Quad q) {
loader.addQuad(q.getGraph(), q.getSubject(), q.getPredicate(), q.getObject());
}
@Override
public void close() {
loader.finishBulkUpdate();
}
}
@Path("")
@POST
@Consumes("text/x-nquads")
public Response bulkLoad(@Context HttpServletRequest r) {
StoreLoaderPlus loader = (StoreLoaderPlus) getStore().getLoader();
SDBBulkSink sink = new SDBBulkSink(loader);
try {
LangNQuads parser = RiotReader.createParserNQuads(r.getInputStream(), sink);
parser.parse();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
sink.close();
}
return Response.noContent().build();
}
@Path("dump")
@GET
@Produces("text/x-nquads")
public DatasetGraph dump() {
return getDataset().asDatasetGraph();
}
}
| src/main/java/com/oreilly/rdf/tenuki/jaxrs/BulkLoadResource.java | package com.oreilly.rdf.tenuki.jaxrs;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.openjena.atlas.lib.Sink;
import org.openjena.riot.RiotReader;
import org.openjena.riot.lang.LangNQuads;
import com.hp.hpl.jena.sdb.store.StoreLoaderPlus;
import com.hp.hpl.jena.sparql.core.DatasetGraph;
import com.hp.hpl.jena.sparql.core.Quad;
@Path("/bulk")
public class BulkLoadResource extends DatasetAccessResource {
public class SDBBulkSink implements Sink<Quad> {
private StoreLoaderPlus loader;
public SDBBulkSink(StoreLoaderPlus loader){
this.loader = loader;
loader.setChunkSize(100000);
loader.startBulkUpdate();
}
@Override
public void flush() {
}
@Override
public void send(Quad q) {
loader.addQuad(q.getGraph(), q.getSubject(), q.getPredicate(), q.getObject());
}
@Override
public void close() {
loader.finishBulkUpdate();
}
}
@Path("")
@POST
@Consumes("text/x-nquads")
public Response bulkLoad(@Context HttpServletRequest r) {
StoreLoaderPlus loader = (StoreLoaderPlus) getStore().getLoader();
SDBBulkSink sink = new SDBBulkSink(loader);
try {
LangNQuads parser = RiotReader.createParserNQuads(r.getInputStream(), sink);
parser.parse();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sink.close();
return Response.noContent().build();
}
@Path("dump")
@GET
@Produces("text/x-nquads")
public DatasetGraph dump() {
return getDataset().asDatasetGraph();
}
}
| Always close the bulk loader
| src/main/java/com/oreilly/rdf/tenuki/jaxrs/BulkLoadResource.java | Always close the bulk loader |
|
Java | apache-2.0 | 187f86b4e2e2911862b365df88847fd77ec790d6 | 0 | Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient | package org.sagebionetworks.web.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.xhr.client.XMLHttpRequest;
public class GWTWrapperImpl implements GWTWrapper {
@Override
public String getHostPageBaseURL() {
return GWT.getHostPageBaseURL();
}
@Override
public String getModuleBaseURL() {
return GWT.getModuleBaseURL();
}
@Override
public void replaceThisWindowWith(String url){
Window.Location.replace(url);
}
@Override
public String encodeQueryString(String queryString){
return URL.encodeQueryString(queryString);
}
@Override
public XMLHttpRequest createXMLHttpRequest() {
return XMLHttpRequest.create();
}
@Override
public NumberFormat getNumberFormat(String pattern) {
return NumberFormat.getFormat(pattern);
}
@Override
public String getHostPrefix() {
return com.google.gwt.user.client.Window.Location.getProtocol()+"//"+com.google.gwt.user.client.Window.Location.getHost();
}
}
| src/main/java/org/sagebionetworks/web/client/GWTWrapperImpl.java | package org.sagebionetworks.web.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.xhr.client.XMLHttpRequest;
public class GWTWrapperImpl implements GWTWrapper {
@Override
public String getHostPageBaseURL() {
return GWT.getHostPageBaseURL();
}
@Override
public String getModuleBaseURL() {
return GWT.getModuleBaseURL();
}
@Override
public void replaceThisWindowWith(String url){
Window.Location.replace(url);
}
@Override
public String encodeQueryString(String queryString){
return URL.encodeQueryString(queryString);
}
@Override
public XMLHttpRequest createXMLHttpRequest() {
return XMLHttpRequest.create();
}
@Override
public NumberFormat getNumberFormat(String pattern) {
return NumberFormat.getFormat(pattern);
}
@Override
public String getHostPrefix() {
return com.google.gwt.user.client.Window.Location.getProtocol()+"//"+com.google.gwt.user.client.Window.Location.getHost();
}
}
| whitespace
| src/main/java/org/sagebionetworks/web/client/GWTWrapperImpl.java | whitespace |
|
Java | apache-2.0 | 24de2431c72c0d7e03fed38d1e308a218e144b7b | 0 | zhangkun83/grpc-java,carl-mastrangelo/grpc-java,dapengzhang0/grpc-java,anuraaga/grpc-java,ejona86/grpc-java,rmichela/grpc-java,zpencer/grpc-java,elandau/grpc-java,rmichela/grpc-java,grpc/grpc-java,elandau/grpc-java,dapengzhang0/grpc-java,zhangkun83/grpc-java,grpc/grpc-java,zpencer/grpc-java,rmichela/grpc-java,dapengzhang0/grpc-java,grpc/grpc-java,carl-mastrangelo/grpc-java,dapengzhang0/grpc-java,ejona86/grpc-java,ejona86/grpc-java,nmittler/grpc-java,zhangkun83/grpc-java,zhangkun83/grpc-java,pieterjanpintens/grpc-java,simonhorlick/grpc-java,stanley-cheung/grpc-java,rmichela/grpc-java,nmittler/grpc-java,anuraaga/grpc-java,elandau/grpc-java,ejona86/grpc-java,pieterjanpintens/grpc-java,pieterjanpintens/grpc-java,simonhorlick/grpc-java,nmittler/grpc-java,elandau/grpc-java,stanley-cheung/grpc-java,zpencer/grpc-java,grpc/grpc-java,simonhorlick/grpc-java,carl-mastrangelo/grpc-java,anuraaga/grpc-java,carl-mastrangelo/grpc-java,zpencer/grpc-java,stanley-cheung/grpc-java,pieterjanpintens/grpc-java,simonhorlick/grpc-java,stanley-cheung/grpc-java | /*
* Copyright 2014, Google Inc. 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 Google Inc. 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 io.grpc.protobuf.lite;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.ExtensionRegistryLite;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import com.google.protobuf.Parser;
import io.grpc.ExperimentalApi;
import io.grpc.KnownLength;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor.Marshaller;
import io.grpc.MethodDescriptor.PrototypeMarshaller;
import io.grpc.Status;
import io.grpc.internal.GrpcUtil;
import java.io.IOException;
import java.io.InputStream;
/**
* Utility methods for using protobuf with grpc.
*/
@ExperimentalApi("Experimental until Lite is stable in protobuf")
public class ProtoLiteUtils {
private static volatile ExtensionRegistryLite globalRegistry =
ExtensionRegistryLite.getEmptyRegistry();
/**
* Sets the global registry for proto marshalling shared across all servers and clients.
*
* <p>Warning: This API will likely change over time. It is not possible to have separate
* registries per Process, Server, Channel, Service, or Method. This is intentional until there
* is a more appropriate API to set them.
*
* <p>Warning: Do NOT modify the extension registry after setting it. It is thread safe to call
* {@link #setExtensionRegistry}, but not to modify the underlying object.
*
* <p>If you need custom parsing behavior for protos, you will need to make your own
* {@code MethodDescriptor.Marhsaller} for the time being.
*
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1787")
public static void setExtensionRegistry(ExtensionRegistryLite newRegistry) {
globalRegistry = checkNotNull(newRegistry, "newRegistry");
}
/** Create a {@code Marshaller} for protos of the same type as {@code defaultInstance}. */
public static <T extends MessageLite> Marshaller<T> marshaller(final T defaultInstance) {
@SuppressWarnings("unchecked")
final Parser<T> parser = (Parser<T>) defaultInstance.getParserForType();
// TODO(ejona): consider changing return type to PrototypeMarshaller (assuming ABI safe)
return new PrototypeMarshaller<T>() {
@SuppressWarnings("unchecked")
@Override
public Class<T> getMessageClass() {
// Precisely T since protobuf doesn't let messages extend other messages.
return (Class<T>) defaultInstance.getClass();
}
@Override
public T getMessagePrototype() {
return defaultInstance;
}
@Override
public InputStream stream(T value) {
return new ProtoInputStream(value, parser);
}
@Override
public T parse(InputStream stream) {
if (stream instanceof ProtoInputStream) {
ProtoInputStream protoStream = (ProtoInputStream) stream;
// Optimization for in-memory transport. Returning provided object is safe since protobufs
// are immutable.
//
// However, we can't assume the types match, so we have to verify the parser matches.
// Today the parser is always the same for a given proto, but that isn't guaranteed. Even
// if not, using the same MethodDescriptor would ensure the parser matches and permit us
// to enable this optimization.
if (protoStream.parser() == parser) {
try {
@SuppressWarnings("unchecked")
T message = (T) ((ProtoInputStream) stream).message();
return message;
} catch (IllegalStateException ex) {
// Stream must have been read from, which is a strange state. Since the point of this
// optimization is to be transparent, instead of throwing an error we'll continue,
// even though it seems likely there's a bug.
}
}
}
CodedInputStream cis = null;
try {
if (stream instanceof KnownLength) {
int size = stream.available();
if (size > 0 && size <= GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE) {
byte[] buf = new byte[size];
int chunkSize;
int position = 0;
while ((chunkSize = stream.read(buf, position, buf.length - position)) != -1) {
position += chunkSize;
}
if (buf.length != position) {
throw new RuntimeException("size inaccurate: " + buf.length + " != " + position);
}
cis = CodedInputStream.newInstance(buf);
} else if (size == 0) {
return defaultInstance;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
if (cis == null) {
cis = CodedInputStream.newInstance(stream);
}
// Pre-create the CodedInputStream so that we can remove the size limit restriction
// when parsing.
cis.setSizeLimit(Integer.MAX_VALUE);
try {
return parseFrom(cis);
} catch (InvalidProtocolBufferException ipbe) {
throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence")
.withCause(ipbe).asRuntimeException();
}
}
private T parseFrom(CodedInputStream stream) throws InvalidProtocolBufferException {
T message = parser.parseFrom(stream, globalRegistry);
try {
stream.checkLastTagWas(0);
return message;
} catch (InvalidProtocolBufferException e) {
e.setUnfinishedMessage(message);
throw e;
}
}
};
}
/**
* Produce a metadata marshaller for a protobuf type.
*/
public static <T extends MessageLite> Metadata.BinaryMarshaller<T> metadataMarshaller(
final T instance) {
return new Metadata.BinaryMarshaller<T>() {
@Override
public byte[] toBytes(T value) {
return value.toByteArray();
}
@Override
@SuppressWarnings("unchecked")
public T parseBytes(byte[] serialized) {
try {
return (T) instance.getParserForType().parseFrom(serialized, globalRegistry);
} catch (InvalidProtocolBufferException ipbe) {
throw new IllegalArgumentException(ipbe);
}
}
};
}
private ProtoLiteUtils() {
}
}
| protobuf-lite/src/main/java/io/grpc/protobuf/lite/ProtoLiteUtils.java | /*
* Copyright 2014, Google Inc. 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 Google Inc. 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 io.grpc.protobuf.lite;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.ExtensionRegistryLite;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import com.google.protobuf.Parser;
import io.grpc.ExperimentalApi;
import io.grpc.KnownLength;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor.Marshaller;
import io.grpc.MethodDescriptor.PrototypeMarshaller;
import io.grpc.Status;
import io.grpc.internal.GrpcUtil;
import java.io.IOException;
import java.io.InputStream;
/**
* Utility methods for using protobuf with grpc.
*/
@ExperimentalApi("Experimental until Lite is stable in protobuf")
public class ProtoLiteUtils {
private static volatile ExtensionRegistryLite globalRegistry =
ExtensionRegistryLite.getEmptyRegistry();
/**
* Sets the global registry for proto marshalling shared across all servers and clients.
*
* <p>Warning: This API will likely change over time. It is not possible to have separate
* registries per Process, Server, Channel, Service, or Method. This is intentional until there
* is a more appropriate API to set them.
*
* <p>Warning: Do NOT modify the extension registry after setting it. It is thread safe to call
* {@link #setExtensionRegistry}, but not to modify the underlying object.
*
* <p>If you need custom parsing behavior for protos, you will need to make your own
* {@code MethodDescriptor.Marhsaller} for the time being.
*
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1787")
public static void setExtensionRegistry(ExtensionRegistryLite newRegistry) {
globalRegistry = checkNotNull(newRegistry, "newRegistry");
}
/** Create a {@code Marshaller} for protos of the same type as {@code defaultInstance}. */
public static <T extends MessageLite> Marshaller<T> marshaller(final T defaultInstance) {
@SuppressWarnings("unchecked")
final Parser<T> parser = (Parser<T>) defaultInstance.getParserForType();
// TODO(ejona): consider changing return type to PrototypeMarshaller (assuming ABI safe)
return new PrototypeMarshaller<T>() {
@SuppressWarnings("unchecked")
@Override
public Class<T> getMessageClass() {
// Precisely T since protobuf doesn't let messages extend other messages.
return (Class<T>) defaultInstance.getClass();
}
@Override
public T getMessagePrototype() {
return defaultInstance;
}
@Override
public InputStream stream(T value) {
return new ProtoInputStream(value, parser);
}
@Override
public T parse(InputStream stream) {
if (stream instanceof ProtoInputStream) {
ProtoInputStream protoStream = (ProtoInputStream) stream;
// Optimization for in-memory transport. Returning provided object is safe since protobufs
// are immutable.
//
// However, we can't assume the types match, so we have to verify the parser matches.
// Today the parser is always the same for a given proto, but that isn't guaranteed. Even
// if not, using the same MethodDescriptor would ensure the parser matches and permit us
// to enable this optimization.
if (protoStream.parser() == parser) {
try {
@SuppressWarnings("unchecked")
T message = (T) ((ProtoInputStream) stream).message();
return message;
} catch (IllegalStateException ex) {
// Stream must have been read from, which is a strange state. Since the point of this
// optimization is to be transparent, instead of throwing an error we'll continue,
// even though it seems likely there's a bug.
}
}
}
CodedInputStream cis = null;
try {
if (stream instanceof KnownLength) {
int size = stream.available();
if (size > 0 && size <= GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE) {
byte[] buf = new byte[size];
int chunkSize;
int position = 0;
while ((chunkSize = stream.read(buf, position, buf.length - position)) != -1) {
position += chunkSize;
}
if (buf.length != position) {
throw new RuntimeException("size inaccurate: " + buf.length + " != " + position);
}
cis = CodedInputStream.newInstance(buf);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
if (cis == null) {
cis = CodedInputStream.newInstance(stream);
}
// Pre-create the CodedInputStream so that we can remove the size limit restriction
// when parsing.
cis.setSizeLimit(Integer.MAX_VALUE);
try {
return parseFrom(cis);
} catch (InvalidProtocolBufferException ipbe) {
throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence")
.withCause(ipbe).asRuntimeException();
}
}
private T parseFrom(CodedInputStream stream) throws InvalidProtocolBufferException {
T message = parser.parseFrom(stream, globalRegistry);
try {
stream.checkLastTagWas(0);
return message;
} catch (InvalidProtocolBufferException e) {
e.setUnfinishedMessage(message);
throw e;
}
}
};
}
/**
* Produce a metadata marshaller for a protobuf type.
*/
public static <T extends MessageLite> Metadata.BinaryMarshaller<T> metadataMarshaller(
final T instance) {
return new Metadata.BinaryMarshaller<T>() {
@Override
public byte[] toBytes(T value) {
return value.toByteArray();
}
@Override
@SuppressWarnings("unchecked")
public T parseBytes(byte[] serialized) {
try {
return (T) instance.getParserForType().parseFrom(serialized, globalRegistry);
} catch (InvalidProtocolBufferException ipbe) {
throw new IllegalArgumentException(ipbe);
}
}
};
}
private ProtoLiteUtils() {
}
}
| protobuf: fast path zero sized messages
| protobuf-lite/src/main/java/io/grpc/protobuf/lite/ProtoLiteUtils.java | protobuf: fast path zero sized messages |
|
Java | apache-2.0 | 970eb071c67ac9626a7c9baa7cad9eb5791cce04 | 0 | hugojosefson/joda-time,hedefalk/joda-time | /*
* Copyright 2001-2007 Stephen Colebourne
*
* 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.joda.time.base;
import java.io.Serializable;
import org.joda.time.Chronology;
import org.joda.time.DateTimeUtils;
import org.joda.time.Duration;
import org.joda.time.DurationFieldType;
import org.joda.time.MutablePeriod;
import org.joda.time.PeriodType;
import org.joda.time.ReadWritablePeriod;
import org.joda.time.ReadableDuration;
import org.joda.time.ReadableInstant;
import org.joda.time.ReadablePartial;
import org.joda.time.ReadablePeriod;
import org.joda.time.convert.ConverterManager;
import org.joda.time.convert.PeriodConverter;
import org.joda.time.field.FieldUtils;
/**
* BasePeriod is an abstract implementation of ReadablePeriod that stores
* data in a <code>PeriodType</code> and an <code>int[]</code>.
* <p>
* This class should generally not be used directly by API users.
* The {@link ReadablePeriod} interface should be used when different
* kinds of period objects are to be referenced.
* <p>
* BasePeriod subclasses may be mutable and not thread-safe.
*
* @author Brian S O'Neill
* @author Stephen Colebourne
* @since 1.0
*/
public abstract class BasePeriod
extends AbstractPeriod
implements ReadablePeriod, Serializable {
/** Serialization version */
private static final long serialVersionUID = -2110953284060001145L;
/** The type of period */
private PeriodType iType;
/** The values */
private int[] iValues;
//-----------------------------------------------------------------------
/**
* Creates a period from a set of field values.
*
* @param years amount of years in this period, which must be zero if unsupported
* @param months amount of months in this period, which must be zero if unsupported
* @param weeks amount of weeks in this period, which must be zero if unsupported
* @param days amount of days in this period, which must be zero if unsupported
* @param hours amount of hours in this period, which must be zero if unsupported
* @param minutes amount of minutes in this period, which must be zero if unsupported
* @param seconds amount of seconds in this period, which must be zero if unsupported
* @param millis amount of milliseconds in this period, which must be zero if unsupported
* @param type which set of fields this period supports
* @throws IllegalArgumentException if period type is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(int years, int months, int weeks, int days,
int hours, int minutes, int seconds, int millis,
PeriodType type) {
super();
type = checkPeriodType(type);
iType = type;
setPeriodInternal(years, months, weeks, days, hours, minutes, seconds, millis); // internal method
}
/**
* Creates a period from the given interval endpoints.
*
* @param startInstant interval start, in milliseconds
* @param endInstant interval end, in milliseconds
* @param type which set of fields this period supports, null means standard
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(long startInstant, long endInstant, PeriodType type, Chronology chrono) {
super();
type = checkPeriodType(type);
chrono = DateTimeUtils.getChronology(chrono);
iType = type;
iValues = chrono.get(this, startInstant, endInstant);
}
/**
* Creates a period from the given interval endpoints.
*
* @param startInstant interval start, null means now
* @param endInstant interval end, null means now
* @param type which set of fields this period supports, null means standard
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
if (startInstant == null && endInstant == null) {
iType = type;
iValues = new int[size()];
} else {
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
}
/**
* Creates a period from the given duration and end point.
* <p>
* The two partials must contain the same fields, thus you can
* specify two <code>LocalDate</code> objects, or two <code>LocalTime</code>
* objects, but not one of each.
* As these are Partial objects, time zones have no effect on the result.
* <p>
* The two partials must also both be contiguous - see
* {@link DateTimeUtils#isContiguous(ReadablePartial)} for a
* definition. Both <code>LocalDate</code> and <code>LocalTime</code> are contiguous.
*
* @param start the start of the period, must not be null
* @param end the end of the period, must not be null
* @param type which set of fields this period supports, null means standard
* @throws IllegalArgumentException if the partials are null or invalid
* @since 1.1
*/
protected BasePeriod(ReadablePartial start, ReadablePartial end, PeriodType type) {
super();
if (start == null || end == null) {
throw new IllegalArgumentException("ReadablePartial objects must not be null");
}
if (start instanceof BaseLocal && end instanceof BaseLocal && start.getClass() == end.getClass()) {
// for performance
type = checkPeriodType(type);
long startMillis = ((BaseLocal) start).getLocalMillis();
long endMillis = ((BaseLocal) end).getLocalMillis();
Chronology chrono = start.getChronology();
chrono = DateTimeUtils.getChronology(chrono);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
} else {
if (start.size() != end.size()) {
throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields");
}
for (int i = 0, isize = start.size(); i < isize; i++) {
if (start.getFieldType(i) != end.getFieldType(i)) {
throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields");
}
}
if (DateTimeUtils.isContiguous(start) == false) {
throw new IllegalArgumentException("ReadablePartial objects must be contiguous");
}
iType = checkPeriodType(type);
Chronology chrono = DateTimeUtils.getChronology(start.getChronology()).withUTC();
iValues = chrono.get(this, chrono.set(start, 0L), chrono.set(end, 0L));
}
}
/**
* Creates a period from the given start point and duration.
*
* @param startInstant the interval start, null means now
* @param duration the duration of the interval, null means zero-length
* @param type which set of fields this period supports, null means standard
*/
protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) {
super();
type = checkPeriodType(type);
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
long endMillis = FieldUtils.safeAdd(startMillis, durationMillis);
Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
/**
* Creates a period from the given duration and end point.
*
* @param duration the duration of the interval, null means zero-length
* @param endInstant the interval end, null means now
* @param type which set of fields this period supports, null means standard
*/
protected BasePeriod(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
long startMillis = FieldUtils.safeSubtract(endMillis, durationMillis);
Chronology chrono = DateTimeUtils.getInstantChronology(endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
/**
* Creates a period from the given millisecond duration, which is only really
* suitable for durations less than one day.
* <p>
* Only fields that are precise will be used.
* Thus the largest precise field may have a large value.
*
* @param duration the duration, in milliseconds
* @param type which set of fields this period supports, null means standard
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(long duration, PeriodType type, Chronology chrono) {
super();
type = checkPeriodType(type);
chrono = DateTimeUtils.getChronology(chrono);
iType = type;
iValues = chrono.get(this, duration);
}
/**
* Creates a new period based on another using the {@link ConverterManager}.
*
* @param period the period to convert
* @param type which set of fields this period supports, null means use type from object
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
super();
PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
type = (type == null ? converter.getPeriodType(period) : type);
type = checkPeriodType(type);
iType = type;
if (this instanceof ReadWritablePeriod) {
iValues = new int[size()];
chrono = DateTimeUtils.getChronology(chrono);
converter.setInto((ReadWritablePeriod) this, period, chrono);
} else {
iValues = new MutablePeriod(period, type, chrono).getValues();
}
}
/**
* Constructor used when we trust ourselves.
* Do not expose publically.
*
* @param values the values to use, not null, not cloned
* @param type which set of fields this period supports, not null
*/
protected BasePeriod(int[] values, PeriodType type) {
super();
iType = type;
iValues = values;
}
//-----------------------------------------------------------------------
/**
* Validates a period type, converting nulls to a default value and
* checking the type is suitable for this instance.
*
* @param type the type to check, may be null
* @return the validated type to use, not null
* @throws IllegalArgumentException if the period type is invalid
*/
protected PeriodType checkPeriodType(PeriodType type) {
return DateTimeUtils.getPeriodType(type);
}
//-----------------------------------------------------------------------
/**
* Gets the period type.
*
* @return the period type
*/
public PeriodType getPeriodType() {
return iType;
}
//-----------------------------------------------------------------------
/**
* Gets the number of fields that this period supports.
*
* @return the number of fields supported
*/
public int size() {
return iType.size();
}
/**
* Gets the field type at the specified index.
*
* @param index the index to retrieve
* @return the field at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
public DurationFieldType getFieldType(int index) {
return iType.getFieldType(index);
}
/**
* Gets the value at the specified index.
*
* @param index the index to retrieve
* @return the value of the field at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
public int getValue(int index) {
return iValues[index];
}
//-----------------------------------------------------------------------
/**
* Gets the total millisecond duration of this period relative to a start instant.
* <p>
* This method adds the period to the specified instant in order to
* calculate the duration.
* <p>
* An instant must be supplied as the duration of a period varies.
* For example, a period of 1 month could vary between the equivalent of
* 28 and 31 days in milliseconds due to different length months.
* Similarly, a day can vary at Daylight Savings cutover, typically between
* 23 and 25 hours.
*
* @param startInstant the instant to add the period to, thus obtaining the duration
* @return the total length of the period as a duration relative to the start instant
* @throws ArithmeticException if the millis exceeds the capacity of the duration
*/
public Duration toDurationFrom(ReadableInstant startInstant) {
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
long endMillis = chrono.add(this, startMillis, 1);
return new Duration(startMillis, endMillis);
}
/**
* Gets the total millisecond duration of this period relative to an
* end instant.
* <p>
* This method subtracts the period from the specified instant in order
* to calculate the duration.
* <p>
* An instant must be supplied as the duration of a period varies.
* For example, a period of 1 month could vary between the equivalent of
* 28 and 31 days in milliseconds due to different length months.
* Similarly, a day can vary at Daylight Savings cutover, typically between
* 23 and 25 hours.
*
* @param endInstant the instant to subtract the period from, thus obtaining the duration
* @return the total length of the period as a duration relative to the end instant
* @throws ArithmeticException if the millis exceeds the capacity of the duration
*/
public Duration toDurationTo(ReadableInstant endInstant) {
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
Chronology chrono = DateTimeUtils.getInstantChronology(endInstant);
long startMillis = chrono.add(this, endMillis, -1);
return new Duration(startMillis, endMillis);
}
//-----------------------------------------------------------------------
/**
* Checks whether a field type is supported, and if so adds the new value
* to the relevent index in the specified array.
*
* @param type the field type
* @param values the array to update
* @param newValue the new value to store if successful
*/
private void checkAndUpdate(DurationFieldType type, int[] values, int newValue) {
int index = indexOf(type);
if (index == -1) {
if (newValue != 0) {
throw new IllegalArgumentException(
"Period does not support field '" + type.getName() + "'");
}
} else {
values[index] = newValue;
}
}
//-----------------------------------------------------------------------
/**
* Sets all the fields of this period from another.
*
* @param period the period to copy from, not null
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected void setPeriod(ReadablePeriod period) {
if (period == null) {
setValues(new int[size()]);
} else {
setPeriodInternal(period);
}
}
/**
* Private method called from constructor.
*/
private void setPeriodInternal(ReadablePeriod period) {
int[] newValues = new int[size()];
for (int i = 0, isize = period.size(); i < isize; i++) {
DurationFieldType type = period.getFieldType(i);
int value = period.getValue(i);
checkAndUpdate(type, newValues, value);
}
iValues = newValues;
}
/**
* Sets the eight standard the fields in one go.
*
* @param years amount of years in this period, which must be zero if unsupported
* @param months amount of months in this period, which must be zero if unsupported
* @param weeks amount of weeks in this period, which must be zero if unsupported
* @param days amount of days in this period, which must be zero if unsupported
* @param hours amount of hours in this period, which must be zero if unsupported
* @param minutes amount of minutes in this period, which must be zero if unsupported
* @param seconds amount of seconds in this period, which must be zero if unsupported
* @param millis amount of milliseconds in this period, which must be zero if unsupported
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected void setPeriod(int years, int months, int weeks, int days,
int hours, int minutes, int seconds, int millis) {
setPeriodInternal(years, months, weeks, days, hours, minutes, seconds, millis);
}
/**
* Private method called from constructor.
*/
private void setPeriodInternal(int years, int months, int weeks, int days,
int hours, int minutes, int seconds, int millis) {
int[] newValues = new int[size()];
checkAndUpdate(DurationFieldType.years(), newValues, years);
checkAndUpdate(DurationFieldType.months(), newValues, months);
checkAndUpdate(DurationFieldType.weeks(), newValues, weeks);
checkAndUpdate(DurationFieldType.days(), newValues, days);
checkAndUpdate(DurationFieldType.hours(), newValues, hours);
checkAndUpdate(DurationFieldType.minutes(), newValues, minutes);
checkAndUpdate(DurationFieldType.seconds(), newValues, seconds);
checkAndUpdate(DurationFieldType.millis(), newValues, millis);
iValues = newValues;
}
//-----------------------------------------------------------------------
/**
* Sets the value of a field in this period.
*
* @param field the field to set
* @param value the value to set
* @throws IllegalArgumentException if field is is null or not supported.
*/
protected void setField(DurationFieldType field, int value) {
setFieldInto(iValues, field, value);
}
/**
* Sets the value of a field in this period.
*
* @param values the array of values to update
* @param field the field to set
* @param value the value to set
* @throws IllegalArgumentException if field is null or not supported.
*/
protected void setFieldInto(int[] values, DurationFieldType field, int value) {
int index = indexOf(field);
if (index == -1) {
if (value != 0 || field == null) {
throw new IllegalArgumentException(
"Period does not support field '" + field + "'");
}
} else {
values[index] = value;
}
}
/**
* Adds the value of a field in this period.
*
* @param field the field to set
* @param value the value to set
* @throws IllegalArgumentException if field is is null or not supported.
*/
protected void addField(DurationFieldType field, int value) {
addFieldInto(iValues, field, value);
}
/**
* Adds the value of a field in this period.
*
* @param values the array of values to update
* @param field the field to set
* @param value the value to set
* @throws IllegalArgumentException if field is is null or not supported.
*/
protected void addFieldInto(int[] values, DurationFieldType field, int value) {
int index = indexOf(field);
if (index == -1) {
if (value != 0 || field == null) {
throw new IllegalArgumentException(
"Period does not support field '" + field + "'");
}
} else {
values[index] = FieldUtils.safeAdd(values[index], value);
}
}
/**
* Merges the fields from another period.
*
* @param period the period to add from, not null
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected void mergePeriod(ReadablePeriod period) {
if (period != null) {
iValues = mergePeriodInto(getValues(), period);
}
}
/**
* Merges the fields from another period.
*
* @param values the array of values to update
* @param period the period to add from, not null
* @return the updated values
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected int[] mergePeriodInto(int[] values, ReadablePeriod period) {
for (int i = 0, isize = period.size(); i < isize; i++) {
DurationFieldType type = period.getFieldType(i);
int value = period.getValue(i);
checkAndUpdate(type, values, value);
}
return values;
}
/**
* Adds the fields from another period.
*
* @param period the period to add from, not null
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected void addPeriod(ReadablePeriod period) {
if (period != null) {
iValues = addPeriodInto(getValues(), period);
}
}
/**
* Adds the fields from another period.
*
* @param values the array of values to update
* @param period the period to add from, not null
* @return the updated values
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected int[] addPeriodInto(int[] values, ReadablePeriod period) {
for (int i = 0, isize = period.size(); i < isize; i++) {
DurationFieldType type = period.getFieldType(i);
int value = period.getValue(i);
if (value != 0) {
int index = indexOf(type);
if (index == -1) {
throw new IllegalArgumentException(
"Period does not support field '" + type.getName() + "'");
} else {
values[index] = FieldUtils.safeAdd(getValue(index), value);
}
}
}
return values;
}
//-----------------------------------------------------------------------
/**
* Sets the value of the field at the specifed index.
*
* @param index the index
* @param value the value to set
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected void setValue(int index, int value) {
iValues[index] = value;
}
/**
* Sets the values of all fields.
*
* @param values the array of values
*/
protected void setValues(int[] values) {
iValues = values;
}
}
| src/java/org/joda/time/base/BasePeriod.java | /*
* Copyright 2001-2007 Stephen Colebourne
*
* 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.joda.time.base;
import java.io.Serializable;
import org.joda.time.Chronology;
import org.joda.time.DateTimeUtils;
import org.joda.time.Duration;
import org.joda.time.DurationFieldType;
import org.joda.time.MutablePeriod;
import org.joda.time.PeriodType;
import org.joda.time.ReadWritablePeriod;
import org.joda.time.ReadableDuration;
import org.joda.time.ReadableInstant;
import org.joda.time.ReadablePartial;
import org.joda.time.ReadablePeriod;
import org.joda.time.convert.ConverterManager;
import org.joda.time.convert.PeriodConverter;
import org.joda.time.field.FieldUtils;
/**
* BasePeriod is an abstract implementation of ReadablePeriod that stores
* data in a <code>PeriodType</code> and an <code>int[]</code>.
* <p>
* This class should generally not be used directly by API users.
* The {@link ReadablePeriod} interface should be used when different
* kinds of period objects are to be referenced.
* <p>
* BasePeriod subclasses may be mutable and not thread-safe.
*
* @author Brian S O'Neill
* @author Stephen Colebourne
* @since 1.0
*/
public abstract class BasePeriod
extends AbstractPeriod
implements ReadablePeriod, Serializable {
/** Serialization version */
private static final long serialVersionUID = -2110953284060001145L;
/** The type of period */
private PeriodType iType;
/** The values */
private int[] iValues;
//-----------------------------------------------------------------------
/**
* Creates a period from a set of field values.
*
* @param years amount of years in this period, which must be zero if unsupported
* @param months amount of months in this period, which must be zero if unsupported
* @param weeks amount of weeks in this period, which must be zero if unsupported
* @param days amount of days in this period, which must be zero if unsupported
* @param hours amount of hours in this period, which must be zero if unsupported
* @param minutes amount of minutes in this period, which must be zero if unsupported
* @param seconds amount of seconds in this period, which must be zero if unsupported
* @param millis amount of milliseconds in this period, which must be zero if unsupported
* @param type which set of fields this period supports
* @throws IllegalArgumentException if period type is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(int years, int months, int weeks, int days,
int hours, int minutes, int seconds, int millis,
PeriodType type) {
super();
type = checkPeriodType(type);
iType = type;
setPeriodInternal(years, months, weeks, days, hours, minutes, seconds, millis); // internal method
}
/**
* Creates a period from the given interval endpoints.
*
* @param startInstant interval start, in milliseconds
* @param endInstant interval end, in milliseconds
* @param type which set of fields this period supports, null means standard
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(long startInstant, long endInstant, PeriodType type, Chronology chrono) {
super();
type = checkPeriodType(type);
chrono = DateTimeUtils.getChronology(chrono);
iType = type;
iValues = chrono.get(this, startInstant, endInstant);
}
/**
* Creates a period from the given interval endpoints.
*
* @param startInstant interval start, null means now
* @param endInstant interval end, null means now
* @param type which set of fields this period supports, null means standard
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
if (startInstant == null && endInstant == null) {
iType = type;
iValues = new int[size()];
} else {
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
}
/**
* Creates a period from the given duration and end point.
* <p>
* The two partials must contain the same fields, thus you can
* specify two <code>LocalDate</code> objects, or two <code>LocalTime</code>
* objects, but not one of each.
* As these are Partial objects, time zones have no effect on the result.
* <p>
* The two partials must also both be contiguous - see
* {@link DateTimeUtils#isContiguous(ReadablePartial)} for a
* definition. Both <code>LocalDate</code> and <code>LocalTime</code> are contiguous.
*
* @param start the start of the period, must not be null
* @param end the end of the period, must not be null
* @param type which set of fields this period supports, null means standard
* @throws IllegalArgumentException if the partials are null or invalid
* @since 1.1
*/
protected BasePeriod(ReadablePartial start, ReadablePartial end, PeriodType type) {
super();
if (start == null || end == null) {
throw new IllegalArgumentException("ReadablePartial objects must not be null");
}
if (start instanceof BaseLocal && end instanceof BaseLocal && start.getClass() == end.getClass()) {
// for performance
type = checkPeriodType(type);
long startMillis = ((BaseLocal) start).getLocalMillis();
long endMillis = ((BaseLocal) end).getLocalMillis();
Chronology chrono = start.getChronology();
chrono = DateTimeUtils.getChronology(chrono);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
} else {
if (start.size() != end.size()) {
throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields");
}
for (int i = 0, isize = start.size(); i < isize; i++) {
if (start.getFieldType(i) != end.getFieldType(i)) {
throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields");
}
}
if (DateTimeUtils.isContiguous(start) == false) {
throw new IllegalArgumentException("ReadablePartial objects must be contiguous");
}
iType = checkPeriodType(type);
Chronology chrono = DateTimeUtils.getChronology(start.getChronology()).withUTC();
iValues = chrono.get(this, chrono.set(start, 0L), chrono.set(end, 0L));
}
}
/**
* Creates a period from the given start point and duration.
*
* @param startInstant the interval start, null means now
* @param duration the duration of the interval, null means zero-length
* @param type which set of fields this period supports, null means standard
*/
protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) {
super();
type = checkPeriodType(type);
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
long endMillis = FieldUtils.safeAdd(startMillis, durationMillis);
Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
/**
* Creates a period from the given duration and end point.
*
* @param duration the duration of the interval, null means zero-length
* @param endInstant the interval end, null means now
* @param type which set of fields this period supports, null means standard
*/
protected BasePeriod(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
long startMillis = FieldUtils.safeSubtract(endMillis, durationMillis);
Chronology chrono = DateTimeUtils.getInstantChronology(endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
/**
* Creates a period from the given millisecond duration, which is only really
* suitable for durations less than one day.
* <p>
* Only fields that are precise will be used.
* Thus the largest precise field may have a large value.
*
* @param duration the duration, in milliseconds
* @param type which set of fields this period supports, null means standard
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(long duration, PeriodType type, Chronology chrono) {
super();
type = checkPeriodType(type);
chrono = DateTimeUtils.getChronology(chrono);
iType = type;
iValues = chrono.get(this, duration);
}
/**
* Creates a new period based on another using the {@link ConverterManager}.
*
* @param period the period to convert
* @param type which set of fields this period supports, null means use type from object
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
super();
PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
type = (type == null ? converter.getPeriodType(period) : type);
type = checkPeriodType(type);
iType = type;
if (this instanceof ReadWritablePeriod) {
iValues = new int[size()];
chrono = DateTimeUtils.getChronology(chrono);
converter.setInto((ReadWritablePeriod) this, period, chrono);
} else {
iValues = new MutablePeriod(period, type, chrono).getValues();
}
}
/**
* Constructor used when we trust ourselves.
* Do not expose publically.
*
* @param values the values to use, not null, not cloned
* @param type which set of fields this period supports, not null
*/
protected BasePeriod(int[] values, PeriodType type) {
super();
iType = type;
iValues = values;
}
//-----------------------------------------------------------------------
/**
* Validates a period type, converting nulls to a default value and
* checking the type is suitable for this instance.
*
* @param type the type to check, may be null
* @return the validated type to use, not null
* @throws IllegalArgumentException if the period type is invalid
*/
protected PeriodType checkPeriodType(PeriodType type) {
return DateTimeUtils.getPeriodType(type);
}
//-----------------------------------------------------------------------
/**
* Gets the period type.
*
* @return the period type
*/
public PeriodType getPeriodType() {
return iType;
}
//-----------------------------------------------------------------------
/**
* Gets the number of fields that this period supports.
*
* @return the number of fields supported
*/
public int size() {
return iType.size();
}
/**
* Gets the field type at the specified index.
*
* @param index the index to retrieve
* @return the field at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
public DurationFieldType getFieldType(int index) {
return iType.getFieldType(index);
}
/**
* Gets the value at the specified index.
*
* @param index the index to retrieve
* @return the value of the field at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
public int getValue(int index) {
return iValues[index];
}
//-----------------------------------------------------------------------
/**
* Gets the total millisecond duration of this period relative to a start instant.
* <p>
* This method adds the period to the specifed instant in order to
* calculate the duration.
* <p>
* An instant must be supplied as the duration of a period varies.
* For example, a period of 1 month could vary between the equivalent of
* 28 and 31 days in milliseconds due to different length months.
* Similarly, a day can vary at Daylight Savings cutover, typically between
* 23 and 25 hours.
*
* @param startInstant the instant to add the period to, thus obtaining the duration
* @return the total length of the period as a duration relative to the start instant
* @throws ArithmeticException if the millis exceeds the capacity of the duration
*/
public Duration toDurationFrom(ReadableInstant startInstant) {
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
long endMillis = chrono.add(this, startMillis, 1);
return new Duration(startMillis, endMillis);
}
/**
* Gets the total millisecond duration of this period relative to an
* end instant.
* <p>
* This method subtracts the period from the specified instant in order
* to calculate the duration.
* <p>
* An instant must be supplied as the duration of a period varies.
* For example, a period of 1 month could vary between the equivalent of
* 28 and 31 days in milliseconds due to different length months.
* Similarly, a day can vary at Daylight Savings cutover, typically between
* 23 and 25 hours.
*
* @param endInstant the instant to subtract the period from, thus obtaining the duration
* @return the total length of the period as a duration relative to the end instant
* @throws ArithmeticException if the millis exceeds the capacity of the duration
*/
public Duration toDurationTo(ReadableInstant endInstant) {
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
Chronology chrono = DateTimeUtils.getInstantChronology(endInstant);
long startMillis = chrono.add(this, endMillis, -1);
return new Duration(startMillis, endMillis);
}
//-----------------------------------------------------------------------
/**
* Checks whether a field type is supported, and if so adds the new value
* to the relevent index in the specified array.
*
* @param type the field type
* @param values the array to update
* @param newValue the new value to store if successful
*/
private void checkAndUpdate(DurationFieldType type, int[] values, int newValue) {
int index = indexOf(type);
if (index == -1) {
if (newValue != 0) {
throw new IllegalArgumentException(
"Period does not support field '" + type.getName() + "'");
}
} else {
values[index] = newValue;
}
}
//-----------------------------------------------------------------------
/**
* Sets all the fields of this period from another.
*
* @param period the period to copy from, not null
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected void setPeriod(ReadablePeriod period) {
if (period == null) {
setValues(new int[size()]);
} else {
setPeriodInternal(period);
}
}
/**
* Private method called from constructor.
*/
private void setPeriodInternal(ReadablePeriod period) {
int[] newValues = new int[size()];
for (int i = 0, isize = period.size(); i < isize; i++) {
DurationFieldType type = period.getFieldType(i);
int value = period.getValue(i);
checkAndUpdate(type, newValues, value);
}
iValues = newValues;
}
/**
* Sets the eight standard the fields in one go.
*
* @param years amount of years in this period, which must be zero if unsupported
* @param months amount of months in this period, which must be zero if unsupported
* @param weeks amount of weeks in this period, which must be zero if unsupported
* @param days amount of days in this period, which must be zero if unsupported
* @param hours amount of hours in this period, which must be zero if unsupported
* @param minutes amount of minutes in this period, which must be zero if unsupported
* @param seconds amount of seconds in this period, which must be zero if unsupported
* @param millis amount of milliseconds in this period, which must be zero if unsupported
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected void setPeriod(int years, int months, int weeks, int days,
int hours, int minutes, int seconds, int millis) {
setPeriodInternal(years, months, weeks, days, hours, minutes, seconds, millis);
}
/**
* Private method called from constructor.
*/
private void setPeriodInternal(int years, int months, int weeks, int days,
int hours, int minutes, int seconds, int millis) {
int[] newValues = new int[size()];
checkAndUpdate(DurationFieldType.years(), newValues, years);
checkAndUpdate(DurationFieldType.months(), newValues, months);
checkAndUpdate(DurationFieldType.weeks(), newValues, weeks);
checkAndUpdate(DurationFieldType.days(), newValues, days);
checkAndUpdate(DurationFieldType.hours(), newValues, hours);
checkAndUpdate(DurationFieldType.minutes(), newValues, minutes);
checkAndUpdate(DurationFieldType.seconds(), newValues, seconds);
checkAndUpdate(DurationFieldType.millis(), newValues, millis);
iValues = newValues;
}
//-----------------------------------------------------------------------
/**
* Sets the value of a field in this period.
*
* @param field the field to set
* @param value the value to set
* @throws IllegalArgumentException if field is is null or not supported.
*/
protected void setField(DurationFieldType field, int value) {
setFieldInto(iValues, field, value);
}
/**
* Sets the value of a field in this period.
*
* @param values the array of values to update
* @param field the field to set
* @param value the value to set
* @throws IllegalArgumentException if field is null or not supported.
*/
protected void setFieldInto(int[] values, DurationFieldType field, int value) {
int index = indexOf(field);
if (index == -1) {
if (value != 0 || field == null) {
throw new IllegalArgumentException(
"Period does not support field '" + field + "'");
}
} else {
values[index] = value;
}
}
/**
* Adds the value of a field in this period.
*
* @param field the field to set
* @param value the value to set
* @throws IllegalArgumentException if field is is null or not supported.
*/
protected void addField(DurationFieldType field, int value) {
addFieldInto(iValues, field, value);
}
/**
* Adds the value of a field in this period.
*
* @param values the array of values to update
* @param field the field to set
* @param value the value to set
* @throws IllegalArgumentException if field is is null or not supported.
*/
protected void addFieldInto(int[] values, DurationFieldType field, int value) {
int index = indexOf(field);
if (index == -1) {
if (value != 0 || field == null) {
throw new IllegalArgumentException(
"Period does not support field '" + field + "'");
}
} else {
values[index] = FieldUtils.safeAdd(values[index], value);
}
}
/**
* Merges the fields from another period.
*
* @param period the period to add from, not null
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected void mergePeriod(ReadablePeriod period) {
if (period != null) {
iValues = mergePeriodInto(getValues(), period);
}
}
/**
* Merges the fields from another period.
*
* @param values the array of values to update
* @param period the period to add from, not null
* @return the updated values
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected int[] mergePeriodInto(int[] values, ReadablePeriod period) {
for (int i = 0, isize = period.size(); i < isize; i++) {
DurationFieldType type = period.getFieldType(i);
int value = period.getValue(i);
checkAndUpdate(type, values, value);
}
return values;
}
/**
* Adds the fields from another period.
*
* @param period the period to add from, not null
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected void addPeriod(ReadablePeriod period) {
if (period != null) {
iValues = addPeriodInto(getValues(), period);
}
}
/**
* Adds the fields from another period.
*
* @param values the array of values to update
* @param period the period to add from, not null
* @return the updated values
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected int[] addPeriodInto(int[] values, ReadablePeriod period) {
for (int i = 0, isize = period.size(); i < isize; i++) {
DurationFieldType type = period.getFieldType(i);
int value = period.getValue(i);
if (value != 0) {
int index = indexOf(type);
if (index == -1) {
throw new IllegalArgumentException(
"Period does not support field '" + type.getName() + "'");
} else {
values[index] = FieldUtils.safeAdd(getValue(index), value);
}
}
}
return values;
}
//-----------------------------------------------------------------------
/**
* Sets the value of the field at the specifed index.
*
* @param index the index
* @param value the value to set
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected void setValue(int index, int value) {
iValues[index] = value;
}
/**
* Sets the values of all fields.
*
* @param values the array of values
*/
protected void setValues(int[] values) {
iValues = values;
}
}
| Fix spelling
git-svn-id: 73f3b8c70a47e7dda158ff80e9f8be635a78c1e8@1236 1e1cfbb7-5c0e-0410-a2f0-f98d92ec03a1
| src/java/org/joda/time/base/BasePeriod.java | Fix spelling |
|
Java | apache-2.0 | e3501fdafc13f30bb9d0bb243a57ed19e4ce70e8 | 0 | getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern,getlantern/lantern-java,lqch14102/lantern,getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern | package org.lantern;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.littleshoot.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Configures Lantern. This can be either on the first run of the application
* or through the user changing his or her configurations in the configuration
* screen.
*/
public class Configurator {
private final Logger log = LoggerFactory.getLogger(getClass());
public void configure() {
final File home = new File(System.getProperty("user.home"), ".lantern");
if (!home.isDirectory()) {
if (!home.mkdir()) {
log.error("Could not make lantern directory?");
}
}
final File props = new File(home, "lantern.properties");
if (!props.isFile()) {
System.out.println("PLEASE ENTER YOUR GOOGLE ACCOUNT DATA IN " + props+
"in the following form:" +
"\[email protected]\ngoogle.pwd=your_password");
try {
props.createNewFile();
} catch (IOException e) {
log.error("Could not create file?", e);
}
}
final File git = new File(".git");
if (git.isDirectory()) {
log.info("Running from repository...not auto-configuring proxy.");
return;
}
log.info("Auto-configuring proxy...");
// We only want to configure the proxy if the user is in censored mode.
if (SystemUtils.IS_OS_MAC_OSX) {
configureOsxProxy();
} else if (SystemUtils.IS_OS_WINDOWS) {
configureWindowsProxy();
// The firewall config is actually handled in a bat file from the
// installer.
//configureWindowsFirewall();
}
}
private void configureWindowsFirewall() {
final boolean oldNetSh;
if (SystemUtils.IS_OS_WINDOWS_2000 ||
SystemUtils.IS_OS_WINDOWS_XP) {
oldNetSh = true;
}
else {
oldNetSh = false;
}
if (oldNetSh) {
final String[] commands = {
"netsh", "firewall", "add", "allowedprogram",
"\""+SystemUtils.getUserDir()+"/Lantern.exe\"", "\"Lantern\"",
"ENABLE"
};
CommonUtils.nativeCall(commands);
} else {
final String[] commands = {
"netsh", "advfirewall", "firewall", "add", "rule",
"name=\"Lantern\"", "dir=in", "action=allow",
"program=\""+SystemUtils.getUserDir()+"/Lantern.exe\"",
"enable=yes", "profile=any"
};
CommonUtils.nativeCall(commands);
}
}
private void configureOsxProxy() {
CommonUtils.nativeCall("networksetup -setwebproxy Airport 127.0.0.1 " +
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT);
CommonUtils.nativeCall("networksetup -setwebproxy Ethernet 127.0.0.1 " +
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT);
// Also set it for HTTPS!!
CommonUtils.nativeCall("networksetup -setsecurewebproxy Airport 127.0.0.1 " +
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT);
CommonUtils.nativeCall("networksetup -setsecurewebproxy Ethernet 127.0.0.1 " +
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT);
final Thread hook = new Thread(new Runnable() {
public void run() {
CommonUtils.nativeCall("networksetup -setwebproxystate Airport off");
CommonUtils.nativeCall("networksetup -setwebproxystate Ethernet off");
CommonUtils.nativeCall("networksetup -setsecurewebproxystate Airport off");
CommonUtils.nativeCall("networksetup -setsecurewebproxystate Ethernet off");
}
}, "Unset-Web-Proxy-OSX");
Runtime.getRuntime().addShutdownHook(hook);
}
private void configureWindowsProxy() {
if (!SystemUtils.IS_OS_WINDOWS) {
log.info("Not running on Windows");
return;
}
final String key =
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\" +
"Internet Settings";
final String ps = "ProxyServer";
final String pe = "ProxyEnable";
// We first want to read the start values so we can return the
// registry to the original state when we shut down.
final String proxyServerOriginal = WindowsRegistry.read(key, ps);
final String proxyEnableOriginal = WindowsRegistry.read(key, pe);
final String proxyServerUs = "127.0.0.1:"+
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT;
final String proxyEnableUs = "1";
log.info("Setting registry to use MG as a proxy...");
final int enableResult =
WindowsRegistry.writeREG_SZ(key, ps, proxyServerUs);
final int serverResult =
WindowsRegistry.writeREG_DWORD(key, pe, proxyEnableUs);
if (enableResult != 0) {
log.error("Error enabling the proxy server? Result: "+enableResult);
}
if (serverResult != 0) {
log.error("Error setting proxy server? Result: "+serverResult);
}
copyFirefoxConfig();
final Runnable runner = new Runnable() {
public void run() {
log.info("Resetting Windows registry settings to " +
"original values.");
// On shutdown, we need to check if the user has modified the
// registry since we originally set it. If they have, we want
// to keep their setting. If not, we want to revert back to
// before MG started.
final String proxyServer = WindowsRegistry.read(key, ps);
final String proxyEnable = WindowsRegistry.read(key, pe);
//LOG.info("Proxy enable original: '{}'", proxyEnableUs);
//LOG.info("Proxy enable now: '{}'", proxyEnable);
if (proxyEnable.equals(proxyEnableUs)) {
log.info("Setting proxy enable back to: {}",
proxyEnableOriginal);
WindowsRegistry.writeREG_DWORD(key, pe,proxyEnableOriginal);
log.info("Successfully reset proxy enable");
}
if (proxyServer.equals(proxyServerUs)) {
log.info("Setting proxy server back to: {}",
proxyServerOriginal);
WindowsRegistry.writeREG_SZ(key, ps, proxyServerOriginal);
log.info("Successfully reset proxy server");
}
log.info("Done resetting the Windows registry");
}
};
// We don't make this a daemon thread because we want to make sure it
// executes before shutdown.
Runtime.getRuntime().addShutdownHook(new Thread (runner));
}
/**
* Installs the FireFox config file on startup. Public for testing.
*/
private void copyFirefoxConfig() {
final File ff =
new File(System.getenv("ProgramFiles"), "Mozilla Firefox");
final File pref = new File(new File(ff, "defaults"), "pref");
log.info("Prefs dir: {}", pref);
if (!pref.isDirectory()) {
log.error("No directory at: {}", pref);
}
final File config = new File("all-bravenewsoftware.js");
if (!config.isFile()) {
log.error("NO CONFIG FILE AT {}", config);
}
else {
try {
FileUtils.copyFileToDirectory(config, pref);
final File installedConfig = new File(pref, config.getName());
installedConfig.deleteOnExit();
} catch (final IOException e) {
log.error("Could not copy config file?", e);
}
}
}
}
| src/main/java/org/lantern/Configurator.java | package org.lantern;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.littleshoot.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Configures Lantern. This can be either on the first run of the application
* or through the user changing his or her configurations in the configuration
* screen.
*/
public class Configurator {
private final Logger log = LoggerFactory.getLogger(getClass());
public void configure() {
final File git = new File(".git");
if (git.isDirectory()) {
log.info("Running from repository...not auto-configuring proxy.");
return;
}
log.info("Auto-configuring proxy...");
// We only want to configure the proxy if the user is in censored mode.
if (SystemUtils.IS_OS_MAC_OSX) {
configureOsxProxy();
} else if (SystemUtils.IS_OS_WINDOWS) {
configureWindowsProxy();
// The firewall config is actually handled in a bat file from the
// installer.
//configureWindowsFirewall();
}
}
private void configureWindowsFirewall() {
final boolean oldNetSh;
if (SystemUtils.IS_OS_WINDOWS_2000 ||
SystemUtils.IS_OS_WINDOWS_XP) {
oldNetSh = true;
}
else {
oldNetSh = false;
}
if (oldNetSh) {
final String[] commands = {
"netsh", "firewall", "add", "allowedprogram",
"\""+SystemUtils.getUserDir()+"/Lantern.exe\"", "\"Lantern\"",
"ENABLE"
};
CommonUtils.nativeCall(commands);
} else {
final String[] commands = {
"netsh", "advfirewall", "firewall", "add", "rule",
"name=\"Lantern\"", "dir=in", "action=allow",
"program=\""+SystemUtils.getUserDir()+"/Lantern.exe\"",
"enable=yes", "profile=any"
};
CommonUtils.nativeCall(commands);
}
}
private void configureOsxProxy() {
CommonUtils.nativeCall("networksetup -setwebproxy Airport 127.0.0.1 " +
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT);
CommonUtils.nativeCall("networksetup -setwebproxy Ethernet 127.0.0.1 " +
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT);
// Also set it for HTTPS!!
CommonUtils.nativeCall("networksetup -setsecurewebproxy Airport 127.0.0.1 " +
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT);
CommonUtils.nativeCall("networksetup -setsecurewebproxy Ethernet 127.0.0.1 " +
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT);
final Thread hook = new Thread(new Runnable() {
public void run() {
CommonUtils.nativeCall("networksetup -setwebproxystate Airport off");
CommonUtils.nativeCall("networksetup -setwebproxystate Ethernet off");
CommonUtils.nativeCall("networksetup -setsecurewebproxystate Airport off");
CommonUtils.nativeCall("networksetup -setsecurewebproxystate Ethernet off");
}
}, "Unset-Web-Proxy-OSX");
Runtime.getRuntime().addShutdownHook(hook);
}
private void configureWindowsProxy() {
if (!SystemUtils.IS_OS_WINDOWS) {
log.info("Not running on Windows");
return;
}
final String key =
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\" +
"Internet Settings";
final String ps = "ProxyServer";
final String pe = "ProxyEnable";
// We first want to read the start values so we can return the
// registry to the original state when we shut down.
final String proxyServerOriginal = WindowsRegistry.read(key, ps);
final String proxyEnableOriginal = WindowsRegistry.read(key, pe);
final String proxyServerUs = "127.0.0.1:"+
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT;
final String proxyEnableUs = "1";
log.info("Setting registry to use MG as a proxy...");
final int enableResult =
WindowsRegistry.writeREG_SZ(key, ps, proxyServerUs);
final int serverResult =
WindowsRegistry.writeREG_DWORD(key, pe, proxyEnableUs);
if (enableResult != 0) {
log.error("Error enabling the proxy server? Result: "+enableResult);
}
if (serverResult != 0) {
log.error("Error setting proxy server? Result: "+serverResult);
}
copyFirefoxConfig();
final Runnable runner = new Runnable() {
public void run() {
log.info("Resetting Windows registry settings to " +
"original values.");
// On shutdown, we need to check if the user has modified the
// registry since we originally set it. If they have, we want
// to keep their setting. If not, we want to revert back to
// before MG started.
final String proxyServer = WindowsRegistry.read(key, ps);
final String proxyEnable = WindowsRegistry.read(key, pe);
//LOG.info("Proxy enable original: '{}'", proxyEnableUs);
//LOG.info("Proxy enable now: '{}'", proxyEnable);
if (proxyEnable.equals(proxyEnableUs)) {
log.info("Setting proxy enable back to: {}",
proxyEnableOriginal);
WindowsRegistry.writeREG_DWORD(key, pe,proxyEnableOriginal);
log.info("Successfully reset proxy enable");
}
if (proxyServer.equals(proxyServerUs)) {
log.info("Setting proxy server back to: {}",
proxyServerOriginal);
WindowsRegistry.writeREG_SZ(key, ps, proxyServerOriginal);
log.info("Successfully reset proxy server");
}
log.info("Done resetting the Windows registry");
}
};
// We don't make this a daemon thread because we want to make sure it
// executes before shutdown.
Runtime.getRuntime().addShutdownHook(new Thread (runner));
}
/**
* Installs the FireFox config file on startup. Public for testing.
*/
private void copyFirefoxConfig() {
final File ff =
new File(System.getenv("ProgramFiles"), "Mozilla Firefox");
final File pref = new File(new File(ff, "defaults"), "pref");
log.info("Prefs dir: {}", pref);
if (!pref.isDirectory()) {
log.error("No directory at: {}", pref);
}
final File config = new File("all-bravenewsoftware.js");
if (!config.isFile()) {
log.error("NO CONFIG FILE AT {}", config);
}
else {
try {
FileUtils.copyFileToDirectory(config, pref);
final File installedConfig = new File(pref, config.getName());
installedConfig.deleteOnExit();
} catch (final IOException e) {
log.error("Could not copy config file?", e);
}
}
}
}
| Added props check
| src/main/java/org/lantern/Configurator.java | Added props check |
|
Java | apache-2.0 | b37f824cace10b0e254a6f5bbfa87ee782ac9af6 | 0 | MaTriXy/json-io,KaiHufenbach/json-io,MaTriXy/json-io,kpartlow/json-io,kpartlow/json-io,jdereg/json-io,jdereg/json-io,KaiHufenbach/json-io | package com.cedarsoftware.util.io;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.FilterReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Read an object graph in JSON format and make it available in Java objects, or
* in a "Map of Maps." (untyped representation). This code handles cyclic references
* and can deserialize any Object graph without requiring a class to be 'Serializeable'
* or have any specific methods on it. It will handle classes with non public constructors.
* <br/><br/>
* Usages:
* <ul><li>
* Call the static method: {@code JsonReader.objectToJava(String json)}. This will
* return a typed Java object graph.</li>
* <li>
* Call the static method: {@code JsonReader.jsonToMaps(String json)}. This will
* return an untyped object representation of the JSON String as a Map of Maps, where
* the fields are the Map keys, and the field values are the associated Map's values. You can
* call the JsonWriter.objectToJava() method with the returned Map, and it will serialize
* the Graph into the identical JSON stream from which it was read.
* <li>
* Instantiate the JsonReader with an InputStream: {@code JsonReader(InputStream in)} and then call
* {@code readObject()}. Cast the return value of readObject() to the Java class that was the root of
* the graph.
* </li>
* <li>
* Instantiate the JsonReader with an InputStream: {@code JsonReader(InputStream in, true)} and then call
* {@code readObject()}. The return value will be a Map of Maps.
* </li></ul><br/>
*
* @author John DeRegnaucourt ([email protected])
* <br/>
* Copyright (c) Cedar Software LLC
* <br/><br/>
* 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
* <br/><br/>
* http://www.apache.org/licenses/LICENSE-2.0
* <br/><br/>
* 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.
*/
public class JsonReader implements Closeable
{
private static final int STATE_READ_START_OBJECT = 0;
private static final int STATE_READ_FIELD = 1;
private static final int STATE_READ_VALUE = 2;
private static final int STATE_READ_POST_VALUE = 3;
private static final String EMPTY_ARRAY = "~!a~"; // compared with ==
private static final String EMPTY_OBJECT = "~!o~"; // compared with ==
private static final Character[] _charCache = new Character[128];
private static final Byte[] _byteCache = new Byte[256];
private static final Map<String, String> _stringCache = new HashMap<String, String>();
private static final Set<Class> _prims = new HashSet<Class>();
private static final Map<Class, Object[]> _constructors = new HashMap<Class, Object[]>();
private static final Map<String, Class> _nameToClass = new HashMap<String, Class>();
private static final Class[] _emptyClassArray = new Class[]{};
private static final List<Object[]> _readers = new ArrayList<Object[]>();
private static final Set<Class> _notCustom = new HashSet<Class>();
private static final Map<String, String> _months = new LinkedHashMap<String, String>();
private static final Map<Class, ClassFactory> _factory = new LinkedHashMap<Class, ClassFactory>();
private static final Pattern _datePattern1 = Pattern.compile("^(\\d{4})[\\./-](\\d{1,2})[\\./-](\\d{1,2})");
private static final Pattern _datePattern2 = Pattern.compile("^(\\d{1,2})[\\./-](\\d{1,2})[\\./-](\\d{4})");
private static final Pattern _datePattern3 = Pattern.compile("(Jan|Feb|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|Sep|Sept|Oct|Nov|Dec)[ ,]+(\\d{1,2})[ ,]+(\\d{4})", Pattern.CASE_INSENSITIVE);
private static final Pattern _datePattern4 = Pattern.compile("(\\d{1,2})[ ,](Jan|Feb|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|Sep|Sept|Oct|Nov|Dec)[ ,]+(\\d{4})", Pattern.CASE_INSENSITIVE);
private static final Pattern _timePattern1 = Pattern.compile("(\\d{2})[:.](\\d{2})[:.](\\d{2})[.](\\d{1,3})");
private static final Pattern _timePattern2 = Pattern.compile("(\\d{2})[:.](\\d{2})[:.](\\d{2})");
private static final Pattern _timePattern3 = Pattern.compile("(\\d{2})[:.](\\d{2})");
private static final Pattern _extraQuotes = Pattern.compile("([\"]*)([^\"]*)([\"]*)");
private final Map<Long, JsonObject> _objsRead = new LinkedHashMap<Long, JsonObject>();
private final Collection<UnresolvedReference> _unresolvedRefs = new ArrayList<UnresolvedReference>();
private final Collection<Object[]> _prettyMaps = new ArrayList<Object[]>();
private final FastPushbackReader _in;
private boolean _noObjects = false;
private final char[] _numBuf = new char[256];
private final StringBuilder _strBuf = new StringBuilder();
static final ThreadLocal<Deque<char[]>> _snippet = new ThreadLocal<Deque<char[]>>()
{
public Deque<char[]> initialValue()
{
return new ArrayDeque<char[]>(128);
}
};
static final ThreadLocal<Integer> _line = new ThreadLocal<Integer>()
{
public Integer initialValue()
{
return 1;
}
};
static final ThreadLocal<Integer> _col = new ThreadLocal<Integer>()
{
public Integer initialValue()
{
return 1;
}
};
static
{
// Save memory by re-using common Characters (Characters are immutable)
for (int i = 0; i < _charCache.length; i++)
{
_charCache[i] = (char) i;
}
// Save memory by re-using all byte instances (Bytes are immutable)
for (int i = 0; i < _byteCache.length; i++)
{
_byteCache[i] = (byte) (i - 128);
}
// Save heap memory by re-using common strings (String's immutable)
_stringCache.put("", "");
_stringCache.put("true", "true");
_stringCache.put("True", "True");
_stringCache.put("TRUE", "TRUE");
_stringCache.put("false", "false");
_stringCache.put("False", "False");
_stringCache.put("FALSE", "FALSE");
_stringCache.put("null", "null");
_stringCache.put("yes", "yes");
_stringCache.put("Yes", "Yes");
_stringCache.put("YES", "YES");
_stringCache.put("no", "no");
_stringCache.put("No", "No");
_stringCache.put("NO", "NO");
_stringCache.put("on", "on");
_stringCache.put("On", "On");
_stringCache.put("ON", "ON");
_stringCache.put("off", "off");
_stringCache.put("Off", "Off");
_stringCache.put("OFF", "OFF");
_stringCache.put("@id", "@id");
_stringCache.put("@ref", "@ref");
_stringCache.put("@items", "@items");
_stringCache.put("@type", "@type");
_stringCache.put("@keys", "@keys");
_stringCache.put("0", "0");
_stringCache.put("1", "1");
_stringCache.put("2", "2");
_stringCache.put("3", "3");
_stringCache.put("4", "4");
_stringCache.put("5", "5");
_stringCache.put("6", "6");
_stringCache.put("7", "7");
_stringCache.put("8", "8");
_stringCache.put("9", "9");
_prims.add(Byte.class);
_prims.add(Integer.class);
_prims.add(Long.class);
_prims.add(Double.class);
_prims.add(Character.class);
_prims.add(Float.class);
_prims.add(Boolean.class);
_prims.add(Short.class);
_nameToClass.put("string", String.class);
_nameToClass.put("boolean", boolean.class);
_nameToClass.put("char", char.class);
_nameToClass.put("byte", byte.class);
_nameToClass.put("short", short.class);
_nameToClass.put("int", int.class);
_nameToClass.put("long", long.class);
_nameToClass.put("float", float.class);
_nameToClass.put("double", double.class);
_nameToClass.put("date", Date.class);
_nameToClass.put("class", Class.class);
addReader(String.class, new StringReader());
addReader(Date.class, new DateReader());
addReader(BigInteger.class, new BigIntegerReader());
addReader(BigDecimal.class, new BigDecimalReader());
addReader(java.sql.Date.class, new SqlDateReader());
addReader(Timestamp.class, new TimestampReader());
addReader(Calendar.class, new CalendarReader());
addReader(TimeZone.class, new TimeZoneReader());
addReader(Locale.class, new LocaleReader());
addReader(Class.class, new ClassReader());
addReader(StringBuilder.class, new StringBuilderReader());
addReader(StringBuffer.class, new StringBufferReader());
ClassFactory colFactory = new CollectionFactory();
assignInstantiator(Collection.class, colFactory);
assignInstantiator(List.class, colFactory);
assignInstantiator(Set.class, colFactory);
assignInstantiator(SortedSet.class, colFactory);
assignInstantiator(Collection.class, colFactory);
ClassFactory mapFactory = new MapFactory();
assignInstantiator(Map.class, mapFactory);
assignInstantiator(SortedMap.class, mapFactory);
// Month name to number map
_months.put("jan", "1");
_months.put("january", "1");
_months.put("feb", "2");
_months.put("february", "2");
_months.put("mar", "3");
_months.put("march", "3");
_months.put("apr", "4");
_months.put("april", "4");
_months.put("may", "5");
_months.put("jun", "6");
_months.put("june", "6");
_months.put("jul", "7");
_months.put("july", "7");
_months.put("aug", "8");
_months.put("august", "8");
_months.put("sep", "9");
_months.put("sept", "9");
_months.put("september", "9");
_months.put("oct", "10");
_months.put("october", "10");
_months.put("nov", "11");
_months.put("november", "11");
_months.put("dec", "12");
_months.put("december", "12");
}
public interface JsonClassReader
{
Object read(Object jOb, LinkedList<JsonObject<String, Object>> stack) throws IOException;
}
public interface ClassFactory
{
Object newInstance(Class c);
}
/**
* For difficult to instantiate classes, you can add your own ClassFactory
* which will be called when the passed in class 'c' is encountered. Your
* ClassFactory will be called with newInstance(c) and your factory is expected
* to return a new instance of 'c'.
*
* This API is an 'escape hatch' to allow ANY object to be instantiated by JsonReader
* and is useful when you encounter a class that JsonReader cannot instantiate using its
* internal exhausting attempts (trying all constructors, varying arguments to them, etc.)
*/
public static void assignInstantiator(Class c, ClassFactory factory)
{
_factory.put(c, factory);
}
/**
* Use to create new instances of collection interfaces (needed for empty collections)
*/
public static class CollectionFactory implements ClassFactory
{
public Object newInstance(Class c)
{
if (List.class.isAssignableFrom(c))
{
return new ArrayList();
}
else if (SortedSet.class.isAssignableFrom(c))
{
return new TreeSet();
}
else if (Set.class.isAssignableFrom(c))
{
return new LinkedHashSet();
}
else if (Collection.class.isAssignableFrom(c))
{
return new ArrayList();
}
throw new RuntimeException("CollectionFactory handed Class for which it was not expecting: " + c.getName());
}
}
/**
* Use to create new instances of Map interfaces (needed for empty Maps)
*/
public static class MapFactory implements ClassFactory
{
public Object newInstance(Class c)
{
if (SortedMap.class.isAssignableFrom(c))
{
return new TreeMap();
}
else if (Map.class.isAssignableFrom(c))
{
return new LinkedHashMap();
}
throw new RuntimeException("MapFactory handed Class for which it was not expecting: " + c.getName());
}
}
public static class TimeZoneReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = (JsonObject)o;
Object zone = jObj.get("zone");
if (zone == null)
{
error("java.util.TimeZone must specify 'zone' field");
}
return jObj.target = TimeZone.getTimeZone((String) zone);
}
}
public static class LocaleReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = (JsonObject) o;
Object language = jObj.get("language");
if (language == null)
{
error("java.util.Locale must specify 'language' field");
}
Object country = jObj.get("country");
Object variant = jObj.get("variant");
if (country == null)
{
return jObj.target = new Locale((String) language);
}
if (variant == null)
{
return jObj.target = new Locale((String) language, (String) country);
}
return jObj.target = new Locale((String) language, (String) country, (String) variant);
}
}
public static class CalendarReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
String time = null;
try
{
JsonObject jObj = (JsonObject) o;
time = (String) jObj.get("time");
if (time == null)
{
error("Calendar missing 'time' field");
}
Date date = JsonWriter._dateFormat.get().parse(time);
Class c;
if (jObj.getTarget() != null)
{
c = jObj.getTarget().getClass();
}
else
{
Object type = jObj.type;
c = classForName2((String) type);
}
Calendar calendar = (Calendar) newInstance(c);
calendar.setTime(date);
jObj.setTarget(calendar);
String zone = (String) jObj.get("zone");
if (zone != null)
{
calendar.setTimeZone(TimeZone.getTimeZone(zone));
}
return calendar;
}
catch(Exception e)
{
return error("Failed to parse calendar, time: " + time);
}
}
}
public static class DateReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof Long)
{
return new Date((Long) o);
}
else if (o instanceof String)
{
return parseDate((String)o);
}
else if (o instanceof JsonObject)
{
JsonObject jObj = (JsonObject)o;
Object val = jObj.get("value");
if (val instanceof Long)
{
return new Date((Long) val);
}
else if (val instanceof String)
{
return parseDate((String) val);
}
return error("Unable to parse date: " + o);
}
else
{
return error("Unable to parse date, encountered unknown object: " + o);
}
}
private static Date parseDate(String dateStr) throws IOException
{
dateStr = dateStr.trim();
// Determine which date pattern (Matcher) to use
Matcher matcher = _datePattern1.matcher(dateStr);
String year, month = null, day, mon = null;
if (matcher.find())
{
year = matcher.group(1);
month = matcher.group(2);
day = matcher.group(3);
}
else
{
matcher = _datePattern2.matcher(dateStr);
if (matcher.find())
{
month = matcher.group(1);
day = matcher.group(2);
year = matcher.group(3);
}
else
{
matcher = _datePattern3.matcher(dateStr);
if (matcher.find())
{
mon = matcher.group(1);
day = matcher.group(2);
year = matcher.group(3);
}
else
{
matcher = _datePattern4.matcher(dateStr);
if (!matcher.find())
{
error("Unable to parse: " + dateStr);
}
day = matcher.group(1);
mon = matcher.group(2);
year = matcher.group(3);
}
}
}
if (mon != null)
{
month = _months.get(mon.trim().toLowerCase());
if (month == null)
{
error("Unable to parse month portion of date: " + dateStr);
}
}
// Determine which date pattern (Matcher) to use
matcher = _timePattern1.matcher(dateStr);
if (!matcher.find())
{
matcher = _timePattern2.matcher(dateStr);
if (!matcher.find())
{
matcher = _timePattern3.matcher(dateStr);
if (!matcher.find())
{
matcher = null;
}
}
}
Calendar c = Calendar.getInstance();
c.clear();
int y = 0;
int m = 0;
int d = 0;
try
{
y = Integer.parseInt(year);
m = Integer.parseInt(month) - 1; // months are 0-based
d = Integer.parseInt(day);
}
catch (Exception e)
{
error("Unable to parse: " + dateStr, e);
}
if (matcher == null)
{ // no [valid] time portion
c.set(y, m, d);
}
else
{
String hour = matcher.group(1);
String min = matcher.group(2);
String sec = "00";
String milli = "000";
if (matcher.groupCount() > 2)
{
sec = matcher.group(3);
}
if (matcher.groupCount() > 3)
{
milli = matcher.group(4);
}
int h = 0;
int mn = 0;
int s = 0;
int ms = 0;
try
{
h = Integer.parseInt(hour);
mn = Integer.parseInt(min);
s = Integer.parseInt(sec);
ms = Integer.parseInt(milli);
}
catch (Exception e)
{
error("Unable to parse time: " + dateStr, e);
}
c.set(y, m, d, h, mn, s);
c.set(Calendar.MILLISECOND, ms);
}
return c.getTime();
}
}
public static class SqlDateReader extends DateReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
return new java.sql.Date(((Date) super.read(o, stack)).getTime());
}
}
public static class StringReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof String)
{
return o;
}
if (isPrimitive(o.getClass()))
{
return o.toString();
}
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
return jObj.target = jObj.get("value");
}
return error("String missing 'value' field");
}
}
public static class ClassReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof String)
{
return classForName2((String)o);
}
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
return jObj.target = classForName2((String) jObj.get("value"));
}
return error("Class missing 'value' field");
}
}
public static class BigIntegerReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = null;
Object value = o;
if (o instanceof JsonObject)
{
jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
value = jObj.get("value");
}
else
{
return error("BigInteger missing 'value' field");
}
}
BigInteger x = null;
if (value instanceof JsonObject)
{
JsonObject valueObj = (JsonObject)value;
if ("java.math.BigDecimal".equals(valueObj.type))
{
BigDecimalReader reader = new BigDecimalReader();
value = reader.read(value, stack);
}
else if ("java.math.BigInteger".equals(valueObj.type))
{
value = read(value, stack);
}
else
{
return error("Unknown object type attempted to be assigned to BigInteger field: " + value);
}
}
if (value instanceof String)
{
x = new BigInteger(removeLeadingAndTrailingQuotes((String) value));
}
if (value instanceof BigInteger)
{
x = (BigInteger) value;
}
if (value instanceof BigDecimal)
{
BigDecimal bd = (BigDecimal) value;
String str = bd.toPlainString();
if (str.contains("."))
{
return error("Cannot assign BigDecimal to BigInteger if BigDecimal has fractional part: " + value);
}
x = new BigInteger(str);
}
if (value instanceof Boolean)
{
x = new BigInteger(((Boolean) value) ? "1" : "0");
}
if (value instanceof Double || value instanceof Float)
{
return error("Cannot assign floating point value to a BigInteger: " + value);
}
if (value instanceof Long || value instanceof Integer ||
value instanceof Short || value instanceof Byte)
{
x = new BigInteger(value.toString());
}
if (jObj != null)
{
jObj.target = x;
}
return x != null ? x : error("BigInteger 'value' convertible to a BigInteger: " + value);
}
}
public static class BigDecimalReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = null;
Object value = o;
if (o instanceof JsonObject)
{
jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
value = jObj.get("value");
}
else
{
return error("BigDecimal missing 'value' field");
}
}
BigDecimal x = null;
if (value instanceof JsonObject)
{
JsonObject valueObj = (JsonObject)value;
if ("java.math.BigInteger".equals(valueObj.type))
{
BigIntegerReader reader = new BigIntegerReader();
value = reader.read(value, stack);
}
else if ("java.math.BigDecimal".equals(valueObj.type))
{
value = read(value, stack);
}
else
{
return error("Unknown object type attempted to be assigned to BigInteger field: " + value);
}
}
if (value instanceof String)
{
x = new BigDecimal(removeLeadingAndTrailingQuotes((String) value));
}
if (value instanceof BigDecimal)
{
x = (BigDecimal) value;
}
if (value instanceof BigInteger)
{
x = new BigDecimal((BigInteger)value);
}
if (value instanceof Boolean)
{
x = new BigDecimal(((Boolean) value) ? "1" : "0");
}
if (value instanceof Long || value instanceof Double || value instanceof Integer ||
value instanceof Short || value instanceof Byte || value instanceof Float || value instanceof BigInteger)
{
x = new BigDecimal(value.toString());
}
if (jObj != null)
{
jObj.target = x;
}
return x != null ? x : error("BigDecimal missing 'value' field not convertible to a BigDecimal: " + value);
}
}
public static class StringBuilderReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof String)
{
return new StringBuilder((String) o);
}
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
return jObj.target = new StringBuilder((String) jObj.get("value"));
}
return error("StringBuilder missing 'value' field");
}
}
public static class StringBufferReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof String)
{
return new StringBuffer((String) o);
}
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
return jObj.target = new StringBuffer((String) jObj.get("value"));
}
return error("StringBuffer missing 'value' field");
}
}
public static class TimestampReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = (JsonObject) o;
Object time = jObj.get("time");
if (time == null)
{
error("java.sql.Timestamp must specify 'time' field");
}
Object nanos = jObj.get("nanos");
if (nanos == null)
{
return jObj.target = new Timestamp(Long.valueOf((String) time));
}
Timestamp tstamp = new Timestamp(Long.valueOf((String) time));
tstamp.setNanos(Integer.valueOf((String) nanos));
return jObj.target = tstamp;
}
}
public static void addReader(Class c, JsonClassReader reader)
{
for (Object[] item : _readers)
{
Class clz = (Class)item[0];
if (clz == c)
{
item[1] = reader; // Replace reader
return;
}
}
_readers.add(new Object[] {c, reader});
}
public static void addNotCustomReader(Class c)
{
_notCustom.add(c);
}
protected Object readIfMatching(Object o, Class compType, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o == null)
{
error("Bug in json-io, null must be checked before calling this method.");
}
if (_notCustom.contains(o.getClass()))
{
return null;
}
if (compType != null)
{
if (_notCustom.contains(compType))
{
return null;
}
}
boolean isJsonObject = o instanceof JsonObject;
if (!isJsonObject && compType == null)
{ // If not a JsonObject (like a Long that represents a date, then compType must be set)
return null;
}
Class c;
boolean needsType = false;
// Set up class type to check against reader classes (specified as @type, or jObj.target, or compType)
if (isJsonObject)
{
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("@ref"))
{
return null;
}
if (jObj.target == null)
{ // '@type' parameter used
String typeStr = null;
try
{
Object type = jObj.type;
if (type != null)
{
typeStr = (String) type;
c = classForName((String) type);
}
else
{
if (compType != null)
{
c = compType;
needsType = true;
}
else
{
return null;
}
}
}
catch(Exception e)
{
return error("Class listed in @type [" + typeStr + "] is not found", e);
}
}
else
{ // Type inferred from target object
c = jObj.target.getClass();
}
}
else
{
c = compType;
}
JsonClassReader closestReader = null;
int minDistance = Integer.MAX_VALUE;
for (Object[] item : _readers)
{
Class clz = (Class)item[0];
if (clz == c)
{
closestReader = (JsonClassReader)item[1];
break;
}
int distance = JsonWriter.getDistance(clz, c);
if (distance < minDistance)
{
minDistance = distance;
closestReader = (JsonClassReader)item[1];
}
}
if (closestReader == null)
{
return null;
}
if (needsType && isJsonObject)
{
((JsonObject)o).setType(c.getName());
}
return closestReader.read(o, stack);
}
/**
* UnresolvedReference is created to hold a logical pointer to a reference that
* could not yet be loaded, as the @ref appears ahead of the referenced object's
* definition. This can point to a field reference or an array/Collection element reference.
*/
private static class UnresolvedReference
{
private JsonObject referencingObj;
private String field;
private long refId;
private int index = -1;
private UnresolvedReference(JsonObject referrer, String fld, long id)
{
referencingObj = referrer;
field = fld;
refId = id;
}
private UnresolvedReference(JsonObject referrer, int idx, long id)
{
referencingObj = referrer;
index = idx;
refId = id;
}
}
/**
* Convert the passed in JSON string into a Java object graph.
*
* @param json String JSON input
* @return Java object graph matching JSON input, or null if an
* error occurred.
*/
@Deprecated
public static Object toJava(String json)
{
throw new RuntimeException("Use com.cedarsoftware.util.JsonReader");
}
/**
* Convert the passed in JSON string into a Java object graph.
*
* @param json String JSON input
* @return Java object graph matching JSON input
* @throws java.io.IOException If an I/O error occurs
*/
public static Object jsonToJava(String json) throws IOException
{
ByteArrayInputStream ba = new ByteArrayInputStream(json.getBytes("UTF-8"));
JsonReader jr = new JsonReader(ba, false);
Object obj = jr.readObject();
jr.close();
return obj;
}
/**
* Convert the passed in JSON string into a Java object graph
* that consists solely of Java Maps where the keys are the
* fields and the values are primitives or other Maps (in the
* case of objects).
*
* @param json String JSON input
* @return Java object graph of Maps matching JSON input,
* or null if an error occurred.
*/
@Deprecated
public static Map toMaps(String json)
{
try
{
return jsonToMaps(json);
}
catch (Exception ignored)
{
return null;
}
}
/**
* Convert the passed in JSON string into a Java object graph
* that consists solely of Java Maps where the keys are the
* fields and the values are primitives or other Maps (in the
* case of objects).
*
* @param json String JSON input
* @return Java object graph of Maps matching JSON input,
* or null if an error occurred.
* @throws java.io.IOException If an I/O error occurs
*/
public static Map jsonToMaps(String json) throws IOException
{
ByteArrayInputStream ba = new ByteArrayInputStream(json.getBytes("UTF-8"));
JsonReader jr = new JsonReader(ba, true);
Map map = (Map) jr.readObject();
jr.close();
return map;
}
public JsonReader()
{
_noObjects = false;
_in = null;
}
public JsonReader(InputStream in)
{
this(in, false);
}
public JsonReader(InputStream in, boolean noObjects)
{
_noObjects = noObjects;
try
{
_in = new FastPushbackReader(new BufferedReader(new InputStreamReader(in, "UTF-8")));
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException("Your JVM does not support UTF-8. Get a new JVM.", e);
}
}
/**
* Finite State Machine (FSM) used to parse the JSON input into
* JsonObject's (Maps). Then, if requested, the JsonObjects are
* converted into Java instances.
*
* @return Java Object graph constructed from InputStream supplying
* JSON serialized content.
* @throws IOException for stream errors or parsing errors.
*/
public Object readObject() throws IOException
{
Object o = readJsonObject();
if (o == EMPTY_OBJECT)
{
return new JsonObject();
}
Object graph = convertParsedMapsToJava((JsonObject) o);
// Allow a complete 'Map' return (Javascript style)
if (_noObjects)
{
return o;
}
return graph;
}
/**
* Convert a root JsonObject that represents parsed JSON, into
* an actual Java object.
* @param root JsonObject instance that was the root object from the
* JSON input that was parsed in an earlier call to JsonReader.
* @return a typed Java instance that was serialized into JSON.
*/
public Object jsonObjectsToJava(JsonObject root) throws IOException
{
_noObjects = false;
return convertParsedMapsToJava(root);
}
/**
* This method converts a root Map, (which contains nested Maps
* and so forth representing a Java Object graph), to a Java
* object instance. The root map came from using the JsonReader
* to parse a JSON graph (using the API that puts the graph
* into Maps, not the typed representation).
* @param root JsonObject instance that was the root object from the
* JSON input that was parsed in an earlier call to JsonReader.
* @return a typed Java instance that was serialized into JSON.
*/
private Object convertParsedMapsToJava(JsonObject root) throws IOException
{
createJavaObjectInstance(Object.class, root);
Object graph = convertMapsToObjects((JsonObject<String, Object>) root);
patchUnresolvedReferences();
rehashMaps();
_objsRead.clear();
_unresolvedRefs.clear();
_prettyMaps.clear();
return graph;
}
/**
* Walk a JsonObject (Map of String keys to values) and return the
* Java object equivalent filled in as best as possible (everything
* except unresolved reference fields or unresolved array/collection elements).
*
* @param root JsonObject reference to a Map-of-Maps representation of the JSON
* input after it has been completely read.
* @return Properly constructed, typed, Java object graph built from a Map
* of Maps representation (JsonObject root).
* @throws IOException for stream errors or parsing errors.
*/
private Object convertMapsToObjects(JsonObject<String, Object> root) throws IOException
{
LinkedList<JsonObject<String, Object>> stack = new LinkedList<JsonObject<String, Object>>();
stack.addFirst(root);
final boolean useMaps = _noObjects;
while (!stack.isEmpty())
{
JsonObject<String, Object> jsonObj = stack.removeFirst();
if (useMaps)
{
if (jsonObj.isArray() || jsonObj.isCollection())
{
traverseCollectionNoObj(stack, jsonObj);
}
else if (jsonObj.isMap())
{
traverseMap(stack, jsonObj);
}
else
{
traverseFieldsNoObj(stack, jsonObj);
}
}
else
{
if (jsonObj.isArray())
{
traverseArray(stack, jsonObj);
}
else if (jsonObj.isCollection())
{
traverseCollection(stack, jsonObj);
}
else if (jsonObj.isMap())
{
traverseMap(stack, jsonObj);
}
else
{
traverseFields(stack, jsonObj);
}
// Reduce heap footprint during processing
jsonObj.clear();
}
}
return root.target;
}
/**
* Traverse the JsonObject associated to an array (of any type). Convert and
* assign the list of items in the JsonObject (stored in the @items field)
* to each array element. All array elements are processed excluding elements
* that reference an unresolved object. These are filled in later.
*
* @param stack a Stack (LinkedList) used to support graph traversal.
* @param jsonObj a Map-of-Map representation of the JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private void traverseArray(LinkedList<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) throws IOException
{
int len = jsonObj.getLength();
if (len == 0)
{
return;
}
Class compType = jsonObj.getComponentType();
if (char.class == compType)
{
return;
}
if (byte.class == compType)
{ // Handle byte[] special for performance boost.
jsonObj.moveBytesToMate();
jsonObj.clearArray();
return;
}
boolean isPrimitive = isPrimitive(compType);
Object array = jsonObj.target;
Object[] items = jsonObj.getArray();
for (int i = 0; i < len; i++)
{
Object element = items[i];
Object special;
if (element == null)
{
Array.set(array, i, null);
}
else if (element == EMPTY_OBJECT)
{ // Use either explicitly defined type in ObjectMap associated to JSON, or array component type.
Object arrayElement = createJavaObjectInstance(compType, new JsonObject());
Array.set(array, i, arrayElement);
}
else if ((special = readIfMatching(element, compType, stack)) != null)
{
Array.set(array, i, special);
}
else if (isPrimitive)
{ // Primitive component type array
Array.set(array, i, newPrimitiveWrapper(compType, element));
}
else if (element.getClass().isArray())
{ // Array of arrays
if (char[].class == compType)
{ // Specially handle char[] because we are writing these
// out as UTF-8 strings for compactness and speed.
Object[] jsonArray = (Object[]) element;
if (jsonArray.length == 0)
{
Array.set(array, i, new char[]{});
}
else
{
String value = (String) jsonArray[0];
int numChars = value.length();
char[] chars = new char[numChars];
for (int j = 0; j < numChars; j++)
{
chars[j] = value.charAt(j);
}
Array.set(array, i, chars);
}
}
else
{
JsonObject<String, Object> jsonObject = new JsonObject<String, Object>();
jsonObject.put("@items", element);
Array.set(array, i, createJavaObjectInstance(compType, jsonObject));
stack.addFirst(jsonObject);
}
}
else if (element instanceof JsonObject)
{
JsonObject<String, Object> jsonObject = (JsonObject<String, Object>) element;
Long ref = (Long) jsonObject.get("@ref");
if (ref != null)
{ // Connect reference
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
if (refObject.target != null)
{ // Array element with @ref to existing object
Array.set(array, i, refObject.target);
}
else
{ // Array with a forward @ref as an element
_unresolvedRefs.add(new UnresolvedReference(jsonObj, i, ref));
}
}
else
{ // Convert JSON HashMap to Java Object instance and assign values
Object arrayElement = createJavaObjectInstance(compType, jsonObject);
Array.set(array, i, arrayElement);
if (!isPrimitive(arrayElement.getClass()))
{ // Skip walking primitives, primitive wrapper classes,, Strings, and Classes
stack.addFirst(jsonObject);
}
}
}
else
{ // Setting primitive values into an Object[]
Array.set(array, i, element);
}
}
jsonObj.clearArray();
}
/**
* Process java.util.Collection and it's derivatives. Collections are written specially
* so that the serialization does not expose the Collection's internal structure, for
* example a TreeSet. All entries are processed, except unresolved references, which
* are filled in later. For an indexable collection, the unresolved references are set
* back into the proper element location. For non-indexable collections (Sets), the
* unresolved references are added via .add().
* @param stack a Stack (LinkedList) used to support graph traversal.
* @param jsonObj a Map-of-Map representation of the JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private void traverseCollectionNoObj(LinkedList<JsonObject<String, Object>> stack, JsonObject jsonObj) throws IOException
{
Object[] items = jsonObj.getArray();
if (items == null || items.length == 0)
{
return;
}
int idx = 0;
List copy = new ArrayList(items.length);
for (Object element : items)
{
if (element == EMPTY_OBJECT)
{
copy.add(new JsonObject());
continue;
}
copy.add(element);
if (element instanceof Object[])
{ // array element inside Collection
JsonObject<String, Object> jsonObject = new JsonObject<String, Object>();
jsonObject.put("@items", element);
stack.addFirst(jsonObject);
}
else if (element instanceof JsonObject)
{
JsonObject<String, Object> jsonObject = (JsonObject<String, Object>) element;
Long ref = (Long) jsonObject.get("@ref");
if (ref != null)
{ // connect reference
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
copy.set(idx, refObject);
}
else
{
stack.addFirst(jsonObject);
}
}
idx++;
}
jsonObj.target = null; // don't waste space (used for typed return, not generic Map return)
for (int i=0; i < items.length; i++)
{
items[i] = copy.get(i);
}
}
/**
* Process java.util.Collection and it's derivatives. Collections are written specially
* so that the serialization does not expose the Collection's internal structure, for
* example a TreeSet. All entries are processed, except unresolved references, which
* are filled in later. For an indexable collection, the unresolved references are set
* back into the proper element location. For non-indexable collections (Sets), the
* unresolved references are added via .add().
* @param jsonObj a Map-of-Map representation of the JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private void traverseCollection(LinkedList<JsonObject<String, Object>> stack, JsonObject jsonObj) throws IOException
{
Object[] items = jsonObj.getArray();
if (items == null || items.length == 0)
{
return;
}
Collection col = (Collection) jsonObj.target;
boolean isList = col instanceof List;
int idx = 0;
for (Object element : items)
{
Object special;
if (element == null)
{
col.add(null);
}
else if (element == EMPTY_OBJECT)
{ // Handles {}
col.add(new JsonObject());
}
else if ((special = readIfMatching(element, null, stack)) != null)
{
col.add(special);
}
else if (element instanceof String || element instanceof Boolean || element instanceof Double || element instanceof Long)
{ // Allow Strings, Booleans, Longs, and Doubles to be "inline" without Java object decoration (@id, @type, etc.)
col.add(element);
}
else if (element.getClass().isArray())
{
JsonObject jObj = new JsonObject();
jObj.put("@items", element);
createJavaObjectInstance(Object.class, jObj);
col.add(jObj.target);
convertMapsToObjects(jObj);
}
else // if (element instanceof JsonObject)
{
JsonObject jObj = (JsonObject) element;
Long ref = (Long) jObj.get("@ref");
if (ref != null)
{
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
if (refObject.target != null)
{
col.add(refObject.target);
}
else
{
_unresolvedRefs.add(new UnresolvedReference(jsonObj, idx, ref));
if (isList)
{ // Indexable collection, so set 'null' as element for now - will be patched in later.
col.add(null);
}
}
}
else
{
createJavaObjectInstance(Object.class, jObj);
if (!isPrimitive(jObj.getTargetClass()))
{
convertMapsToObjects(jObj);
}
col.add(jObj.target);
}
}
idx++;
}
jsonObj.remove("@items"); // Reduce memory required during processing
}
/**
* Process java.util.Map and it's derivatives. These can be written specially
* so that the serialization would not expose the derivative class internals
* (internal fields of TreeMap for example).
* @param stack a Stack (LinkedList) used to support graph traversal.
* @param jsonObj a Map-of-Map representation of the JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private void traverseMap(LinkedList<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) throws IOException
{
// Convert @keys to a Collection of Java objects.
convertMapToKeysItems(jsonObj);
Object[] keys = (Object[]) jsonObj.get("@keys");
Object[] items = jsonObj.getArray();
if (keys == null || items == null)
{
if (keys != items)
{
error("Map written where one of @keys or @items is empty");
}
return;
}
int size = keys.length;
if (size != items.length)
{
error("Map written with @keys and @items entries of different sizes");
}
JsonObject jsonKeyCollection = new JsonObject();
jsonKeyCollection.put("@items", keys);
Object[] javaKeys = new Object[size];
jsonKeyCollection.target = javaKeys;
stack.addFirst(jsonKeyCollection);
// Convert @items to a Collection of Java objects.
JsonObject jsonItemCollection = new JsonObject();
jsonItemCollection.put("@items", items);
Object[] javaValues = new Object[size];
jsonItemCollection.target = javaValues;
stack.addFirst(jsonItemCollection);
// Save these for later so that unresolved references inside keys or values
// get patched first, and then build the Maps.
_prettyMaps.add(new Object[] {jsonObj, javaKeys, javaValues});
}
private void traverseFieldsNoObj(LinkedList<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) throws IOException
{
final Object target = jsonObj.target;
for (Map.Entry<String, Object> e : jsonObj.entrySet())
{
String key = e.getKey();
if (key.charAt(0) == '@')
{ // Skip our own meta fields
continue;
}
Field field = null;
if (target != null)
{
field = getDeclaredField(target.getClass(), key);
}
Object value = e.getValue();
if (value == null)
{
jsonObj.put(key, null);
}
else if (value == EMPTY_OBJECT)
{
jsonObj.put(key, new JsonObject());
}
else if (value.getClass().isArray())
{ // LHS of assignment is an [] field or RHS is an array and LHS is Object (Map)
JsonObject<String, Object> jsonArray = new JsonObject<String, Object>();
jsonArray.put("@items", value);
stack.addFirst(jsonArray);
jsonObj.put(key, jsonArray);
}
else if (value instanceof JsonObject)
{
JsonObject<String, Object> jObj = (JsonObject) value;
if (field != null && jObj.isPrimitiveWrapper(field.getType()))
{
jObj.put("value", newPrimitiveWrapper(field.getType(),jObj.get("value")));
continue;
}
Long ref = (Long) jObj.get("@ref");
if (ref != null)
{ // Correct field references
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
jsonObj.put(key, refObject); // Update Map-of-Maps reference
}
else
{
stack.addFirst(jObj);
}
}
else if (field != null)
{
Class fieldType = field.getType();
if (isPrimitive(fieldType))
{
jsonObj.put(key, newPrimitiveWrapper(fieldType, value));
}
else if (BigDecimal.class == fieldType)
{
jsonObj.put(key, new BigDecimal(value.toString()));
}
else if (BigInteger.class == fieldType)
{
jsonObj.put(key, new BigInteger(value.toString()));
}
}
}
jsonObj.target = null; // don't waste space (used for typed return, not for Map return)
}
/**
* Walk the Java object fields and copy them from the JSON object to the Java object, performing
* any necessary conversions on primitives, or deep traversals for field assignments to other objects,
* arrays, Collections, or Maps.
* @param stack Stack (LinkedList) used for graph traversal.
* @param jsonObj a Map-of-Map representation of the current object being examined (containing all fields).
* @throws IOException
*/
private void traverseFields(LinkedList<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) throws IOException
{
Object special;
if ((special = readIfMatching(jsonObj, null, stack)) != null)
{
jsonObj.target = special;
return;
}
Object javaMate = jsonObj.target;
Iterator<Map.Entry<String, Object>> i = jsonObj.entrySet().iterator();
Class cls = javaMate.getClass();
while (i.hasNext())
{
Map.Entry<String, Object> e = i.next();
String key = e.getKey();
Field field = getDeclaredField(cls, key);
Object rhs = e.getValue();
if (field != null)
{
assignField(stack, jsonObj, field, rhs);
}
}
jsonObj.clear(); // Reduce memory required during processing
}
/**
* Map Json Map object field to Java object field.
*
* @param stack Stack (LinkedList) used for graph traversal.
* @param jsonObj a Map-of-Map representation of the current object being examined (containing all fields).
* @param field a Java Field object representing where the jsonObj should be converted and stored.
* @param rhs the JSON value that will be converted and stored in the 'field' on the associated
* Java target object.
* @throws IOException for stream errors or parsing errors.
*/
private void assignField(LinkedList<JsonObject<String, Object>> stack, JsonObject jsonObj, Field field, Object rhs) throws IOException
{
Object target = jsonObj.target;
try
{
Class fieldType = field.getType();
if (Collection.class.isAssignableFrom(fieldType))
{ // Process Collection (and potentially generic objects within it) by marketing contained items with
// template info if it exists, and the items do not have @type specified on them.
if (rhs instanceof JsonObject)
{
JsonObject col = (JsonObject) rhs;
Object[] items = col.getArray();
markSubobjectTypes(field, items, 0);
}
}
else if (Map.class.isAssignableFrom(fieldType))
{
if (rhs instanceof JsonObject)
{
JsonObject map = (JsonObject) rhs;
convertMapToKeysItems(map);
if (map.get("@keys") instanceof Object[])
{
Object[] keys = (Object[]) map.get("@keys");
markSubobjectTypes(field, keys, 0);
}
if (map.get("@items") instanceof Object[])
{
Object[] values = (Object[]) map.get("@items");
markSubobjectTypes(field, values, 1);
}
}
}
if (rhs instanceof JsonObject)
{ // Ensure .type field set on JsonObject
JsonObject job = (JsonObject) rhs;
String type = job.type;
if (type == null || type.isEmpty())
{
job.setType(fieldType.getName());
}
}
Object special;
if (rhs == null)
{
field.set(target, null);
}
else if (rhs == EMPTY_OBJECT)
{
JsonObject jObj = new JsonObject();
jObj.type = fieldType.getName();
Object value = createJavaObjectInstance(fieldType, jObj);
field.set(target, value);
}
else if ((special = readIfMatching(rhs, field.getType(), stack)) != null)
{
field.set(target, special);
}
else if (rhs.getClass().isArray())
{ // LHS of assignment is an [] field or RHS is an array and LHS is Object
Object[] elements = (Object[]) rhs;
JsonObject<String, Object> jsonArray = new JsonObject<String, Object>();
if (char[].class == fieldType)
{ // Specially handle char[] because we are writing these
// out as UTF8 strings for compactness and speed.
if (elements.length == 0)
{
field.set(target, new char[]{});
}
else
{
field.set(target, ((String) elements[0]).toCharArray());
}
}
else
{
jsonArray.put("@items", elements);
createJavaObjectInstance(fieldType, jsonArray);
field.set(target, jsonArray.target);
stack.addFirst(jsonArray);
}
}
else if (rhs instanceof JsonObject)
{
JsonObject<String, Object> jObj = (JsonObject) rhs;
Long ref = (Long) jObj.get("@ref");
if (ref != null)
{ // Correct field references
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
if (refObject.target != null)
{
field.set(target, refObject.target);
}
else
{
_unresolvedRefs.add(new UnresolvedReference(jsonObj, field.getName(), ref));
}
}
else
{ // Assign ObjectMap's to Object (or derived) fields
field.set(target, createJavaObjectInstance(fieldType, jObj));
if (!isPrimitive(jObj.getTargetClass()))
{
stack.addFirst((JsonObject) rhs);
}
}
}
else // Primitives and primitive wrappers
{
if (isPrimitive(fieldType))
{
field.set(target, newPrimitiveWrapper(fieldType, rhs));
}
else
{
field.set(target, rhs);
}
}
}
catch (Exception e)
{
error("IllegalAccessException setting field '" + field.getName() + "' on target: " + target + " with value: " + rhs, e);
}
}
/**
* Convert an input JsonObject map (known to represent a Map.class or derivative) that has regular keys and values
* to have its keys placed into @keys, and its values placed into @items.
* @param map Map to convert
*/
private void convertMapToKeysItems(JsonObject map)
{
if (!map.containsKey("@keys") && !map.containsKey("@ref"))
{
Object[] keys = new Object[map.keySet().size()];
Object[] values = new Object[map.keySet().size()];
int i=0;
for (Object e : map.entrySet())
{
Map.Entry entry = (Map.Entry)e;
keys[i] = entry.getKey();
values[i] = entry.getValue();
i++;
}
String saveType = map.getType();
map.clear();
map.setType(saveType);
map.put("@keys", keys);
map.put("@items", values);
}
}
/**
* Mark the @type field on JsonObject's that have no type information,
* no target, but where the Field generic type information contains the
* type of the enclosed objects.
* @param field Field instance containing the Generic info of the Collection that holds the enclosed objects.
* @param items Object[] of JsonObjects that may be type-less.
* @param typeArg Used to indicate whether to use type argument 0 or 1 (Collection or Map).
*/
private void markSubobjectTypes(Field field, Object[] items, int typeArg)
{
if (items == null || items.length == 0)
{
return;
}
for (Object o : items)
{
if (o instanceof JsonObject)
{
JsonObject item = (JsonObject) o;
String type = item.getType();
if (type == null || type.isEmpty())
{
if (field.getGenericType() instanceof ParameterizedType)
{
ParameterizedType paramType = (ParameterizedType) field.getGenericType();
Type[] typeArgs = paramType.getActualTypeArguments();
if (typeArgs != null && typeArgs.length > typeArg && typeArgs[typeArg] instanceof Class)
{
Class c = (Class) typeArgs[typeArg];
item.setType(c.getName());
}
}
}
}
}
}
/**
* This method creates a Java Object instance based on the passed in parameters.
* If the JsonObject contains a key '@type' then that is used, as the type was explicitly
* set in the JSON stream. If the key '@type' does not exist, then the passed in Class
* is used to create the instance, handling creating an Array or regular Object
* instance.
* <p/>
* The '@type' is not often specified in the JSON input stream, as in many
* cases it can be inferred from a field reference or array component type.
*
* @param clazz Instance will be create of this class.
* @param jsonObj Map-of-Map representation of object to create.
* @return a new Java object of the appropriate type (clazz) using the jsonObj to provide
* enough hints to get the right class instantiated. It is not populated when returned.
* @throws IOException for stream errors or parsing errors.
*/
private Object createJavaObjectInstance(Class clazz, JsonObject jsonObj) throws IOException
{
String type = jsonObj.type;
Object mate;
// @type always takes precedence over inferred Java (clazz) type.
if (type != null)
{ // @type is explicitly set, use that as it always takes precedence
Class c = classForName(type);
if (c.isArray())
{ // Handle []
Object[] items = jsonObj.getArray();
int size = (items == null) ? 0 : items.length;
if (c == char[].class)
{
jsonObj.moveCharsToMate();
mate = jsonObj.target;
}
else
{
mate = Array.newInstance(c.getComponentType(), size);
}
}
else
{ // Handle regular field.object reference
if (isPrimitive(c))
{
mate = newPrimitiveWrapper(c, jsonObj.get("value"));
}
else if (c == Class.class)
{
mate = classForName((String) jsonObj.get("value"));
}
else if (c.isEnum())
{
mate = getEnum(c, jsonObj);
}
else if (Enum.class.isAssignableFrom(c)) // anonymous subclass of an enum
{
mate = getEnum(c.getSuperclass(), jsonObj);
}
else if ("java.util.Arrays$ArrayList".equals(c.getName()))
{ // Special case: Arrays$ArrayList does not allow .add() to be called on it.
mate = new ArrayList();
}
else
{
mate = newInstance(c);
}
}
}
else
{ // @type, not specified, figure out appropriate type
Object[] items = jsonObj.getArray();
// if @items is specified, it must be an [] type.
// if clazz.isArray(), then it must be an [] type.
if (clazz.isArray() || (items != null && clazz == Object.class && !jsonObj.containsKey("@keys")))
{
int size = (items == null) ? 0 : items.length;
mate = Array.newInstance(clazz.isArray() ? clazz.getComponentType() : Object.class, size);
}
else if (clazz.isEnum())
{
mate = getEnum(clazz, jsonObj);
}
else if (Enum.class.isAssignableFrom(clazz)) // anonymous subclass of an enum
{
mate = getEnum(clazz.getSuperclass(), jsonObj);
}
else if ("java.util.Arrays$ArrayList".equals(clazz.getName()))
{ // Special case: Arrays$ArrayList does not allow .add() to be called on it.
mate = new ArrayList();
}
else if (clazz == Object.class && !_noObjects)
{
if (jsonObj.isMap() || jsonObj.size() > 0)
{ // Map-Like (has @keys and @items, or it has entries) but either way, type and class are not set.
mate = new JsonObject();
}
else
{ // Dunno
mate = newInstance(clazz);
}
}
else
{
mate = newInstance(clazz);
}
}
return jsonObj.target = mate;
}
/**
* Fetch enum value (may need to try twice, due to potential 'name' field shadowing by enum subclasses
*/
private static Object getEnum(Class c, JsonObject jsonObj)
{
try
{
return Enum.valueOf(c, (String) jsonObj.get("name"));
}
catch (Exception e)
{ // In case the enum class has it's own 'name' member variable (shadowing the 'name' variable on Enum)
return Enum.valueOf(c, (String) jsonObj.get("java.lang.Enum.name"));
}
}
// Parser code
private Object readJsonObject() throws IOException
{
boolean done = false;
String field = null;
JsonObject<String, Object> object = new JsonObject<String, Object>();
int state = STATE_READ_START_OBJECT;
boolean objectRead = false;
final FastPushbackReader in = _in;
while (!done)
{
int c;
switch (state)
{
case STATE_READ_START_OBJECT:
c = skipWhitespaceRead();
if (c == '{')
{
objectRead = true;
object.line = _line.get();
object.col = _col.get();
c = skipWhitespaceRead();
if (c == '}')
{ // empty object
return EMPTY_OBJECT;
}
in.unread(c);
state = STATE_READ_FIELD;
}
else if (c == '[')
{
in.unread('[');
state = STATE_READ_VALUE;
}
else
{
error("Input is invalid JSON; does not start with '{' or '[', c=" + c);
}
break;
case STATE_READ_FIELD:
c = skipWhitespaceRead();
if (c == '"')
{
field = readString();
c = skipWhitespaceRead();
if (c != ':')
{
error("Expected ':' between string field and value");
}
skipWhitespace();
state = STATE_READ_VALUE;
}
else
{
error("Expected quote");
}
break;
case STATE_READ_VALUE:
if (field == null)
{ // field is null when you have an untyped Object[], so we place
// the JsonArray on the @items field.
field = "@items";
}
Object value = readValue(object);
object.put(field, value);
// If object is referenced (has @id), then put it in the _objsRead table.
if ("@id".equals(field))
{
_objsRead.put((Long)value, object);
}
state = STATE_READ_POST_VALUE;
break;
case STATE_READ_POST_VALUE:
c = skipWhitespaceRead();
if (c == -1 && objectRead)
{
error("EOF reached before closing '}'");
}
if (c == '}' || c == -1)
{
done = true;
}
else if (c == ',')
{
state = STATE_READ_FIELD;
}
else
{
error("Object not ended with '}' or ']'");
}
break;
}
}
if (_noObjects && object.isPrimitive())
{
return object.getPrimitiveValue();
}
return object;
}
private Object readValue(JsonObject object) throws IOException
{
int c = _in.read();
if (c == '"')
{
return readString();
}
if (isDigit(c) || c == '-')
{
return readNumber(c);
}
if (c == '{')
{
_in.unread('{');
return readJsonObject();
}
if (c == 't' || c == 'T')
{
_in.unread(c);
readToken("true");
return Boolean.TRUE;
}
if (c == 'f' || c == 'F')
{
_in.unread(c);
readToken("false");
return Boolean.FALSE;
}
if (c == 'n' || c == 'N')
{
_in.unread(c);
readToken("null");
return null;
}
if (c == '[')
{
return readArray(object);
}
if (c == ']')
{ // [] empty array
_in.unread(']');
return EMPTY_ARRAY;
}
if (c == -1)
{
error("EOF reached prematurely");
}
return error("Unknown JSON value type");
}
/**
* Read a JSON array
*/
private Object readArray(JsonObject object) throws IOException
{
Collection array = new ArrayList();
while (true)
{
skipWhitespace();
Object o = readValue(object);
if (o != EMPTY_ARRAY)
{
array.add(o);
}
int c = skipWhitespaceRead();
if (c == ']')
{
break;
}
if (c != ',')
{
error("Expected ',' or ']' inside array");
}
}
return array.toArray();
}
/**
* Return the specified token from the reader. If it is not found,
* throw an IOException indicating that. Converting to c to
* (char) c is acceptable because the 'tokens' allowed in a
* JSON input stream (true, false, null) are all ASCII.
*/
private String readToken(String token) throws IOException
{
int len = token.length();
for (int i = 0; i < len; i++)
{
int c = _in.read();
if (c == -1)
{
error("EOF reached while reading token: " + token);
}
c = Character.toLowerCase((char) c);
int loTokenChar = token.charAt(i);
if (loTokenChar != c)
{
error("Expected token: " + token);
}
}
return token;
}
/**
* Read a JSON number
*
* @param c int a character representing the first digit of the number that
* was already read.
* @return a Number (a Long or a Double) depending on whether the number is
* a decimal number or integer. This choice allows all smaller types (Float, int, short, byte)
* to be represented as well.
* @throws IOException for stream errors or parsing errors.
*/
private Number readNumber(int c) throws IOException
{
final FastPushbackReader in = _in;
final char[] numBuf = _numBuf;
numBuf[0] = (char) c;
int len = 1;
boolean isFloat = false;
try
{
while (true)
{
c = in.read();
if ((c >= '0' && c <= '9') || c == '-' || c == '+') // isDigit() inlined for speed here
{
numBuf[len++] = (char) c;
}
else if (c == '.' || c == 'e' || c == 'E')
{
numBuf[len++] = (char) c;
isFloat = true;
}
else if (c == -1)
{
error("Reached EOF while reading number");
}
else
{
in.unread(c);
break;
}
}
}
catch (ArrayIndexOutOfBoundsException e)
{
error("Too many digits in number");
}
if (isFloat)
{ // Floating point number needed
String num = new String(numBuf, 0, len);
try
{
return Double.parseDouble(num);
}
catch (NumberFormatException e)
{
error("Invalid floating point number: " + num, e);
}
}
boolean isNeg = numBuf[0] == '-';
long n = 0;
for (int i = (isNeg ? 1 : 0); i < len; i++)
{
n = (numBuf[i] - '0') + n * 10;
}
return isNeg ? -n : n;
}
/**
* Read a JSON string
* This method assumes the initial quote has already been read.
*
* @return String read from JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private String readString() throws IOException
{
final StringBuilder strBuf = _strBuf;
strBuf.setLength(0);
StringBuilder hex = new StringBuilder();
boolean done = false;
final int STATE_STRING_START = 0;
final int STATE_STRING_SLASH = 1;
final int STATE_HEX_DIGITS = 2;
int state = STATE_STRING_START;
while (!done)
{
int c = _in.read();
if (c == -1)
{
error("EOF reached while reading JSON string");
}
switch (state)
{
case STATE_STRING_START:
if (c == '\\')
{
state = STATE_STRING_SLASH;
}
else if (c == '"')
{
done = true;
}
else
{
strBuf.append(toChars(c));
}
break;
case STATE_STRING_SLASH:
if (c == 'n')
{
strBuf.append('\n');
}
else if (c == 'r')
{
strBuf.append('\r');
}
else if (c == 't')
{
strBuf.append('\t');
}
else if (c == 'f')
{
strBuf.append('\f');
}
else if (c == 'b')
{
strBuf.append('\b');
}
else if (c == '\\')
{
strBuf.append('\\');
}
else if (c == '/')
{
strBuf.append('/');
}
else if (c == '"')
{
strBuf.append('"');
}
else if (c == '\'')
{
strBuf.append('\'');
}
else if (c == 'u')
{
state = STATE_HEX_DIGITS;
hex.setLength(0);
break;
}
else
{
error("Invalid character escape sequence specified");
}
state = STATE_STRING_START;
break;
case STATE_HEX_DIGITS:
if (c == 'a' || c == 'A' || c == 'b' || c == 'B' || c == 'c' || c == 'C' || c == 'd' || c == 'D' || c == 'e' || c == 'E' || c == 'f' || c == 'F' || isDigit(c))
{
hex.append((char) c);
if (hex.length() == 4)
{
int value = Integer.parseInt(hex.toString(), 16);
strBuf.append(valueOf((char) value));
state = STATE_STRING_START;
}
}
else
{
error("Expected hexadecimal digits");
}
break;
}
}
String s = strBuf.toString();
String cacheHit = _stringCache.get(s);
return cacheHit == null ? s : cacheHit;
}
private static Object newInstance(Class c) throws IOException
{
if (_factory.containsKey(c))
{
return _factory.get(c).newInstance(c);
}
// Constructor not cached, go find a constructor
Object[] constructorInfo = _constructors.get(c);
if (constructorInfo != null)
{ // Constructor was cached
Constructor constructor = (Constructor) constructorInfo[0];
Boolean useNull = (Boolean) constructorInfo[1];
Class[] paramTypes = constructor.getParameterTypes();
if (paramTypes == null || paramTypes.length == 0)
{
try
{
return constructor.newInstance();
}
catch (Exception e)
{ // Should never happen, as the code that fetched the constructor was able to instantiate it once already
error("Could not instantiate " + c.getName(), e);
}
}
Object[] values = fillArgs(paramTypes, useNull);
try
{
return constructor.newInstance(values);
}
catch (Exception e)
{ // Should never happen, as the code that fetched the constructor was able to instantiate it once already
error("Could not instantiate " + c.getName(), e);
}
}
Object[] ret = newInstanceEx(c);
_constructors.put(c, new Object[] {ret[1], ret[2]});
return ret[0];
}
/**
* Return constructor and instance as elements 0 and 1, respectively.
*/
private static Object[] newInstanceEx(Class c) throws IOException
{
try
{
Constructor constructor = c.getConstructor(_emptyClassArray);
if (constructor != null)
{
return new Object[] {constructor.newInstance(), constructor, true};
}
return tryOtherConstructors(c);
}
catch (Exception e)
{
// OK, this class does not have a public no-arg constructor. Instantiate with
// first constructor found, filling in constructor values with null or
// defaults for primitives.
return tryOtherConstructors(c);
}
}
private static Object[] tryOtherConstructors(Class c) throws IOException
{
Constructor[] constructors = c.getDeclaredConstructors();
if (constructors.length == 0)
{
error("Cannot instantiate '" + c.getName() + "' - Primitive, interface, array[] or void");
}
// Try each constructor (private, protected, or public) with null values for non-primitives.
for (Constructor constructor : constructors)
{
constructor.setAccessible(true);
Class[] argTypes = constructor.getParameterTypes();
Object[] values = fillArgs(argTypes, true);
try
{
return new Object[] {constructor.newInstance(values), constructor, true};
}
catch (Exception ignored)
{ }
}
// Try each constructor (private, protected, or public) with non-null values for primitives.
for (Constructor constructor : constructors)
{
constructor.setAccessible(true);
Class[] argTypes = constructor.getParameterTypes();
Object[] values = fillArgs(argTypes, false);
try
{
return new Object[] {constructor.newInstance(values), constructor, false};
}
catch (Exception ignored)
{ }
}
error("Could not instantiate " + c.getName() + " using any constructor");
return null;
}
private static Object[] fillArgs(Class[] argTypes, boolean useNull) throws IOException
{
Object[] values = new Object[argTypes.length];
for (int i = 0; i < argTypes.length; i++)
{
final Class argType = argTypes[i];
if (isPrimitive(argType))
{
values[i] = newPrimitiveWrapper(argType, null);
}
else if (useNull)
{
values[i] = null;
}
else
{
if (argType == String.class)
{
values[i] = "";
}
else if (argType == Date.class)
{
values[i] = new Date();
}
else if (List.class.isAssignableFrom(argType))
{
values[i] = new ArrayList();
}
else if (SortedSet.class.isAssignableFrom(argType))
{
values[i] = new TreeSet();
}
else if (Set.class.isAssignableFrom(argType))
{
values[i] = new LinkedHashSet();
}
else if (SortedMap.class.isAssignableFrom(argType))
{
values[i] = new TreeMap();
}
else if (Map.class.isAssignableFrom(argType))
{
values[i] = new LinkedHashMap();
}
else if (Collection.class.isAssignableFrom(argType))
{
values[i] = new ArrayList();
}
else if (Calendar.class.isAssignableFrom(argType))
{
values[i] = Calendar.getInstance();
}
else if (TimeZone.class.isAssignableFrom(argType))
{
values[i] = TimeZone.getDefault();
}
else if (argType == BigInteger.class)
{
values[i] = BigInteger.TEN;
}
else if (argType == BigDecimal.class)
{
values[i] = BigDecimal.TEN;
}
else if (argType == StringBuilder.class)
{
values[i] = new StringBuilder();
}
else if (argType == StringBuffer.class)
{
values[i] = new StringBuffer();
}
else if (argType == Locale.class)
{
values[i] = Locale.FRANCE; // overwritten
}
else if (argType == Class.class)
{
values[i] = String.class;
}
else if (argType == java.sql.Timestamp.class)
{
values[i] = new Timestamp(System.currentTimeMillis());
}
else if (argType == java.sql.Date.class)
{
values[i] = new java.sql.Date(System.currentTimeMillis());
}
else
{
values[i] = null;
}
}
}
return values;
}
public static boolean isPrimitive(Class c)
{
return c.isPrimitive() || _prims.contains(c);
}
private static Object newPrimitiveWrapper(Class c, Object rhs) throws IOException
{
if (c == Byte.class || c == byte.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0";
}
return Byte.parseByte((String)rhs);
}
return rhs != null ? _byteCache[((Number) rhs).byteValue() + 128] : (byte) 0;
}
if (c == Boolean.class || c == boolean.class)
{ // Booleans are tokenized into Boolean.TRUE or Boolean.FALSE
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "false";
}
return Boolean.parseBoolean((String)rhs);
}
return rhs != null ? rhs : Boolean.FALSE;
}
if (c == Integer.class || c == int.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0";
}
return Integer.parseInt((String)rhs);
}
return rhs != null ? ((Number) rhs).intValue() : 0;
}
if (c == Long.class || c == long.class || c == Number.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0";
}
return Long.parseLong((String)rhs);
}
return rhs != null ? rhs : 0L;
}
if (c == Double.class || c == double.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0.0";
}
return Double.parseDouble((String)rhs);
}
return rhs != null ? rhs : 0.0d;
}
if (c == Character.class || c == char.class)
{
if (rhs == null)
{
return '\u0000';
}
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "\u0000";
}
return valueOf(((String) rhs).charAt(0));
}
if (rhs instanceof Character)
{
return rhs;
}
}
if (c == Short.class || c == short.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0";
}
return Short.parseShort((String)rhs);
}
return rhs != null ? ((Number) rhs).shortValue() : (short) 0;
}
if (c == Float.class || c == float.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0.0f";
}
return Float.parseFloat((String)rhs);
}
return rhs != null ? ((Number) rhs).floatValue() : 0.0f;
}
return error("Class '" + c.getName() + "' requested for special instantiation - isPrimitive() does not match newPrimitiveWrapper()");
}
static String removeLeadingAndTrailingQuotes(String s)
{
Matcher m = _extraQuotes.matcher(s);
if (m.find())
{
s = m.group(2);
}
return s;
}
private static boolean isDigit(int c)
{
return c >= '0' && c <= '9';
}
private static boolean isWhitespace(int c)
{
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
private static Class classForName(String name) throws IOException
{
if (name == null || name.isEmpty())
{
error("Invalid class name specified");
}
try
{
Class c = _nameToClass.get(name);
return c == null ? loadClass(name) : c;
}
catch (ClassNotFoundException e)
{
return (Class) error("Class instance '" + name + "' could not be created", e);
}
}
static Class classForName2(String name) throws IOException
{
if (name == null || name.isEmpty())
{
error("Empty class name.");
}
try
{
Class c = _nameToClass.get(name);
return c == null ? loadClass(name) : c;
}
catch (ClassNotFoundException e)
{
error("Class instance '" + name + "' could not be created.", e);
return null;
}
}
// loadClass() provided by: Thomas Margreiter
private static Class loadClass(String name) throws ClassNotFoundException
{
String className = name;
boolean arrayType = false;
Class primitiveArray = null;
while (className.startsWith("["))
{
arrayType = true;
if (className.endsWith(";")) className = className.substring(0,className.length()-1);
if (className.equals("[B")) primitiveArray = byte[].class;
else if (className.equals("[S")) primitiveArray = short[].class;
else if (className.equals("[I")) primitiveArray = int[].class;
else if (className.equals("[J")) primitiveArray = long[].class;
else if (className.equals("[F")) primitiveArray = float[].class;
else if (className.equals("[D")) primitiveArray = double[].class;
else if (className.equals("[Z")) primitiveArray = boolean[].class;
else if (className.equals("[C")) primitiveArray = char[].class;
int startpos = className.startsWith("[L") ? 2 : 1;
className = className.substring(startpos);
}
Class currentClass = null;
if (null == primitiveArray)
{
currentClass = Thread.currentThread().getContextClassLoader().loadClass(className);
}
if (arrayType)
{
currentClass = (null != primitiveArray) ? primitiveArray : Array.newInstance(currentClass, 0).getClass();
while (name.startsWith("[["))
{
currentClass = Array.newInstance(currentClass, 0).getClass();
name = name.substring(1);
}
}
return currentClass;
}
/**
* Get a Field object using a String field name and a Class instance. This
* method will start on the Class passed in, and if not found there, will
* walk up super classes until it finds the field, or throws an IOException
* if it cannot find the field.
*
* @param c Class containing the desired field.
* @param fieldName String name of the desired field.
* @return Field object obtained from the passed in class (by name). The Field
* returned is cached so that it is only obtained via reflection once.
* @throws IOException for stream errors or parsing errors.
*/
private static Field getDeclaredField(Class c, String fieldName) throws IOException
{
return JsonWriter.getDeepDeclaredFields(c).get(fieldName);
}
/**
* Read until non-whitespace character and then return it.
* This saves extra read/pushback.
*
* @return int representing the next non-whitespace character in the stream.
* @throws IOException for stream errors or parsing errors.
*/
private int skipWhitespaceRead() throws IOException
{
final FastPushbackReader in = _in;
int c = in.read();
while (isWhitespace(c))
{
c = in.read();
}
return c;
}
private void skipWhitespace() throws IOException
{
_in.unread(skipWhitespaceRead());
}
public void close()
{
try
{
if (_in != null)
{
_in.close();
}
}
catch (IOException ignored) { }
}
/**
* For all fields where the value was "@ref":"n" where 'n' was the id of an object
* that had not yet been encountered in the stream, make the final substitution.
* @throws IOException
*/
private void patchUnresolvedReferences() throws IOException
{
Iterator i = _unresolvedRefs.iterator();
while (i.hasNext())
{
UnresolvedReference ref = (UnresolvedReference) i.next();
Object objToFix = ref.referencingObj.target;
JsonObject objReferenced = _objsRead.get(ref.refId);
if (objReferenced == null)
{
// System.err.println("Back reference (" + ref.refId + ") does not match any object id in input, field '" + ref.field + '\'');
continue;
}
if (objReferenced.target == null)
{
// System.err.println("Back referenced object does not exist, @ref " + ref.refId + ", field '" + ref.field + '\'');
continue;
}
if (objToFix == null)
{
// System.err.println("Referencing object is null, back reference, @ref " + ref.refId + ", field '" + ref.field + '\'');
continue;
}
if (ref.index >= 0)
{ // Fix []'s and Collections containing a forward reference.
if (objToFix instanceof List)
{ // Patch up Indexable Collections
List list = (List) objToFix;
list.set(ref.index, objReferenced.target);
}
else if (objToFix instanceof Collection)
{ // Add element (since it was not indexable, add it to collection)
Collection col = (Collection) objToFix;
col.add(objReferenced.target);
}
else
{
Array.set(objToFix, ref.index, objReferenced.target); // patch array element here
}
}
else
{ // Fix field forward reference
Field field = getDeclaredField(objToFix.getClass(), ref.field);
if (field != null)
{
try
{
field.set(objToFix, objReferenced.target); // patch field here
}
catch (Exception e)
{
error("Error setting field while resolving references '" + field.getName() + "', @ref = " + ref.refId, e);
}
}
}
i.remove();
}
int count = _unresolvedRefs.size();
if (count > 0)
{
StringBuilder out = new StringBuilder();
out.append(count);
out.append(" unresolved references:\n");
i = _unresolvedRefs.iterator();
count = 1;
while (i.hasNext())
{
UnresolvedReference ref = (UnresolvedReference) i.next();
out.append(" Unresolved reference ");
out.append(count);
out.append('\n');
out.append(" @ref ");
out.append(ref.refId);
out.append('\n');
out.append(" field ");
out.append(ref.field);
out.append("\n\n");
count++;
}
error(out.toString());
}
}
/**
* Process Maps/Sets (fix up their internal indexing structure)
* This is required because Maps hash items using hashCode(), which will
* change between VMs. Rehashing the map fixes this.
*
* If _noObjects==true, then move @keys to keys and @items to values
* and then drop these two entries from the map.
*/
private void rehashMaps()
{
final boolean useMaps = _noObjects;
for (Object[] mapPieces : _prettyMaps)
{
JsonObject jObj = (JsonObject) mapPieces[0];
Object[] javaKeys, javaValues;
Map map;
if (useMaps)
{ // Make the @keys be the actual keys of the map.
map = jObj;
javaKeys = (Object[]) jObj.remove("@keys");
javaValues = (Object[]) jObj.remove("@items");
}
else
{
map = (Map) jObj.target;
javaKeys = (Object[]) mapPieces[1];
javaValues = (Object[]) mapPieces[2];
jObj.clear();
}
int j=0;
while (javaKeys != null && j < javaKeys.length)
{
map.put(javaKeys[j], javaValues[j]);
j++;
}
}
}
private static String getErrorMessage(String msg)
{
return msg + "\nLast read: " + getLastReadSnippet() + "\nline: " + _line.get() + ", col: " + _col.get();
}
static Object error(String msg) throws IOException
{
throw new IOException(getErrorMessage(msg));
}
static Object error(String msg, Exception e) throws IOException
{
throw new IOException(getErrorMessage(msg), e);
}
private static String getLastReadSnippet()
{
StringBuilder s = new StringBuilder();
for (char[] chars : _snippet.get())
{
s.append(chars);
}
return s.toString();
}
/**
* This is a performance optimization. The lowest 128 characters are re-used.
*
* @param c char to match to a Character.
* @return a Character that matches the passed in char. If the value is
* less than 127, then the same Character instances are re-used.
*/
private static Character valueOf(char c)
{
return c <= 127 ? _charCache[(int) c] : c;
}
public static final int MAX_CODE_POINT = 0x10ffff;
public static final int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000;
public static final char MIN_LOW_SURROGATE = '\uDC00';
public static final char MIN_HIGH_SURROGATE = '\uD800';
private static char[] toChars(int codePoint)
{
if (codePoint < 0 || codePoint > MAX_CODE_POINT)
{ // int UTF-8 char must be in range
throw new IllegalArgumentException("value ' + codePoint + ' outside UTF-8 range");
}
if (codePoint < MIN_SUPPLEMENTARY_CODE_POINT)
{ // if the int character fits in two bytes...
return new char[]{(char) codePoint};
}
char[] result = new char[2];
int offset = codePoint - MIN_SUPPLEMENTARY_CODE_POINT;
result[1] = (char) ((offset & 0x3ff) + MIN_LOW_SURROGATE);
result[0] = (char) ((offset >>> 10) + MIN_HIGH_SURROGATE);
return result;
}
/**
* This class adds significant performance increase over using the JDK
* PushbackReader. This is due to this class not using synchronization
* as it is not needed.
*/
private static class FastPushbackReader extends FilterReader
{
private final int[] _buf;
private int _idx;
private FastPushbackReader(Reader reader, int size)
{
super(reader);
_snippet.get().clear();
_line.set(1);
_col.set(1);
if (size <= 0)
{
throw new IllegalArgumentException("size <= 0");
}
_buf = new int[size];
_idx = size;
}
private FastPushbackReader(Reader r)
{
this(r, 1);
}
public int read() throws IOException
{
int ch;
if (_idx < _buf.length)
{ // read from push-back buffer
ch = _buf[_idx++];
}
else
{
ch = super.read();
}
if (ch >= 0)
{
if (ch == 0x0a)
{
_line.set(_line.get() + 1);
_col.set(0);
}
else
{
_col.set(_col.get() + 1);
}
Deque<char[]> buffer = _snippet.get();
buffer.addLast(toChars(ch));
if (buffer.size() > 100)
{
buffer.removeFirst();
}
}
return ch;
}
public void unread(int c) throws IOException
{
if (_idx == 0)
{
error("unread(int c) called more than buffer size (" + _buf.length + ")");
}
if (c == 0x0a)
{
_line.set(_line.get() - 1);
}
else
{
_col.set(_col.get() - 1);
}
_buf[--_idx] = c;
_snippet.get().removeLast();
}
/**
* Closes the stream and releases any system resources associated with
* it. Once the stream has been closed, further read(),
* unread(), ready(), or skip() invocations will throw an IOException.
* Closing a previously closed stream has no effect.
*
* @throws java.io.IOException If an I/O error occurs
*/
public void close() throws IOException
{
super.close();
_snippet.remove();
_line.remove();
_col.remove();
}
}
}
| src/main/java/com/cedarsoftware/util/io/JsonReader.java | package com.cedarsoftware.util.io;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.FilterReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Read an object graph in JSON format and make it available in Java objects, or
* in a "Map of Maps." (untyped representation). This code handles cyclic references
* and can deserialize any Object graph without requiring a class to be 'Serializeable'
* or have any specific methods on it. It will handle classes with non public constructors.
* <br/><br/>
* Usages:
* <ul><li>
* Call the static method: {@code JsonReader.objectToJava(String json)}. This will
* return a typed Java object graph.</li>
* <li>
* Call the static method: {@code JsonReader.jsonToMaps(String json)}. This will
* return an untyped object representation of the JSON String as a Map of Maps, where
* the fields are the Map keys, and the field values are the associated Map's values. You can
* call the JsonWriter.objectToJava() method with the returned Map, and it will serialize
* the Graph into the identical JSON stream from which it was read.
* <li>
* Instantiate the JsonReader with an InputStream: {@code JsonReader(InputStream in)} and then call
* {@code readObject()}. Cast the return value of readObject() to the Java class that was the root of
* the graph.
* </li>
* <li>
* Instantiate the JsonReader with an InputStream: {@code JsonReader(InputStream in, true)} and then call
* {@code readObject()}. The return value will be a Map of Maps.
* </li></ul><br/>
*
* @author John DeRegnaucourt ([email protected])
* <br/>
* Copyright (c) Cedar Software LLC
* <br/><br/>
* 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
* <br/><br/>
* http://www.apache.org/licenses/LICENSE-2.0
* <br/><br/>
* 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.
*/
public class JsonReader implements Closeable
{
private static final int STATE_READ_START_OBJECT = 0;
private static final int STATE_READ_FIELD = 1;
private static final int STATE_READ_VALUE = 2;
private static final int STATE_READ_POST_VALUE = 3;
private static final String EMPTY_ARRAY = "~!a~"; // compared with ==
private static final String EMPTY_OBJECT = "~!o~"; // compared with ==
private static final Character[] _charCache = new Character[128];
private static final Byte[] _byteCache = new Byte[256];
private static final Map<String, String> _stringCache = new HashMap<String, String>();
private static final Set<Class> _prims = new HashSet<Class>();
private static final Map<Class, Object[]> _constructors = new HashMap<Class, Object[]>();
private static final Map<String, Class> _nameToClass = new HashMap<String, Class>();
private static final Class[] _emptyClassArray = new Class[]{};
private static final List<Object[]> _readers = new ArrayList<Object[]>();
private static final Set<Class> _notCustom = new HashSet<Class>();
private static final Map<String, String> _months = new LinkedHashMap<String, String>();
private static final Map<Class, ClassFactory> _factory = new LinkedHashMap<Class, ClassFactory>();
private static final Pattern _datePattern1 = Pattern.compile("^(\\d{4})[\\./-](\\d{1,2})[\\./-](\\d{1,2})");
private static final Pattern _datePattern2 = Pattern.compile("^(\\d{1,2})[\\./-](\\d{1,2})[\\./-](\\d{4})");
private static final Pattern _datePattern3 = Pattern.compile("(Jan|Feb|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|Sep|Sept|Oct|Nov|Dec)[ ,]+(\\d{1,2})[ ,]+(\\d{4})", Pattern.CASE_INSENSITIVE);
private static final Pattern _datePattern4 = Pattern.compile("(\\d{1,2})[ ,](Jan|Feb|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|Sep|Sept|Oct|Nov|Dec)[ ,]+(\\d{4})", Pattern.CASE_INSENSITIVE);
private static final Pattern _timePattern1 = Pattern.compile("(\\d{2})[:.](\\d{2})[:.](\\d{2})[.](\\d{1,3})");
private static final Pattern _timePattern2 = Pattern.compile("(\\d{2})[:.](\\d{2})[:.](\\d{2})");
private static final Pattern _timePattern3 = Pattern.compile("(\\d{2})[:.](\\d{2})");
private static final Pattern _extraQuotes = Pattern.compile("([\"]*)([^\"]*)([\"]*)");
private final Map<Long, JsonObject> _objsRead = new LinkedHashMap<Long, JsonObject>();
private final Collection<UnresolvedReference> _unresolvedRefs = new ArrayList<UnresolvedReference>();
private final Collection<Object[]> _prettyMaps = new ArrayList<Object[]>();
private final FastPushbackReader _in;
private boolean _noObjects = false;
private final char[] _numBuf = new char[256];
private final StringBuilder _strBuf = new StringBuilder();
static final ThreadLocal<Deque<char[]>> _snippet = new ThreadLocal<Deque<char[]>>()
{
public Deque<char[]> initialValue()
{
return new ArrayDeque<char[]>(128);
}
};
static final ThreadLocal<Integer> _line = new ThreadLocal<Integer>()
{
public Integer initialValue()
{
return 1;
}
};
static final ThreadLocal<Integer> _col = new ThreadLocal<Integer>()
{
public Integer initialValue()
{
return 1;
}
};
static
{
// Save memory by re-using common Characters (Characters are immutable)
for (int i = 0; i < _charCache.length; i++)
{
_charCache[i] = (char) i;
}
// Save memory by re-using all byte instances (Bytes are immutable)
for (int i = 0; i < _byteCache.length; i++)
{
_byteCache[i] = (byte) (i - 128);
}
// Save heap memory by re-using common strings (String's immutable)
_stringCache.put("", "");
_stringCache.put("true", "true");
_stringCache.put("True", "True");
_stringCache.put("TRUE", "TRUE");
_stringCache.put("false", "false");
_stringCache.put("False", "False");
_stringCache.put("FALSE", "FALSE");
_stringCache.put("null", "null");
_stringCache.put("yes", "yes");
_stringCache.put("Yes", "Yes");
_stringCache.put("YES", "YES");
_stringCache.put("no", "no");
_stringCache.put("No", "No");
_stringCache.put("NO", "NO");
_stringCache.put("on", "on");
_stringCache.put("On", "On");
_stringCache.put("ON", "ON");
_stringCache.put("off", "off");
_stringCache.put("Off", "Off");
_stringCache.put("OFF", "OFF");
_stringCache.put("@id", "@id");
_stringCache.put("@ref", "@ref");
_stringCache.put("@items", "@items");
_stringCache.put("@type", "@type");
_stringCache.put("@keys", "@keys");
_stringCache.put("0", "0");
_stringCache.put("1", "1");
_stringCache.put("2", "2");
_stringCache.put("3", "3");
_stringCache.put("4", "4");
_stringCache.put("5", "5");
_stringCache.put("6", "6");
_stringCache.put("7", "7");
_stringCache.put("8", "8");
_stringCache.put("9", "9");
_prims.add(Byte.class);
_prims.add(Integer.class);
_prims.add(Long.class);
_prims.add(Double.class);
_prims.add(Character.class);
_prims.add(Float.class);
_prims.add(Boolean.class);
_prims.add(Short.class);
_nameToClass.put("string", String.class);
_nameToClass.put("boolean", boolean.class);
_nameToClass.put("char", char.class);
_nameToClass.put("byte", byte.class);
_nameToClass.put("short", short.class);
_nameToClass.put("int", int.class);
_nameToClass.put("long", long.class);
_nameToClass.put("float", float.class);
_nameToClass.put("double", double.class);
_nameToClass.put("date", Date.class);
_nameToClass.put("class", Class.class);
addReader(String.class, new StringReader());
addReader(Date.class, new DateReader());
addReader(BigInteger.class, new BigIntegerReader());
addReader(BigDecimal.class, new BigDecimalReader());
addReader(java.sql.Date.class, new SqlDateReader());
addReader(Timestamp.class, new TimestampReader());
addReader(Calendar.class, new CalendarReader());
addReader(TimeZone.class, new TimeZoneReader());
addReader(Locale.class, new LocaleReader());
addReader(Class.class, new ClassReader());
addReader(StringBuilder.class, new StringBuilderReader());
addReader(StringBuffer.class, new StringBufferReader());
ClassFactory colFactory = new CollectionFactory();
assignInstantiator(Collection.class, colFactory);
assignInstantiator(List.class, colFactory);
assignInstantiator(Set.class, colFactory);
assignInstantiator(SortedSet.class, colFactory);
assignInstantiator(Collection.class, colFactory);
ClassFactory mapFactory = new MapFactory();
assignInstantiator(Map.class, mapFactory);
assignInstantiator(SortedMap.class, mapFactory);
// Month name to number map
_months.put("jan", "1");
_months.put("january", "1");
_months.put("feb", "2");
_months.put("february", "2");
_months.put("mar", "3");
_months.put("march", "3");
_months.put("apr", "4");
_months.put("april", "4");
_months.put("may", "5");
_months.put("jun", "6");
_months.put("june", "6");
_months.put("jul", "7");
_months.put("july", "7");
_months.put("aug", "8");
_months.put("august", "8");
_months.put("sep", "9");
_months.put("sept", "9");
_months.put("september", "9");
_months.put("oct", "10");
_months.put("october", "10");
_months.put("nov", "11");
_months.put("november", "11");
_months.put("dec", "12");
_months.put("december", "12");
}
public interface JsonClassReader
{
Object read(Object jOb, LinkedList<JsonObject<String, Object>> stack) throws IOException;
}
public interface ClassFactory
{
Object newInstance(Class c);
}
/**
* For difficult to instantiate classes, you can add your own ClassFactory
* which will be called when the passed in class 'c' is encountered. Your
* ClassFactory will be called with newInstance(c) and your factory is expected
* to return a new instance of 'c'.
*
* This API is an 'escape hatch' to allow ANY object to be instantiated by JsonReader
* and is useful when you encounter a class that JsonReader cannot instantiate using its
* internal exhausting attempts (trying all constructors, varying arguments to them, etc.)
*/
public static void assignInstantiator(Class c, ClassFactory factory)
{
_factory.put(c, factory);
}
/**
* Use to create new instances of collection interfaces (needed for empty collections)
*/
public static class CollectionFactory implements ClassFactory
{
public Object newInstance(Class c)
{
if (List.class.isAssignableFrom(c))
{
return new ArrayList();
}
else if (SortedSet.class.isAssignableFrom(c))
{
return new TreeSet();
}
else if (Set.class.isAssignableFrom(c))
{
return new LinkedHashSet();
}
else if (Collection.class.isAssignableFrom(c))
{
return new ArrayList();
}
throw new RuntimeException("CollectionFactory handed Class for which it was not expecting: " + c.getName());
}
}
/**
* Use to create new instances of Map interfaces (needed for empty Maps)
*/
public static class MapFactory implements ClassFactory
{
public Object newInstance(Class c)
{
if (SortedMap.class.isAssignableFrom(c))
{
return new TreeMap();
}
else if (Map.class.isAssignableFrom(c))
{
return new LinkedHashMap();
}
throw new RuntimeException("MapFactory handed Class for which it was not expecting: " + c.getName());
}
}
public static class TimeZoneReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = (JsonObject)o;
Object zone = jObj.get("zone");
if (zone == null)
{
error("java.util.TimeZone must specify 'zone' field");
}
return jObj.target = TimeZone.getTimeZone((String) zone);
}
}
public static class LocaleReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = (JsonObject) o;
Object language = jObj.get("language");
if (language == null)
{
error("java.util.Locale must specify 'language' field");
}
Object country = jObj.get("country");
Object variant = jObj.get("variant");
if (country == null)
{
return jObj.target = new Locale((String) language);
}
if (variant == null)
{
return jObj.target = new Locale((String) language, (String) country);
}
return jObj.target = new Locale((String) language, (String) country, (String) variant);
}
}
public static class CalendarReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
String time = null;
try
{
JsonObject jObj = (JsonObject) o;
time = (String) jObj.get("time");
if (time == null)
{
error("Calendar missing 'time' field");
}
Date date = JsonWriter._dateFormat.get().parse(time);
Class c;
if (jObj.getTarget() != null)
{
c = jObj.getTarget().getClass();
}
else
{
Object type = jObj.type;
c = classForName2((String) type);
}
Calendar calendar = (Calendar) newInstance(c);
calendar.setTime(date);
jObj.setTarget(calendar);
String zone = (String) jObj.get("zone");
if (zone != null)
{
calendar.setTimeZone(TimeZone.getTimeZone(zone));
}
return calendar;
}
catch(Exception e)
{
return error("Failed to parse calendar, time: " + time);
}
}
}
public static class DateReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof Long)
{
return new Date((Long) o);
}
else if (o instanceof String)
{
return parseDate((String)o);
}
else if (o instanceof JsonObject)
{
JsonObject jObj = (JsonObject)o;
Object val = jObj.get("value");
if (val instanceof Long)
{
return new Date((Long) val);
}
else if (val instanceof String)
{
return parseDate((String) val);
}
return error("Unable to parse date: " + o);
}
else
{
return error("Unable to parse date, encountered unknown object: " + o);
}
}
private static Date parseDate(String dateStr) throws IOException
{
dateStr = dateStr.trim();
// Determine which date pattern (Matcher) to use
Matcher matcher = _datePattern1.matcher(dateStr);
String year, month = null, day, mon = null;
if (matcher.find())
{
year = matcher.group(1);
month = matcher.group(2);
day = matcher.group(3);
}
else
{
matcher = _datePattern2.matcher(dateStr);
if (matcher.find())
{
month = matcher.group(1);
day = matcher.group(2);
year = matcher.group(3);
}
else
{
matcher = _datePattern3.matcher(dateStr);
if (matcher.find())
{
mon = matcher.group(1);
day = matcher.group(2);
year = matcher.group(3);
}
else
{
matcher = _datePattern4.matcher(dateStr);
if (!matcher.find())
{
error("Unable to parse: " + dateStr);
}
day = matcher.group(1);
mon = matcher.group(2);
year = matcher.group(3);
}
}
}
if (mon != null)
{
month = _months.get(mon.trim().toLowerCase());
if (month == null)
{
error("Unable to parse month portion of date: " + dateStr);
}
}
// Determine which date pattern (Matcher) to use
matcher = _timePattern1.matcher(dateStr);
if (!matcher.find())
{
matcher = _timePattern2.matcher(dateStr);
if (!matcher.find())
{
matcher = _timePattern3.matcher(dateStr);
if (!matcher.find())
{
matcher = null;
}
}
}
Calendar c = Calendar.getInstance();
c.clear();
int y = 0;
int m = 0;
int d = 0;
try
{
y = Integer.parseInt(year);
m = Integer.parseInt(month) - 1; // months are 0-based
d = Integer.parseInt(day);
}
catch (Exception e)
{
error("Unable to parse: " + dateStr, e);
}
if (matcher == null)
{ // no [valid] time portion
c.set(y, m, d);
}
else
{
String hour = matcher.group(1);
String min = matcher.group(2);
String sec = "00";
String milli = "000";
if (matcher.groupCount() > 2)
{
sec = matcher.group(3);
}
if (matcher.groupCount() > 3)
{
milli = matcher.group(4);
}
int h = 0;
int mn = 0;
int s = 0;
int ms = 0;
try
{
h = Integer.parseInt(hour);
mn = Integer.parseInt(min);
s = Integer.parseInt(sec);
ms = Integer.parseInt(milli);
}
catch (Exception e)
{
error("Unable to parse time: " + dateStr, e);
}
c.set(y, m, d, h, mn, s);
c.set(Calendar.MILLISECOND, ms);
}
return c.getTime();
}
}
public static class SqlDateReader extends DateReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
return new java.sql.Date(((Date) super.read(o, stack)).getTime());
}
}
public static class StringReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof String)
{
return o;
}
if (isPrimitive(o.getClass()))
{
return o.toString();
}
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
return jObj.target = jObj.get("value");
}
return error("String missing 'value' field");
}
}
public static class ClassReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof String)
{
return classForName2((String)o);
}
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
return jObj.target = classForName2((String) jObj.get("value"));
}
return error("Class missing 'value' field");
}
}
public static class BigIntegerReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = null;
Object value = o;
if (o instanceof JsonObject)
{
jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
value = jObj.get("value");
}
else
{
return error("BigInteger missing 'value' field");
}
}
BigInteger x = null;
if (value instanceof JsonObject)
{
JsonObject valueObj = (JsonObject)value;
if ("java.math.BigDecimal".equals(valueObj.type))
{
BigDecimalReader reader = new BigDecimalReader();
value = reader.read(value, stack);
}
else if ("java.math.BigInteger".equals(valueObj.type))
{
value = read(value, stack);
}
else
{
return error("Unknown object type attempted to be assigned to BigInteger field: " + value);
}
}
if (value instanceof String)
{
x = new BigInteger(removeLeadingAndTrailingQuotes((String) value));
}
if (value instanceof BigInteger)
{
x = (BigInteger) value;
}
if (value instanceof BigDecimal)
{
BigDecimal bd = (BigDecimal) value;
String str = bd.toPlainString();
if (str.contains("."))
{
return error("Cannot assign BigDecimal to BigInteger if BigDecimal has fractional part: " + value);
}
x = new BigInteger(str);
}
if (value instanceof Boolean)
{
x = new BigInteger(((Boolean) value) ? "1" : "0");
}
if (value instanceof Double || value instanceof Float)
{
return error("Cannot assign floating point value to a BigInteger: " + value);
}
if (value instanceof Long || value instanceof Integer ||
value instanceof Short || value instanceof Byte)
{
x = new BigInteger(value.toString());
}
if (jObj != null)
{
jObj.target = x;
}
return x != null ? x : error("BigInteger 'value' convertible to a BigInteger: " + value);
}
}
public static class BigDecimalReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = null;
Object value = o;
if (o instanceof JsonObject)
{
jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
value = jObj.get("value");
}
else
{
return error("BigDecimal missing 'value' field");
}
}
BigDecimal x = null;
if (value instanceof JsonObject)
{
JsonObject valueObj = (JsonObject)value;
if ("java.math.BigInteger".equals(valueObj.type))
{
BigIntegerReader reader = new BigIntegerReader();
value = reader.read(value, stack);
}
else if ("java.math.BigDecimal".equals(valueObj.type))
{
value = read(value, stack);
}
else
{
return error("Unknown object type attempted to be assigned to BigInteger field: " + value);
}
}
if (value instanceof String)
{
x = new BigDecimal(removeLeadingAndTrailingQuotes((String) value));
}
if (value instanceof BigDecimal)
{
x = (BigDecimal) value;
}
if (value instanceof BigInteger)
{
x = new BigDecimal((BigInteger)value);
}
if (value instanceof Boolean)
{
x = new BigDecimal(((Boolean) value) ? "1" : "0");
}
if (value instanceof Long || value instanceof Double || value instanceof Integer ||
value instanceof Short || value instanceof Byte || value instanceof Float || value instanceof BigInteger)
{
x = new BigDecimal(value.toString());
}
if (jObj != null)
{
jObj.target = x;
}
return x != null ? x : error("BigDecimal missing 'value' field not convertible to a BigDecimal: " + value);
}
}
public static class StringBuilderReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof String)
{
return new StringBuilder((String) o);
}
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
return jObj.target = new StringBuilder((String) jObj.get("value"));
}
return error("StringBuilder missing 'value' field");
}
}
public static class StringBufferReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o instanceof String)
{
return new StringBuffer((String) o);
}
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("value"))
{
return jObj.target = new StringBuffer((String) jObj.get("value"));
}
return error("StringBuffer missing 'value' field");
}
}
public static class TimestampReader implements JsonClassReader
{
public Object read(Object o, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
JsonObject jObj = (JsonObject) o;
Object time = jObj.get("time");
if (time == null)
{
error("java.sql.Timestamp must specify 'time' field");
}
Object nanos = jObj.get("nanos");
if (nanos == null)
{
return jObj.target = new Timestamp(Long.valueOf((String) time));
}
Timestamp tstamp = new Timestamp(Long.valueOf((String) time));
tstamp.setNanos(Integer.valueOf((String) nanos));
return jObj.target = tstamp;
}
}
public static void addReader(Class c, JsonClassReader reader)
{
for (Object[] item : _readers)
{
Class clz = (Class)item[0];
if (clz == c)
{
item[1] = reader; // Replace reader
return;
}
}
_readers.add(new Object[] {c, reader});
}
public static void addNotCustomReader(Class c)
{
_notCustom.add(c);
}
protected Object readIfMatching(Object o, Class compType, LinkedList<JsonObject<String, Object>> stack) throws IOException
{
if (o == null)
{
error("Bug in json-io, null must be checked before calling this method.");
}
if (_notCustom.contains(o.getClass()))
{
return null;
}
if (compType != null)
{
if (_notCustom.contains(compType))
{
return null;
}
}
boolean isJsonObject = o instanceof JsonObject;
if (!isJsonObject && compType == null)
{ // If not a JsonObject (like a Long that represents a date, then compType must be set)
return null;
}
Class c;
boolean needsType = false;
// Set up class type to check against reader classes (specified as @type, or jObj.target, or compType)
if (isJsonObject)
{
JsonObject jObj = (JsonObject) o;
if (jObj.containsKey("@ref"))
{
return null;
}
if (jObj.target == null)
{ // '@type' parameter used
String typeStr = null;
try
{
Object type = jObj.type;
if (type != null)
{
typeStr = (String) type;
c = classForName((String) type);
}
else
{
if (compType != null)
{
c = compType;
needsType = true;
}
else
{
return null;
}
}
}
catch(Exception e)
{
return error("Class listed in @type [" + typeStr + "] is not found", e);
}
}
else
{ // Type inferred from target object
c = jObj.target.getClass();
}
}
else
{
c = compType;
}
JsonClassReader closestReader = null;
int minDistance = Integer.MAX_VALUE;
for (Object[] item : _readers)
{
Class clz = (Class)item[0];
if (clz == c)
{
closestReader = (JsonClassReader)item[1];
break;
}
int distance = JsonWriter.getDistance(clz, c);
if (distance < minDistance)
{
minDistance = distance;
closestReader = (JsonClassReader)item[1];
}
}
if (closestReader == null)
{
return null;
}
if (needsType && isJsonObject)
{
((JsonObject)o).setType(c.getName());
}
return closestReader.read(o, stack);
}
/**
* UnresolvedReference is created to hold a logical pointer to a reference that
* could not yet be loaded, as the @ref appears ahead of the referenced object's
* definition. This can point to a field reference or an array/Collection element reference.
*/
private static class UnresolvedReference
{
private JsonObject referencingObj;
private String field;
private long refId;
private int index = -1;
private UnresolvedReference(JsonObject referrer, String fld, long id)
{
referencingObj = referrer;
field = fld;
refId = id;
}
private UnresolvedReference(JsonObject referrer, int idx, long id)
{
referencingObj = referrer;
index = idx;
refId = id;
}
}
/**
* Convert the passed in JSON string into a Java object graph.
*
* @param json String JSON input
* @return Java object graph matching JSON input, or null if an
* error occurred.
*/
@Deprecated
public static Object toJava(String json)
{
throw new RuntimeException("Use com.cedarsoftware.util.JsonReader");
}
/**
* Convert the passed in JSON string into a Java object graph.
*
* @param json String JSON input
* @return Java object graph matching JSON input
* @throws java.io.IOException If an I/O error occurs
*/
public static Object jsonToJava(String json) throws IOException
{
ByteArrayInputStream ba = new ByteArrayInputStream(json.getBytes("UTF-8"));
JsonReader jr = new JsonReader(ba, false);
Object obj = jr.readObject();
jr.close();
return obj;
}
/**
* Convert the passed in JSON string into a Java object graph
* that consists solely of Java Maps where the keys are the
* fields and the values are primitives or other Maps (in the
* case of objects).
*
* @param json String JSON input
* @return Java object graph of Maps matching JSON input,
* or null if an error occurred.
*/
@Deprecated
public static Map toMaps(String json)
{
try
{
return jsonToMaps(json);
}
catch (Exception ignored)
{
return null;
}
}
/**
* Convert the passed in JSON string into a Java object graph
* that consists solely of Java Maps where the keys are the
* fields and the values are primitives or other Maps (in the
* case of objects).
*
* @param json String JSON input
* @return Java object graph of Maps matching JSON input,
* or null if an error occurred.
* @throws java.io.IOException If an I/O error occurs
*/
public static Map jsonToMaps(String json) throws IOException
{
ByteArrayInputStream ba = new ByteArrayInputStream(json.getBytes("UTF-8"));
JsonReader jr = new JsonReader(ba, true);
Map map = (Map) jr.readObject();
jr.close();
return map;
}
public JsonReader()
{
_noObjects = false;
_in = null;
}
public JsonReader(InputStream in)
{
this(in, false);
}
public JsonReader(InputStream in, boolean noObjects)
{
_noObjects = noObjects;
try
{
_in = new FastPushbackReader(new BufferedReader(new InputStreamReader(in, "UTF-8")));
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException("Your JVM does not support UTF-8. Get a new JVM.", e);
}
}
/**
* Finite State Machine (FSM) used to parse the JSON input into
* JsonObject's (Maps). Then, if requested, the JsonObjects are
* converted into Java instances.
*
* @return Java Object graph constructed from InputStream supplying
* JSON serialized content.
* @throws IOException for stream errors or parsing errors.
*/
public Object readObject() throws IOException
{
Object o = readJsonObject();
if (o == EMPTY_OBJECT)
{
return new JsonObject();
}
Object graph = convertParsedMapsToJava((JsonObject) o);
// Allow a complete 'Map' return (Javascript style)
if (_noObjects)
{
return o;
}
return graph;
}
/**
* Convert a root JsonObject that represents parsed JSON, into
* an actual Java object.
* @param root JsonObject instance that was the root object from the
* JSON input that was parsed in an earlier call to JsonReader.
* @return a typed Java instance that was serialized into JSON.
*/
public Object jsonObjectsToJava(JsonObject root) throws IOException
{
_noObjects = false;
return convertParsedMapsToJava(root);
}
/**
* This method converts a root Map, (which contains nested Maps
* and so forth representing a Java Object graph), to a Java
* object instance. The root map came from using the JsonReader
* to parse a JSON graph (using the API that puts the graph
* into Maps, not the typed representation).
* @param root JsonObject instance that was the root object from the
* JSON input that was parsed in an earlier call to JsonReader.
* @return a typed Java instance that was serialized into JSON.
*/
private Object convertParsedMapsToJava(JsonObject root) throws IOException
{
createJavaObjectInstance(Object.class, root);
Object graph = convertMapsToObjects((JsonObject<String, Object>) root);
patchUnresolvedReferences();
rehashMaps();
_objsRead.clear();
_unresolvedRefs.clear();
_prettyMaps.clear();
return graph;
}
/**
* Walk a JsonObject (Map of String keys to values) and return the
* Java object equivalent filled in as best as possible (everything
* except unresolved reference fields or unresolved array/collection elements).
*
* @param root JsonObject reference to a Map-of-Maps representation of the JSON
* input after it has been completely read.
* @return Properly constructed, typed, Java object graph built from a Map
* of Maps representation (JsonObject root).
* @throws IOException for stream errors or parsing errors.
*/
private Object convertMapsToObjects(JsonObject<String, Object> root) throws IOException
{
LinkedList<JsonObject<String, Object>> stack = new LinkedList<JsonObject<String, Object>>();
stack.addFirst(root);
final boolean useMaps = _noObjects;
while (!stack.isEmpty())
{
JsonObject<String, Object> jsonObj = stack.removeFirst();
if (useMaps)
{
if (jsonObj.isArray() || jsonObj.isCollection())
{
traverseCollectionNoObj(stack, jsonObj);
}
else if (jsonObj.isMap())
{
traverseMap(stack, jsonObj);
}
else
{
traverseFieldsNoObj(stack, jsonObj);
}
}
else
{
if (jsonObj.isArray())
{
traverseArray(stack, jsonObj);
}
else if (jsonObj.isCollection())
{
traverseCollection(stack, jsonObj);
}
else if (jsonObj.isMap())
{
traverseMap(stack, jsonObj);
}
else
{
traverseFields(stack, jsonObj);
}
// Reduce heap footprint during processing
jsonObj.clear();
}
}
return root.target;
}
/**
* Traverse the JsonObject associated to an array (of any type). Convert and
* assign the list of items in the JsonObject (stored in the @items field)
* to each array element. All array elements are processed excluding elements
* that reference an unresolved object. These are filled in later.
*
* @param stack a Stack (LinkedList) used to support graph traversal.
* @param jsonObj a Map-of-Map representation of the JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private void traverseArray(LinkedList<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) throws IOException
{
int len = jsonObj.getLength();
if (len == 0)
{
return;
}
Class compType = jsonObj.getComponentType();
if (char.class == compType)
{
return;
}
if (byte.class == compType)
{ // Handle byte[] special for performance boost.
jsonObj.moveBytesToMate();
jsonObj.clearArray();
return;
}
boolean isPrimitive = isPrimitive(compType);
Object array = jsonObj.target;
Object[] items = jsonObj.getArray();
for (int i = 0; i < len; i++)
{
Object element = items[i];
Object special;
if (element == null)
{
Array.set(array, i, null);
}
else if (element == EMPTY_OBJECT)
{ // Use either explicitly defined type in ObjectMap associated to JSON, or array component type.
Object arrayElement = createJavaObjectInstance(compType, new JsonObject());
Array.set(array, i, arrayElement);
}
else if ((special = readIfMatching(element, compType, stack)) != null)
{
Array.set(array, i, special);
}
else if (isPrimitive)
{ // Primitive component type array
Array.set(array, i, newPrimitiveWrapper(compType, element));
}
else if (element.getClass().isArray())
{ // Array of arrays
if (char[].class == compType)
{ // Specially handle char[] because we are writing these
// out as UTF-8 strings for compactness and speed.
Object[] jsonArray = (Object[]) element;
if (jsonArray.length == 0)
{
Array.set(array, i, new char[]{});
}
else
{
String value = (String) jsonArray[0];
int numChars = value.length();
char[] chars = new char[numChars];
for (int j = 0; j < numChars; j++)
{
chars[j] = value.charAt(j);
}
Array.set(array, i, chars);
}
}
else
{
JsonObject<String, Object> jsonObject = new JsonObject<String, Object>();
jsonObject.put("@items", element);
Array.set(array, i, createJavaObjectInstance(compType, jsonObject));
stack.addFirst(jsonObject);
}
}
else if (element instanceof JsonObject)
{
JsonObject<String, Object> jsonObject = (JsonObject<String, Object>) element;
Long ref = (Long) jsonObject.get("@ref");
if (ref != null)
{ // Connect reference
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
if (refObject.target != null)
{ // Array element with @ref to existing object
Array.set(array, i, refObject.target);
}
else
{ // Array with a forward @ref as an element
_unresolvedRefs.add(new UnresolvedReference(jsonObj, i, ref));
}
}
else
{ // Convert JSON HashMap to Java Object instance and assign values
Object arrayElement = createJavaObjectInstance(compType, jsonObject);
Array.set(array, i, arrayElement);
if (!isPrimitive(arrayElement.getClass()))
{ // Skip walking primitives, primitive wrapper classes,, Strings, and Classes
stack.addFirst(jsonObject);
}
}
}
else
{ // Setting primitive values into an Object[]
Array.set(array, i, element);
}
}
jsonObj.clearArray();
}
/**
* Process java.util.Collection and it's derivatives. Collections are written specially
* so that the serialization does not expose the Collection's internal structure, for
* example a TreeSet. All entries are processed, except unresolved references, which
* are filled in later. For an indexable collection, the unresolved references are set
* back into the proper element location. For non-indexable collections (Sets), the
* unresolved references are added via .add().
* @param stack a Stack (LinkedList) used to support graph traversal.
* @param jsonObj a Map-of-Map representation of the JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private void traverseCollectionNoObj(LinkedList<JsonObject<String, Object>> stack, JsonObject jsonObj) throws IOException
{
Object[] items = jsonObj.getArray();
if (items == null || items.length == 0)
{
return;
}
int idx = 0;
List copy = new ArrayList(items.length);
for (Object element : items)
{
if (element == EMPTY_OBJECT)
{
copy.add(new JsonObject());
continue;
}
copy.add(element);
if (element instanceof Object[])
{ // array element inside Collection
JsonObject<String, Object> jsonObject = new JsonObject<String, Object>();
jsonObject.put("@items", element);
stack.addFirst(jsonObject);
}
else if (element instanceof JsonObject)
{
JsonObject<String, Object> jsonObject = (JsonObject<String, Object>) element;
Long ref = (Long) jsonObject.get("@ref");
if (ref != null)
{ // connect reference
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
copy.set(idx, refObject);
}
else
{
stack.addFirst(jsonObject);
}
}
idx++;
}
jsonObj.target = null; // don't waste space (used for typed return, not generic Map return)
for (int i=0; i < items.length; i++)
{
items[i] = copy.get(i);
}
}
/**
* Process java.util.Collection and it's derivatives. Collections are written specially
* so that the serialization does not expose the Collection's internal structure, for
* example a TreeSet. All entries are processed, except unresolved references, which
* are filled in later. For an indexable collection, the unresolved references are set
* back into the proper element location. For non-indexable collections (Sets), the
* unresolved references are added via .add().
* @param jsonObj a Map-of-Map representation of the JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private void traverseCollection(LinkedList<JsonObject<String, Object>> stack, JsonObject jsonObj) throws IOException
{
Object[] items = jsonObj.getArray();
if (items == null || items.length == 0)
{
return;
}
Collection col = (Collection) jsonObj.target;
boolean isList = col instanceof List;
int idx = 0;
for (Object element : items)
{
Object special;
if (element == null)
{
col.add(null);
}
else if (element == EMPTY_OBJECT)
{ // Handles {}
col.add(new JsonObject());
}
else if ((special = readIfMatching(element, null, stack)) != null)
{
col.add(special);
}
else if (element instanceof String || element instanceof Boolean || element instanceof Double || element instanceof Long)
{ // Allow Strings, Booleans, Longs, and Doubles to be "inline" without Java object decoration (@id, @type, etc.)
col.add(element);
}
else if (element.getClass().isArray())
{
JsonObject jObj = new JsonObject();
jObj.put("@items", element);
createJavaObjectInstance(Object.class, jObj);
col.add(jObj.target);
convertMapsToObjects(jObj);
}
else // if (element instanceof JsonObject)
{
JsonObject jObj = (JsonObject) element;
Long ref = (Long) jObj.get("@ref");
if (ref != null)
{
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
if (refObject.target != null)
{
col.add(refObject.target);
}
else
{
_unresolvedRefs.add(new UnresolvedReference(jsonObj, idx, ref));
if (isList)
{ // Indexable collection, so set 'null' as element for now - will be patched in later.
col.add(null);
}
}
}
else
{
createJavaObjectInstance(Object.class, jObj);
if (!isPrimitive(jObj.getTargetClass()))
{
convertMapsToObjects(jObj);
}
col.add(jObj.target);
}
}
idx++;
}
jsonObj.remove("@items"); // Reduce memory required during processing
}
/**
* Process java.util.Map and it's derivatives. These can be written specially
* so that the serialization would not expose the derivative class internals
* (internal fields of TreeMap for example).
* @param stack a Stack (LinkedList) used to support graph traversal.
* @param jsonObj a Map-of-Map representation of the JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private void traverseMap(LinkedList<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) throws IOException
{
// Convert @keys to a Collection of Java objects.
convertMapToKeysItems(jsonObj);
Object[] keys = (Object[]) jsonObj.get("@keys");
Object[] items = jsonObj.getArray();
if (keys == null || items == null)
{
if (keys != items)
{
error("Map written where one of @keys or @items is empty");
}
return;
}
int size = keys.length;
if (size != items.length)
{
error("Map written with @keys and @items entries of different sizes");
}
JsonObject jsonKeyCollection = new JsonObject();
jsonKeyCollection.put("@items", keys);
Object[] javaKeys = new Object[size];
jsonKeyCollection.target = javaKeys;
stack.addFirst(jsonKeyCollection);
// Convert @items to a Collection of Java objects.
JsonObject jsonItemCollection = new JsonObject();
jsonItemCollection.put("@items", items);
Object[] javaValues = new Object[size];
jsonItemCollection.target = javaValues;
stack.addFirst(jsonItemCollection);
// Save these for later so that unresolved references inside keys or values
// get patched first, and then build the Maps.
_prettyMaps.add(new Object[] {jsonObj, javaKeys, javaValues});
}
private void traverseFieldsNoObj(LinkedList<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) throws IOException
{
final Object target = jsonObj.target;
for (Map.Entry<String, Object> e : jsonObj.entrySet())
{
String key = e.getKey();
if (key.charAt(0) == '@')
{ // Skip our own meta fields
continue;
}
Field field = null;
if (target != null)
{
field = getDeclaredField(target.getClass(), key);
}
Object value = e.getValue();
if (value == null)
{
jsonObj.put(key, null);
}
else if (value == EMPTY_OBJECT)
{
jsonObj.put(key, new JsonObject());
}
else if (value.getClass().isArray())
{ // LHS of assignment is an [] field or RHS is an array and LHS is Object (Map)
JsonObject<String, Object> jsonArray = new JsonObject<String, Object>();
jsonArray.put("@items", value);
stack.addFirst(jsonArray);
jsonObj.put(key, jsonArray);
}
else if (value instanceof JsonObject)
{
JsonObject<String, Object> jObj = (JsonObject) value;
if (field != null && jObj.isPrimitiveWrapper(field.getType()))
{
jObj.put("value", newPrimitiveWrapper(field.getType(),jObj.get("value")));
continue;
}
Long ref = (Long) jObj.get("@ref");
if (ref != null)
{ // Correct field references
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
jsonObj.put(key, refObject); // Update Map-of-Maps reference
}
else
{
stack.addFirst(jObj);
}
}
else if (field != null)
{
Class fieldType = field.getType();
if (isPrimitive(fieldType))
{
jsonObj.put(key, newPrimitiveWrapper(fieldType, value));
}
else if (BigDecimal.class == fieldType)
{
jsonObj.put(key, new BigDecimal(value.toString()));
}
else if (BigInteger.class == fieldType)
{
jsonObj.put(key, new BigInteger(value.toString()));
}
}
}
jsonObj.target = null; // don't waste space (used for typed return, not for Map return)
}
/**
* Walk the Java object fields and copy them from the JSON object to the Java object, performing
* any necessary conversions on primitives, or deep traversals for field assignments to other objects,
* arrays, Collections, or Maps.
* @param stack Stack (LinkedList) used for graph traversal.
* @param jsonObj a Map-of-Map representation of the current object being examined (containing all fields).
* @throws IOException
*/
private void traverseFields(LinkedList<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) throws IOException
{
Object special;
if ((special = readIfMatching(jsonObj, null, stack)) != null)
{
jsonObj.target = special;
return;
}
Object javaMate = jsonObj.target;
Iterator<Map.Entry<String, Object>> i = jsonObj.entrySet().iterator();
Class cls = javaMate.getClass();
while (i.hasNext())
{
Map.Entry<String, Object> e = i.next();
String key = e.getKey();
Field field = getDeclaredField(cls, key);
Object rhs = e.getValue();
if (field != null)
{
assignField(stack, jsonObj, field, rhs);
}
}
jsonObj.clear(); // Reduce memory required during processing
}
/**
* Map Json Map object field to Java object field.
*
* @param stack Stack (LinkedList) used for graph traversal.
* @param jsonObj a Map-of-Map representation of the current object being examined (containing all fields).
* @param field a Java Field object representing where the jsonObj should be converted and stored.
* @param rhs the JSON value that will be converted and stored in the 'field' on the associated
* Java target object.
* @throws IOException for stream errors or parsing errors.
*/
private void assignField(LinkedList<JsonObject<String, Object>> stack, JsonObject jsonObj, Field field, Object rhs) throws IOException
{
Object target = jsonObj.target;
try
{
Class fieldType = field.getType();
if (Collection.class.isAssignableFrom(fieldType))
{ // Process Collection (and potentially generic objects within it) by marketing contained items with
// template info if it exists, and the items do not have @type specified on them.
if (rhs instanceof JsonObject)
{
JsonObject col = (JsonObject) rhs;
Object[] items = col.getArray();
markSubobjectTypes(field, items, 0);
}
}
else if (Map.class.isAssignableFrom(fieldType))
{
if (rhs instanceof JsonObject)
{
JsonObject map = (JsonObject) rhs;
convertMapToKeysItems(map);
if (map.get("@keys") instanceof Object[])
{
Object[] keys = (Object[]) map.get("@keys");
markSubobjectTypes(field, keys, 0);
}
if (map.get("@items") instanceof Object[])
{
Object[] values = (Object[]) map.get("@items");
markSubobjectTypes(field, values, 1);
}
}
}
if (rhs instanceof JsonObject)
{ // Ensure .type field set on JsonObject
JsonObject job = (JsonObject) rhs;
String type = job.type;
if (type == null || type.isEmpty())
{
job.setType(fieldType.getName());
}
}
Object special;
if (rhs == null)
{
field.set(target, null);
}
else if (rhs == EMPTY_OBJECT)
{
JsonObject jObj = new JsonObject();
jObj.type = fieldType.getName();
Object value = createJavaObjectInstance(fieldType, jObj);
field.set(target, value);
}
else if ((special = readIfMatching(rhs, field.getType(), stack)) != null)
{
field.set(target, special);
}
else if (rhs.getClass().isArray())
{ // LHS of assignment is an [] field or RHS is an array and LHS is Object
Object[] elements = (Object[]) rhs;
JsonObject<String, Object> jsonArray = new JsonObject<String, Object>();
if (char[].class == fieldType)
{ // Specially handle char[] because we are writing these
// out as UTF8 strings for compactness and speed.
if (elements.length == 0)
{
field.set(target, new char[]{});
}
else
{
field.set(target, ((String) elements[0]).toCharArray());
}
}
else
{
jsonArray.put("@items", elements);
createJavaObjectInstance(fieldType, jsonArray);
field.set(target, jsonArray.target);
stack.addFirst(jsonArray);
}
}
else if (rhs instanceof JsonObject)
{
JsonObject<String, Object> jObj = (JsonObject) rhs;
Long ref = (Long) jObj.get("@ref");
if (ref != null)
{ // Correct field references
JsonObject refObject = _objsRead.get(ref);
if (refObject == null)
{
error("Forward reference @ref: " + ref + ", but no object defined (@id) with that value");
}
if (refObject.target != null)
{
field.set(target, refObject.target);
}
else
{
_unresolvedRefs.add(new UnresolvedReference(jsonObj, field.getName(), ref));
}
}
else
{ // Assign ObjectMap's to Object (or derived) fields
field.set(target, createJavaObjectInstance(fieldType, jObj));
if (!isPrimitive(jObj.getTargetClass()))
{
stack.addFirst((JsonObject) rhs);
}
}
}
else // Primitives and primitive wrappers
{
if (fieldType == Object.class)
{ // Case when field type is Object, then attempt to assign rhs directly to it (handles String, Double, Boolean, Long, null)
field.set(target, rhs);
}
else
{
field.set(target, newPrimitiveWrapper(fieldType, rhs));
}
}
}
catch (Exception e)
{
error("IllegalAccessException setting field '" + field.getName() + "' on target: " + target + " with value: " + rhs, e);
}
}
/**
* Convert an input JsonObject map (known to represent a Map.class or derivative) that has regular keys and values
* to have its keys placed into @keys, and its values placed into @items.
* @param map Map to convert
*/
private void convertMapToKeysItems(JsonObject map)
{
if (!map.containsKey("@keys") && !map.containsKey("@ref"))
{
Object[] keys = new Object[map.keySet().size()];
Object[] values = new Object[map.keySet().size()];
int i=0;
for (Object e : map.entrySet())
{
Map.Entry entry = (Map.Entry)e;
keys[i] = entry.getKey();
values[i] = entry.getValue();
i++;
}
String saveType = map.getType();
map.clear();
map.setType(saveType);
map.put("@keys", keys);
map.put("@items", values);
}
}
/**
* Mark the @type field on JsonObject's that have no type information,
* no target, but where the Field generic type information contains the
* type of the enclosed objects.
* @param field Field instance containing the Generic info of the Collection that holds the enclosed objects.
* @param items Object[] of JsonObjects that may be type-less.
* @param typeArg Used to indicate whether to use type argument 0 or 1 (Collection or Map).
*/
private void markSubobjectTypes(Field field, Object[] items, int typeArg)
{
if (items == null || items.length == 0)
{
return;
}
for (Object o : items)
{
if (o instanceof JsonObject)
{
JsonObject item = (JsonObject) o;
String type = item.getType();
if (type == null || type.isEmpty())
{
if (field.getGenericType() instanceof ParameterizedType)
{
ParameterizedType paramType = (ParameterizedType) field.getGenericType();
Type[] typeArgs = paramType.getActualTypeArguments();
if (typeArgs != null && typeArgs.length > typeArg && typeArgs[typeArg] instanceof Class)
{
Class c = (Class) typeArgs[typeArg];
item.setType(c.getName());
}
}
}
}
}
}
/**
* This method creates a Java Object instance based on the passed in parameters.
* If the JsonObject contains a key '@type' then that is used, as the type was explicitly
* set in the JSON stream. If the key '@type' does not exist, then the passed in Class
* is used to create the instance, handling creating an Array or regular Object
* instance.
* <p/>
* The '@type' is not often specified in the JSON input stream, as in many
* cases it can be inferred from a field reference or array component type.
*
* @param clazz Instance will be create of this class.
* @param jsonObj Map-of-Map representation of object to create.
* @return a new Java object of the appropriate type (clazz) using the jsonObj to provide
* enough hints to get the right class instantiated. It is not populated when returned.
* @throws IOException for stream errors or parsing errors.
*/
private Object createJavaObjectInstance(Class clazz, JsonObject jsonObj) throws IOException
{
String type = jsonObj.type;
Object mate;
// @type always takes precedence over inferred Java (clazz) type.
if (type != null)
{ // @type is explicitly set, use that as it always takes precedence
Class c = classForName(type);
if (c.isArray())
{ // Handle []
Object[] items = jsonObj.getArray();
int size = (items == null) ? 0 : items.length;
if (c == char[].class)
{
jsonObj.moveCharsToMate();
mate = jsonObj.target;
}
else
{
mate = Array.newInstance(c.getComponentType(), size);
}
}
else
{ // Handle regular field.object reference
if (isPrimitive(c))
{
mate = newPrimitiveWrapper(c, jsonObj.get("value"));
}
else if (c == Class.class)
{
mate = classForName((String) jsonObj.get("value"));
}
else if (c.isEnum())
{
mate = getEnum(c, jsonObj);
}
else if (Enum.class.isAssignableFrom(c)) // anonymous subclass of an enum
{
mate = getEnum(c.getSuperclass(), jsonObj);
}
else if ("java.util.Arrays$ArrayList".equals(c.getName()))
{ // Special case: Arrays$ArrayList does not allow .add() to be called on it.
mate = new ArrayList();
}
else
{
mate = newInstance(c);
}
}
}
else
{ // @type, not specified, figure out appropriate type
Object[] items = jsonObj.getArray();
// if @items is specified, it must be an [] type.
// if clazz.isArray(), then it must be an [] type.
if (clazz.isArray() || (items != null && clazz == Object.class && !jsonObj.containsKey("@keys")))
{
int size = (items == null) ? 0 : items.length;
mate = Array.newInstance(clazz.isArray() ? clazz.getComponentType() : Object.class, size);
}
else if (clazz.isEnum())
{
mate = getEnum(clazz, jsonObj);
}
else if (Enum.class.isAssignableFrom(clazz)) // anonymous subclass of an enum
{
mate = getEnum(clazz.getSuperclass(), jsonObj);
}
else if ("java.util.Arrays$ArrayList".equals(clazz.getName()))
{ // Special case: Arrays$ArrayList does not allow .add() to be called on it.
mate = new ArrayList();
}
else if (clazz == Object.class && !_noObjects)
{
if (jsonObj.isMap() || jsonObj.size() > 0)
{ // Map-Like (has @keys and @items, or it has entries) but either way, type and class are not set.
mate = new JsonObject();
}
else
{ // Dunno
mate = newInstance(clazz);
}
}
else
{
mate = newInstance(clazz);
}
}
return jsonObj.target = mate;
}
/**
* Fetch enum value (may need to try twice, due to potential 'name' field shadowing by enum subclasses
*/
private static Object getEnum(Class c, JsonObject jsonObj)
{
try
{
return Enum.valueOf(c, (String) jsonObj.get("name"));
}
catch (Exception e)
{ // In case the enum class has it's own 'name' member variable (shadowing the 'name' variable on Enum)
return Enum.valueOf(c, (String) jsonObj.get("java.lang.Enum.name"));
}
}
// Parser code
private Object readJsonObject() throws IOException
{
boolean done = false;
String field = null;
JsonObject<String, Object> object = new JsonObject<String, Object>();
int state = STATE_READ_START_OBJECT;
boolean objectRead = false;
final FastPushbackReader in = _in;
while (!done)
{
int c;
switch (state)
{
case STATE_READ_START_OBJECT:
c = skipWhitespaceRead();
if (c == '{')
{
objectRead = true;
object.line = _line.get();
object.col = _col.get();
c = skipWhitespaceRead();
if (c == '}')
{ // empty object
return EMPTY_OBJECT;
}
in.unread(c);
state = STATE_READ_FIELD;
}
else if (c == '[')
{
in.unread('[');
state = STATE_READ_VALUE;
}
else
{
error("Input is invalid JSON; does not start with '{' or '[', c=" + c);
}
break;
case STATE_READ_FIELD:
c = skipWhitespaceRead();
if (c == '"')
{
field = readString();
c = skipWhitespaceRead();
if (c != ':')
{
error("Expected ':' between string field and value");
}
skipWhitespace();
state = STATE_READ_VALUE;
}
else
{
error("Expected quote");
}
break;
case STATE_READ_VALUE:
if (field == null)
{ // field is null when you have an untyped Object[], so we place
// the JsonArray on the @items field.
field = "@items";
}
Object value = readValue(object);
object.put(field, value);
// If object is referenced (has @id), then put it in the _objsRead table.
if ("@id".equals(field))
{
_objsRead.put((Long)value, object);
}
state = STATE_READ_POST_VALUE;
break;
case STATE_READ_POST_VALUE:
c = skipWhitespaceRead();
if (c == -1 && objectRead)
{
error("EOF reached before closing '}'");
}
if (c == '}' || c == -1)
{
done = true;
}
else if (c == ',')
{
state = STATE_READ_FIELD;
}
else
{
error("Object not ended with '}' or ']'");
}
break;
}
}
if (_noObjects && object.isPrimitive())
{
return object.getPrimitiveValue();
}
return object;
}
private Object readValue(JsonObject object) throws IOException
{
int c = _in.read();
if (c == '"')
{
return readString();
}
if (isDigit(c) || c == '-')
{
return readNumber(c);
}
if (c == '{')
{
_in.unread('{');
return readJsonObject();
}
if (c == 't' || c == 'T')
{
_in.unread(c);
readToken("true");
return Boolean.TRUE;
}
if (c == 'f' || c == 'F')
{
_in.unread(c);
readToken("false");
return Boolean.FALSE;
}
if (c == 'n' || c == 'N')
{
_in.unread(c);
readToken("null");
return null;
}
if (c == '[')
{
return readArray(object);
}
if (c == ']')
{ // [] empty array
_in.unread(']');
return EMPTY_ARRAY;
}
if (c == -1)
{
error("EOF reached prematurely");
}
return error("Unknown JSON value type");
}
/**
* Read a JSON array
*/
private Object readArray(JsonObject object) throws IOException
{
Collection array = new ArrayList();
while (true)
{
skipWhitespace();
Object o = readValue(object);
if (o != EMPTY_ARRAY)
{
array.add(o);
}
int c = skipWhitespaceRead();
if (c == ']')
{
break;
}
if (c != ',')
{
error("Expected ',' or ']' inside array");
}
}
return array.toArray();
}
/**
* Return the specified token from the reader. If it is not found,
* throw an IOException indicating that. Converting to c to
* (char) c is acceptable because the 'tokens' allowed in a
* JSON input stream (true, false, null) are all ASCII.
*/
private String readToken(String token) throws IOException
{
int len = token.length();
for (int i = 0; i < len; i++)
{
int c = _in.read();
if (c == -1)
{
error("EOF reached while reading token: " + token);
}
c = Character.toLowerCase((char) c);
int loTokenChar = token.charAt(i);
if (loTokenChar != c)
{
error("Expected token: " + token);
}
}
return token;
}
/**
* Read a JSON number
*
* @param c int a character representing the first digit of the number that
* was already read.
* @return a Number (a Long or a Double) depending on whether the number is
* a decimal number or integer. This choice allows all smaller types (Float, int, short, byte)
* to be represented as well.
* @throws IOException for stream errors or parsing errors.
*/
private Number readNumber(int c) throws IOException
{
final FastPushbackReader in = _in;
final char[] numBuf = _numBuf;
numBuf[0] = (char) c;
int len = 1;
boolean isFloat = false;
try
{
while (true)
{
c = in.read();
if ((c >= '0' && c <= '9') || c == '-' || c == '+') // isDigit() inlined for speed here
{
numBuf[len++] = (char) c;
}
else if (c == '.' || c == 'e' || c == 'E')
{
numBuf[len++] = (char) c;
isFloat = true;
}
else if (c == -1)
{
error("Reached EOF while reading number");
}
else
{
in.unread(c);
break;
}
}
}
catch (ArrayIndexOutOfBoundsException e)
{
error("Too many digits in number");
}
if (isFloat)
{ // Floating point number needed
String num = new String(numBuf, 0, len);
try
{
return Double.parseDouble(num);
}
catch (NumberFormatException e)
{
error("Invalid floating point number: " + num, e);
}
}
boolean isNeg = numBuf[0] == '-';
long n = 0;
for (int i = (isNeg ? 1 : 0); i < len; i++)
{
n = (numBuf[i] - '0') + n * 10;
}
return isNeg ? -n : n;
}
/**
* Read a JSON string
* This method assumes the initial quote has already been read.
*
* @return String read from JSON input stream.
* @throws IOException for stream errors or parsing errors.
*/
private String readString() throws IOException
{
final StringBuilder strBuf = _strBuf;
strBuf.setLength(0);
StringBuilder hex = new StringBuilder();
boolean done = false;
final int STATE_STRING_START = 0;
final int STATE_STRING_SLASH = 1;
final int STATE_HEX_DIGITS = 2;
int state = STATE_STRING_START;
while (!done)
{
int c = _in.read();
if (c == -1)
{
error("EOF reached while reading JSON string");
}
switch (state)
{
case STATE_STRING_START:
if (c == '\\')
{
state = STATE_STRING_SLASH;
}
else if (c == '"')
{
done = true;
}
else
{
strBuf.append(toChars(c));
}
break;
case STATE_STRING_SLASH:
if (c == 'n')
{
strBuf.append('\n');
}
else if (c == 'r')
{
strBuf.append('\r');
}
else if (c == 't')
{
strBuf.append('\t');
}
else if (c == 'f')
{
strBuf.append('\f');
}
else if (c == 'b')
{
strBuf.append('\b');
}
else if (c == '\\')
{
strBuf.append('\\');
}
else if (c == '/')
{
strBuf.append('/');
}
else if (c == '"')
{
strBuf.append('"');
}
else if (c == '\'')
{
strBuf.append('\'');
}
else if (c == 'u')
{
state = STATE_HEX_DIGITS;
hex.setLength(0);
break;
}
else
{
error("Invalid character escape sequence specified");
}
state = STATE_STRING_START;
break;
case STATE_HEX_DIGITS:
if (c == 'a' || c == 'A' || c == 'b' || c == 'B' || c == 'c' || c == 'C' || c == 'd' || c == 'D' || c == 'e' || c == 'E' || c == 'f' || c == 'F' || isDigit(c))
{
hex.append((char) c);
if (hex.length() == 4)
{
int value = Integer.parseInt(hex.toString(), 16);
strBuf.append(valueOf((char) value));
state = STATE_STRING_START;
}
}
else
{
error("Expected hexadecimal digits");
}
break;
}
}
String s = strBuf.toString();
String cacheHit = _stringCache.get(s);
return cacheHit == null ? s : cacheHit;
}
private static Object newInstance(Class c) throws IOException
{
if (_factory.containsKey(c))
{
return _factory.get(c).newInstance(c);
}
// Constructor not cached, go find a constructor
Object[] constructorInfo = _constructors.get(c);
if (constructorInfo != null)
{ // Constructor was cached
Constructor constructor = (Constructor) constructorInfo[0];
Boolean useNull = (Boolean) constructorInfo[1];
Class[] paramTypes = constructor.getParameterTypes();
if (paramTypes == null || paramTypes.length == 0)
{
try
{
return constructor.newInstance();
}
catch (Exception e)
{ // Should never happen, as the code that fetched the constructor was able to instantiate it once already
error("Could not instantiate " + c.getName(), e);
}
}
Object[] values = fillArgs(paramTypes, useNull);
try
{
return constructor.newInstance(values);
}
catch (Exception e)
{ // Should never happen, as the code that fetched the constructor was able to instantiate it once already
error("Could not instantiate " + c.getName(), e);
}
}
Object[] ret = newInstanceEx(c);
_constructors.put(c, new Object[] {ret[1], ret[2]});
return ret[0];
}
/**
* Return constructor and instance as elements 0 and 1, respectively.
*/
private static Object[] newInstanceEx(Class c) throws IOException
{
try
{
Constructor constructor = c.getConstructor(_emptyClassArray);
if (constructor != null)
{
return new Object[] {constructor.newInstance(), constructor, true};
}
return tryOtherConstructors(c);
}
catch (Exception e)
{
// OK, this class does not have a public no-arg constructor. Instantiate with
// first constructor found, filling in constructor values with null or
// defaults for primitives.
return tryOtherConstructors(c);
}
}
private static Object[] tryOtherConstructors(Class c) throws IOException
{
Constructor[] constructors = c.getDeclaredConstructors();
if (constructors.length == 0)
{
error("Cannot instantiate '" + c.getName() + "' - Primitive, interface, array[] or void");
}
// Try each constructor (private, protected, or public) with null values for non-primitives.
for (Constructor constructor : constructors)
{
constructor.setAccessible(true);
Class[] argTypes = constructor.getParameterTypes();
Object[] values = fillArgs(argTypes, true);
try
{
return new Object[] {constructor.newInstance(values), constructor, true};
}
catch (Exception ignored)
{ }
}
// Try each constructor (private, protected, or public) with non-null values for primitives.
for (Constructor constructor : constructors)
{
constructor.setAccessible(true);
Class[] argTypes = constructor.getParameterTypes();
Object[] values = fillArgs(argTypes, false);
try
{
return new Object[] {constructor.newInstance(values), constructor, false};
}
catch (Exception ignored)
{ }
}
error("Could not instantiate " + c.getName() + " using any constructor");
return null;
}
private static Object[] fillArgs(Class[] argTypes, boolean useNull) throws IOException
{
Object[] values = new Object[argTypes.length];
for (int i = 0; i < argTypes.length; i++)
{
final Class argType = argTypes[i];
if (isPrimitive(argType))
{
values[i] = newPrimitiveWrapper(argType, null);
}
else if (useNull)
{
values[i] = null;
}
else
{
if (argType == String.class)
{
values[i] = "";
}
else if (argType == Date.class)
{
values[i] = new Date();
}
else if (List.class.isAssignableFrom(argType))
{
values[i] = new ArrayList();
}
else if (SortedSet.class.isAssignableFrom(argType))
{
values[i] = new TreeSet();
}
else if (Set.class.isAssignableFrom(argType))
{
values[i] = new LinkedHashSet();
}
else if (SortedMap.class.isAssignableFrom(argType))
{
values[i] = new TreeMap();
}
else if (Map.class.isAssignableFrom(argType))
{
values[i] = new LinkedHashMap();
}
else if (Collection.class.isAssignableFrom(argType))
{
values[i] = new ArrayList();
}
else if (Calendar.class.isAssignableFrom(argType))
{
values[i] = Calendar.getInstance();
}
else if (TimeZone.class.isAssignableFrom(argType))
{
values[i] = TimeZone.getDefault();
}
else if (argType == BigInteger.class)
{
values[i] = BigInteger.TEN;
}
else if (argType == BigDecimal.class)
{
values[i] = BigDecimal.TEN;
}
else if (argType == StringBuilder.class)
{
values[i] = new StringBuilder();
}
else if (argType == StringBuffer.class)
{
values[i] = new StringBuffer();
}
else if (argType == Locale.class)
{
values[i] = Locale.FRANCE; // overwritten
}
else if (argType == Class.class)
{
values[i] = String.class;
}
else if (argType == java.sql.Timestamp.class)
{
values[i] = new Timestamp(System.currentTimeMillis());
}
else if (argType == java.sql.Date.class)
{
values[i] = new java.sql.Date(System.currentTimeMillis());
}
else
{
values[i] = null;
}
}
}
return values;
}
public static boolean isPrimitive(Class c)
{
return c.isPrimitive() || _prims.contains(c);
}
private static Object newPrimitiveWrapper(Class c, Object rhs) throws IOException
{
if (c == Byte.class || c == byte.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0";
}
return Byte.parseByte((String)rhs);
}
return rhs != null ? _byteCache[((Number) rhs).byteValue() + 128] : (byte) 0;
}
if (c == Boolean.class || c == boolean.class)
{ // Booleans are tokenized into Boolean.TRUE or Boolean.FALSE
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "false";
}
return Boolean.parseBoolean((String)rhs);
}
return rhs != null ? rhs : Boolean.FALSE;
}
if (c == Integer.class || c == int.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0";
}
return Integer.parseInt((String)rhs);
}
return rhs != null ? ((Number) rhs).intValue() : 0;
}
if (c == Long.class || c == long.class || c == Number.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0";
}
return Long.parseLong((String)rhs);
}
return rhs != null ? rhs : 0L;
}
if (c == Double.class || c == double.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0.0";
}
return Double.parseDouble((String)rhs);
}
return rhs != null ? rhs : 0.0d;
}
if (c == Character.class || c == char.class)
{
if (rhs == null)
{
return '\u0000';
}
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "\u0000";
}
return valueOf(((String) rhs).charAt(0));
}
if (rhs instanceof Character)
{
return rhs;
}
}
if (c == Short.class || c == short.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0";
}
return Short.parseShort((String)rhs);
}
return rhs != null ? ((Number) rhs).shortValue() : (short) 0;
}
if (c == Float.class || c == float.class)
{
if (rhs instanceof String)
{
rhs = removeLeadingAndTrailingQuotes((String) rhs);
if ("".equals(rhs))
{
rhs = "0.0f";
}
return Float.parseFloat((String)rhs);
}
return rhs != null ? ((Number) rhs).floatValue() : 0.0f;
}
return error("Class '" + c.getName() + "' requested for special instantiation - isPrimitive() does not match newPrimitiveWrapper()");
}
static String removeLeadingAndTrailingQuotes(String s)
{
Matcher m = _extraQuotes.matcher(s);
if (m.find())
{
s = m.group(2);
}
return s;
}
private static boolean isDigit(int c)
{
return c >= '0' && c <= '9';
}
private static boolean isWhitespace(int c)
{
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
private static Class classForName(String name) throws IOException
{
if (name == null || name.isEmpty())
{
error("Invalid class name specified");
}
try
{
Class c = _nameToClass.get(name);
return c == null ? loadClass(name) : c;
}
catch (ClassNotFoundException e)
{
return (Class) error("Class instance '" + name + "' could not be created", e);
}
}
static Class classForName2(String name) throws IOException
{
if (name == null || name.isEmpty())
{
error("Empty class name.");
}
try
{
Class c = _nameToClass.get(name);
return c == null ? loadClass(name) : c;
}
catch (ClassNotFoundException e)
{
error("Class instance '" + name + "' could not be created.", e);
return null;
}
}
// loadClass() provided by: Thomas Margreiter
private static Class loadClass(String name) throws ClassNotFoundException
{
String className = name;
boolean arrayType = false;
Class primitiveArray = null;
while (className.startsWith("["))
{
arrayType = true;
if (className.endsWith(";")) className = className.substring(0,className.length()-1);
if (className.equals("[B")) primitiveArray = byte[].class;
else if (className.equals("[S")) primitiveArray = short[].class;
else if (className.equals("[I")) primitiveArray = int[].class;
else if (className.equals("[J")) primitiveArray = long[].class;
else if (className.equals("[F")) primitiveArray = float[].class;
else if (className.equals("[D")) primitiveArray = double[].class;
else if (className.equals("[Z")) primitiveArray = boolean[].class;
else if (className.equals("[C")) primitiveArray = char[].class;
int startpos = className.startsWith("[L") ? 2 : 1;
className = className.substring(startpos);
}
Class currentClass = null;
if (null == primitiveArray)
{
currentClass = Thread.currentThread().getContextClassLoader().loadClass(className);
}
if (arrayType)
{
currentClass = (null != primitiveArray) ? primitiveArray : Array.newInstance(currentClass, 0).getClass();
while (name.startsWith("[["))
{
currentClass = Array.newInstance(currentClass, 0).getClass();
name = name.substring(1);
}
}
return currentClass;
}
/**
* Get a Field object using a String field name and a Class instance. This
* method will start on the Class passed in, and if not found there, will
* walk up super classes until it finds the field, or throws an IOException
* if it cannot find the field.
*
* @param c Class containing the desired field.
* @param fieldName String name of the desired field.
* @return Field object obtained from the passed in class (by name). The Field
* returned is cached so that it is only obtained via reflection once.
* @throws IOException for stream errors or parsing errors.
*/
private static Field getDeclaredField(Class c, String fieldName) throws IOException
{
return JsonWriter.getDeepDeclaredFields(c).get(fieldName);
}
/**
* Read until non-whitespace character and then return it.
* This saves extra read/pushback.
*
* @return int representing the next non-whitespace character in the stream.
* @throws IOException for stream errors or parsing errors.
*/
private int skipWhitespaceRead() throws IOException
{
final FastPushbackReader in = _in;
int c = in.read();
while (isWhitespace(c))
{
c = in.read();
}
return c;
}
private void skipWhitespace() throws IOException
{
_in.unread(skipWhitespaceRead());
}
public void close()
{
try
{
if (_in != null)
{
_in.close();
}
}
catch (IOException ignored) { }
}
/**
* For all fields where the value was "@ref":"n" where 'n' was the id of an object
* that had not yet been encountered in the stream, make the final substitution.
* @throws IOException
*/
private void patchUnresolvedReferences() throws IOException
{
Iterator i = _unresolvedRefs.iterator();
while (i.hasNext())
{
UnresolvedReference ref = (UnresolvedReference) i.next();
Object objToFix = ref.referencingObj.target;
JsonObject objReferenced = _objsRead.get(ref.refId);
if (objReferenced == null)
{
// System.err.println("Back reference (" + ref.refId + ") does not match any object id in input, field '" + ref.field + '\'');
continue;
}
if (objReferenced.target == null)
{
// System.err.println("Back referenced object does not exist, @ref " + ref.refId + ", field '" + ref.field + '\'');
continue;
}
if (objToFix == null)
{
// System.err.println("Referencing object is null, back reference, @ref " + ref.refId + ", field '" + ref.field + '\'');
continue;
}
if (ref.index >= 0)
{ // Fix []'s and Collections containing a forward reference.
if (objToFix instanceof List)
{ // Patch up Indexable Collections
List list = (List) objToFix;
list.set(ref.index, objReferenced.target);
}
else if (objToFix instanceof Collection)
{ // Add element (since it was not indexable, add it to collection)
Collection col = (Collection) objToFix;
col.add(objReferenced.target);
}
else
{
Array.set(objToFix, ref.index, objReferenced.target); // patch array element here
}
}
else
{ // Fix field forward reference
Field field = getDeclaredField(objToFix.getClass(), ref.field);
if (field != null)
{
try
{
field.set(objToFix, objReferenced.target); // patch field here
}
catch (Exception e)
{
error("Error setting field while resolving references '" + field.getName() + "', @ref = " + ref.refId, e);
}
}
}
i.remove();
}
int count = _unresolvedRefs.size();
if (count > 0)
{
StringBuilder out = new StringBuilder();
out.append(count);
out.append(" unresolved references:\n");
i = _unresolvedRefs.iterator();
count = 1;
while (i.hasNext())
{
UnresolvedReference ref = (UnresolvedReference) i.next();
out.append(" Unresolved reference ");
out.append(count);
out.append('\n');
out.append(" @ref ");
out.append(ref.refId);
out.append('\n');
out.append(" field ");
out.append(ref.field);
out.append("\n\n");
count++;
}
error(out.toString());
}
}
/**
* Process Maps/Sets (fix up their internal indexing structure)
* This is required because Maps hash items using hashCode(), which will
* change between VMs. Rehashing the map fixes this.
*
* If _noObjects==true, then move @keys to keys and @items to values
* and then drop these two entries from the map.
*/
private void rehashMaps()
{
final boolean useMaps = _noObjects;
for (Object[] mapPieces : _prettyMaps)
{
JsonObject jObj = (JsonObject) mapPieces[0];
Object[] javaKeys, javaValues;
Map map;
if (useMaps)
{ // Make the @keys be the actual keys of the map.
map = jObj;
javaKeys = (Object[]) jObj.remove("@keys");
javaValues = (Object[]) jObj.remove("@items");
}
else
{
map = (Map) jObj.target;
javaKeys = (Object[]) mapPieces[1];
javaValues = (Object[]) mapPieces[2];
jObj.clear();
}
int j=0;
while (javaKeys != null && j < javaKeys.length)
{
map.put(javaKeys[j], javaValues[j]);
j++;
}
}
}
private static String getErrorMessage(String msg)
{
return msg + "\nLast read: " + getLastReadSnippet() + "\nline: " + _line.get() + ", col: " + _col.get();
}
static Object error(String msg) throws IOException
{
throw new IOException(getErrorMessage(msg));
}
static Object error(String msg, Exception e) throws IOException
{
throw new IOException(getErrorMessage(msg), e);
}
private static String getLastReadSnippet()
{
StringBuilder s = new StringBuilder();
for (char[] chars : _snippet.get())
{
s.append(chars);
}
return s.toString();
}
/**
* This is a performance optimization. The lowest 128 characters are re-used.
*
* @param c char to match to a Character.
* @return a Character that matches the passed in char. If the value is
* less than 127, then the same Character instances are re-used.
*/
private static Character valueOf(char c)
{
return c <= 127 ? _charCache[(int) c] : c;
}
public static final int MAX_CODE_POINT = 0x10ffff;
public static final int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000;
public static final char MIN_LOW_SURROGATE = '\uDC00';
public static final char MIN_HIGH_SURROGATE = '\uD800';
private static char[] toChars(int codePoint)
{
if (codePoint < 0 || codePoint > MAX_CODE_POINT)
{ // int UTF-8 char must be in range
throw new IllegalArgumentException("value ' + codePoint + ' outside UTF-8 range");
}
if (codePoint < MIN_SUPPLEMENTARY_CODE_POINT)
{ // if the int character fits in two bytes...
return new char[]{(char) codePoint};
}
char[] result = new char[2];
int offset = codePoint - MIN_SUPPLEMENTARY_CODE_POINT;
result[1] = (char) ((offset & 0x3ff) + MIN_LOW_SURROGATE);
result[0] = (char) ((offset >>> 10) + MIN_HIGH_SURROGATE);
return result;
}
/**
* This class adds significant performance increase over using the JDK
* PushbackReader. This is due to this class not using synchronization
* as it is not needed.
*/
private static class FastPushbackReader extends FilterReader
{
private final int[] _buf;
private int _idx;
private FastPushbackReader(Reader reader, int size)
{
super(reader);
_snippet.get().clear();
_line.set(1);
_col.set(1);
if (size <= 0)
{
throw new IllegalArgumentException("size <= 0");
}
_buf = new int[size];
_idx = size;
}
private FastPushbackReader(Reader r)
{
this(r, 1);
}
public int read() throws IOException
{
int ch;
if (_idx < _buf.length)
{ // read from push-back buffer
ch = _buf[_idx++];
}
else
{
ch = super.read();
}
if (ch >= 0)
{
if (ch == 0x0a)
{
_line.set(_line.get() + 1);
_col.set(0);
}
else
{
_col.set(_col.get() + 1);
}
Deque<char[]> buffer = _snippet.get();
buffer.addLast(toChars(ch));
if (buffer.size() > 100)
{
buffer.removeFirst();
}
}
return ch;
}
public void unread(int c) throws IOException
{
if (_idx == 0)
{
error("unread(int c) called more than buffer size (" + _buf.length + ")");
}
if (c == 0x0a)
{
_line.set(_line.get() - 1);
}
else
{
_col.set(_col.get() - 1);
}
_buf[--_idx] = c;
_snippet.get().removeLast();
}
/**
* Closes the stream and releases any system resources associated with
* it. Once the stream has been closed, further read(),
* unread(), ready(), or skip() invocations will throw an IOException.
* Closing a previously closed stream has no effect.
*
* @throws java.io.IOException If an I/O error occurs
*/
public void close() throws IOException
{
super.close();
_snippet.remove();
_line.remove();
_col.remove();
}
}
}
| - Widened support for allowing primitives to be set into unknown field types (Comparable, Object, etc. all valid when right hand side is String, Date, Double, etc.)
| src/main/java/com/cedarsoftware/util/io/JsonReader.java | - Widened support for allowing primitives to be set into unknown field types (Comparable, Object, etc. all valid when right hand side is String, Date, Double, etc.) |
|
Java | apache-2.0 | 9469c2d5bb1d9f0284e665da24f620d904c0a518 | 0 | Nithanim/gw2api | package me.nithanim.gw2api.v2.util.rest;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.Response;
import me.nithanim.gw2api.v2.GuildWars2Api;
import me.nithanim.gw2api.v2.exceptions.GuildWars2ApiIOException;
import me.nithanim.gw2api.v2.exceptions.GuildWars2ApiMappingException;
import me.nithanim.gw2api.v2.exceptions.GuildWars2ApiRequestException;
public class RequestHelperImpl implements RequestHelper {
private static final MultivaluedHashMap<String, Object> DEFAULT_HEADERS = new MultivaluedHashMap<>();
static {
DEFAULT_HEADERS.add("Accept", "application/json");
}
@Override
public <T> T getRequest(WebTarget wr, Type type) {
try {
String json = wr
.request()
.headers(DEFAULT_HEADERS)
.get(String.class);
return jsonToObject(json, type);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> T getRequest(WebTarget wr, String apiKey, Class<T> clazz) {
try {
String json = wr
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get(String.class);
return jsonToObject(json, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> PaginationResult<T> getRequestExtended(WebTarget wr, String apiKey, Class<T> clazz) {
try {
Response response = wr
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get();
return new ResultImpl<>(response, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> T getRequest(WebTarget wr, Type type, String arg0Name, String arg0Value) {
try {
String json = wr
.queryParam(arg0Name, arg0Value)
.request()
.headers(DEFAULT_HEADERS)
.get(String.class);
return jsonToObject(json, type);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> T getRequest(WebTarget wr, String apiKey, Class<T> clazz, String arg0Name, String arg0Value) {
try {
String json = wr
.queryParam(arg0Name, arg0Value)
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get(String.class);
return jsonToObject(json, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> PaginationResult<T> getRequestExtended(WebTarget wr, String apiKey, Class<T> clazz, String arg0Name, String arg0Value) {
try {
Response response = wr
.queryParam(arg0Name, arg0Value)
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get();
return new ResultImpl<>(response, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> T getRequest(WebTarget wr, Type type, String arg0Name, String arg0Value, String arg1Name, String arg1Value) {
try {
String json = wr
.queryParam(arg0Name, arg0Value)
.queryParam(arg1Name, arg1Value)
.request()
.headers(DEFAULT_HEADERS)
.get(String.class);
return jsonToObject(json, type);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> PaginationResult<T> getRequestExtended(WebTarget wr, String apiKey, Class<T> clazz, String arg0Name, String arg0Value, String arg1Name, String arg1Value) {
try {
Response response = wr
.queryParam(arg0Name, arg0Value)
.queryParam(arg1Name, arg1Value)
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get();
return new ResultImpl<>(response, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
private static GuildWars2ApiIOException genWebApplicationException(Exception ex) {
return new GuildWars2ApiIOException("The server could not handle the request!", ex);
}
static <T> T jsonToObject(String json, Type type) {
try {
//First try normal mapping
return GuildWars2Api.GSON.fromJson(json, type);
} catch (JsonSyntaxException mappingEx) {
//If that fails...
try {
//Check if it is a error response in json format
JsonApiError jae = GuildWars2Api.GSON.fromJson(json, JsonApiError.class);
throw new GuildWars2ApiRequestException("The api returned the following json error string: " + jae.getText());
} catch (JsonSyntaxException droppedEx) {
//If it was no json error then assume mapping to type failed
throw new GuildWars2ApiMappingException("Unable to map json to " + type + ": " + json, mappingEx);
}
}
}
private static class JsonApiError {
private String text;
public String getText() {
return text;
}
}
RequestHelperImpl() {
}
}
| src/main/java/me/nithanim/gw2api/v2/util/rest/RequestHelperImpl.java | package me.nithanim.gw2api.v2.util.rest;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.Response;
import me.nithanim.gw2api.v2.GuildWars2Api;
import me.nithanim.gw2api.v2.exceptions.GuildWars2ApiIOException;
import me.nithanim.gw2api.v2.exceptions.GuildWars2ApiMappingException;
import me.nithanim.gw2api.v2.exceptions.GuildWars2ApiRequestException;
public class RequestHelperImpl implements RequestHelper {
private static final MultivaluedHashMap<String, Object> DEFAULT_HEADERS = new MultivaluedHashMap<>();
static {
DEFAULT_HEADERS.add("Accept", "application/json");
DEFAULT_HEADERS.add("Cache-Control", "max-age=0, no-cache");
}
@Override
public <T> T getRequest(WebTarget wr, Type type) {
try {
String json = wr
.request()
.headers(DEFAULT_HEADERS)
.get(String.class);
return jsonToObject(json, type);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> T getRequest(WebTarget wr, String apiKey, Class<T> clazz) {
try {
String json = wr
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get(String.class);
return jsonToObject(json, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> PaginationResult<T> getRequestExtended(WebTarget wr, String apiKey, Class<T> clazz) {
try {
Response response = wr
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get();
return new ResultImpl<>(response, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> T getRequest(WebTarget wr, Type type, String arg0Name, String arg0Value) {
try {
String json = wr
.queryParam(arg0Name, arg0Value)
.request()
.headers(DEFAULT_HEADERS)
.get(String.class);
return jsonToObject(json, type);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> T getRequest(WebTarget wr, String apiKey, Class<T> clazz, String arg0Name, String arg0Value) {
try {
String json = wr
.queryParam(arg0Name, arg0Value)
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get(String.class);
return jsonToObject(json, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> PaginationResult<T> getRequestExtended(WebTarget wr, String apiKey, Class<T> clazz, String arg0Name, String arg0Value) {
try {
Response response = wr
.queryParam(arg0Name, arg0Value)
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get();
return new ResultImpl<>(response, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> T getRequest(WebTarget wr, Type type, String arg0Name, String arg0Value, String arg1Name, String arg1Value) {
try {
String json = wr
.queryParam(arg0Name, arg0Value)
.queryParam(arg1Name, arg1Value)
.request()
.headers(DEFAULT_HEADERS)
.get(String.class);
return jsonToObject(json, type);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
@Override
public <T> PaginationResult<T> getRequestExtended(WebTarget wr, String apiKey, Class<T> clazz, String arg0Name, String arg0Value, String arg1Name, String arg1Value) {
try {
Response response = wr
.queryParam(arg0Name, arg0Value)
.queryParam(arg1Name, arg1Value)
.request()
.headers(DEFAULT_HEADERS)
.header("Authorization", "Bearer " + apiKey)
.get();
return new ResultImpl<>(response, clazz);
} catch (ProcessingException | WebApplicationException ex) {
throw genWebApplicationException(ex);
}
}
private static GuildWars2ApiIOException genWebApplicationException(Exception ex) {
return new GuildWars2ApiIOException("The server could not handle the request!", ex);
}
static <T> T jsonToObject(String json, Type type) {
try {
//First try normal mapping
return GuildWars2Api.GSON.fromJson(json, type);
} catch (JsonSyntaxException mappingEx) {
//If that fails...
try {
//Check if it is a error response in json format
JsonApiError jae = GuildWars2Api.GSON.fromJson(json, JsonApiError.class);
throw new GuildWars2ApiRequestException("The api returned the following json error string: " + jae.getText());
} catch (JsonSyntaxException droppedEx) {
//If it was no json error then assume mapping to type failed
throw new GuildWars2ApiMappingException("Unable to map json to " + type + ": " + json, mappingEx);
}
}
}
private static class JsonApiError {
private String text;
public String getText() {
return text;
}
}
RequestHelperImpl() {
}
}
| Removed additional cache header #20
because they are already sent by the server and match the server's internal cache.
| src/main/java/me/nithanim/gw2api/v2/util/rest/RequestHelperImpl.java | Removed additional cache header #20 because they are already sent by the server and match the server's internal cache. |
|
Java | apache-2.0 | 04158d6fa2e1eb3feac645e63f56f22d7c59aa84 | 0 | Airpy/KeywordDrivenAutoTest | package com.keyword.automation.base.utils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
/**
* JSON操作工具类
*
* @author Amio_
*/
public class JsonUtils {
/**
* 将泛型List对象序列成JSON字符串
* before: [aaa, bbb, ccc]
* after: ["aaa","bbb","ccc"]
*
* @param list List对象
* @param <T> 泛型形参
* @return JSON字符串
*/
public static <T> String toJsonStringFromList(List<T> list) {
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
}
/**
* 将指定对象序列化成JSON字符串
* before: Student{username='小明',sex='男',tel=['13999999991','02588888888'],Score{chinese=99,math=100}}
* after: [{"username":"小明","sex":"男","tel":["13999999991","02588888888"],"score":{"chinese":99,"math":100}}]
*
* @param object 指定对象
* @return JSON字符串
*/
public static String toJsonStringFromObject(Object object) {
JSONArray jsonArray = JSONArray.fromObject(object);
return jsonArray.toString();
}
/**
* 将对象序列化成List数组
* before: Student{username='小明',sex='男',tel=['13999999991','02588888888'],Score{chinese=99,math=100}}
* after: [小明, 男, ["13999999991","02588888888"], {"chinese":99,"math":100}]
*
* @param object 指定对象
* @return List数组
*/
public static List toListFromObject(Object object) {
List<Object> list = new ArrayList<>();
JSONArray jsonArray = JSONArray.fromObject(object);
for (Object aJsonArray : jsonArray) {
JSONObject jsonObject = (JSONObject) aJsonArray;
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
Object key = keys.next();
Object value = jsonObject.get(key);
list.add(value);
}
}
return list;
}
public static List toListFromJson(JSONArray jsonArray) {
List<Object> list = new ArrayList<>();
for (Object obj : jsonArray) {
if (obj instanceof JSONArray) {
list.add(toListFromJson((JSONArray) obj));
} else if (obj instanceof JSONObject) {
list.add(toMapFromJson((JSONObject) obj));
} else {
list.add(obj);
}
}
return list;
}
public static Map<String, Object> toMapFromJson(String json) {
JSONObject obj = JSONObject.fromObject(json);
return toMapFromJson(obj);
}
public static Map<String, Object> toMapFromJson(JSONObject obj) {
Set<?> set = obj.keySet();
Map<String, Object> map = new HashMap<>(set.size());
for (Object key : obj.keySet()) {
Object value = obj.get(key);
if (value instanceof JSONArray) {
map.put(key.toString(), toListFromJson((JSONArray) value));
} else if (value instanceof JSONObject) {
map.put(key.toString(), toMapFromJson((JSONObject) value));
} else {
map.put(key.toString(), obj.get(key));
}
}
return map;
}
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
JSONObject subJSON = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObject.put("username", "小明");
jsonObject.put("sex", "男");
jsonArray.add("13999999991");
jsonArray.add("02588888888");
jsonObject.put("tel", jsonArray);
subJSON.put("chinese", 99);
subJSON.put("math", 100);
jsonObject.put("score", subJSON);
JSONArray jsonArray1 = new JSONArray();
jsonArray1.add(jsonObject);
System.out.println(JsonUtils.toListFromJson(jsonArray1));
}
}
| src/main/java/com/keyword/automation/base/utils/JsonUtils.java | package com.keyword.automation.base.utils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* JSON操作工具类
*
* @author Amio_
*/
public class JsonUtils {
/**
* 将泛型List对象虚列成JSON字符串
*
* @param list List对象
* @param <T> 泛型形参
* @return JSON字符串
*/
public static <T> String toJson(List<T> list) {
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
}
/**
* 将指定对象序列化成JSON字符串
*
* @param object 指定对象
* @return JSON字符串
*/
public static String toJson(Object object) {
JSONObject jsonObject = JSONObject.fromObject(object);
return jsonObject.toString();
}
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
System.out.println(list.toString());
String temp = JsonUtils.toJson(list);
System.out.println(temp);
}
}
| add json method
| src/main/java/com/keyword/automation/base/utils/JsonUtils.java | add json method |
|
Java | apache-2.0 | 9992e89ca74b4194c4d16b3d8cd24e8a7a91c578 | 0 | topicusonderwijs/wicket,freiheit-com/wicket,aldaris/wicket,apache/wicket,AlienQueen/wicket,zwsong/wicket,mafulafunk/wicket,AlienQueen/wicket,aldaris/wicket,bitstorm/wicket,martin-g/wicket-osgi,astrapi69/wicket,freiheit-com/wicket,mosoft521/wicket,mosoft521/wicket,apache/wicket,Servoy/wicket,Servoy/wicket,topicusonderwijs/wicket,klopfdreh/wicket,martin-g/wicket-osgi,apache/wicket,topicusonderwijs/wicket,dashorst/wicket,mosoft521/wicket,aldaris/wicket,Servoy/wicket,bitstorm/wicket,AlienQueen/wicket,aldaris/wicket,klopfdreh/wicket,selckin/wicket,mosoft521/wicket,klopfdreh/wicket,aldaris/wicket,dashorst/wicket,AlienQueen/wicket,mafulafunk/wicket,freiheit-com/wicket,bitstorm/wicket,klopfdreh/wicket,mosoft521/wicket,Servoy/wicket,dashorst/wicket,martin-g/wicket-osgi,astrapi69/wicket,klopfdreh/wicket,freiheit-com/wicket,topicusonderwijs/wicket,bitstorm/wicket,apache/wicket,topicusonderwijs/wicket,zwsong/wicket,selckin/wicket,selckin/wicket,dashorst/wicket,dashorst/wicket,freiheit-com/wicket,AlienQueen/wicket,astrapi69/wicket,apache/wicket,mafulafunk/wicket,zwsong/wicket,selckin/wicket,selckin/wicket,astrapi69/wicket,zwsong/wicket,bitstorm/wicket,Servoy/wicket | /*
* $Id$ $Revision$
* $Date$
*
* ==================================================================== 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 wicket.examples.repeater;
import wicket.markup.html.basic.Label;
import wicket.markup.html.link.Link;
import wicket.markup.html.panel.FeedbackPanel;
import wicket.markup.html.panel.Panel;
import wicket.model.IModel;
import wicket.model.PropertyModel;
import wicket.version.undo.Change;
/**
* Base page for component demo pages.
*
* @author igor
*/
public class BasePage extends ExamplePage
{
private Contact selected;
/**
* Constructor
*/
public BasePage()
{
add(new Label("selectedLabel", new PropertyModel(this, "selectedContactLabel")));
add(new FeedbackPanel("feedback"));
}
/**
* @return string representation of selceted contact property
*/
public String getSelectedContactLabel()
{
if (selected == null)
{
return "No Contact Selected";
}
else
{
return selected.getFirstName() + " " + selected.getLastName();
}
}
/**
*
*/
class ActionPanel extends Panel
{
/**
* @param id
* component id
* @param model
* model for contact
*/
public ActionPanel(String id, IModel model)
{
super(id, model);
add(new Link("select")
{
public void onClick()
{
BasePage.this.selected = (Contact)getParent().getModelObject();
}
});
}
}
public Contact getSelected()
{
return selected;
}
public void setSelected(Contact selected)
{
addStateChange(new Change()
{
private final Contact old = BasePage.this.selected;
public void undo()
{
BasePage.this.selected = old;
}
});
this.selected = selected;
}
}
| wicket-examples/src/main/java/wicket/examples/repeater/BasePage.java | /*
* $Id$ $Revision$
* $Date$
*
* ==================================================================== 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 wicket.examples.repeater;
import wicket.markup.html.basic.Label;
import wicket.markup.html.link.Link;
import wicket.markup.html.panel.FeedbackPanel;
import wicket.markup.html.panel.Panel;
import wicket.model.IModel;
import wicket.model.PropertyModel;
/**
* Base page for component demo pages.
*
* @author igor
*/
public class BasePage extends ExamplePage
{
private Contact selected;
/**
* Constructor
*/
public BasePage()
{
add(new Label("selectedLabel", new PropertyModel(this, "selectedContactLabel")));
add(new FeedbackPanel("feedback"));
}
/**
* @return string representation of selceted contact property
*/
public String getSelectedContactLabel()
{
if (selected == null)
{
return "No Contact Selected";
}
else
{
return selected.getFirstName() + " " + selected.getLastName();
}
}
/**
*
*/
class ActionPanel extends Panel
{
/**
* @param id
* component id
* @param model
* model for contact
*/
public ActionPanel(String id, IModel model)
{
super(id, model);
add(new Link("select")
{
public void onClick()
{
BasePage.this.selected = (Contact)getParent().getModelObject();
}
});
}
}
public Contact getSelected()
{
return selected;
}
public void setSelected(Contact selected)
{
this.selected = selected;
}
}
| tweak
git-svn-id: 6d6ade8e88b1292e17cba3559b7335a947e495e0@485796 13f79535-47bb-0310-9956-ffa450edef68
| wicket-examples/src/main/java/wicket/examples/repeater/BasePage.java | tweak |
|
Java | apache-2.0 | 1c09cdc9f769523b07b418dd616cc505533edcd7 | 0 | bauna/drools-gorm,bauna/drools-gorm | package org.drools.gorm.session;
import java.util.Collections;
import java.util.Date;
import java.util.IdentityHashMap;
import java.util.Map;
import org.drools.KnowledgeBase;
import org.drools.RuleBase;
import org.drools.SessionConfiguration;
import org.drools.command.Command;
import org.drools.command.Context;
import org.drools.command.impl.ContextImpl;
import org.drools.command.impl.GenericCommand;
import org.drools.command.impl.KnowledgeCommandContext;
import org.drools.command.runtime.DisposeCommand;
import org.drools.common.EndOperationListener;
import org.drools.common.InternalKnowledgeRuntime;
import org.drools.gorm.GrailsIntegration;
import org.drools.gorm.impl.GormDroolsTransactionManager;
import org.drools.gorm.session.marshalling.GormSessionMarshallingHelper;
import org.drools.impl.KnowledgeBaseImpl;
import org.drools.persistence.session.JpaJDKTimerService;
import org.drools.persistence.session.JpaManager;
import org.drools.persistence.session.TransactionManager;
import org.drools.persistence.session.TransactionSynchronization;
import org.drools.process.instance.WorkItemManager;
import org.drools.runtime.Environment;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SingleSessionCommandService
implements
org.drools.command.SingleSessionCommandService {
Logger logger = LoggerFactory.getLogger( getClass() );
private SessionInfo sessionInfo;
private GormSessionMarshallingHelper marshallingHelper;
private StatefulKnowledgeSession ksession;
private Environment env;
private KnowledgeCommandContext kContext;
private TransactionManager txm;
private JpaManager jpm;
private volatile boolean doRollback;
private static Map<Object, Object> synchronizations = Collections.synchronizedMap( new IdentityHashMap<Object, Object>() );
// public static Map<Object, Object> txManagerClasses = Collections.synchronizedMap( new IdentityHashMap<Object, Object>() );
public void checkEnvironment(Environment env) {
}
public SingleSessionCommandService(RuleBase ruleBase,
SessionConfiguration conf,
Environment env) {
this( new KnowledgeBaseImpl( ruleBase ),
conf,
env );
}
public SingleSessionCommandService(int sessionId,
RuleBase ruleBase,
SessionConfiguration conf,
Environment env) {
this( sessionId,
new KnowledgeBaseImpl( ruleBase ),
conf,
env );
}
public SingleSessionCommandService(KnowledgeBase kbase,
KnowledgeSessionConfiguration conf,
Environment env) {
if ( conf == null ) {
conf = new SessionConfiguration();
}
this.env = env;
checkEnvironment( this.env );
this.sessionInfo = GrailsIntegration.getGormDomainService().getNewSessionInfo();
initTransactionManager( this.env );
// create session but bypass command service
this.ksession = kbase.newStatefulKnowledgeSession(conf, this.env);
this.kContext = new KnowledgeCommandContext( new ContextImpl( "ksession",
null ),
null,
null,
this.ksession,
null );
((JpaJDKTimerService) ((InternalKnowledgeRuntime) ksession).getTimerService()).setCommandService( this );
this.marshallingHelper = new GormSessionMarshallingHelper( this.ksession,
conf );
this.sessionInfo.setMarshallingHelper( this.marshallingHelper );
((InternalKnowledgeRuntime) this.ksession).setEndOperationListener( new EndOperationListenerImpl( this.sessionInfo ) );
// Use the App scoped EntityManager if the user has provided it, and it is open.
try {
this.txm.begin();
//this.appScopedEntityManager.joinTransaction();
registerRollbackSync();
jpm.getApplicationScopedEntityManager().persist( this.sessionInfo );
this.txm.commit();
} catch ( Exception t1 ) {
try {
this.txm.rollback();
} catch ( Throwable t2 ) {
throw new RuntimeException( "Could not commit session or rollback",
t2 );
}
throw new RuntimeException( "Could not commit session",
t1 );
}
// update the session id to be the same as the session info id
((InternalKnowledgeRuntime) ksession).setId( this.sessionInfo.getId() );
}
public SingleSessionCommandService(int sessionId,
KnowledgeBase kbase,
KnowledgeSessionConfiguration conf,
Environment env) {
if ( conf == null ) {
conf = new SessionConfiguration();
}
this.env = env;
checkEnvironment( this.env );
initTransactionManager( this.env );
initKsession( sessionId,
kbase,
conf );
}
public void initKsession(int sessionId,
KnowledgeBase kbase,
KnowledgeSessionConfiguration conf) {
if ( !doRollback && this.ksession != null ) {
return;
// nothing to initialise
}
this.doRollback = false;
try {
this.sessionInfo = GrailsIntegration.getGormDomainService().getSessionInfo(sessionId);
} catch ( Exception e ) {
throw new RuntimeException( "Could not find session data for id " + sessionId,
e );
}
if ( sessionInfo == null ) {
throw new RuntimeException( "Could not find session data for id " + sessionId );
}
if ( this.marshallingHelper == null ) {
// this should only happen when this class is first constructed
this.marshallingHelper = new GormSessionMarshallingHelper( kbase,
conf,
env );
}
this.sessionInfo.setMarshallingHelper( this.marshallingHelper );
// if this.ksession is null, it'll create a new one, else it'll use the existing one
this.ksession = this.marshallingHelper.loadSnapshot( this.sessionInfo.getData(),
this.ksession );
// update the session id to be the same as the session info id
((InternalKnowledgeRuntime) ksession).setId( this.sessionInfo.getId() );
((InternalKnowledgeRuntime) this.ksession).setEndOperationListener( new EndOperationListenerImpl( this.sessionInfo ) );
((JpaJDKTimerService) ((InternalKnowledgeRuntime) ksession).getTimerService()).setCommandService( this );
if ( this.kContext == null ) {
// this should only happen when this class is first constructed
this.kContext = new KnowledgeCommandContext( new ContextImpl( "ksession",
null ),
null,
null,
this.ksession,
null );
}
}
public void initTransactionManager(Environment env) {
jpm = new DefaultGormManager(env);
txm = new GormDroolsTransactionManager(GrailsIntegration.getTransactionManager());
// Object tm = env.get( EnvironmentName.TRANSACTION_MANAGER );
// if ( tm != null && tm.getClass().getName().startsWith( "org.springframework" ) ) {
// try {
// Class<?> cls = Class.forName( "org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager" );
// Constructor<?> con = cls.getConstructors()[0];
// this.txm = (TransactionManager) con.newInstance( tm );
// logger.debug( "Instantiating DroolsSpringTransactionManager" );
//
// if ( tm.getClass().getName().toLowerCase().contains( "jpa" ) ) {
// // configure spring for JPA and local transactions
// cls = Class.forName( "org.drools.container.spring.beans.persistence.DroolsSpringJpaManager" );
// con = cls.getConstructors()[0];
// this.jpm = ( JpaManager) con.newInstance( new Object[] { this.env } );
// } else {
// // configure spring for JPA and distributed transactions
// }
// } catch ( Exception e ) {
// logger.warn( "Could not instatiate DroolsSpringTransactionManager" );
// throw new RuntimeException( "Could not instatiate org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager", e );
// }
// } else {
// logger.debug( "Instantiating JtaTransactionManager" );
// this.txm = new JtaTransactionManager( env.get( EnvironmentName.TRANSACTION ),
// env.get( EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY ),
// tm );
// this.jpm = new DefaultGormManager(this.env);
// }
}
public static class EndOperationListenerImpl
implements
EndOperationListener {
private SessionInfo info;
public EndOperationListenerImpl(SessionInfo info) {
this.info = info;
}
public void endOperation(InternalKnowledgeRuntime kruntime) {
this.info.setLastModificationDate( new Date( kruntime.getLastIdleTimestamp() ) );
}
}
public Context getContext() {
return this.kContext;
}
public synchronized <T> T execute(Command<T> command) {
try {
txm.begin();
initKsession( this.sessionInfo.getId(),
this.marshallingHelper.getKbase(),
this.marshallingHelper.getConf() );
this.jpm.beginCommandScopedEntityManager();
registerRollbackSync();
T result = ((GenericCommand<T>) command).execute( this.kContext );
txm.commit();
return result;
}catch (RuntimeException re){
rollbackTransaction(re);
throw re;
} catch ( Exception t1 ) {
rollbackTransaction(t1);
throw new RuntimeException("Wrapped exception see cause", t1);
} finally {
if ( command instanceof DisposeCommand ) {
this.jpm.dispose();
}
}
}
private void rollbackTransaction(Exception t1) {
try {
logger.error( "Could not commit session", t1 );
txm.rollback();
} catch ( Exception t2 ) {
logger.error( "Could not rollback", t2 );
throw new RuntimeException( "Could not commit session or rollback", t2 );
}
}
public void dispose() {
if ( ksession != null ) {
ksession.dispose();
}
}
public int getSessionId() {
return sessionInfo.getId();
}
private void registerRollbackSync() {
if ( synchronizations.get( this ) == null ) {
txm.registerTransactionSynchronization( new SynchronizationImpl() );
synchronizations.put( this,
this );
}
}
private class SynchronizationImpl
implements
TransactionSynchronization {
public void afterCompletion(int status) {
if ( status != TransactionManager.STATUS_COMMITTED ) {
SingleSessionCommandService.this.rollback();
}
// always cleanup thread local whatever the result
SingleSessionCommandService.synchronizations.remove( SingleSessionCommandService.this );
try {
SingleSessionCommandService.this.jpm.endCommandScopedEntityManager();
} catch (Exception e) {
logger.error("afterCompletion endCommandScopedEntityManager()" , e);
}
StatefulKnowledgeSession ksession = SingleSessionCommandService.this.ksession;
// clean up cached process and work item instances
if ( ksession != null ) {
((InternalKnowledgeRuntime) ksession).getProcessRuntime().clearProcessInstances();
((WorkItemManager) ksession.getWorkItemManager()).clear();
}
}
public void beforeCompletion() {
}
}
private void rollback() {
this.doRollback = true;
}
} | src/java/org/drools/gorm/session/SingleSessionCommandService.java | package org.drools.gorm.session;
import java.util.Collections;
import java.util.Date;
import java.util.IdentityHashMap;
import java.util.Map;
import org.drools.KnowledgeBase;
import org.drools.RuleBase;
import org.drools.SessionConfiguration;
import org.drools.command.Command;
import org.drools.command.Context;
import org.drools.command.impl.ContextImpl;
import org.drools.command.impl.GenericCommand;
import org.drools.command.impl.KnowledgeCommandContext;
import org.drools.command.runtime.DisposeCommand;
import org.drools.common.EndOperationListener;
import org.drools.common.InternalKnowledgeRuntime;
import org.drools.gorm.GrailsIntegration;
import org.drools.gorm.impl.GormDroolsTransactionManager;
import org.drools.gorm.session.marshalling.GormSessionMarshallingHelper;
import org.drools.impl.KnowledgeBaseImpl;
import org.drools.persistence.session.JpaJDKTimerService;
import org.drools.persistence.session.JpaManager;
import org.drools.persistence.session.TransactionManager;
import org.drools.persistence.session.TransactionSynchronization;
import org.drools.process.instance.WorkItemManager;
import org.drools.runtime.Environment;
import org.drools.runtime.EnvironmentName;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SingleSessionCommandService
implements
org.drools.command.SingleSessionCommandService {
Logger logger = LoggerFactory.getLogger( getClass() );
private SessionInfo sessionInfo;
private GormSessionMarshallingHelper marshallingHelper;
private StatefulKnowledgeSession ksession;
private Environment env;
private KnowledgeCommandContext kContext;
private TransactionManager txm;
private JpaManager jpm;
private volatile boolean doRollback;
private static Map<Object, Object> synchronizations = Collections.synchronizedMap( new IdentityHashMap<Object, Object>() );
// public static Map<Object, Object> txManagerClasses = Collections.synchronizedMap( new IdentityHashMap<Object, Object>() );
public void checkEnvironment(Environment env) {
}
public SingleSessionCommandService(RuleBase ruleBase,
SessionConfiguration conf,
Environment env) {
this( new KnowledgeBaseImpl( ruleBase ),
conf,
env );
}
public SingleSessionCommandService(int sessionId,
RuleBase ruleBase,
SessionConfiguration conf,
Environment env) {
this( sessionId,
new KnowledgeBaseImpl( ruleBase ),
conf,
env );
}
public SingleSessionCommandService(KnowledgeBase kbase,
KnowledgeSessionConfiguration conf,
Environment env) {
if ( conf == null ) {
conf = new SessionConfiguration();
}
this.env = env;
checkEnvironment( this.env );
this.sessionInfo = GrailsIntegration.getGormDomainService().getNewSessionInfo();
initTransactionManager( this.env );
// create session but bypass command service
this.ksession = kbase.newStatefulKnowledgeSession(conf, this.env);
this.kContext = new KnowledgeCommandContext( new ContextImpl( "ksession",
null ),
null,
null,
this.ksession,
null );
((JpaJDKTimerService) ((InternalKnowledgeRuntime) ksession).getTimerService()).setCommandService( this );
this.marshallingHelper = new GormSessionMarshallingHelper( this.ksession,
conf );
this.sessionInfo.setMarshallingHelper( this.marshallingHelper );
((InternalKnowledgeRuntime) this.ksession).setEndOperationListener( new EndOperationListenerImpl( this.sessionInfo ) );
// Use the App scoped EntityManager if the user has provided it, and it is open.
try {
this.txm.begin();
//this.appScopedEntityManager.joinTransaction();
registerRollbackSync();
jpm.getApplicationScopedEntityManager().persist( this.sessionInfo );
this.txm.commit();
} catch ( Exception t1 ) {
try {
this.txm.rollback();
} catch ( Throwable t2 ) {
throw new RuntimeException( "Could not commit session or rollback",
t2 );
}
throw new RuntimeException( "Could not commit session",
t1 );
}
// update the session id to be the same as the session info id
((InternalKnowledgeRuntime) ksession).setId( this.sessionInfo.getId() );
}
public SingleSessionCommandService(int sessionId,
KnowledgeBase kbase,
KnowledgeSessionConfiguration conf,
Environment env) {
if ( conf == null ) {
conf = new SessionConfiguration();
}
this.env = env;
checkEnvironment( this.env );
initTransactionManager( this.env );
initKsession( sessionId,
kbase,
conf );
}
public void initKsession(int sessionId,
KnowledgeBase kbase,
KnowledgeSessionConfiguration conf) {
if ( !doRollback && this.ksession != null ) {
return;
// nothing to initialise
}
this.doRollback = false;
try {
this.sessionInfo = GrailsIntegration.getGormDomainService().getSessionInfo(sessionId);
} catch ( Exception e ) {
throw new RuntimeException( "Could not find session data for id " + sessionId,
e );
}
if ( sessionInfo == null ) {
throw new RuntimeException( "Could not find session data for id " + sessionId );
}
if ( this.marshallingHelper == null ) {
// this should only happen when this class is first constructed
this.marshallingHelper = new GormSessionMarshallingHelper( kbase,
conf,
env );
}
this.sessionInfo.setMarshallingHelper( this.marshallingHelper );
// if this.ksession is null, it'll create a new one, else it'll use the existing one
this.ksession = this.marshallingHelper.loadSnapshot( this.sessionInfo.getData(),
this.ksession );
// update the session id to be the same as the session info id
((InternalKnowledgeRuntime) ksession).setId( this.sessionInfo.getId() );
((InternalKnowledgeRuntime) this.ksession).setEndOperationListener( new EndOperationListenerImpl( this.sessionInfo ) );
((JpaJDKTimerService) ((InternalKnowledgeRuntime) ksession).getTimerService()).setCommandService( this );
if ( this.kContext == null ) {
// this should only happen when this class is first constructed
this.kContext = new KnowledgeCommandContext( new ContextImpl( "ksession",
null ),
null,
null,
this.ksession,
null );
}
}
public void initTransactionManager(Environment env) {
jpm = new DefaultGormManager(env);
txm = new GormDroolsTransactionManager(GrailsIntegration.getTransactionManager());
// Object tm = env.get( EnvironmentName.TRANSACTION_MANAGER );
// if ( tm != null && tm.getClass().getName().startsWith( "org.springframework" ) ) {
// try {
// Class<?> cls = Class.forName( "org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager" );
// Constructor<?> con = cls.getConstructors()[0];
// this.txm = (TransactionManager) con.newInstance( tm );
// logger.debug( "Instantiating DroolsSpringTransactionManager" );
//
// if ( tm.getClass().getName().toLowerCase().contains( "jpa" ) ) {
// // configure spring for JPA and local transactions
// cls = Class.forName( "org.drools.container.spring.beans.persistence.DroolsSpringJpaManager" );
// con = cls.getConstructors()[0];
// this.jpm = ( JpaManager) con.newInstance( new Object[] { this.env } );
// } else {
// // configure spring for JPA and distributed transactions
// }
// } catch ( Exception e ) {
// logger.warn( "Could not instatiate DroolsSpringTransactionManager" );
// throw new RuntimeException( "Could not instatiate org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager", e );
// }
// } else {
// logger.debug( "Instantiating JtaTransactionManager" );
// this.txm = new JtaTransactionManager( env.get( EnvironmentName.TRANSACTION ),
// env.get( EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY ),
// tm );
// this.jpm = new DefaultGormManager(this.env);
// }
}
public static class EndOperationListenerImpl
implements
EndOperationListener {
private SessionInfo info;
public EndOperationListenerImpl(SessionInfo info) {
this.info = info;
}
public void endOperation(InternalKnowledgeRuntime kruntime) {
this.info.setLastModificationDate( new Date( kruntime.getLastIdleTimestamp() ) );
}
}
public Context getContext() {
return this.kContext;
}
public synchronized <T> T execute(Command<T> command) {
try {
txm.begin();
initKsession( this.sessionInfo.getId(),
this.marshallingHelper.getKbase(),
this.marshallingHelper.getConf() );
this.jpm.beginCommandScopedEntityManager();
registerRollbackSync();
T result = ((GenericCommand<T>) command).execute( this.kContext );
txm.commit();
return result;
}catch (RuntimeException re){
rollbackTransaction(re);
throw re;
} catch ( Exception t1 ) {
rollbackTransaction(t1);
throw new RuntimeException("Wrapped exception see cause", t1);
} finally {
if ( command instanceof DisposeCommand ) {
this.jpm.dispose();
}
}
}
private void rollbackTransaction(Exception t1) {
try {
logger.error( "Could not commit session", t1 );
txm.rollback();
} catch ( Exception t2 ) {
logger.error( "Could not rollback", t2 );
throw new RuntimeException( "Could not commit session or rollback", t2 );
}
}
public void dispose() {
if ( ksession != null ) {
ksession.dispose();
}
}
public int getSessionId() {
return sessionInfo.getId();
}
private void registerRollbackSync() {
if ( synchronizations.get( this ) == null ) {
txm.registerTransactionSynchronization( new SynchronizationImpl() );
synchronizations.put( this,
this );
}
}
private class SynchronizationImpl
implements
TransactionSynchronization {
public void afterCompletion(int status) {
if ( status != TransactionManager.STATUS_COMMITTED ) {
SingleSessionCommandService.this.rollback();
}
// always cleanup thread local whatever the result
SingleSessionCommandService.synchronizations.remove( SingleSessionCommandService.this );
try {
SingleSessionCommandService.this.jpm.endCommandScopedEntityManager();
} catch (Exception e) {
logger.error("afterCompletion endCommandScopedEntityManager()" , e);
}
StatefulKnowledgeSession ksession = SingleSessionCommandService.this.ksession;
// clean up cached process and work item instances
if ( ksession != null ) {
((InternalKnowledgeRuntime) ksession).getProcessRuntime().clearProcessInstances();
((WorkItemManager) ksession.getWorkItemManager()).clear();
}
}
public void beforeCompletion() {
}
}
private void rollback() {
this.doRollback = true;
}
} | remove unused imports
| src/java/org/drools/gorm/session/SingleSessionCommandService.java | remove unused imports |
|
Java | apache-2.0 | 8510b95e8e4d91b108565b8f4721c3b76b346972 | 0 | haroldcarr/rdf-triple-browser,haroldcarr/rdf-triple-browser | //
// Created : 2006 Jun 14 (Wed) 18:29:38 by Harold Carr.
// Last Modified : 2008 May 29 (Thu) 19:20:10 by Harold Carr.
//
package org.openhc.trowser.gwt.client;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import org.openhc.trowser.gwt.common.QueryRequest;
import org.openhc.trowser.gwt.common.QueryResponse;
import org.openhc.trowser.gwt.common.Triple;
public class QueryManager
{
private final Main main;
QueryManager(Main main)
{
this.main = main;
}
public void doQuery()
{
List triples = new ArrayList();
Iterator hpi = main.getQueryPanel().getPanel().iterator();
while (hpi.hasNext()) {
HorizontalPanel triple = (HorizontalPanel) hpi.next();
Iterator i = triple.iterator();
i.next(); // skip Button;
i.next(); // skip RadioButton;
i.next(); // skip subject MenuBar
final String subject =
getSPVQueryValue(main.qsubject, (TextBox) i.next());
i.next(); // skip property MenuBar
final String property =
getSPVQueryValue(main.qproperty, (TextBox) i.next());
i.next(); // skip value MenuBar
final String value =
getSPVQueryValue(main.qvalue, (TextBox) i.next());
triples.add(new Triple(subject, property, value));
}
doQuery(triples, main.qsubject + main.qproperty + main.qvalue);
}
public void doQuery(final String subject, final String property,
final String value, final String setContentsOf)
{
List triples = new ArrayList();
triples.add(new Triple(subject, property, value));
doQuery(triples, setContentsOf);
}
public void doQuery(final List triples, final String setContentsOf)
{
QueryRequest queryRequest = new QueryRequest(triples, setContentsOf);
main.getServerCalls().doQuery(queryRequest);
}
public void handleQueryResponse(QueryResponse queryResponse)
{
String setContentsOf = queryResponse.getSetContentsOf();
if (setContentsOf.indexOf(main.qsubject) != -1) {
main.getSPVPanel().getSubjectPanel()
.setContents(queryResponse.getSubject());
}
if (setContentsOf.indexOf(main.qproperty) != -1) {
main.getSPVPanel().getPropertyPanel()
.setContents(queryResponse.getProperty());
}
if (setContentsOf.indexOf(main.qvalue) != -1) {
main.getSPVPanel().getValuePanel()
.setContents(queryResponse.getValue());
}
}
public void spvLinkClicked(final String category, final String url)
{
if (category.equals(main.subject)) {
main.getQueryPanel().getSubjectTextBox().setText(url);
} else if (category.equals(main.property)) {
main.getQueryPanel().getPropertyTextBox().setText(url);
} else if (category.equals(main.value)) {
main.getQueryPanel().getValueTextBox().setText(url);
} else {
// TODO: FIX
main.getQueryPanel().getSubjectTextBox().setText("ERROR");
return;
}
doQuery();
}
//
// The default is only there in case user puts in a blank string.
// The system will never do that.
//
private String getSPVQueryValue(String def, TextBox textBox)
{
String text = textBox.getText();
if (text != null && (! text.equals(""))) {
return text;
}
return def;
}
}
// End of file.
| gwt/src/main/java/org/openhc/triplebrowser/gwt/client/QueryManager.java | //
// Created : 2006 Jun 14 (Wed) 18:29:38 by Harold Carr.
// Last Modified : 2008 May 29 (Thu) 14:07:46 by Harold Carr.
//
package org.openhc.trowser.gwt.client;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import org.openhc.trowser.gwt.common.QueryRequest;
import org.openhc.trowser.gwt.common.QueryResponse;
import org.openhc.trowser.gwt.common.Triple;
public class QueryManager
{
private final Main main;
QueryManager(Main main)
{
this.main = main;
}
public void doQuery()
{
List triples = new ArrayList();
Iterator hpi = main.getQueryPanel().getPanel().iterator();
while (hpi.hasNext()) {
HorizontalPanel triple = (HorizontalPanel) hpi.next();
Iterator i = triple.iterator();
i.next(); // skip RadioButton;
i.next(); // skip Button;
i.next(); // skip subject MenuBar
final String subject =
getSPVQueryValue(main.qsubject, (TextBox) i.next());
i.next(); // skip property MenuBar
final String property =
getSPVQueryValue(main.qproperty, (TextBox) i.next());
i.next(); // skip value MenuBar
final String value =
getSPVQueryValue(main.qvalue, (TextBox) i.next());
triples.add(new Triple(subject, property, value));
}
doQuery(triples, main.qsubject + main.qproperty + main.qvalue);
}
public void doQuery(final String subject, final String property,
final String value, final String setContentsOf)
{
List triples = new ArrayList();
triples.add(new Triple(subject, property, value));
doQuery(triples, setContentsOf);
}
public void doQuery(final List triples, final String setContentsOf)
{
QueryRequest queryRequest = new QueryRequest(triples, setContentsOf);
main.getServerCalls().doQuery(queryRequest);
}
public void handleQueryResponse(QueryResponse queryResponse)
{
String setContentsOf = queryResponse.getSetContentsOf();
if (setContentsOf.indexOf(main.qsubject) != -1) {
main.getSPVPanel().getSubjectPanel()
.setContents(queryResponse.getSubject());
}
if (setContentsOf.indexOf(main.qproperty) != -1) {
main.getSPVPanel().getPropertyPanel()
.setContents(queryResponse.getProperty());
}
if (setContentsOf.indexOf(main.qvalue) != -1) {
main.getSPVPanel().getValuePanel()
.setContents(queryResponse.getValue());
}
}
public void spvLinkClicked(final String category, final String url)
{
if (category.equals(main.subject)) {
main.getQueryPanel().getSubjectTextBox().setText(url);
} else if (category.equals(main.property)) {
main.getQueryPanel().getPropertyTextBox().setText(url);
} else if (category.equals(main.value)) {
main.getQueryPanel().getValueTextBox().setText(url);
} else {
// TODO: FIX
main.getQueryPanel().getSubjectTextBox().setText("ERROR");
return;
}
doQuery();
}
//
// The default is only there in case user puts in a blank string.
// The system will never do that.
//
private String getSPVQueryValue(String def, TextBox textBox)
{
String text = textBox.getText();
if (text != null && (! text.equals(""))) {
return text;
}
return def;
}
}
// End of file.
| ["Change comments to match code.\n", ""] | gwt/src/main/java/org/openhc/triplebrowser/gwt/client/QueryManager.java | ["Change comments to match code.\n", ""] |
|
Java | apache-2.0 | 1ba9d32c9f212ff4095dca0ec770561336d14b3d | 0 | ahmadassaf/CommaFeed-RSS-Reader,zhangzuoqiang/commafeed,tlvince/commafeed,Hubcapp/commafeed,tlvince/commafeed,Hubcapp/commafeed,RavenB/commafeed,tlvince/commafeed,wesley1001/commafeed,Athou/commafeed,wesley1001/commafeed,RavenB/commafeed,RavenB/commafeed,ebraminio/commafeed,syshk/commafeed,Athou/commafeed,ahmadassaf/CommaFeed-RSS-Reader,ebraminio/commafeed,syshk/commafeed,zhangzuoqiang/commafeed,zhangzuoqiang/commafeed,ebraminio/commafeed,RavenB/commafeed,Hubcapp/commafeed,ahmadassaf/CommaFeed-RSS-Reader,Hubcapp/commafeed,wesley1001/commafeed,ahmadassaf/CommaFeed-RSS-Reader,zhangzuoqiang/commafeed,Athou/commafeed,ebraminio/commafeed,syshk/commafeed,tlvince/commafeed,Athou/commafeed,syshk/commafeed,wesley1001/commafeed | package com.commafeed.frontend.rest.resources;
import java.lang.reflect.Method;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.wicket.ThreadContext;
import org.apache.wicket.authentication.IAuthenticationStrategy;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.protocol.http.servlet.ServletWebResponse;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.crypt.Base64;
import com.commafeed.backend.MetricsBean;
import com.commafeed.backend.dao.FeedCategoryDAO;
import com.commafeed.backend.dao.FeedDAO;
import com.commafeed.backend.dao.FeedEntryDAO;
import com.commafeed.backend.dao.FeedEntryStatusDAO;
import com.commafeed.backend.dao.FeedSubscriptionDAO;
import com.commafeed.backend.dao.UserDAO;
import com.commafeed.backend.dao.UserRoleDAO;
import com.commafeed.backend.dao.UserSettingsDAO;
import com.commafeed.backend.feeds.FeedFetcher;
import com.commafeed.backend.feeds.OPMLImporter;
import com.commafeed.backend.model.User;
import com.commafeed.backend.model.UserRole.Role;
import com.commafeed.backend.services.ApplicationSettingsService;
import com.commafeed.backend.services.FeedEntryService;
import com.commafeed.backend.services.FeedSubscriptionService;
import com.commafeed.backend.services.PasswordEncryptionService;
import com.commafeed.backend.services.UserService;
import com.commafeed.frontend.CommaFeedApplication;
import com.commafeed.frontend.CommaFeedSession;
import com.commafeed.frontend.SecurityCheck;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public abstract class AbstractREST {
@Context
HttpServletRequest request;
@Context
HttpServletResponse response;
@Inject
ApplicationSettingsService applicationSettingsService;
@Inject
FeedDAO feedDAO;
@Inject
FeedSubscriptionDAO feedSubscriptionDAO;
@Inject
FeedSubscriptionService feedSubscriptionService;
@Inject
FeedCategoryDAO feedCategoryDAO;
@Inject
FeedEntryDAO feedEntryDAO;
@Inject
FeedEntryStatusDAO feedEntryStatusDAO;
@Inject
FeedEntryService feedEntryService;
@Inject
UserDAO userDAO;
@Inject
UserService userService;
@Inject
UserSettingsDAO userSettingsDAO;
@Inject
UserRoleDAO userRoleDAO;
@Inject
OPMLImporter opmlImporter;
@Inject
PasswordEncryptionService encryptionService;
@Inject
FeedFetcher feedFetcher;
@Inject
MetricsBean metricsBean;
@PostConstruct
public void init() {
CommaFeedApplication app = CommaFeedApplication.get();
ServletWebRequest swreq = new ServletWebRequest(request, "");
ServletWebResponse swresp = new ServletWebResponse(swreq, response);
RequestCycle cycle = app.createRequestCycle(swreq, swresp);
ThreadContext.setRequestCycle(cycle);
CommaFeedSession session = (CommaFeedSession) app
.fetchCreateAndSetSession(cycle);
if (session.getUser() == null) {
IAuthenticationStrategy authenticationStrategy = app
.getSecuritySettings().getAuthenticationStrategy();
String[] data = authenticationStrategy.load();
if (data != null && data.length > 1) {
session.signIn(data[0], data[1]);
} else {
String value = swreq.getHeader(HttpHeaders.AUTHORIZATION);
if (value != null && value.startsWith("Basic ")) {
value = value.substring(6);
String decoded = new String(Base64.decodeBase64(value));
data = decoded.split(":");
if (data != null && data.length > 1) {
session.signIn(data[0], data[1]);
}
}
}
}
}
protected User getUser() {
return CommaFeedSession.get().getUser();
}
@AroundInvoke
public Object checkSecurity(InvocationContext context) throws Exception {
User user = getUser();
boolean allowed = true;
Method method = context.getMethod();
if (method.isAnnotationPresent(SecurityCheck.class)) {
allowed = checkRole(user, method.getAnnotation(SecurityCheck.class));
} else if (method.getDeclaringClass().isAnnotationPresent(
SecurityCheck.class)) {
allowed = checkRole(
user,
method.getDeclaringClass().getAnnotation(
SecurityCheck.class));
}
if (!allowed) {
if (user == null) {
throw new WebApplicationException(Response
.status(Status.UNAUTHORIZED)
.entity("You are not authorized to do this.")
.header(HttpHeaders.WWW_AUTHENTICATE,
"Basic realm=\"CommaFeed\"").build());
} else {
throw new WebApplicationException(Response
.status(Status.FORBIDDEN)
.entity("You are not authorized to do this.").build());
}
}
return context.proceed();
}
private boolean checkRole(User user, SecurityCheck annotation) {
Role requiredRole = annotation.value();
if (requiredRole == Role.NONE) {
return true;
}
Roles roles = CommaFeedSession.get().getRoles();
boolean authorized = roles.hasAnyRole(new Roles(requiredRole.name()));
return authorized;
}
}
| src/main/java/com/commafeed/frontend/rest/resources/AbstractREST.java | package com.commafeed.frontend.rest.resources;
import java.lang.reflect.Method;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.wicket.ThreadContext;
import org.apache.wicket.authentication.IAuthenticationStrategy;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.protocol.http.servlet.ServletWebResponse;
import org.apache.wicket.request.cycle.RequestCycle;
import com.commafeed.backend.MetricsBean;
import com.commafeed.backend.dao.FeedCategoryDAO;
import com.commafeed.backend.dao.FeedDAO;
import com.commafeed.backend.dao.FeedEntryDAO;
import com.commafeed.backend.dao.FeedEntryStatusDAO;
import com.commafeed.backend.dao.FeedSubscriptionDAO;
import com.commafeed.backend.dao.UserDAO;
import com.commafeed.backend.dao.UserRoleDAO;
import com.commafeed.backend.dao.UserSettingsDAO;
import com.commafeed.backend.feeds.FeedFetcher;
import com.commafeed.backend.feeds.OPMLImporter;
import com.commafeed.backend.model.User;
import com.commafeed.backend.model.UserRole.Role;
import com.commafeed.backend.services.ApplicationSettingsService;
import com.commafeed.backend.services.FeedEntryService;
import com.commafeed.backend.services.FeedSubscriptionService;
import com.commafeed.backend.services.PasswordEncryptionService;
import com.commafeed.backend.services.UserService;
import com.commafeed.frontend.CommaFeedApplication;
import com.commafeed.frontend.CommaFeedSession;
import com.commafeed.frontend.SecurityCheck;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public abstract class AbstractREST {
@Context
HttpServletRequest request;
@Context
HttpServletResponse response;
@Inject
ApplicationSettingsService applicationSettingsService;
@Inject
FeedDAO feedDAO;
@Inject
FeedSubscriptionDAO feedSubscriptionDAO;
@Inject
FeedSubscriptionService feedSubscriptionService;
@Inject
FeedCategoryDAO feedCategoryDAO;
@Inject
FeedEntryDAO feedEntryDAO;
@Inject
FeedEntryStatusDAO feedEntryStatusDAO;
@Inject
FeedEntryService feedEntryService;
@Inject
UserDAO userDAO;
@Inject
UserService userService;
@Inject
UserSettingsDAO userSettingsDAO;
@Inject
UserRoleDAO userRoleDAO;
@Inject
OPMLImporter opmlImporter;
@Inject
PasswordEncryptionService encryptionService;
@Inject
FeedFetcher feedFetcher;
@Inject
MetricsBean metricsBean;
@PostConstruct
public void init() {
CommaFeedApplication app = CommaFeedApplication.get();
ServletWebRequest swreq = new ServletWebRequest(request, "");
ServletWebResponse swresp = new ServletWebResponse(swreq, response);
RequestCycle cycle = app.createRequestCycle(swreq, swresp);
ThreadContext.setRequestCycle(cycle);
CommaFeedSession session = (CommaFeedSession) app
.fetchCreateAndSetSession(cycle);
if (session.getUser() == null) {
IAuthenticationStrategy authenticationStrategy = app
.getSecuritySettings().getAuthenticationStrategy();
String[] data = authenticationStrategy.load();
if (data != null && data.length > 1) {
session.signIn(data[0], data[1]);
}
}
}
protected User getUser() {
return CommaFeedSession.get().getUser();
}
@AroundInvoke
public Object checkSecurity(InvocationContext context) throws Exception {
User user = getUser();
boolean allowed = true;
Method method = context.getMethod();
if (method.isAnnotationPresent(SecurityCheck.class)) {
allowed = checkRole(user, method.getAnnotation(SecurityCheck.class));
} else if (method.getDeclaringClass().isAnnotationPresent(
SecurityCheck.class)) {
allowed = checkRole(
user,
method.getDeclaringClass().getAnnotation(
SecurityCheck.class));
}
if (!allowed) {
throw new WebApplicationException(Response.status(Status.FORBIDDEN)
.entity("You are not authorized to do this.").build());
}
return context.proceed();
}
private boolean checkRole(User user, SecurityCheck annotation) {
Role requiredRole = annotation.value();
if (requiredRole == Role.NONE) {
return true;
}
Roles roles = CommaFeedSession.get().getRoles();
boolean authorized = roles.hasAnyRole(new Roles(requiredRole.name()));
return authorized;
}
}
| use basic authentication if cookie is not found
| src/main/java/com/commafeed/frontend/rest/resources/AbstractREST.java | use basic authentication if cookie is not found |
|
Java | apache-2.0 | f8a5c70f847463ae26f729fa57a15dda3617b9b4 | 0 | joh12041/graphhopper,joh12041/graphhopper,joh12041/graphhopper,joh12041/graphhopper | package com.graphhopper.reader.osm;
import com.graphhopper.GHRequest;
import com.graphhopper.GHResponse;
import com.graphhopper.GraphHopper;
import com.graphhopper.PathWrapper;
import com.graphhopper.matching.EdgeMatch;
import com.graphhopper.matching.MapMatching;
import com.graphhopper.matching.MatchResult;
import com.graphhopper.routing.AlgorithmOptions;
import com.graphhopper.routing.Path;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.HintsMap;
import com.graphhopper.util.*;
import java.util.*;
import java.io.*;
import java.util.List;
/**
* Created by isaac on 09/14/16.
*/
public class runKSP {
String city;
String route_type;
ArrayList<FileWriter> outputFiles;
private String osmFile = "./reader-osm/files/";
private String graphFolder = "./reader-osm/target/tmp/";
private String inputPointsFN = "../data/intermediate/";
private String outputPointsFN = "../data/output/";
private String gvfnStem = "../data/intermediate/";
private ArrayList<String> gridValuesFNs = new ArrayList<>();
private HashMap<String, Integer> gvHeaderMap;
private HashMap<String, Float> gridBeauty;
private GraphHopper hopper;
private MapMatching mapMatching;
private String outputheader = "ID,polyline_points,total_time_in_sec,total_distance_in_meters,number_of_steps,maneuvers,beauty,simplicity" +
System.getProperty("line.separator");
public runKSP(String city, String route_type) {
this.city = city;
this.route_type = route_type;
this.outputFiles = new ArrayList<>(4);
}
public void setCity(String city) {
this.city = city;
}
public void setRouteType(String route_type) {
this.route_type = route_type;
}
public PathWrapper GPXToPath(ArrayList<GPXEntry> gpxEntries) {
PathWrapper matchGHRsp = new PathWrapper();
try {
MatchResult mr = mapMatching.doWork(gpxEntries);
Path path = mapMatching.calcPath(mr);
new PathMerger().doWork(matchGHRsp, Collections.singletonList(path), new TranslationMap().doImport().getWithFallBack(Locale.US));
}
catch (RuntimeException e) {
System.out.println("Broken GPX trace.");
System.out.println(e.getMessage());
}
return matchGHRsp;
}
public void PointsToPath(String fin, String fout) throws IOException {
Scanner sc_in = new Scanner(new File(fin));
String[] pointsHeader = sc_in.nextLine().split(",");
int idIdx = -1;
int latIdx = -1;
int lonIdx = -1;
int timeIdx = -1;
for (int i=0; i<pointsHeader.length; i++) {
if (pointsHeader[i].equalsIgnoreCase("ID")) {
idIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("lat")) {
latIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("lon")) {
lonIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("millis")) {
timeIdx = i;
}
else {
System.out.println("Unexpected header value: " + pointsHeader[i]);
}
}
String line;
String[] vals;
String routeID = "";
String prevRouteID = "";
double lat;
double lon;
long time;
ArrayList<GPXEntry> pointsList = new ArrayList<>();
PathWrapper path;
FileWriter sc_out = new FileWriter(fout, true);
sc_out.write(outputheader);
int i = 0;
float score;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
routeID = vals[idIdx];
lat = Double.valueOf(vals[latIdx]);
lon = Double.valueOf(vals[lonIdx]);
time = Long.valueOf(vals[timeIdx]);
GPXEntry pt = new GPXEntry(lat, lon, time);
if (routeID.equalsIgnoreCase(prevRouteID)) {
pointsList.add(pt);
}
else if (pointsList.size() > 0) {
path = GPXToPath(pointsList);
//path = trimPath(path, pointsList);
if (path.getDistance() > 0) {
score = getBeauty(path);
writeOutput(sc_out, i, "Google", prevRouteID, path, score);
}
pointsList.clear();
i++;
pointsList.add(pt);
if (i % 10 == 0) {
for (FileWriter fw : outputFiles) {
fw.flush();
}
}
}
prevRouteID = routeID;
}
if (pointsList.size() > 0) {
path = GPXToPath(pointsList);
if (path.getDistance() > 0) {
score = getBeauty(path);
writeOutput(sc_out, i, "Google", prevRouteID, path, score);
}
}
sc_out.close();
sc_in.close();
}
public PathWrapper trimPath(PathWrapper path, ArrayList<GPXEntry> original) {
return new PathWrapper();
}
public void setDataSources() throws Exception {
if (city.equals("SF")) {
osmFile = osmFile + "san-francisco-bay_california.osm.pbf";
graphFolder = graphFolder + "ghosm_sf_noch";
inputPointsFN = inputPointsFN + "sf_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "sf_" + route_type + "_gh_routes.csv";
gridValuesFNs.add(gvfnStem + "06075_logfractionempath_flickr.csv");
} else if (city.equals("NYC")) {
osmFile = osmFile + "new-york_new-york.osm.pbf";
graphFolder = graphFolder + "ghosm_nyc_noch";
inputPointsFN = inputPointsFN + "nyc_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "nyc_" + route_type + "gh_routes.csv";
gridValuesFNs.add(gvfnStem + "36005_beauty_flickr.csv");
gridValuesFNs.add(gvfnStem + "36047_beauty_flickr.csv");
gridValuesFNs.add(gvfnStem + "36061_beauty_flickr.csv");
gridValuesFNs.add(gvfnStem + "36081_beauty_flickr.csv");
gridValuesFNs.add(gvfnStem + "36085_beauty_flickr.csv");
} else if (city.equals("BOS")) {
osmFile = osmFile + "boston_massachusetts.osm.pbf";
graphFolder = graphFolder + "ghosm_bos_noch";
inputPointsFN = inputPointsFN + "bos_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "bos_" + route_type + "gh_routes.csv";
gridValuesFNs.add(gvfnStem + "25025_beauty_twitter.csv");
} else {
throw new Exception("Invalid Parameters: city must be of 'SF','NYC', or 'BOS' and route_type of 'grid' or 'rand'");
}
}
public void getGridValues() throws Exception {
gvHeaderMap = new HashMap<>();
gridBeauty = new HashMap<>();
for (String fn : gridValuesFNs) {
Scanner sc_in = new Scanner(new File(fn));
String[] gvHeader = sc_in.nextLine().split(",");
int i = 0;
for (String col : gvHeader) {
gvHeaderMap.put(col, i);
i++;
}
String line;
String[] vals;
String rc;
float beauty;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
rc = vals[gvHeaderMap.get("rid")] + "," + vals[gvHeaderMap.get("cid")];
beauty = Float.valueOf(vals[gvHeaderMap.get("beauty")]);
gridBeauty.put(rc, beauty);
}
}
}
public void prepareGraphHopper() {
// create one GraphHopper instance
hopper = new GraphHopperOSM().forDesktop().setCHEnabled(false);
hopper.setDataReaderFile(osmFile);
// where to store graphhopper files?
hopper.setGraphHopperLocation(graphFolder);
hopper.setEncodingManager(new EncodingManager("car"));
// now this can take minutes if it imports or a few seconds for loading
// of course this is dependent on the area you import
hopper.importOrLoad();
}
public void prepMapMatcher() {
// create MapMatching object, can and should be shared accross threads
AlgorithmOptions algoOpts = AlgorithmOptions.start().
algorithm(Parameters.Algorithms.DIJKSTRA).
traversalMode(hopper.getTraversalMode()).
hints(new HintsMap().put("weighting", "fastest").put("vehicle", "car")).
build();
mapMatching = new MapMatching(hopper, algoOpts);
mapMatching.setTransitionProbabilityBeta(0.00959442);
// mapMatching.setTransitionProbabilityBeta(0.000959442);
mapMatching.setMeasurementErrorSigma(100);
}
public void writeOutput(FileWriter fw, int i, String optimized, String od_id, PathWrapper bestPath, float score) throws IOException {
// points, distance in meters and time in seconds (convert from ms) of the full path
PointList pointList = bestPath.getPoints();
int simplicity = bestPath.getSimplicity();
double distance = Math.round(bestPath.getDistance() * 100) / 100;
long timeInSec = bestPath.getTime() / 1000;
InstructionList il = bestPath.getInstructions();
int numDirections = il.getSize();
// iterate over every turn instruction
ArrayList<String> maneuvers = new ArrayList<>();
for (Instruction instruction : il) {
maneuvers.add(instruction.getSimpleTurnDescription());
}
fw.write(od_id + "," + "\"[" + pointList + "]\"," + timeInSec + "," + distance + "," + numDirections +
",\"" + maneuvers.toString() + "\"" + "," + score + "," + simplicity + System.getProperty("line.separator"));
System.out.println(i + " (" + optimized + "): Distance: " + distance + "m;\tTime: " + timeInSec + "sec;\t# Directions: " + numDirections + ";\tSimplicity: " + simplicity + ";\tScore: " + score);
}
public float getBeauty(PathWrapper path) {
HashSet<String> roundedPoints = path.roundPoints();
float score = 0;
for (String pt : roundedPoints) {
if (gridBeauty.containsKey(pt)) {
score = score + gridBeauty.get(pt);
}
}
score = score / roundedPoints.size();
return score;
}
public void augment_routes() throws Exception {
}
public void process_routes() throws Exception {
ArrayList<float[]> inputPoints = new ArrayList<float[]>();
ArrayList<String> id_to_points = new ArrayList<String>();
// Prep Filewriters (Optimized, Worst-but-same-distance, Fastest, Simplest)
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_beauty.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_ugly.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_fast.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_simple.csv"), true));
for (FileWriter fw : outputFiles) {
fw.write(outputheader);
}
// Bring in origin-destination pairs for processing
Scanner sc_in = new Scanner(new File(inputPointsFN));
String header = sc_in.nextLine();
String od_id;
float laF;
float loF;
float laT;
float loT;
float idx = 0;
System.out.println("Input data points header: " + header);
while (sc_in.hasNext()) {
idx = idx + 1;
String line = sc_in.nextLine();
String[] vals = line.split(",");
od_id = vals[0];
loF = Float.valueOf(vals[1]);
laF = Float.valueOf(vals[2]);
loT = Float.valueOf(vals[3]);
laT = Float.valueOf(vals[4]);
inputPoints.add(new float[]{laF, loF, laT, loT, idx});
id_to_points.add(od_id);
}
int numPairs = inputPoints.size();
System.out.println(numPairs + " origin-destination pairs.");
// Loop through origin-destination pairs, processing each one for beauty, non-beautiful matched, fastest, and simplest
float[] points;
int routes_skipped = 0;
for (int i=0; i<numPairs; i++) {
if (i % 50 == 0) {
for (FileWriter fw : outputFiles) {
fw.flush();
}
}
// Get Routes
points = inputPoints.get(i);
od_id = id_to_points.get(i);
GHRequest req = new GHRequest(points[0], points[1], points[2], points[3]). // latFrom, lonFrom, latTo, lonTo
setWeighting("fastest").
setVehicle("car").
setLocale(Locale.US).
setAlgorithm("ksp");
GHResponse rsp = hopper.route(req);
System.out.println("Num Responses: " + rsp.getAll().size());
// first check for errors
if (rsp.hasErrors()) {
// handle them!
System.out.println(rsp.getErrors().toString());
System.out.println(i + ": Skipping.");
String outputRow = od_id + "," + "\"[(" + points[0] + "," + points[1] + "),(" + points[2] + "," + points[3]
+ ")]\"," + "-1,-1,-1,[]" + System.getProperty("line.separator");
for (FileWriter fw: outputFiles) {
fw.write(outputRow);
}
routes_skipped++;
continue;
}
// Get All Routes (up to 10K right now)
List<PathWrapper> paths = rsp.getAll();
// Score each route on beauty to determine most beautiful
int j = 0;
float bestscore = -1000;
int routeidx = -1;
for (PathWrapper path : paths) {
float score = getBeauty(path);
if (score > bestscore) {
bestscore = score;
routeidx = j;
}
j++;
}
writeOutput(outputFiles.get(0), i, "Best", od_id, paths.get(routeidx), bestscore);
// Find least-beautiful route within similar distance constraints
double beautyDistance = paths.get(routeidx).getDistance();
j = 0;
bestscore = 1000;
routeidx = -1;
double uglydistance;
for (PathWrapper path : paths) {
uglydistance = path.getDistance();
if (uglydistance / beautyDistance < 1.05 && uglydistance / beautyDistance > 0.95) {
float score = getBeauty(path);
if (score < bestscore) {
bestscore = score;
routeidx = j;
}
}
j++;
}
writeOutput(outputFiles.get(1), i, "Wrst", od_id, paths.get(routeidx), bestscore);
// Simplest Route
j = 0;
bestscore = 10000;
routeidx = 0;
float beauty = -1;
for (PathWrapper path : paths) {
int score = path.getSimplicity();
if (score < bestscore) {
bestscore = score;
routeidx = j;
beauty = getBeauty(path);
}
j++;
}
writeOutput(outputFiles.get(2), i, "Simp", od_id, paths.get(routeidx), beauty);
// Fastest Route
PathWrapper bestPath = paths.get(0);
beauty = getBeauty(bestPath);
writeOutput(outputFiles.get(3), i, "Fast", od_id, bestPath, beauty);
}
// Finished analysis: close filewriters and indicate how many paths skipped
System.out.println(routes_skipped + " routes skipped out of " + numPairs);
for (FileWriter fw : outputFiles) {
fw.close();
}
}
public static void main(String[] args) throws Exception {
// PBF from: https://mapzen.com/data/metro-extracts/
// SF Grid
runKSP ksp = new runKSP("SF", "grid");
// SF Random
//runKSP ksp = new runKSP("SF", "rand");
// NYC Grid
//runKSP ksp = new runKSP("NYC", "grid");
// NYC Random
//runKSP ksp = new runKSP("NYC", "rand");
// BOS Check
//runKSP ksp = new runKSP("BOS", "check");
// Get routes and scores for origin-destination pairs
ksp.setDataSources();
ksp.getGridValues();
ksp.prepareGraphHopper();
//ksp.process_routes();
// Score external API routes
//ksp.setCity("SF");
//ksp.setRouteType("grid");
ksp.prepMapMatcher();
//ksp.PointsToPath("../data/output/sf_grid_google_gpx.csv", "../data/output/sf_grid_google_ghenhanced_sigma100_transitionDefault.csv");
ksp.PointsToPath("../data/output/sf_grid_mapquest_gpx.csv", "../data/output/sf_grid_mapquest_ghenhanced_sigma100_transitionDefault.csv");
ksp.PointsToPath("../data/output/nyc_grid_mapquest_gpx.csv", "../data/output/nyc_grid_mapquest_ghenhanced_sigma100_transitionDefault.csv");
ksp.PointsToPath("../data/output/nyc_grid_google_gpx.csv", "../data/output/nyc_grid_google_ghenhanced_sigma100_transitionDefault.csv");
}
}
| reader-osm/src/main/java/com/graphhopper/reader/osm/runKSP.java | package com.graphhopper.reader.osm;
import com.graphhopper.GHRequest;
import com.graphhopper.GHResponse;
import com.graphhopper.GraphHopper;
import com.graphhopper.PathWrapper;
import com.graphhopper.matching.MapMatching;
import com.graphhopper.matching.MatchResult;
import com.graphhopper.routing.AlgorithmOptions;
import com.graphhopper.routing.Path;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.HintsMap;
import com.graphhopper.util.*;
import java.util.*;
import java.io.*;
import java.util.List;
/**
* Created by isaac on 09/14/16.
*/
public class runKSP {
String city;
String route_type;
ArrayList<FileWriter> outputFiles;
private String osmFile = "./reader-osm/files/";
private String graphFolder = "./reader-osm/target/tmp/";
private String inputPointsFN = "../data/intermediate/";
private String outputPointsFN = "../data/output/";
private String gvfnStem = "../data/intermediate/";
private ArrayList<String> gridValuesFNs = new ArrayList<>();
private HashMap<String, Integer> gvHeaderMap;
private HashMap<String, Float> gridBeauty;
private GraphHopper hopper;
private MapMatching mapMatching;
private String outputheader = "ID,polyline_points,total_time_in_sec,total_distance_in_meters,number_of_steps,maneuvers,beauty,simplicity" +
System.getProperty("line.separator");
public runKSP(String city, String route_type) {
this.city = city;
this.route_type = route_type;
this.outputFiles = new ArrayList<>(4);
}
public void setCity(String city) {
this.city = city;
}
public void setRouteType(String route_type) {
this.route_type = route_type;
}
public PathWrapper GPXToPath(ArrayList<GPXEntry> gpxEntries) {
PathWrapper matchGHRsp = new PathWrapper();
try {
MatchResult mr = mapMatching.doWork(gpxEntries);
Path path = mapMatching.calcPath(mr);
new PathMerger().doWork(matchGHRsp, Collections.singletonList(path), new TranslationMap().doImport().getWithFallBack(Locale.US));
}
catch (RuntimeException e) {
System.out.println("Broken GPX trace.");
System.out.println(e.getMessage());
}
return matchGHRsp;
}
public void PointsToPath(String fin, String fout) throws IOException {
Scanner sc_in = new Scanner(new File(fin));
String[] pointsHeader = sc_in.nextLine().split(",");
int idIdx = -1;
int latIdx = -1;
int lonIdx = -1;
int timeIdx = -1;
for (int i=0; i<pointsHeader.length; i++) {
if (pointsHeader[i].equalsIgnoreCase("ID")) {
idIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("lat")) {
latIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("lon")) {
lonIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("millis")) {
timeIdx = i;
}
else {
System.out.println("Unexpected header value: " + pointsHeader[i]);
}
}
String line;
String[] vals;
String routeID = "";
String prevRouteID = "";
double lat;
double lon;
long time;
ArrayList<GPXEntry> pointsList = new ArrayList<>();
PathWrapper path;
FileWriter sc_out = new FileWriter(fout, true);
sc_out.write(outputheader);
int i = 0;
float score;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
routeID = vals[idIdx];
lat = Double.valueOf(vals[latIdx]);
lon = Double.valueOf(vals[lonIdx]);
time = Long.valueOf(vals[timeIdx]);
GPXEntry pt = new GPXEntry(lat, lon, time);
if (routeID.equalsIgnoreCase(prevRouteID)) {
pointsList.add(pt);
}
else if (pointsList.size() > 0) {
path = GPXToPath(pointsList);
if (path.getDistance() > 0) {
score = getBeauty(path);
writeOutput(sc_out, i, "Google", routeID, path, score);
}
pointsList.clear();
i++;
}
pointsList.add(pt);
prevRouteID = routeID;
}
if (pointsList.size() > 0) {
path = GPXToPath(pointsList);
if (path.getDistance() > 0) {
score = getBeauty(path);
writeOutput(sc_out, i, "Google", routeID, path, score);
}
}
sc_out.close();
sc_in.close();
}
public void setDataSources() throws Exception {
if (city.equals("SF")) {
osmFile = osmFile + "san-francisco-bay_california.osm.pbf";
graphFolder = graphFolder + "ghosm_sf_noch";
inputPointsFN = inputPointsFN + "sf_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "sf_" + route_type + "_gh_routes.csv";
gridValuesFNs.add(gvfnStem + "06075_logfractionempath_flickr.csv");
} else if (city.equals("NYC")) {
osmFile = osmFile + "new-york_new-york.osm.pbf";
graphFolder = graphFolder + "ghosm_nyc_noch";
inputPointsFN = inputPointsFN + "nyc_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "nyc_" + route_type + "gh_routes.csv";
gridValuesFNs.add(gvfnStem + "36005_beauty_flickr.csv");
gridValuesFNs.add(gvfnStem + "36047_beauty_flickr.csv");
gridValuesFNs.add(gvfnStem + "36061_beauty_flickr.csv");
gridValuesFNs.add(gvfnStem + "36081_beauty_flickr.csv");
gridValuesFNs.add(gvfnStem + "36085_beauty_flickr.csv");
} else if (city.equals("BOS")) {
osmFile = osmFile + "boston_massachusetts.osm.pbf";
graphFolder = graphFolder + "ghosm_bos_noch";
inputPointsFN = inputPointsFN + "bos_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "bos_" + route_type + "gh_routes.csv";
gridValuesFNs.add(gvfnStem + "25025_beauty_twitter.csv");
} else {
throw new Exception("Invalid Parameters: city must be of 'SF','NYC', or 'BOS' and route_type of 'grid' or 'rand'");
}
}
public void getGridValues() throws Exception {
gvHeaderMap = new HashMap<>();
gridBeauty = new HashMap<>();
for (String fn : gridValuesFNs) {
Scanner sc_in = new Scanner(new File(fn));
String[] gvHeader = sc_in.nextLine().split(",");
int i = 0;
for (String col : gvHeader) {
gvHeaderMap.put(col, i);
i++;
}
String line;
String[] vals;
String rc;
float beauty;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
rc = vals[gvHeaderMap.get("rid")] + "," + vals[gvHeaderMap.get("cid")];
beauty = Float.valueOf(vals[gvHeaderMap.get("beauty")]);
gridBeauty.put(rc, beauty);
}
}
}
public void prepareGraphHopper() {
// create one GraphHopper instance
hopper = new GraphHopperOSM().forDesktop().setCHEnabled(false);
hopper.setDataReaderFile(osmFile);
// where to store graphhopper files?
hopper.setGraphHopperLocation(graphFolder);
hopper.setEncodingManager(new EncodingManager("car"));
// now this can take minutes if it imports or a few seconds for loading
// of course this is dependent on the area you import
hopper.importOrLoad();
}
public void prepMapMatcher() {
// create MapMatching object, can and should be shared accross threads
AlgorithmOptions algoOpts = AlgorithmOptions.start().
algorithm(Parameters.Algorithms.DIJKSTRA_BI).
traversalMode(hopper.getTraversalMode()).
hints(new HintsMap().put("weighting", "fastest").put("vehicle", "car")).
build();
mapMatching = new MapMatching(hopper, algoOpts);
mapMatching.setTransitionProbabilityBeta(0.00959442);
mapMatching.setMeasurementErrorSigma(40);
}
public void writeOutput(FileWriter fw, int i, String optimized, String od_id, PathWrapper bestPath, float score) throws IOException {
// points, distance in meters and time in seconds (convert from ms) of the full path
PointList pointList = bestPath.getPoints();
int simplicity = bestPath.getSimplicity();
double distance = Math.round(bestPath.getDistance() * 100) / 100;
long timeInSec = bestPath.getTime() / 1000;
InstructionList il = bestPath.getInstructions();
int numDirections = il.getSize();
// iterate over every turn instruction
ArrayList<String> maneuvers = new ArrayList<>();
for (Instruction instruction : il) {
maneuvers.add(instruction.getSimpleTurnDescription());
}
fw.write(od_id + "," + "\"[" + pointList + "]\"," + timeInSec + "," + distance + "," + numDirections +
",\"" + maneuvers.toString() + "\"" + "," + score + "," + simplicity + System.getProperty("line.separator"));
System.out.println(i + " (" + optimized + "): Distance: " + distance + "m;\tTime: " + timeInSec + "sec;\t# Directions: " + numDirections + ";\tSimplicity: " + simplicity + ";\tScore: " + score);
}
public float getBeauty(PathWrapper path) {
HashSet<String> roundedPoints = path.roundPoints();
float score = 0;
for (String pt : roundedPoints) {
if (gridBeauty.containsKey(pt)) {
score = score + gridBeauty.get(pt);
}
}
score = score / roundedPoints.size();
return score;
}
public void augment_routes() throws Exception {
}
public void process_routes() throws Exception {
ArrayList<float[]> inputPoints = new ArrayList<float[]>();
ArrayList<String> id_to_points = new ArrayList<String>();
// Prep Filewriters (Optimized, Worst-but-same-distance, Fastest, Simplest)
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_beauty.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_ugly.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_fast.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_simple.csv"), true));
for (FileWriter fw : outputFiles) {
fw.write(outputheader);
}
// Bring in origin-destination pairs for processing
Scanner sc_in = new Scanner(new File(inputPointsFN));
String header = sc_in.nextLine();
String od_id;
float laF;
float loF;
float laT;
float loT;
float idx = 0;
System.out.println("Input data points header: " + header);
while (sc_in.hasNext()) {
idx = idx + 1;
String line = sc_in.nextLine();
String[] vals = line.split(",");
od_id = vals[0];
loF = Float.valueOf(vals[1]);
laF = Float.valueOf(vals[2]);
loT = Float.valueOf(vals[3]);
laT = Float.valueOf(vals[4]);
inputPoints.add(new float[]{laF, loF, laT, loT, idx});
id_to_points.add(od_id);
}
int numPairs = inputPoints.size();
System.out.println(numPairs + " origin-destination pairs.");
// Loop through origin-destination pairs, processing each one for beauty, non-beautiful matched, fastest, and simplest
float[] points;
int routes_skipped = 0;
for (int i=0; i<numPairs; i++) {
// Get Routes
points = inputPoints.get(i);
od_id = id_to_points.get(i);
GHRequest req = new GHRequest(points[0], points[1], points[2], points[3]). // latFrom, lonFrom, latTo, lonTo
setWeighting("fastest").
setVehicle("car").
setLocale(Locale.US).
setAlgorithm("ksp");
GHResponse rsp = hopper.route(req);
System.out.println("Num Responses: " + rsp.getAll().size());
// first check for errors
if (rsp.hasErrors()) {
// handle them!
System.out.println(rsp.getErrors().toString());
System.out.println(i + ": Skipping.");
String outputRow = od_id + "," + "\"[(" + points[0] + "," + points[1] + "),(" + points[2] + "," + points[3]
+ ")]\"," + "-1,-1,-1,[]" + System.getProperty("line.separator");
for (FileWriter fw: outputFiles) {
fw.write(outputRow);
}
routes_skipped++;
continue;
}
// Get All Routes (up to 10K right now)
List<PathWrapper> paths = rsp.getAll();
// Score each route on beauty to determine most beautiful
int j = 0;
float bestscore = -1000;
int routeidx = -1;
for (PathWrapper path : paths) {
float score = getBeauty(path);
if (score > bestscore) {
bestscore = score;
routeidx = j;
}
j++;
}
writeOutput(outputFiles.get(0), i, "Best", od_id, paths.get(routeidx), bestscore);
// Find least-beautiful route within similar distance constraints
double beautyDistance = paths.get(routeidx).getDistance();
j = 0;
bestscore = 1000;
routeidx = -1;
double uglydistance;
for (PathWrapper path : paths) {
uglydistance = path.getDistance();
if (uglydistance / beautyDistance < 1.05 && uglydistance / beautyDistance > 0.95) {
float score = getBeauty(path);
if (score < bestscore) {
bestscore = score;
routeidx = j;
}
}
j++;
}
writeOutput(outputFiles.get(1), i, "Wrst", od_id, paths.get(routeidx), bestscore);
// Simplest Route
j = 0;
bestscore = 10000;
routeidx = 0;
float beauty = -1;
for (PathWrapper path : paths) {
int score = path.getSimplicity();
if (score < bestscore) {
bestscore = score;
routeidx = j;
beauty = getBeauty(path);
}
j++;
}
writeOutput(outputFiles.get(2), i, "Simp", od_id, paths.get(routeidx), beauty);
// Fastest Route
PathWrapper bestPath = paths.get(0);
beauty = getBeauty(bestPath);
writeOutput(outputFiles.get(3), i, "Fast", od_id, bestPath, beauty);
}
// Finished analysis: close filewriters and indicate how many paths skipped
System.out.println(routes_skipped + " routes skipped out of " + numPairs);
for (FileWriter fw : outputFiles) {
fw.close();
}
}
public static void main(String[] args) throws Exception {
// PBF from: https://mapzen.com/data/metro-extracts/
// SF Grid
runKSP ksp = new runKSP("SF", "grid");
// SF Random
//runKSP ksp = new runKSP("SF", "rand");
// NYC Grid
//runKSP ksp = new runKSP("NYC", "grid");
// NYC Random
//runKSP ksp = new runKSP("NYC", "rand");
// BOS Check
//runKSP ksp = new runKSP("BOS", "check");
// Get routes and scores for origin-destination pairs
ksp.setDataSources();
ksp.getGridValues();
ksp.prepareGraphHopper();
//ksp.process_routes();
// Score external API routes
//ksp.setCity("SF");
//ksp.setRouteType("grid");
ksp.prepMapMatcher();
ksp.PointsToPath("../data/output/sf_grid_google_gpx.csv", "../data/output/sf_grid_google_ghenhanced.csv");
}
}
| map-matcher defaults (works for like 85% of routes it seems)
| reader-osm/src/main/java/com/graphhopper/reader/osm/runKSP.java | map-matcher defaults (works for like 85% of routes it seems) |
|
Java | bsd-2-clause | 2b4fabc148b3512ca159cc88f87183252ab7a594 | 0 | scifio/scifio | //
// BDReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
Copyright (C) 2009-@year@ Vanderbilt Integrative Cancer Center.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.IniList;
import loci.common.IniParser;
import loci.common.IniTable;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveInteger;
/**
* BDReader is the file format reader for BD Pathway datasets.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/BDReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/BDReader.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Shawn Garbett Shawn.Garbett a t Vanderbilt.edu
*/
public class BDReader extends FormatReader {
// -- Constants --
private static final String EXPERIMENT_FILE = "Experiment.exp";
private static final String[] META_EXT = {"drt", "dye", "exp", "plt", "txt"};
// -- Fields --
private Vector<String> metadataFiles = new Vector<String>();
private Vector<String> channelNames = new Vector<String>();
private Vector<String> wellLabels = new Vector<String>();
private String plateName, plateDescription;
private String[][] tiffs;
private MinimalTiffReader reader;
private String roiFile;
private int[] emWave, exWave;
private double[] gain, offset, exposure;
private String binning, objective;
private int wellRows, wellCols;
private int fieldRows;
private int fieldCols;
// -- Constructor --
/** Constructs a new ScanR reader. */
public BDReader() {
super("BD Pathway", new String[] {"exp", "tif"});
domains = new String[] {FormatTools.HCS_DOMAIN};
suffixSufficient = false;
suffixNecessary = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (name.endsWith(EXPERIMENT_FILE)) return true;
if (!open) return false;
String id = new Location(name).getAbsolutePath();
try {
id = locateExperimentFile(id);
}
catch (FormatException f) {
return false;
}
catch (IOException f) {
return false;
}
if (id.endsWith(EXPERIMENT_FILE)) { return true; }
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser p = new TiffParser(stream);
IFD ifd = p.getFirstIFD();
if (ifd == null) return false;
String software = ifd.getIFDTextValue(IFD.SOFTWARE);
if (software == null) return false;
return software.trim().startsWith("MATROX Imaging Library");
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
for (String file : metadataFiles) {
if (file != null) files.add(file);
}
if (!noPixels && tiffs != null) {
int well = getSeries() / (fieldRows * fieldCols);
for (int i = 0; i<tiffs[well].length; i++) {
files.add(tiffs[well][i]);
}
}
return files.toArray(new String[files.size()]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
if (reader != null) reader.close();
reader = null;
tiffs = null;
plateName = null;
plateDescription = null;
channelNames.clear();
metadataFiles.clear();
wellLabels.clear();
wellRows = 0;
wellCols = 0;
fieldRows = 0;
fieldCols = 0;
}
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return false;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
String file = getFilename(getSeries(), no);
int field = getSeries() % (fieldRows * fieldCols);
int fieldRow = field / fieldCols;
int fieldCol = field % fieldCols;
if (file != null) {
reader.setId(file);
if (fieldRows * fieldCols == 1) {
reader.openBytes(0, buf, x, y, w, h);
}
else {
// fields are stored together in a single image,
// so we need to split them up
int fx = x + (fieldCol * getSizeX());
int fy = y + (fieldRow * getSizeY());
reader.openBytes(0, buf, fx, fy, w, h);
}
}
return buf;
}
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
public int getOptimalTileWidth() {
FormatTools.assertId(currentId, true, 1);
return reader.getOptimalTileWidth();
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
return reader.getOptimalTileHeight();
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
// make sure we have the experiment file
id = locateExperimentFile(id);
super.initFile(id);
Location dir = new Location(id).getAbsoluteFile().getParentFile();
for (String file : dir.list(true)) {
Location f = new Location(dir, file);
if (!f.isDirectory()) {
if (checkSuffix(file, META_EXT)) {
metadataFiles.add(f.getAbsolutePath());
}
}
}
// parse Experiment metadata
IniList experiment = readMetaData(id);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
objective = experiment.getTable("Geometry").get("Name");
IniTable camera = experiment.getTable("Camera");
binning = camera.get("BinX") + "x" + camera.get("BinY");
parseChannelData(dir);
addGlobalMeta("Objective", objective);
addGlobalMeta("Camera binning", binning);
}
Vector<String> uniqueRows = new Vector<String>();
Vector<String> uniqueColumns = new Vector<String>();
for (String well : wellLabels) {
String row = well.substring(0, 1).trim();
String column = well.substring(1).trim();
if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
int nTimepoints = getSizeT();
int nWells = wellLabels.size();
int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC();
if (nChannels == 0) nChannels = 1;
tiffs = getTiffs(dir.getAbsolutePath());
reader = new MinimalTiffReader();
reader.setId(tiffs[0][0]);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int pixelType = reader.getPixelType();
boolean rgb = reader.isRGB();
boolean interleaved = reader.isInterleaved();
boolean indexed = reader.isIndexed();
boolean littleEndian = reader.isLittleEndian();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
IniParser parser = new IniParser();
for (String metadataFile : metadataFiles) {
String filename = new Location(metadataFile).getName();
if (!checkSuffix(metadataFile, "txt")) {
String data = DataTools.readFile(metadataFile);
IniList ini =
parser.parseINI(new BufferedReader(new StringReader(data)));
HashMap<String, String> h = ini.flattenIntoHashMap();
for (String key : h.keySet()) {
addGlobalMeta(filename + " " + key, h.get(key));
}
}
}
}
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].sizeC = nChannels;
core[i].sizeZ = nSlices;
core[i].sizeT = nTimepoints;
core[i].sizeX = sizeX / fieldCols;
core[i].sizeY = sizeY / fieldRows;
core[i].pixelType = pixelType;
core[i].rgb = rgb;
core[i].interleaved = interleaved;
core[i].indexed = indexed;
core[i].littleEndian = littleEndian;
core[i].dimensionOrder = "XYZTC";
core[i].imageCount = nSlices * nTimepoints * nChannels;
}
MetadataStore store = makeFilterMetadata();
boolean populatePlanes =
getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM;
MetadataTools.populatePixels(store, this, populatePlanes);
String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
store.setPlateAcquisitionID(plateAcqID, 0, 0);
store.setPlateAcquisitionMaximumFieldCount(
new PositiveInteger(fieldRows * fieldCols), 0, 0);
for (int row=0; row<wellRows; row++) {
for (int col=0; col<wellCols; col++) {
int index = row * wellCols + col;
store.setWellID(MetadataTools.createLSID("Well", 0, index), 0, index);
store.setWellRow(new NonNegativeInteger(row), 0, index);
store.setWellColumn(new NonNegativeInteger(col), 0, index);
}
}
for (int i=0; i<getSeriesCount(); i++) {
int well = i / (fieldRows * fieldCols);
int field = i % (fieldRows * fieldCols);
MetadataTools.setDefaultCreationDate(store, tiffs[well][0], i);
String name = wellLabels.get(well);
String row = name.substring(0, 1);
Integer col = Integer.parseInt(name.substring(1));
int index = (row.charAt(0) - 'A') * wellCols + col - 1;
String wellSampleID =
MetadataTools.createLSID("WellSample", 0, index, field);
store.setWellSampleID(wellSampleID, 0, index, field);
store.setWellSampleIndex(new NonNegativeInteger(i), 0, index, field);
String imageID = MetadataTools.createLSID("Image", i);
store.setWellSampleImageRef(imageID, 0, index, field);
store.setImageID(imageID, i);
store.setImageName(name + " Field #" + (field + 1), i);
store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, i);
}
MetadataLevel level = getMetadataOptions().getMetadataLevel();
if (level != MetadataLevel.MINIMUM) {
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
if (objective != null) {
String[] tokens = objective.split(" ");
String mag = tokens[0].replaceAll("[xX]", "");
String na = null;
int naIndex = 0;
for (int i=0; i<tokens.length; i++) {
if (tokens[i].equals("NA")) {
naIndex = i + 1;
na = tokens[naIndex];
break;
}
}
store.setObjectiveNominalMagnification(
PositiveInteger.valueOf(mag), 0, 0);
if (na != null) {
na = na.substring(0, 1) + "." + na.substring(1);
store.setObjectiveLensNA(new Double(na), 0, 0);
}
if (naIndex + 1 < tokens.length) {
store.setObjectiveManufacturer(tokens[naIndex + 1], 0, 0);
}
}
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
store.setImageInstrumentRef(instrumentID, i);
store.setImageObjectiveSettingsID(objectiveID, i);
for (int c=0; c<getSizeC(); c++) {
store.setChannelName(channelNames.get(c), i, c);
store.setChannelEmissionWavelength(
new PositiveInteger(emWave[c]), i, c);
store.setChannelExcitationWavelength(
new PositiveInteger(exWave[c]), i, c);
String detectorID = MetadataTools.createLSID("Detector", 0, c);
store.setDetectorID(detectorID, 0, c);
store.setDetectorSettingsID(detectorID, i, c);
store.setDetectorSettingsGain(gain[c], i, c);
store.setDetectorSettingsOffset(offset[c], i, c);
store.setDetectorSettingsBinning(getBinning(binning), i, c);
}
long firstPlane = 0;
for (int p=0; p<getImageCount(); p++) {
int[] zct = getZCTCoords(p);
store.setPlaneExposureTime(exposure[zct[1]], i, p);
String file = getFilename(i, p);
if (file != null) {
long plane = new Location(file).lastModified();
if (p == 0) {
firstPlane = plane;
}
double timestamp = (plane - firstPlane) / 1000.0;
store.setPlaneDeltaT(timestamp, i, p);
}
}
}
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
store.setPlateRowNamingConvention(getNamingConvention("Letter"), 0);
store.setPlateColumnNamingConvention(getNamingConvention("Number"), 0);
store.setPlateName(plateName, 0);
store.setPlateDescription(plateDescription, 0);
if (level != MetadataLevel.NO_OVERLAYS) {
parseROIs(store);
}
}
}
// -- Helper methods --
/* Locate the experiment file given any file in set */
private String locateExperimentFile(String id)
throws FormatException, IOException
{
if (!checkSuffix(id, "exp")) {
Location parent = new Location(id).getAbsoluteFile().getParentFile();
if (checkSuffix(id, "tif")) parent = parent.getParentFile();
for (String file : parent.list()) {
if (file.equals(EXPERIMENT_FILE)) {
return new Location(parent, file).getAbsolutePath();
}
}
throw new FormatException("Could not find " + EXPERIMENT_FILE +
" in " + parent.getAbsolutePath());
}
return id;
}
private IniList readMetaData(String id) throws IOException {
IniParser parser = new IniParser();
IniList exp = parser.parseINI(new BufferedReader(new FileReader(id)));
IniList plate = null;
// Read Plate File
for (String filename : metadataFiles) {
if (checkSuffix(filename, "plt")) {
plate = parser.parseINI(new BufferedReader(new FileReader(filename)));
}
else if (filename.endsWith("RoiSummary.txt")) {
roiFile = filename;
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
RandomAccessInputStream s = new RandomAccessInputStream(filename);
String line = s.readLine().trim();
while (!line.endsWith(".adf\"")) {
line = s.readLine().trim();
}
plateName = line.substring(line.indexOf(":")).trim();
plateName = plateName.replace('/', File.separatorChar);
plateName = plateName.replace('\\', File.separatorChar);
for (int i=0; i<3; i++) {
plateName =
plateName.substring(0, plateName.lastIndexOf(File.separator));
}
plateName =
plateName.substring(plateName.lastIndexOf(File.separator) + 1);
s.close();
}
}
}
if (plate == null) throw new IOException("No Plate File");
IniTable plateType = plate.getTable("PlateType");
if (plateName == null) {
plateName = plateType.get("Brand");
}
plateDescription =
plateType.get("Brand") + " " + plateType.get("Description");
int nWells = Integer.parseInt(plateType.get("Wells"));
if (nWells == 96) {
wellRows = 8;
wellCols = 12;
}
else if (nWells == 384) {
wellRows = 16;
wellCols = 24;
}
Location dir = new Location(id).getAbsoluteFile().getParentFile();
String[] wellList = dir.list();
Arrays.sort(wellList);
for (String filename : wellList) {
if (filename.startsWith("Well ")) {
wellLabels.add(filename.split("\\s|\\.")[1]);
}
}
IniTable imageTable = exp.getTable("Image");
boolean montage = imageTable.get("Montaged").equals("1");
if (montage) {
fieldRows = Integer.parseInt(imageTable.get("TilesY"));
fieldCols = Integer.parseInt(imageTable.get("TilesX"));
}
else {
fieldRows = 1;
fieldCols = 1;
}
core = new CoreMetadata[wellLabels.size() * fieldRows * fieldCols];
core[0] = new CoreMetadata();
// Hack for current testing/development purposes
// Not all channels have the same Z!!! How to handle???
// FIXME FIXME FIXME
core[0].sizeZ=1;
// FIXME FIXME FIXME
// END OF HACK
core[0].sizeC = Integer.parseInt(exp.getTable("General").get("Dyes"));
core[0].bitsPerPixel =
Integer.parseInt(exp.getTable("Camera").get("BitdepthUsed"));
IniTable dyeTable = exp.getTable("Dyes");
for (int i=1; i<=getSizeC(); i++) {
channelNames.add(dyeTable.get(Integer.toString(i)));
}
// Count Images
core[0].sizeT = 0;
Location well = new Location(dir.getAbsolutePath(),
"Well " + wellLabels.get(1));
for (String channelName : channelNames) {
int timepoints = 0;
for (String filename : well.list()) {
if (filename.startsWith(channelName) && filename.endsWith(".tif")) {
timepoints++;
}
}
if (timepoints > getSizeT()) {
core[0].sizeT = timepoints;
}
}
return exp;
}
private void parseChannelData(Location dir) throws IOException {
emWave = new int[channelNames.size()];
exWave = new int[channelNames.size()];
exposure = new double[channelNames.size()];
gain = new double[channelNames.size()];
offset = new double[channelNames.size()];
for (int c=0; c<channelNames.size(); c++) {
Location dyeFile = new Location(dir, channelNames.get(c) + ".dye");
IniList dye = new IniParser().parseINI(
new BufferedReader(new FileReader(dyeFile.getAbsolutePath())));
IniTable numerator = dye.getTable("Numerator");
String em = numerator.get("Emission");
em = em.substring(0, em.indexOf(" "));
emWave[c] = Integer.parseInt(em);
String ex = numerator.get("Excitation");
ex = ex.substring(0, ex.lastIndexOf(" "));
if (ex.indexOf(" ") != -1) {
ex = ex.substring(ex.lastIndexOf(" ") + 1);
}
exWave[c] = Integer.parseInt(ex);
exposure[c] = Double.parseDouble(numerator.get("Exposure"));
gain[c] = Double.parseDouble(numerator.get("Gain"));
offset[c] = Double.parseDouble(numerator.get("Offset"));
}
}
private String[][] getTiffs(String dir) {
Location f = new Location(dir);
Vector<Vector<String>> files = new Vector<Vector<String>>();
String[] wells = f.list(true);
Arrays.sort(wells);
for (String filename : wells) {
Location file = new Location(f, filename).getAbsoluteFile();
if (file.isDirectory() && filename.startsWith("Well ")) {
String[] list = file.list(true);
Vector<String> tiffList = new Vector<String>();
Arrays.sort(list);
for (String tiff : list) {
if (tiff.matches(".* - n\\d\\d\\d\\d\\d\\d\\.tif")) {
tiffList.add(new Location(file, tiff).getAbsolutePath());
}
}
files.add(tiffList);
}
}
String[][] tiffFiles = new String[files.size()][];
for (int i=0; i<tiffFiles.length; i++) {
tiffFiles[i] = files.get(i).toArray(new String[0]);
}
return tiffFiles;
}
private void parseROIs(MetadataStore store) throws IOException {
if (roiFile == null) return;
String roiData = DataTools.readFile(roiFile);
String[] lines = roiData.split("\r\n");
int firstRow = 0;
while (firstRow < lines.length && !lines[firstRow].startsWith("ROI")) {
firstRow++;
}
firstRow += 2;
if (firstRow >= lines.length) return;
for (int i=firstRow; i<lines.length; i++) {
String[] cols = lines[i].split("\t");
if (cols.length < 6) break;
if (cols[2].trim().length() > 0) {
String rectangleID = MetadataTools.createLSID("Shape", i - firstRow, 0);
store.setRectangleID(rectangleID, i - firstRow, 0);
store.setRectangleX(new Double(cols[2]), i - firstRow, 0);
store.setRectangleY(new Double(cols[3]), i - firstRow, 0);
store.setRectangleWidth(new Double(cols[4]), i - firstRow, 0);
store.setRectangleHeight(new Double(cols[5]), i - firstRow, 0);
String roiID = MetadataTools.createLSID("ROI", i - firstRow);
store.setROIID(roiID, i - firstRow);
store.setImageROIRef(roiID, 0, i - firstRow);
}
}
}
private String getFilename(int series, int no) {
int[] zct = getZCTCoords(no);
String channel = channelNames.get(zct[1]);
int well = series / (fieldRows * fieldCols);
for (int i=0; i<tiffs[well].length; i++) {
String name = tiffs[well][i];
name = name.substring(name.lastIndexOf(File.separator) + 1);
name = name.substring(0, name.lastIndexOf("."));
String index = name.substring(name.lastIndexOf("n") + 1);
if (name.startsWith(channel) && Integer.parseInt(index) == zct[2]) {
return tiffs[well][i];
}
}
return null;
}
}
| components/bio-formats/src/loci/formats/in/BDReader.java | //
// BDReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
Copyright (C) 2009-@year@ Vanderbilt Integrative Cancer Center.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.IniList;
import loci.common.IniParser;
import loci.common.IniTable;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveInteger;
/**
* BDReader is the file format reader for BD Pathway datasets.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/BDReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/BDReader.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Shawn Garbett Shawn.Garbett a t Vanderbilt.edu
*/
public class BDReader extends FormatReader {
// -- Constants --
private static final String EXPERIMENT_FILE = "Experiment.exp";
private static final String[] META_EXT = {"drt", "dye", "exp", "plt", "txt"};
// -- Fields --
private Vector<String> metadataFiles = new Vector<String>();
private Vector<String> channelNames = new Vector<String>();
private Vector<String> wellLabels = new Vector<String>();
private String plateName, plateDescription;
private String[][] tiffs;
private MinimalTiffReader reader;
private String roiFile;
private int[] emWave, exWave;
private double[] gain, offset, exposure;
private String binning, objective;
private int wellRows, wellCols;
private int fieldRows;
private int fieldCols;
// -- Constructor --
/** Constructs a new ScanR reader. */
public BDReader() {
super("BD Pathway", new String[] {"exp", "tif"});
domains = new String[] {FormatTools.HCS_DOMAIN};
suffixSufficient = false;
suffixNecessary = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (name.endsWith(EXPERIMENT_FILE)) return true;
if (!open) return false;
String id = new Location(name).getAbsolutePath();
try {
id = locateExperimentFile(id);
}
catch (FormatException f) {
return false;
}
catch (IOException f) {
return false;
}
if (id.endsWith(EXPERIMENT_FILE)) { return true; }
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser p = new TiffParser(stream);
IFD ifd = p.getFirstIFD();
if (ifd == null) return false;
String software = ifd.getIFDTextValue(IFD.SOFTWARE);
if (software == null) return false;
return software.trim().startsWith("MATROX Imaging Library");
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
for (String file : metadataFiles) {
if (file != null) files.add(file);
}
if (!noPixels && tiffs != null) {
int well = getSeries() / (fieldRows * fieldCols);
for (int i = 0; i<tiffs[well].length; i++) {
files.add(tiffs[well][i]);
}
}
return files.toArray(new String[files.size()]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
if (reader != null) reader.close();
reader = null;
tiffs = null;
plateName = null;
plateDescription = null;
channelNames.clear();
metadataFiles.clear();
wellLabels.clear();
wellRows = 0;
wellCols = 0;
fieldRows = 0;
fieldCols = 0;
}
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return false;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
String file = getFilename(getSeries(), no);
int field = getSeries() % (fieldRows * fieldCols);
int fieldRow = field / fieldCols;
int fieldCol = field % fieldCols;
if (file != null) {
reader.setId(file);
if (fieldRows * fieldCols == 1) {
reader.openBytes(0, buf, x, y, w, h);
}
else {
// fields are stored together in a single image,
// so we need to split them up
int fx = x + (fieldCol * getSizeX());
int fy = y + (fieldRow * getSizeY());
reader.openBytes(0, buf, fx, fy, w, h);
}
}
return buf;
}
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
public int getOptimalTileWidth() {
FormatTools.assertId(currentId, true, 1);
return reader.getOptimalTileWidth();
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
return reader.getOptimalTileHeight();
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
// make sure we have the experiment file
id = locateExperimentFile(id);
super.initFile(id);
Location dir = new Location(id).getAbsoluteFile().getParentFile();
for (String file : dir.list(true)) {
Location f = new Location(dir, file);
if (!f.isDirectory()) {
if (checkSuffix(file, META_EXT)) {
metadataFiles.add(f.getAbsolutePath());
}
}
}
// parse Experiment metadata
IniList experiment = readMetaData(id);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
objective = experiment.getTable("Geometry").get("Name");
IniTable camera = experiment.getTable("Camera");
binning = camera.get("BinX") + "x" + camera.get("BinY");
parseChannelData(dir);
addGlobalMeta("Objective", objective);
addGlobalMeta("Camera binning", binning);
}
Vector<String> uniqueRows = new Vector<String>();
Vector<String> uniqueColumns = new Vector<String>();
for (String well : wellLabels) {
String row = well.substring(0, 1).trim();
String column = well.substring(1).trim();
if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
int nTimepoints = getSizeT();
int nWells = wellLabels.size();
int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC();
if (nChannels == 0) nChannels = 1;
tiffs = getTiffs(dir.getAbsolutePath());
reader = new MinimalTiffReader();
reader.setId(tiffs[0][0]);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int pixelType = reader.getPixelType();
boolean rgb = reader.isRGB();
boolean interleaved = reader.isInterleaved();
boolean indexed = reader.isIndexed();
boolean littleEndian = reader.isLittleEndian();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
IniParser parser = new IniParser();
for (String metadataFile : metadataFiles) {
String filename = new Location(metadataFile).getName();
if (!checkSuffix(metadataFile, "txt")) {
String data = DataTools.readFile(metadataFile);
IniList ini =
parser.parseINI(new BufferedReader(new StringReader(data)));
HashMap<String, String> h = ini.flattenIntoHashMap();
for (String key : h.keySet()) {
addGlobalMeta(filename + " " + key, h.get(key));
}
}
}
}
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].sizeC = nChannels;
core[i].sizeZ = nSlices;
core[i].sizeT = nTimepoints;
core[i].sizeX = sizeX / fieldCols;
core[i].sizeY = sizeY / fieldRows;
core[i].pixelType = pixelType;
core[i].rgb = rgb;
core[i].interleaved = interleaved;
core[i].indexed = indexed;
core[i].littleEndian = littleEndian;
core[i].dimensionOrder = "XYZTC";
core[i].imageCount = nSlices * nTimepoints * nChannels;
}
MetadataStore store = makeFilterMetadata();
boolean populatePlanes =
getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM;
MetadataTools.populatePixels(store, this, populatePlanes);
String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
store.setPlateAcquisitionID(plateAcqID, 0, 0);
store.setPlateAcquisitionMaximumFieldCount(
new PositiveInteger(fieldRows * fieldCols), 0, 0);
for (int row=0; row<wellRows; row++) {
for (int col=0; col<wellCols; col++) {
int index = row * wellCols + col;
store.setWellID(MetadataTools.createLSID("Well", 0, index), 0, index);
store.setWellRow(new NonNegativeInteger(row), 0, index);
store.setWellColumn(new NonNegativeInteger(col), 0, index);
}
}
for (int i=0; i<getSeriesCount(); i++) {
int well = i / (fieldRows * fieldCols);
int field = i % (fieldRows * fieldCols);
MetadataTools.setDefaultCreationDate(store, tiffs[well][0], i);
String name = wellLabels.get(well);
String row = name.substring(0, 1);
Integer col = Integer.parseInt(name.substring(1));
int index = (row.charAt(0) - 'A') * wellCols + col - 1;
String wellSampleID =
MetadataTools.createLSID("WellSample", 0, index, field);
store.setWellSampleID(wellSampleID, 0, index, field);
store.setWellSampleIndex(new NonNegativeInteger(i), 0, index, field);
String imageID = MetadataTools.createLSID("Image", i);
store.setWellSampleImageRef(imageID, 0, index, field);
store.setImageID(imageID, i);
store.setImageName(name + " Field #" + (field + 1), i);
store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, i);
}
MetadataLevel level = getMetadataOptions().getMetadataLevel();
if (level != MetadataLevel.MINIMUM) {
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
if (objective != null) {
String[] tokens = objective.split(" ");
String mag = tokens[0].replaceAll("[xX]", "");
String na = null;
int naIndex = 0;
for (int i=0; i<tokens.length; i++) {
if (tokens[i].equals("NA")) {
naIndex = i + 1;
na = tokens[naIndex];
break;
}
}
store.setObjectiveNominalMagnification(
PositiveInteger.valueOf(mag), 0, 0);
if (na != null) {
na = na.substring(0, 1) + "." + na.substring(1);
store.setObjectiveLensNA(new Double(na), 0, 0);
}
if (naIndex + 1 < tokens.length) {
store.setObjectiveManufacturer(tokens[naIndex + 1], 0, 0);
}
}
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
store.setImageInstrumentRef(instrumentID, i);
store.setImageObjectiveSettingsID(objectiveID, i);
for (int c=0; c<getSizeC(); c++) {
store.setChannelName(channelNames.get(c), i, c);
store.setChannelEmissionWavelength(
new PositiveInteger(emWave[c]), i, c);
store.setChannelExcitationWavelength(
new PositiveInteger(exWave[c]), i, c);
String detectorID = MetadataTools.createLSID("Detector", 0, c);
store.setDetectorID(detectorID, 0, c);
store.setDetectorSettingsID(detectorID, i, c);
store.setDetectorSettingsGain(gain[c], i, c);
store.setDetectorSettingsOffset(offset[c], i, c);
store.setDetectorSettingsBinning(getBinning(binning), i, c);
}
long firstPlane = 0;
for (int p=0; p<getImageCount(); p++) {
int[] zct = getZCTCoords(p);
store.setPlaneExposureTime(exposure[zct[1]], i, p);
long plane = new Location(getFilename(i, p)).lastModified();
if (p == 0) {
firstPlane = plane;
}
double timestamp = (plane - firstPlane) / 1000.0;
store.setPlaneDeltaT(timestamp, i, p);
}
}
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
store.setPlateRowNamingConvention(getNamingConvention("Letter"), 0);
store.setPlateColumnNamingConvention(getNamingConvention("Number"), 0);
store.setPlateName(plateName, 0);
store.setPlateDescription(plateDescription, 0);
if (level != MetadataLevel.NO_OVERLAYS) {
parseROIs(store);
}
}
}
// -- Helper methods --
/* Locate the experiment file given any file in set */
private String locateExperimentFile(String id)
throws FormatException, IOException
{
if (!checkSuffix(id, "exp")) {
Location parent = new Location(id).getAbsoluteFile().getParentFile();
if (checkSuffix(id, "tif")) parent = parent.getParentFile();
for (String file : parent.list()) {
if (file.equals(EXPERIMENT_FILE)) {
return new Location(parent, file).getAbsolutePath();
}
}
throw new FormatException("Could not find " + EXPERIMENT_FILE +
" in " + parent.getAbsolutePath());
}
return id;
}
private IniList readMetaData(String id) throws IOException {
IniParser parser = new IniParser();
IniList exp = parser.parseINI(new BufferedReader(new FileReader(id)));
IniList plate = null;
// Read Plate File
for (String filename : metadataFiles) {
if (checkSuffix(filename, "plt")) {
plate = parser.parseINI(new BufferedReader(new FileReader(filename)));
}
else if (filename.endsWith("RoiSummary.txt")) {
roiFile = filename;
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
RandomAccessInputStream s = new RandomAccessInputStream(filename);
String line = s.readLine().trim();
while (!line.endsWith(".adf\"")) {
line = s.readLine().trim();
}
plateName = line.substring(line.indexOf(":")).trim();
plateName = plateName.replace('/', File.separatorChar);
plateName = plateName.replace('\\', File.separatorChar);
for (int i=0; i<3; i++) {
plateName =
plateName.substring(0, plateName.lastIndexOf(File.separator));
}
plateName =
plateName.substring(plateName.lastIndexOf(File.separator) + 1);
s.close();
}
}
}
if (plate == null) throw new IOException("No Plate File");
IniTable plateType = plate.getTable("PlateType");
if (plateName == null) {
plateName = plateType.get("Brand");
}
plateDescription =
plateType.get("Brand") + " " + plateType.get("Description");
int nWells = Integer.parseInt(plateType.get("Wells"));
if (nWells == 96) {
wellRows = 8;
wellCols = 12;
}
else if (nWells == 384) {
wellRows = 16;
wellCols = 24;
}
Location dir = new Location(id).getAbsoluteFile().getParentFile();
String[] wellList = dir.list();
Arrays.sort(wellList);
for (String filename : wellList) {
if (filename.startsWith("Well ")) {
wellLabels.add(filename.split("\\s|\\.")[1]);
}
}
IniTable imageTable = exp.getTable("Image");
boolean montage = imageTable.get("Montaged").equals("1");
if (montage) {
fieldRows = Integer.parseInt(imageTable.get("TilesY"));
fieldCols = Integer.parseInt(imageTable.get("TilesX"));
}
else {
fieldRows = 1;
fieldCols = 1;
}
core = new CoreMetadata[wellLabels.size() * fieldRows * fieldCols];
core[0] = new CoreMetadata();
// Hack for current testing/development purposes
// Not all channels have the same Z!!! How to handle???
// FIXME FIXME FIXME
core[0].sizeZ=1;
// FIXME FIXME FIXME
// END OF HACK
core[0].sizeC = Integer.parseInt(exp.getTable("General").get("Dyes"));
core[0].bitsPerPixel =
Integer.parseInt(exp.getTable("Camera").get("BitdepthUsed"));
IniTable dyeTable = exp.getTable("Dyes");
for (int i=1; i<=getSizeC(); i++) {
channelNames.add(dyeTable.get(Integer.toString(i)));
}
// Count Images
core[0].sizeT = 0;
Location well = new Location(dir.getAbsolutePath(),
"Well " + wellLabels.get(1));
for (String channelName : channelNames) {
int timepoints = 0;
for (String filename : well.list()) {
if (filename.startsWith(channelName) && filename.endsWith(".tif")) {
timepoints++;
}
}
if (timepoints > getSizeT()) {
core[0].sizeT = timepoints;
}
}
return exp;
}
private void parseChannelData(Location dir) throws IOException {
emWave = new int[channelNames.size()];
exWave = new int[channelNames.size()];
exposure = new double[channelNames.size()];
gain = new double[channelNames.size()];
offset = new double[channelNames.size()];
for (int c=0; c<channelNames.size(); c++) {
Location dyeFile = new Location(dir, channelNames.get(c) + ".dye");
IniList dye = new IniParser().parseINI(
new BufferedReader(new FileReader(dyeFile.getAbsolutePath())));
IniTable numerator = dye.getTable("Numerator");
String em = numerator.get("Emission");
em = em.substring(0, em.indexOf(" "));
emWave[c] = Integer.parseInt(em);
String ex = numerator.get("Excitation");
ex = ex.substring(0, ex.lastIndexOf(" "));
if (ex.indexOf(" ") != -1) {
ex = ex.substring(ex.lastIndexOf(" ") + 1);
}
exWave[c] = Integer.parseInt(ex);
exposure[c] = Double.parseDouble(numerator.get("Exposure"));
gain[c] = Double.parseDouble(numerator.get("Gain"));
offset[c] = Double.parseDouble(numerator.get("Offset"));
}
}
private String[][] getTiffs(String dir) {
Location f = new Location(dir);
Vector<Vector<String>> files = new Vector<Vector<String>>();
String[] wells = f.list(true);
Arrays.sort(wells);
for (String filename : wells) {
Location file = new Location(f, filename).getAbsoluteFile();
if (file.isDirectory() && filename.startsWith("Well ")) {
String[] list = file.list(true);
Vector<String> tiffList = new Vector<String>();
Arrays.sort(list);
for (String tiff : list) {
if (tiff.matches(".* - n\\d\\d\\d\\d\\d\\d\\.tif")) {
tiffList.add(new Location(file, tiff).getAbsolutePath());
}
}
files.add(tiffList);
}
}
String[][] tiffFiles = new String[files.size()][];
for (int i=0; i<tiffFiles.length; i++) {
tiffFiles[i] = files.get(i).toArray(new String[0]);
}
return tiffFiles;
}
private void parseROIs(MetadataStore store) throws IOException {
if (roiFile == null) return;
String roiData = DataTools.readFile(roiFile);
String[] lines = roiData.split("\r\n");
int firstRow = 0;
while (firstRow < lines.length && !lines[firstRow].startsWith("ROI")) {
firstRow++;
}
firstRow += 2;
if (firstRow >= lines.length) return;
for (int i=firstRow; i<lines.length; i++) {
String[] cols = lines[i].split("\t");
if (cols.length < 6) break;
if (cols[2].trim().length() > 0) {
String rectangleID = MetadataTools.createLSID("Shape", i - firstRow, 0);
store.setRectangleID(rectangleID, i - firstRow, 0);
store.setRectangleX(new Double(cols[2]), i - firstRow, 0);
store.setRectangleY(new Double(cols[3]), i - firstRow, 0);
store.setRectangleWidth(new Double(cols[4]), i - firstRow, 0);
store.setRectangleHeight(new Double(cols[5]), i - firstRow, 0);
String roiID = MetadataTools.createLSID("ROI", i - firstRow);
store.setROIID(roiID, i - firstRow);
store.setImageROIRef(roiID, 0, i - firstRow);
}
}
}
private String getFilename(int series, int no) {
int[] zct = getZCTCoords(no);
String channel = channelNames.get(zct[1]);
int well = series / (fieldRows * fieldCols);
for (int i=0; i<tiffs[well].length; i++) {
String name = tiffs[well][i];
name = name.substring(name.lastIndexOf(File.separator) + 1);
name = name.substring(0, name.lastIndexOf("."));
String index = name.substring(name.lastIndexOf("n") + 1);
if (name.startsWith(channel) && Integer.parseInt(index) == zct[2]) {
return tiffs[well][i];
}
}
return null;
}
}
| Fix NPE during timestamp population.
| components/bio-formats/src/loci/formats/in/BDReader.java | Fix NPE during timestamp population. |
|
Java | bsd-3-clause | 9495bb715ec8655b0e0f096779e2f83c4c83ae9e | 0 | rmacnak-google/engine,jason-simmons/flutter_engine,devoncarew/engine,chinmaygarde/flutter_engine,flutter/engine,flutter/engine,rmacnak-google/engine,devoncarew/engine,flutter/engine,rmacnak-google/engine,flutter/engine,jason-simmons/flutter_engine,devoncarew/engine,devoncarew/engine,flutter/engine,chinmaygarde/flutter_engine,chinmaygarde/flutter_engine,devoncarew/engine,chinmaygarde/flutter_engine,jason-simmons/flutter_engine,jason-simmons/flutter_engine,chinmaygarde/flutter_engine,jason-simmons/flutter_engine,rmacnak-google/engine,jason-simmons/flutter_engine,devoncarew/engine,rmacnak-google/engine,flutter/engine,jason-simmons/flutter_engine,flutter/engine,chinmaygarde/flutter_engine,jason-simmons/flutter_engine,chinmaygarde/flutter_engine,devoncarew/engine,flutter/engine,rmacnak-google/engine,rmacnak-google/engine | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugin.common;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.view.FlutterNativeView;
import io.flutter.view.FlutterView;
import io.flutter.view.TextureRegistry;
/**
* Container class for Android API listeners used by {@link ActivityPluginBinding}.
*
* <p>This class also contains deprecated v1 embedding APIs used for plugin registration.
*
* <p>In v1 Android applications, an auto-generated and auto-updated plugin registrant class
* (GeneratedPluginRegistrant) makes use of a {@link PluginRegistry} to register contributions from
* each plugin mentioned in the application's pubspec file. The generated registrant class is, again
* by default, called from the application's main {@link android.app.Activity}, which defaults to an
* instance of {@link io.flutter.app.FlutterActivity}, itself a {@link PluginRegistry}.
*/
public interface PluginRegistry {
/**
* Returns a {@link Registrar} for receiving the registrations pertaining to the specified plugin.
*
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return A {@link Registrar} for receiving the registrations pertianing to the specified plugin.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
@NonNull
Registrar registrarFor(@NonNull String pluginKey);
/**
* Returns whether the specified plugin is known to this registry.
*
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return true if this registry has handed out a registrar for the specified plugin.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
boolean hasPlugin(@NonNull String pluginKey);
/**
* Returns the value published by the specified plugin, if any.
*
* <p>Plugins may publish a single value, such as an instance of the plugin's main class, for
* situations where external control or interaction is needed. Clients are expected to know the
* value's type.
*
* @param <T> The type of the value.
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return the published value, possibly null.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
@Nullable
<T> T valuePublishedByPlugin(@NonNull String pluginKey);
/**
* Receiver of registrations from a single plugin.
*
* @deprecated This registrar is for Flutter's v1 embedding. For instructions on migrating a
* plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@Deprecated
interface Registrar {
/**
* Returns the {@link android.app.Activity} that forms the plugin's operating context.
*
* <p>Plugin authors should not assume the type returned by this method is any specific subclass
* of {@code Activity} (such as {@link io.flutter.app.FlutterActivity} or {@link
* io.flutter.app.FlutterFragmentActivity}), as applications are free to use any activity
* subclass.
*
* <p>When there is no foreground activity in the application, this will return null. If a
* {@link Context} is needed, use context() to get the application's context.
*
* <p>This registrar is for Flutter's v1 embedding. To access an {@code Activity} from a plugin
* using the v2 embedding, see {@link ActivityPluginBinding#getActivity()}. To obtain an
* instance of an {@link ActivityPluginBinding} in a Flutter plugin, implement the {@link
* ActivityAware} interface. A binding is provided in {@link
* ActivityAware#onAttachedToActivity(ActivityPluginBinding)} and {@link
* ActivityAware#onReattachedToActivityForConfigChanges(ActivityPluginBinding)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@Nullable
Activity activity();
/**
* Returns the {@link android.app.Application}'s {@link Context}.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code Context} from a plugin
* using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getApplicationContext()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
Context context();
/**
* Returns the active {@link Context}.
*
* <p>This registrar is for Flutter's v1 embedding. In the v2 embedding, there is no concept of
* an "active context". Either use the application {@code Context} or an attached {@code
* Activity}. See {@link #context()} and {@link #activity()} for more details.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @return the current {@link #activity() Activity}, if not null, otherwise the {@link
* #context() Application}.
*/
@NonNull
Context activeContext();
/**
* Returns a {@link BinaryMessenger} which the plugin can use for creating channels for
* communicating with the Dart side.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code BinaryMessenger} from a
* plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getBinaryMessenger()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
BinaryMessenger messenger();
/**
* Returns a {@link TextureRegistry} which the plugin can use for managing backend textures.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code TextureRegistry} from a
* plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getTextureRegistry()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
TextureRegistry textures();
/**
* Returns the application's {@link PlatformViewRegistry}.
*
* <p>Plugins can use the platform registry to register their view factories.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code PlatformViewRegistry}
* from a plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getPlatformViewRegistry()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
PlatformViewRegistry platformViewRegistry();
/**
* Returns the {@link FlutterView} that's instantiated by this plugin's {@link #activity()
* activity}.
*
* <p>This registrar is for Flutter's v1 embedding. The {@link FlutterView} referenced by this
* method does not exist in the v2 embedding. Additionally, no {@code View} is exposed to any
* plugins in the v2 embedding. Platform views can access their containing {@code View} using
* the platform views APIs. If you have a use-case that absolutely requires a plugin to access
* an Android {@code View}, please file a ticket on GitHub.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
FlutterView view();
/**
* Returns the file name for the given asset. The returned file name can be used to access the
* asset in the APK through the {@link android.content.res.AssetManager} API.
*
* <p>TODO(mattcarroll): point this method towards new lookup method.
*
* @param asset the name of the asset. The name can be hierarchical
* @return the filename to be used with {@link android.content.res.AssetManager}
*/
@NonNull
String lookupKeyForAsset(@NonNull String asset);
/**
* Returns the file name for the given asset which originates from the specified packageName.
* The returned file name can be used to access the asset in the APK through the {@link
* android.content.res.AssetManager} API.
*
* <p>TODO(mattcarroll): point this method towards new lookup method.
*
* @param asset the name of the asset. The name can be hierarchical
* @param packageName the name of the package from which the asset originates
* @return the file name to be used with {@link android.content.res.AssetManager}
*/
@NonNull
String lookupKeyForAsset(@NonNull String asset, @NonNull String packageName);
/**
* Publishes a value associated with the plugin being registered.
*
* <p>The published value is available to interested clients via {@link
* PluginRegistry#valuePublishedByPlugin(String)}.
*
* <p>Publication should be done only when client code needs to interact with the plugin in a
* way that cannot be accomplished by the plugin registering callbacks with client APIs.
*
* <p>Overwrites any previously published value.
*
* <p>This registrar is for Flutter's v1 embedding. The concept of publishing values from
* plugins is not supported in the v2 embedding.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param value the value, possibly null.
* @return this {@link Registrar}.
*/
@NonNull
Registrar publish(@Nullable Object value);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@code
* Activity#onRequestPermissionsResult(int, String[], int[])} or {@code
* androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int,
* String[], int[])}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for permission results in the v2
* embedding, use {@link
* ActivityPluginBinding#addRequestPermissionsResultListener(PluginRegistry.RequestPermissionsResultListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link RequestPermissionsResultListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addRequestPermissionsResultListener(
@NonNull RequestPermissionsResultListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onActivityResult(int, int, Intent)}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for {@code Activity} results in
* the v2 embedding, use {@link
* ActivityPluginBinding#addActivityResultListener(PluginRegistry.ActivityResultListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener an {@link ActivityResultListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addActivityResultListener(@NonNull ActivityResultListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onNewIntent(Intent)}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for new {@code Intent}s in the v2
* embedding, use {@link
* ActivityPluginBinding#addOnNewIntentListener(PluginRegistry.NewIntentListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link NewIntentListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addNewIntentListener(@NonNull NewIntentListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onUserLeaveHint()}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for leave hints in the v2
* embedding, use {@link
* ActivityPluginBinding#addOnUserLeaveHintListener(PluginRegistry.UserLeaveHintListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link UserLeaveHintListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addUserLeaveHintListener(@NonNull UserLeaveHintListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onDestroy()}.
*
* <p>This registrar is for Flutter's v1 embedding. The concept of {@code View} destruction does
* not exist in the v2 embedding. However, plugins in the v2 embedding can respond to {@link
* ActivityAware#onDetachedFromActivityForConfigChanges()} and {@link
* ActivityAware#onDetachedFromActivity()}, which indicate the loss of a visual context for the
* running Flutter experience. Developers should implement {@link ActivityAware} for their
* {@link FlutterPlugin} if such callbacks are needed. Also, plugins can respond to {@link
* FlutterPlugin#onDetachedFromEngine(FlutterPlugin.FlutterPluginBinding)}, which indicates that
* the given plugin has been completely disconnected from the associated Flutter experience and
* should clean up any resources.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link ViewDestroyListener} callback.
* @return this {@link Registrar}.
*/
// TODO(amirh): Add a line in the javadoc above that points to a Platform Views website guide
// when one is available (but not a website API doc)
@NonNull
Registrar addViewDestroyListener(@NonNull ViewDestroyListener listener);
}
/**
* Delegate interface for handling result of permissions requests on behalf of the main {@link
* Activity}.
*/
interface RequestPermissionsResultListener {
/**
* @param requestCode The request code passed in {@code
* ActivityCompat.requestPermissions(android.app.Activity, String[], int)}.
* @param permissions The requested permissions.
* @param grantResults The grant results for the corresponding permissions which is either
* {@code PackageManager.PERMISSION_GRANTED} or {@code PackageManager.PERMISSION_DENIED}.
* @return true if the result has been handled.
*/
boolean onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults);
}
/**
* Delegate interface for handling activity results on behalf of the main {@link
* android.app.Activity}.
*/
interface ActivityResultListener {
/**
* @param requestCode The integer request code originally supplied to {@code
* startActivityForResult()}, allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its {@code
* setResult()}.
* @param data An Intent, which can return result data to the caller (various data can be
* attached to Intent "extras").
* @return true if the result has been handled.
*/
boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data);
}
/**
* Delegate interface for handling new intents on behalf of the main {@link android.app.Activity}.
*/
interface NewIntentListener {
/**
* @param intent The new intent that was started for the activity.
* @return true if the new intent has been handled.
*/
boolean onNewIntent(@NonNull Intent intent);
}
/**
* Delegate interface for handling user leave hints on behalf of the main {@link
* android.app.Activity}.
*/
interface UserLeaveHintListener {
void onUserLeaveHint();
}
/**
* Delegate interface for handling an {@link android.app.Activity}'s onDestroy method being
* called. A plugin that implements this interface can adopt the {@link FlutterNativeView} by
* retaining a reference and returning true.
*
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
interface ViewDestroyListener {
boolean onViewDestroy(@NonNull FlutterNativeView view);
}
/**
* Callback interface for registering plugins with a plugin registry.
*
* <p>For example, an Application may use this callback interface to provide a background service
* with a callback for calling its GeneratedPluginRegistrant.registerWith method.
*
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
interface PluginRegistrantCallback {
void registerWith(@NonNull PluginRegistry registry);
}
}
| shell/platform/android/io/flutter/plugin/common/PluginRegistry.java | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugin.common;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.view.FlutterNativeView;
import io.flutter.view.FlutterView;
import io.flutter.view.TextureRegistry;
/**
* Container class for Android API listeners used by {@link ActivityPluginBinding}.
*
* <p>This class also contains deprecated v1 embedding APIs used for plugin registration.
*
* <p>In v1 Android applications, an auto-generated and auto-updated plugin registrant class
* (GeneratedPluginRegistrant) makes use of a {@link PluginRegistry} to register contributions from
* each plugin mentioned in the application's pubspec file. The generated registrant class is, again
* by default, called from the application's main {@link android.app.Activity}, which defaults to an
* instance of {@link io.flutter.app.FlutterActivity}, itself a {@link PluginRegistry}.
*/
public interface PluginRegistry {
/**
* Returns a {@link Registrar} for receiving the registrations pertaining to the specified plugin.
*
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return A {@link Registrar} for receiving the registrations pertianing to the specified plugin.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
@NonNull
Registrar registrarFor(@NonNull String pluginKey);
/**
* Returns whether the specified plugin is known to this registry.
*
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return true if this registry has handed out a registrar for the specified plugin.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
boolean hasPlugin(@NonNull String pluginKey);
/**
* Returns the value published by the specified plugin, if any.
*
* <p>Plugins may publish a single value, such as an instance of the plugin's main class, for
* situations where external control or interaction is needed. Clients are expected to know the
* value's type.
*
* @param <T> The type of the value.
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return the published value, possibly null.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
@Nullable
<T> T valuePublishedByPlugin(@NonNull String pluginKey);
/**
* Receiver of registrations from a single plugin.
*
* @deprecated This registrar is for Flutter's v1 embedding. For instructions on migrating a
* plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@Deprecated
interface Registrar {
/**
* Returns the {@link android.app.Activity} that forms the plugin's operating context.
*
* <p>Plugin authors should not assume the type returned by this method is any specific subclass
* of {@code Activity} (such as {@link io.flutter.app.FlutterActivity} or {@link
* io.flutter.app.FlutterFragmentActivity}), as applications are free to use any activity
* subclass.
*
* <p>When there is no foreground activity in the application, this will return null. If a
* {@link Context} is needed, use context() to get the application's context.
*
* <p>This registrar is for Flutter's v1 embedding. To access an {@code Activity} from a plugin
* using the v2 embedding, see {@link ActivityPluginBinding#getActivity()}. To obtain an
* instance of an {@link ActivityPluginBinding} in a Flutter plugin, implement the {@link
* ActivityAware} interface. A binding is provided in {@link
* ActivityAware#onAttachedToActivity(ActivityPluginBinding)} and {@link
* ActivityAware#onReattachedToActivityForConfigChanges(ActivityPluginBinding)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@Nullable
Activity activity();
/**
* Returns the {@link android.app.Application}'s {@link Context}.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code Context} from a plugin
* using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getApplicationContext()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
Context context();
/**
* Returns the active {@link Context}.
*
* <p>This registrar is for Flutter's v1 embedding. In the v2 embedding, there is no concept of
* an "active context". Either use the application {@code Context} or an attached {@code
* Activity}. See {@link #context()} and {@link #activity()} for more details.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @return the current {@link #activity() Activity}, if not null, otherwise the {@link
* #context() Application}.
*/
@NonNull
Context activeContext();
/**
* Returns a {@link BinaryMessenger} which the plugin can use for creating channels for
* communicating with the Dart side.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code BinaryMessenger} from a
* plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getBinaryMessenger()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
BinaryMessenger messenger();
/**
* Returns a {@link TextureRegistry} which the plugin can use for managing backend textures.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code TextureRegistry} from a
* plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getTextureRegistry()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
TextureRegistry textures();
/**
* Returns the application's {@link PlatformViewRegistry}.
*
* <p>Plugins can use the platform registry to register their view factories.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code PlatformViewRegistry}
* from a plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getPlatformViewRegistry()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
PlatformViewRegistry platformViewRegistry();
/**
* Returns the {@link FlutterView} that's instantiated by this plugin's {@link #activity()
* activity}.
*
* <p>This registrar is for Flutter's v1 embedding. The {@link FlutterView} referenced by this
* method does not exist in the v2 embedding. Additionally, no {@code View} is exposed to any
* plugins in the v2 embedding. Platform views can access their containing {@code View} using
* the platform views APIs. If you have a use-case that absolutely requires a plugin to access
* an Android {@code View}, please file a ticket on GitHub.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
FlutterView view();
/**
* Returns the file name for the given asset. The returned file name can be used to access the
* asset in the APK through the {@link android.content.res.AssetManager} API.
*
* <p>TODO(mattcarroll): point this method towards new lookup method.
*
* @param asset the name of the asset. The name can be hierarchical
* @return the filename to be used with {@link android.content.res.AssetManager}
*/
@NonNull
String lookupKeyForAsset(@NonNull String asset);
/**
* Returns the file name for the given asset which originates from the specified packageName.
* The returned file name can be used to access the asset in the APK through the {@link
* android.content.res.AssetManager} API.
*
* <p>TODO(mattcarroll): point this method towards new lookup method.
*
* @param asset the name of the asset. The name can be hierarchical
* @param packageName the name of the package from which the asset originates
* @return the file name to be used with {@link android.content.res.AssetManager}
*/
@NonNull
String lookupKeyForAsset(@NonNull String asset, @NonNull String packageName);
/**
* Publishes a value associated with the plugin being registered.
*
* <p>The published value is available to interested clients via {@link
* PluginRegistry#valuePublishedByPlugin(String)}.
*
* <p>Publication should be done only when client code needs to interact with the plugin in a
* way that cannot be accomplished by the plugin registering callbacks with client APIs.
*
* <p>Overwrites any previously published value.
*
* <p>This registrar is for Flutter's v1 embedding. The concept of publishing values from
* plugins is not supported in the v2 embedding.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param value the value, possibly null.
* @return this {@link Registrar}.
*/
@NonNull
Registrar publish(@Nullable Object value);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@code
* Activity#onRequestPermissionsResult(int, String[], int[])} or {@code
* androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int,
* String[], int[])}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for permission results in the v2
* embedding, use {@link
* ActivityPluginBinding#addRequestPermissionsResultListener(PluginRegistry.RequestPermissionsResultListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link RequestPermissionsResultListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addRequestPermissionsResultListener(
@NonNull RequestPermissionsResultListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onActivityResult(int, int, Intent)}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for {@code Activity} results in
* the v2 embedding, use {@link
* ActivityPluginBinding#addActivityResultListener(PluginRegistry.ActivityResultListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener an {@link ActivityResultListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addActivityResultListener(@NonNull ActivityResultListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onNewIntent(Intent)}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for new {@code Intent}s in the v2
* embedding, use {@link
* ActivityPluginBinding#addOnNewIntentListener(PluginRegistry.NewIntentListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link NewIntentListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addNewIntentListener(@NonNull NewIntentListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onUserLeaveHint()}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for leave hints in the v2
* embedding, use {@link
* ActivityPluginBinding#addOnUserLeaveHintListener(PluginRegistry.UserLeaveHintListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link UserLeaveHintListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addUserLeaveHintListener(@NonNull UserLeaveHintListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onDestroy()}.
*
* <p>This registrar is for Flutter's v1 embedding. The concept of {@code View} destruction does
* not exist in the v2 embedding. However, plugins in the v2 embedding can respond to {@link
* ActivityAware#onDetachedFromActivityForConfigChanges()} and {@link
* ActivityAware#onDetachedFromActivity()}, which indicate the loss of a visual context for the
* running Flutter experience. Developers should implement {@link ActivityAware} for their
* {@link FlutterPlugin} if such callbacks are needed. Also, plugins can respond to {@link
* FlutterPlugin#onDetachedFromEngine(FlutterPlugin.FlutterPluginBinding)}, which indicates that
* the given plugin has been completely disconnected from the associated Flutter experience and
* should clean up any resources.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link ViewDestroyListener} callback.
* @return this {@link Registrar}.
*/
// TODO(amirh): Add a line in the javadoc above that points to a Platform Views website guide
// when one is available (but not a website API doc)
@NonNull
Registrar addViewDestroyListener(@NonNull ViewDestroyListener listener);
}
/**
* Delegate interface for handling result of permissions requests on behalf of the main {@link
* Activity}.
*/
interface RequestPermissionsResultListener {
/**
* @param requestCode The request code passed in {@code
* ActivityCompat.requestPermissions(android.app.Activity, String[], int)}.
* @param permissions The requested permissions.
* @param grantResults The grant results for the corresponding permissions which is either
* {@code PackageManager.PERMISSION_GRANTED} or {@code PackageManager.PERMISSION_DENIED}.
* @return true if the result has been handled.
*/
boolean onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults);
}
/**
* Delegate interface for handling activity results on behalf of the main {@link
* android.app.Activity}.
*/
interface ActivityResultListener {
/**
* @param requestCode The integer request code originally supplied to {@code
* startActivityForResult()}, allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its {@code
* setResult()}.
* @param data An Intent, which can return result data to the caller (various data can be
* attached to Intent "extras").
* @return true if the result has been handled.
*/
boolean onActivityResult(int requestCode, int resultCode, @NonNull Intent data);
}
/**
* Delegate interface for handling new intents on behalf of the main {@link android.app.Activity}.
*/
interface NewIntentListener {
/**
* @param intent The new intent that was started for the activity.
* @return true if the new intent has been handled.
*/
boolean onNewIntent(@NonNull Intent intent);
}
/**
* Delegate interface for handling user leave hints on behalf of the main {@link
* android.app.Activity}.
*/
interface UserLeaveHintListener {
void onUserLeaveHint();
}
/**
* Delegate interface for handling an {@link android.app.Activity}'s onDestroy method being
* called. A plugin that implements this interface can adopt the {@link FlutterNativeView} by
* retaining a reference and returning true.
*
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
interface ViewDestroyListener {
boolean onViewDestroy(@NonNull FlutterNativeView view);
}
/**
* Callback interface for registering plugins with a plugin registry.
*
* <p>For example, an Application may use this callback interface to provide a background service
* with a callback for calling its GeneratedPluginRegistrant.registerWith method.
*
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
interface PluginRegistrantCallback {
void registerWith(@NonNull PluginRegistry registry);
}
}
| Fix nullable annotation (#31668)
| shell/platform/android/io/flutter/plugin/common/PluginRegistry.java | Fix nullable annotation (#31668) |
|
Java | bsd-3-clause | e73e15d04caa77110ea8ed1b56da7a820643bda5 | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.calab.dto.characterization;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.service.search.SearchSampleService;
import gov.nih.nci.calab.domain.Instrument;
import gov.nih.nci.calab.domain.InstrumentType;
import gov.nih.nci.calab.domain.Manufacturer;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData;
import gov.nih.nci.calab.service.util.CananoConstants;
import gov.nih.nci.calab.domain.nano.characterization.CharacterizationProtocol;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
/**
* This class represents shared characterization properties to be shown in
* characterization view pages.
*
* @author pansu
*
*/
public class CharacterizationBean {
private static Logger logger = Logger.getLogger(CharacterizationBean.class);
private String id;
private String characterizationSource;
// used to distinguish different instances of characterizations, which are
// shown as different links on the view pages.
private String viewTitle;
private String description;
// not set by application
private String name;
// not set by application
private String classification;
private String createdBy;
private Date createdDate;
private InstrumentBean instrument=new InstrumentBean();
private List<DerivedBioAssayDataBean> derivedBioAssayData = new ArrayList<DerivedBioAssayDataBean>();
private String numberOfDerivedBioAssayData;
private CharacterizationProtocolBean characterizationProtocol = new CharacterizationProtocolBean();
public CharacterizationBean() {
}
public CharacterizationBean(String id, String name, String viewTitle) {
this.id = id;
this.name = name;
this.viewTitle = viewTitle;
}
public CharacterizationBean(Characterization characterization) {
this.setId(characterization.getId().toString());
this.setViewTitle(characterization.getIdentificationName());
this.setCharacterizationSource(characterization.getSource());
this.setCreatedBy(characterization.getCreatedBy());
this.setCreatedDate(characterization.getCreatedDate());
this.setDescription(characterization.getDescription());
if (characterization.getInstrument() != null) {
this.getInstrument().setType(characterization.getInstrument().getInstrumentType().getName());
this.getInstrument().setDescription(characterization.getInstrument().getDescription());
this.getInstrument().setManufacturer(characterization.getInstrument().getManufacturer().getName());
}
this.setNumberOfDerivedBioAssayData(Integer.valueOf(characterization.getDerivedBioAssayDataCollection().size()).toString());
for (DerivedBioAssayData table : characterization.getDerivedBioAssayDataCollection()) {
DerivedBioAssayDataBean ctBean = new DerivedBioAssayDataBean(table);
this.getDerivedBioAssayData().add(ctBean);
}
if (characterization.getCharacterizationProtocol() != null) {
this.getCharacterizationProtocol().setId(characterization.getCharacterizationProtocol().getId());
this.getCharacterizationProtocol().setName(characterization.getCharacterizationProtocol().getName());
this.getCharacterizationProtocol().setVersion(characterization.getCharacterizationProtocol().getVersion());
}
}
public String getCharacterizationSource() {
return characterizationSource;
}
public void setCharacterizationSource(String characterizationSource) {
this.characterizationSource = characterizationSource;
}
public String getViewTitle() {
return viewTitle;
}
public void setViewTitle(String viewTitle) {
this.viewTitle = viewTitle;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Update the domain characterization object from the dto bean properties
*
* @return
*/
public void updateDomainObj(Characterization aChar) {
if (getId() != null && getId().length() > 0) {
aChar.setId(new Long(getId()));
}
aChar.setSource(getCharacterizationSource());
aChar.setIdentificationName(getViewTitle());
aChar.setDescription(getDescription());
aChar.setCreatedBy(getCreatedBy());
aChar.setCreatedDate(getCreatedDate());
for (DerivedBioAssayDataBean table : getDerivedBioAssayData()) {
aChar.getDerivedBioAssayDataCollection().add(
table.getDomainObj());
}
Instrument instrument = new Instrument();
if (getInstrument().getId() != null)
instrument.setId(new Long(getInstrument().getId()));
instrument.setDescription(getInstrument().getDescription());
String iType = getInstrument().getType();
String manuf = getInstrument().getManufacturer();
if (iType != null && manuf != null) {
InstrumentType instrumentType = new InstrumentType();
if (iType.equals(CananoConstants.OTHER))
instrumentType.setName(getInstrument().getOtherInstrumentType());
else
instrumentType.setName(getInstrument().getType());
Manufacturer manufacturer = new Manufacturer();
if (manuf.equals(CananoConstants.OTHER))
manufacturer.setName(getInstrument().getOtherManufacturer());
else
manufacturer.setName(getInstrument().getManufacturer());
instrument.setInstrumentType(instrumentType);
instrument.setManufacturer(manufacturer);
aChar.setInstrument(instrument);
}
CharacterizationProtocolBean characterizationProtocolBean = getCharacterizationProtocol();
if (characterizationProtocolBean.getName() != null && characterizationProtocolBean.getName() != "" &&
characterizationProtocolBean.getVersion() != null && characterizationProtocolBean.getVersion() != "" ) {
CharacterizationProtocol characterizationProtocol = new CharacterizationProtocol();
characterizationProtocol.setName(characterizationProtocolBean.getName());
characterizationProtocol.setVersion(characterizationProtocolBean.getVersion());
characterizationProtocol.setId(characterizationProtocolBean.getId());
aChar.setCharacterizationProtocol(characterizationProtocol);
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getClassification() {
return classification;
}
public String getName() {
return name;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Characterization getDomainObj() {
return null;
}
public List<DerivedBioAssayDataBean> getDerivedBioAssayData() {
return derivedBioAssayData;
}
public void setDerivedBioAssayData(
List<DerivedBioAssayDataBean> derivedBioAssayData) {
this.derivedBioAssayData = derivedBioAssayData;
}
public InstrumentBean getInstrument() {
return instrument;
}
public void setInstrument(InstrumentBean instrument) {
this.instrument = instrument;
}
public DerivedBioAssayDataBean getData(int ind) {
return derivedBioAssayData.get(ind);
}
public void setData(int ind, DerivedBioAssayDataBean table) {
derivedBioAssayData.set(ind, table);
}
public String getNumberOfDerivedBioAssayData() {
return numberOfDerivedBioAssayData;
}
public void setNumberOfDerivedBioAssayData(
String numberOfDerivedBioAssayData) {
this.numberOfDerivedBioAssayData = numberOfDerivedBioAssayData;
}
public CharacterizationProtocolBean getCharacterizationProtocol() {
return characterizationProtocol;
}
public void setCharacterizationProtocol(
CharacterizationProtocolBean characterizationProtocol) {
this.characterizationProtocol = characterizationProtocol;
}
}
| src/gov/nih/nci/calab/dto/characterization/CharacterizationBean.java | package gov.nih.nci.calab.dto.characterization;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.service.search.SearchSampleService;
import gov.nih.nci.calab.domain.Instrument;
import gov.nih.nci.calab.domain.InstrumentType;
import gov.nih.nci.calab.domain.Manufacturer;
import gov.nih.nci.calab.service.util.CananoConstants;
import gov.nih.nci.calab.domain.nano.characterization.CharacterizationProtocol;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
/**
* This class represents shared characterization properties to be shown in
* characterization view pages.
*
* @author pansu
*
*/
public class CharacterizationBean {
private static Logger logger = Logger.getLogger(CharacterizationBean.class);
private String id;
private String characterizationSource;
// used to distinguish different instances of characterizations, which are
// shown as different links on the view pages.
private String viewTitle;
private String description;
// not set by application
private String name;
// not set by application
private String classification;
private String createdBy;
private Date createdDate;
private InstrumentBean instrument=new InstrumentBean();
private List<DerivedBioAssayDataBean> derivedBioAssayData = new ArrayList<DerivedBioAssayDataBean>();
private String numberOfDerivedBioAssayData;
private CharacterizationProtocolBean characterizationProtocol = new CharacterizationProtocolBean();
public CharacterizationBean() {
}
public CharacterizationBean(String id, String name, String viewTitle) {
this.id = id;
this.name = name;
this.viewTitle = viewTitle;
}
public CharacterizationBean(Characterization characterization) {
this.setId(characterization.getId().toString());
this.setViewTitle(characterization.getIdentificationName());
this.setCharacterizationSource(characterization.getSource());
this.setCreatedBy(characterization.getCreatedBy());
this.setCreatedDate(characterization.getCreatedDate());
}
public String getCharacterizationSource() {
return characterizationSource;
}
public void setCharacterizationSource(String characterizationSource) {
this.characterizationSource = characterizationSource;
}
public String getViewTitle() {
return viewTitle;
}
public void setViewTitle(String viewTitle) {
this.viewTitle = viewTitle;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Update the domain characterization object from the dto bean properties
*
* @return
*/
public void updateDomainObj(Characterization aChar) {
if (getId() != null && getId().length() > 0) {
aChar.setId(new Long(getId()));
}
aChar.setSource(getCharacterizationSource());
aChar.setIdentificationName(getViewTitle());
aChar.setDescription(getDescription());
aChar.setCreatedBy(getCreatedBy());
aChar.setCreatedDate(getCreatedDate());
for (DerivedBioAssayDataBean table : getDerivedBioAssayData()) {
aChar.getDerivedBioAssayDataCollection().add(
table.getDomainObj());
}
Instrument instrument = new Instrument();
if (getInstrument().getId() != null)
instrument.setId(new Long(getInstrument().getId()));
instrument.setDescription(getInstrument().getDescription());
String iType = getInstrument().getType();
String manuf = getInstrument().getManufacturer();
if (iType != null && manuf != null) {
InstrumentType instrumentType = new InstrumentType();
if (iType.equals(CananoConstants.OTHER))
instrumentType.setName(getInstrument().getOtherInstrumentType());
else
instrumentType.setName(getInstrument().getType());
Manufacturer manufacturer = new Manufacturer();
if (manuf.equals(CananoConstants.OTHER))
manufacturer.setName(getInstrument().getOtherManufacturer());
else
manufacturer.setName(getInstrument().getManufacturer());
instrument.setInstrumentType(instrumentType);
instrument.setManufacturer(manufacturer);
aChar.setInstrument(instrument);
}
CharacterizationProtocolBean characterizationProtocolBean = getCharacterizationProtocol();
if (characterizationProtocolBean.getName() != null && characterizationProtocolBean.getName() != "" &&
characterizationProtocolBean.getVersion() != null && characterizationProtocolBean.getVersion() != "" ) {
CharacterizationProtocol characterizationProtocol = new CharacterizationProtocol();
characterizationProtocol.setName(characterizationProtocolBean.getName());
characterizationProtocol.setVersion(characterizationProtocolBean.getVersion());
characterizationProtocol.setId(characterizationProtocolBean.getId());
aChar.setCharacterizationProtocol(characterizationProtocol);
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getClassification() {
return classification;
}
public String getName() {
return name;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Characterization getDomainObj() {
return null;
}
public List<DerivedBioAssayDataBean> getDerivedBioAssayData() {
return derivedBioAssayData;
}
public void setDerivedBioAssayData(
List<DerivedBioAssayDataBean> derivedBioAssayData) {
this.derivedBioAssayData = derivedBioAssayData;
}
public InstrumentBean getInstrument() {
return instrument;
}
public void setInstrument(InstrumentBean instrument) {
this.instrument = instrument;
}
public DerivedBioAssayDataBean getData(int ind) {
return derivedBioAssayData.get(ind);
}
public void setData(int ind, DerivedBioAssayDataBean table) {
derivedBioAssayData.set(ind, table);
}
public String getNumberOfDerivedBioAssayData() {
return numberOfDerivedBioAssayData;
}
public void setNumberOfDerivedBioAssayData(
String numberOfDerivedBioAssayData) {
this.numberOfDerivedBioAssayData = numberOfDerivedBioAssayData;
}
public CharacterizationProtocolBean getCharacterizationProtocol() {
return characterizationProtocol;
}
public void setCharacterizationProtocol(
CharacterizationProtocolBean characterizationProtocol) {
this.characterizationProtocol = characterizationProtocol;
}
}
| added code for instrument, derivedBioAssayData and protocol to constructor.
SVN-Revision: 2014
| src/gov/nih/nci/calab/dto/characterization/CharacterizationBean.java | added code for instrument, derivedBioAssayData and protocol to constructor. |
|
Java | bsd-3-clause | 81515d18d1072010fb48ffc3ff32f13b365717ff | 0 | xnlogic/pacer,xnlogic/pacer | package com.xnlogic.pacer.pipes;
import java.util.Iterator;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.pipes.AbstractPipe;
public class EdgesPipe extends AbstractPipe<Graph, Edge> {
private Iterator<Edge> iter;
private Graph starts;
public void setStarts(Iterator<Graph> starts) {
// TODO: Error checking?
this.starts = (Graph)starts.next();
this.iter = this.starts.getEdges().iterator();
}
protected Edge processNextStart() {
return this.iter.next();
}
public void reset() {
this.iter = this.starts.getEdges().iterator();
}
}
| ext/src/main/java/com/xnlogic/pacer/pipes/EdgesPipe.java | package com.xnlogic.pacer.pipes;
import com.tinkerpop.pipes.AbstractPipe;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.Direction;
import java.lang.Iterable;
import java.util.Iterator;
public class EdgesPipe extends AbstractPipe<Graph, Edge> {
private Iterator<Edge> iter;
private Graph starts;
public void setStarts(Iterator<Graph> starts) {
// TODO: Error checking?
this.starts = (Graph)starts.next();
this.iter = this.starts.getEdges().iterator();
}
protected Edge processNextStart() {
return this.iter.next();
}
public void reset() {
this.iter = this.starts.getEdges().iterator();
}
}
| Removing unused imports.
| ext/src/main/java/com/xnlogic/pacer/pipes/EdgesPipe.java | Removing unused imports. |
|
Java | bsd-3-clause | bf03d58e6556e7d072d0100c810b1f494e957400 | 0 | guywithnose/iCal4j,guywithnose/iCal4j,guywithnose/iCal4j | /**
* Copyright (c) 2009, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Ben Fortuna nor the names of any other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.fortuna.ical4j.model.component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.DateRange;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.Validator;
import net.fortuna.ical4j.model.parameter.FbType;
import net.fortuna.ical4j.model.property.Contact;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.FreeBusy;
import net.fortuna.ical4j.model.property.Method;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Url;
import net.fortuna.ical4j.util.CompatibilityHints;
import net.fortuna.ical4j.util.PropertyValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* $Id$ [Apr 5, 2004]
*
* Defines an iCalendar VFREEBUSY component.
*
* <pre>
* 4.6.4 Free/Busy Component
*
* Component Name: VFREEBUSY
*
* Purpose: Provide a grouping of component properties that describe
* either a request for free/busy time, describe a response to a request
* for free/busy time or describe a published set of busy time.
*
* Formal Definition: A "VFREEBUSY" calendar component is defined by the
* following notation:
*
* freebusyc = "BEGIN" ":" "VFREEBUSY" CRLF
* fbprop
* "END" ":" "VFREEBUSY" CRLF
*
* fbprop = *(
*
* ; the following are optional,
* ; but MUST NOT occur more than once
*
* contact / dtstart / dtend / duration / dtstamp /
* organizer / uid / url /
*
* ; the following are optional,
* ; and MAY occur more than once
*
* attendee / comment / freebusy / rstatus / x-prop
*
* )
*
* Description: A "VFREEBUSY" calendar component is a grouping of
* component properties that represents either a request for, a reply to
* a request for free or busy time information or a published set of
* busy time information.
*
* When used to request free/busy time information, the "ATTENDEE"
* property specifies the calendar users whose free/busy time is being
* requested; the "ORGANIZER" property specifies the calendar user who
* is requesting the free/busy time; the "DTSTART" and "DTEND"
* properties specify the window of time for which the free/busy time is
* being requested; the "UID" and "DTSTAMP" properties are specified to
* assist in proper sequencing of multiple free/busy time requests.
*
* When used to reply to a request for free/busy time, the "ATTENDEE"
* property specifies the calendar user responding to the free/busy time
* request; the "ORGANIZER" property specifies the calendar user that
* originally requested the free/busy time; the "FREEBUSY" property
* specifies the free/busy time information (if it exists); and the
* "UID" and "DTSTAMP" properties are specified to assist in proper
* sequencing of multiple free/busy time replies.
*
* When used to publish busy time, the "ORGANIZER" property specifies
* the calendar user associated with the published busy time; the
* "DTSTART" and "DTEND" properties specify an inclusive time window
* that surrounds the busy time information; the "FREEBUSY" property
* specifies the published busy time information; and the "DTSTAMP"
* property specifies the date/time that iCalendar object was created.
*
* The "VFREEBUSY" calendar component cannot be nested within another
* calendar component. Multiple "VFREEBUSY" calendar components can be
* specified within an iCalendar object. This permits the grouping of
* Free/Busy information into logical collections, such as monthly
* groups of busy time information.
*
* The "VFREEBUSY" calendar component is intended for use in iCalendar
* object methods involving requests for free time, requests for busy
* time, requests for both free and busy, and the associated replies.
*
* Free/Busy information is represented with the "FREEBUSY" property.
* This property provides a terse representation of time periods. One or
* more "FREEBUSY" properties can be specified in the "VFREEBUSY"
* calendar component.
*
* When present in a "VFREEBUSY" calendar component, the "DTSTART" and
* "DTEND" properties SHOULD be specified prior to any "FREEBUSY"
* properties. In a free time request, these properties can be used in
* combination with the "DURATION" property to represent a request for a
* duration of free time within a specified window of time.
*
* The recurrence properties ("RRULE", "EXRULE", "RDATE", "EXDATE") are
* not permitted within a "VFREEBUSY" calendar component. Any recurring
* events are resolved into their individual busy time periods using the
* "FREEBUSY" property.
*
* Example: The following is an example of a "VFREEBUSY" calendar
* component used to request free or busy time information:
*
* BEGIN:VFREEBUSY
* ORGANIZER:MAILTO:[email protected]
* ATTENDEE:MAILTO:[email protected]
* DTSTART:19971015T050000Z
* DTEND:19971016T050000Z
* DTSTAMP:19970901T083000Z
* END:VFREEBUSY
*
* The following is an example of a "VFREEBUSY" calendar component used
* to reply to the request with busy time information:
*
* BEGIN:VFREEBUSY
* ORGANIZER:MAILTO:[email protected]
* ATTENDEE:MAILTO:[email protected]
* DTSTAMP:19970901T100000Z
* FREEBUSY;VALUE=PERIOD:19971015T050000Z/PT8H30M,
* 19971015T160000Z/PT5H30M,19971015T223000Z/PT6H30M
* URL:http://host2.com/pub/busy/jpublic-01.ifb
* COMMENT:This iCalendar file contains busy time information for
* the next three months.
* END:VFREEBUSY
*
* The following is an example of a "VFREEBUSY" calendar component used
* to publish busy time information.
*
* BEGIN:VFREEBUSY
* ORGANIZER:[email protected]
* DTSTART:19980313T141711Z
* DTEND:19980410T141711Z
* FREEBUSY:19980314T233000Z/19980315T003000Z
* FREEBUSY:19980316T153000Z/19980316T163000Z
* FREEBUSY:19980318T030000Z/19980318T040000Z
* URL:http://www.host.com/calendar/busytime/jsmith.ifb
* END:VFREEBUSY
* </pre>
*
* Example 1 - Requesting all busy time slots for a given period:
*
* <pre><code>
* // request all busy times between today and 1 week from now..
* DateTime start = new DateTime();
* DateTime end = new DateTime(start.getTime() + 1000 * 60 * 60 * 24 * 7);
*
* VFreeBusy request = new VFreeBusy(start, end);
*
* VFreeBusy reply = new VFreeBusy(request, calendar.getComponents());
* </code></pre>
*
* Example 2 - Requesting all free time slots for a given period of at least the specified duration:
*
* <pre><code>
* // request all free time between today and 1 week from now of
* // duration 2 hours or more..
* DateTime start = new DateTime();
* DateTime end = new DateTime(start.getTime() + 1000 * 60 * 60 * 24 * 7);
*
* VFreeBusy request = new VFreeBusy(start, end, new Dur(0, 2, 0, 0));
*
* VFreeBusy response = new VFreeBusy(request, myCalendar.getComponents());
* </code></pre>
*
* @author Ben Fortuna
*/
public class VFreeBusy extends CalendarComponent {
private static final long serialVersionUID = 1046534053331139832L;
private transient Log log = LogFactory.getLog(VFreeBusy.class);
private final Map methodValidators = new HashMap();
{
methodValidators.put(Method.PUBLISH, new PublishValidator());
methodValidators.put(Method.REPLY, new ReplyValidator());
methodValidators.put(Method.REQUEST, new RequestValidator());
}
/**
* Default constructor.
*/
public VFreeBusy() {
super(VFREEBUSY);
getProperties().add(new DtStamp());
}
/**
* Constructor.
* @param properties a list of properties
*/
public VFreeBusy(final PropertyList properties) {
super(VFREEBUSY, properties);
}
/**
* Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used
* for requesting busy time for a specified period.
* @param start the starting boundary for the VFreeBusy
* @param end the ending boundary for the VFreeBusy
*/
public VFreeBusy(final DateTime start, final DateTime end) {
this();
// 4.8.2.4 Date/Time Start:
//
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start, true));
// 4.8.2.2 Date/Time End
//
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end, true));
}
/**
* Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used
* for requesting free time for a specified duration in given period defined by the start date and end date.
* @param start the starting boundary for the VFreeBusy
* @param end the ending boundary for the VFreeBusy
* @param duration the length of the period being requested
*/
public VFreeBusy(final DateTime start, final DateTime end, final Dur duration) {
this();
// 4.8.2.4 Date/Time Start:
//
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start, true));
// 4.8.2.2 Date/Time End
//
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end, true));
getProperties().add(new Duration(duration));
}
/**
* Constructs a new VFreeBusy instance representing a reply to the specified VFREEBUSY request according to the
* specified list of components.
* If the request argument has its duration set, then the result
* represents a list of <em>free</em> times (that is, parameter FBTYPE
* is set to FbType.FREE).
* If the request argument does not have its duration set, then the result
* represents a list of <em>busy</em> times.
* @param request a VFREEBUSY request
* @param components a component list used to initialise busy time
* @throws ValidationException
*/
public VFreeBusy(final VFreeBusy request, final ComponentList components) {
this();
DtStart start = (DtStart) request.getProperty(Property.DTSTART);
DtEnd end = (DtEnd) request.getProperty(Property.DTEND);
Duration duration = (Duration) request.getProperty(Property.DURATION);
// 4.8.2.4 Date/Time Start:
//
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start.getDate(), true));
// 4.8.2.2 Date/Time End
//
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end.getDate(), true));
if (duration != null) {
getProperties().add(new Duration(duration.getDuration()));
// Initialise with all free time of at least the specified duration..
DateTime freeStart = new DateTime(start.getDate());
DateTime freeEnd = new DateTime(end.getDate());
FreeBusy fb = new FreeTimeBuilder().start(freeStart)
.end(freeEnd)
.duration(duration.getDuration())
.components(components)
.build();
if (fb != null && !fb.getPeriods().isEmpty()) {
getProperties().add(fb);
}
}
else {
// initialise with all busy time for the specified period..
DateTime busyStart = new DateTime(start.getDate());
DateTime busyEnd = new DateTime(end.getDate());
FreeBusy fb = new BusyTimeBuilder().start(busyStart)
.end(busyEnd)
.components(components)
.build();
if (fb != null && !fb.getPeriods().isEmpty()) {
getProperties().add(fb);
}
}
}
/**
* Create a FREEBUSY property representing the busy time for the specified component list. If the component is not
* applicable to FREEBUSY time, or if the component is outside the bounds of the start and end dates, null is
* returned. If no valid busy periods are identified in the component an empty FREEBUSY property is returned (i.e.
* empty period list).
*/
private class BusyTimeBuilder {
private DateTime start;
private DateTime end;
private ComponentList components;
public BusyTimeBuilder start(DateTime start) {
this.start = start;
return this;
}
public BusyTimeBuilder end(DateTime end) {
this.end = end;
return this;
}
public BusyTimeBuilder components(ComponentList components) {
this.components = components;
return this;
}
public FreeBusy build() {
final PeriodList periods = getConsumedTime(components, start, end);
final DateRange range = new DateRange(start, end);
// periods must be in UTC time for freebusy..
periods.setUtc(true);
for (final Iterator i = periods.iterator(); i.hasNext();) {
final Period period = (Period) i.next();
// check if period outside bounds..
if (!range.intersects(period)) {
periods.remove(period);
}
}
return new FreeBusy(periods);
}
}
/**
* Create a FREEBUSY property representing the free time available of the specified duration for the given list of
* components. component. If the component is not applicable to FREEBUSY time, or if the component is outside the
* bounds of the start and end dates, null is returned. If no valid busy periods are identified in the component an
* empty FREEBUSY property is returned (i.e. empty period list).
*/
private class FreeTimeBuilder {
private DateTime start;
private DateTime end;
private Dur duration;
private ComponentList components;
public FreeTimeBuilder start(DateTime start) {
this.start = start;
return this;
}
public FreeTimeBuilder end(DateTime end) {
this.end = end;
return this;
}
private FreeTimeBuilder duration(Dur duration) {
this.duration = duration;
return this;
}
public FreeTimeBuilder components(ComponentList components) {
this.components = components;
return this;
}
public FreeBusy build() {
final FreeBusy fb = new FreeBusy();
fb.getParameters().add(FbType.FREE);
final PeriodList periods = getConsumedTime(components, start, end);
final DateRange range = new DateRange(start, end);
// Add final consumed time to avoid special-case end-of-list processing
periods.add(new Period(end, end));
// debugging..
if (log.isDebugEnabled()) {
log.debug("Busy periods: " + periods);
}
DateTime lastPeriodEnd = new DateTime(start);
// where no time is consumed set the last period end as the range start..
for (final Iterator i = periods.iterator(); i.hasNext();) {
final Period period = (Period) i.next();
// check if period outside bounds..
// if (period.getStart().after(end) || period.getEnd().before(start)) {
if (range.contains(period)) {
// calculate duration between this period start and last period end..
final Duration freeDuration = new Duration(lastPeriodEnd, period.getStart());
if (freeDuration.getDuration().compareTo(duration) >= 0) {
fb.getPeriods().add(new Period(lastPeriodEnd, freeDuration.getDuration()));
}
if (period.getEnd().after(lastPeriodEnd)) {
lastPeriodEnd = period.getEnd();
}
}
else if (range.intersects(period) && lastPeriodEnd.before(period.getEnd())) {
lastPeriodEnd = period.getEnd();
}
}
return fb;
}
}
/**
* Creates a list of periods representing the time consumed by the specified list of components.
* @param components
* @return
*/
private PeriodList getConsumedTime(final ComponentList components, final DateTime rangeStart,
final DateTime rangeEnd) {
PeriodList periods = new PeriodList();
// only events consume time..
for (Iterator i = components.getComponents(Component.VEVENT).iterator(); i.hasNext();) {
Component component = (Component) i.next();
periods.addAll(((VEvent) component).getConsumedTime(rangeStart, rangeEnd, false));
}
return periods.normalise();
}
/**
* {@inheritDoc}
*/
public final void validate(final boolean recurse) throws ValidationException {
if (!CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) {
// From "4.8.4.7 Unique Identifier":
// Conformance: The property MUST be specified in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.UID,
getProperties());
// From "4.8.7.2 Date/Time Stamp":
// Conformance: This property MUST be included in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.DTSTAMP,
getProperties());
}
PropertyValidator validator = PropertyValidator.getInstance();
/*
* ; the following are optional, ; but MUST NOT occur more than once contact / dtstart / dtend / duration /
* dtstamp / organizer / uid / url /
*/
validator.assertOneOrLess(Property.CONTACT, getProperties());
validator.assertOneOrLess(Property.DTSTART, getProperties());
validator.assertOneOrLess(Property.DTEND, getProperties());
validator.assertOneOrLess(Property.DURATION, getProperties());
validator.assertOneOrLess(Property.DTSTAMP, getProperties());
validator.assertOneOrLess(Property.ORGANIZER, getProperties());
validator.assertOneOrLess(Property.UID, getProperties());
validator.assertOneOrLess(Property.URL, getProperties());
/*
* ; the following are optional, ; and MAY occur more than once attendee / comment / freebusy / rstatus / x-prop
*/
/*
* The recurrence properties ("RRULE", "EXRULE", "RDATE", "EXDATE") are not permitted within a "VFREEBUSY"
* calendar component. Any recurring events are resolved into their individual busy time periods using the
* "FREEBUSY" property.
*/
validator.assertNone(Property.RRULE, getProperties());
validator.assertNone(Property.EXRULE, getProperties());
validator.assertNone(Property.RDATE, getProperties());
validator.assertNone(Property.EXDATE, getProperties());
// DtEnd value must be later in time that DtStart..
DtStart dtStart = (DtStart) getProperty(Property.DTSTART);
// 4.8.2.4 Date/Time Start:
//
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
if (dtStart != null && !dtStart.isUtc()) {
throw new ValidationException("DTSTART must be specified in UTC time");
}
DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND);
// 4.8.2.2 Date/Time End
//
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
if (dtEnd != null && !dtEnd.isUtc()) {
throw new ValidationException("DTEND must be specified in UTC time");
}
if (dtStart != null && dtEnd != null
&& !dtStart.getDate().before(dtEnd.getDate())) {
throw new ValidationException("Property [" + Property.DTEND
+ "] must be later in time than [" + Property.DTSTART + "]");
}
if (recurse) {
validateProperties();
}
}
/**
* {@inheritDoc}
*/
protected Validator getValidator(Method method) {
return (Validator) methodValidators.get(method);
}
/**
* <pre>
* Component/Property Presence
* ------------------- ----------------------------------------------
* METHOD 1 MUST be "PUBLISH"
*
* VFREEBUSY 1+
* DTSTAMP 1
* DTSTART 1 DateTime values must be in UTC
* DTEND 1 DateTime values must be in UTC
* FREEBUSY 1+ MUST be BUSYTIME. Multiple instances are
* allowed. Multiple instances must be sorted
* in ascending order
* ORGANIZER 1 MUST contain the address of originator of
* busy time data.
* UID 1
* COMMENT 0 or 1
* CONTACT 0+
* X-PROPERTY 0+
* URL 0 or 1 Specifies busy time URL
*
* ATTENDEE 0
* DURATION 0
* REQUEST-STATUS 0
*
* X-COMPONENT 0+
*
* VEVENT 0
* VTODO 0
* VJOURNAL 0
* VTIMEZONE 0
* VALARM 0
* </pre>
*
*/
private class PublishValidator implements Validator {
public void validate() throws ValidationException {
PropertyValidator.getInstance().assertOneOrMore(Property.FREEBUSY, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL, getProperties());
PropertyValidator.getInstance().assertNone(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.REQUEST_STATUS, getProperties());
}
}
/**
* <pre>
* Component/Property Presence
* ------------------- ----------------------------------------------
* METHOD 1 MUST be "REPLY"
*
* VFREEBUSY 1
* ATTENDEE 1 (address of recipient replying)
* DTSTAMP 1
* DTEND 1 DateTime values must be in UTC
* DTSTART 1 DateTime values must be in UTC
* FREEBUSY 0+ (values MUST all be of the same data
* type. Multiple instances are allowed.
* Multiple instances MUST be sorted in
* ascending order. Values MAY NOT overlap)
* ORGANIZER 1 MUST be the request originator's address
* UID 1
*
* COMMENT 0 or 1
* CONTACT 0+
* REQUEST-STATUS 0+
* URL 0 or 1 (specifies busy time URL)
* X-PROPERTY 0+
* DURATION 0
* SEQUENCE 0
*
* X-COMPONENT 0+
* VALARM 0
* VEVENT 0
* VTODO 0
* VJOURNAL 0
* VTIMEZONE 0
* </pre>
*
*/
private class ReplyValidator implements Validator {
public void validate() throws ValidationException {
// FREEBUSY is 1+ in RFC2446 but 0+ in Calsify
PropertyValidator.getInstance().assertOne(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.SEQUENCE, getProperties());
}
}
/**
* <pre>
* Component/Property Presence
* ------------------- ----------------------------------------------
* METHOD 1 MUST be "REQUEST"
*
* VFREEBUSY 1
* ATTENDEE 1+ contain the address of the calendar store
* DTEND 1 DateTime values must be in UTC
* DTSTAMP 1
* DTSTART 1 DateTime values must be in UTC
* ORGANIZER 1 MUST be the request originator's address
* UID 1
* COMMENT 0 or 1
* CONTACT 0+
* X-PROPERTY 0+
*
* FREEBUSY 0
* DURATION 0
* REQUEST-STATUS 0
* URL 0
*
* X-COMPONENT 0+
* VALARM 0
* VEVENT 0
* VTODO 0
* VJOURNAL 0
* VTIMEZONE 0
* </pre>
*
*/
private class RequestValidator implements Validator {
public void validate() throws ValidationException {
PropertyValidator.getInstance().assertOneOrMore(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertNone(Property.FREEBUSY, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.REQUEST_STATUS, getProperties());
PropertyValidator.getInstance().assertNone(Property.URL, getProperties());
}
}
/**
* @return the CONTACT property or null if not specified
*/
public final Contact getContact() {
return (Contact) getProperty(Property.CONTACT);
}
/**
* @return the DTSTART propery or null if not specified
*/
public final DtStart getStartDate() {
return (DtStart) getProperty(Property.DTSTART);
}
/**
* @return the DTEND property or null if not specified
*/
public final DtEnd getEndDate() {
return (DtEnd) getProperty(Property.DTEND);
}
/**
* @return the DURATION property or null if not specified
*/
public final Duration getDuration() {
return (Duration) getProperty(Property.DURATION);
}
/**
* @return the DTSTAMP property or null if not specified
*/
public final DtStamp getDateStamp() {
return (DtStamp) getProperty(Property.DTSTAMP);
}
/**
* @return the ORGANIZER property or null if not specified
*/
public final Organizer getOrganizer() {
return (Organizer) getProperty(Property.ORGANIZER);
}
/**
* @return the URL property or null if not specified
*/
public final Url getUrl() {
return (Url) getProperty(Property.URL);
}
/**
* Returns the UID property of this component if available.
* @return a Uid instance, or null if no UID property exists
*/
public final Uid getUid() {
return (Uid) getProperty(Property.UID);
}
/**
* @param stream
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(final java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
log = LogFactory.getLog(VFreeBusy.class);
}
}
| source/net/fortuna/ical4j/model/component/VFreeBusy.java | /**
* Copyright (c) 2009, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Ben Fortuna nor the names of any other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.fortuna.ical4j.model.component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.Validator;
import net.fortuna.ical4j.model.parameter.FbType;
import net.fortuna.ical4j.model.property.Contact;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.FreeBusy;
import net.fortuna.ical4j.model.property.Method;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Url;
import net.fortuna.ical4j.util.CompatibilityHints;
import net.fortuna.ical4j.util.PropertyValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* $Id$ [Apr 5, 2004]
*
* Defines an iCalendar VFREEBUSY component.
*
* <pre>
* 4.6.4 Free/Busy Component
*
* Component Name: VFREEBUSY
*
* Purpose: Provide a grouping of component properties that describe
* either a request for free/busy time, describe a response to a request
* for free/busy time or describe a published set of busy time.
*
* Formal Definition: A "VFREEBUSY" calendar component is defined by the
* following notation:
*
* freebusyc = "BEGIN" ":" "VFREEBUSY" CRLF
* fbprop
* "END" ":" "VFREEBUSY" CRLF
*
* fbprop = *(
*
* ; the following are optional,
* ; but MUST NOT occur more than once
*
* contact / dtstart / dtend / duration / dtstamp /
* organizer / uid / url /
*
* ; the following are optional,
* ; and MAY occur more than once
*
* attendee / comment / freebusy / rstatus / x-prop
*
* )
*
* Description: A "VFREEBUSY" calendar component is a grouping of
* component properties that represents either a request for, a reply to
* a request for free or busy time information or a published set of
* busy time information.
*
* When used to request free/busy time information, the "ATTENDEE"
* property specifies the calendar users whose free/busy time is being
* requested; the "ORGANIZER" property specifies the calendar user who
* is requesting the free/busy time; the "DTSTART" and "DTEND"
* properties specify the window of time for which the free/busy time is
* being requested; the "UID" and "DTSTAMP" properties are specified to
* assist in proper sequencing of multiple free/busy time requests.
*
* When used to reply to a request for free/busy time, the "ATTENDEE"
* property specifies the calendar user responding to the free/busy time
* request; the "ORGANIZER" property specifies the calendar user that
* originally requested the free/busy time; the "FREEBUSY" property
* specifies the free/busy time information (if it exists); and the
* "UID" and "DTSTAMP" properties are specified to assist in proper
* sequencing of multiple free/busy time replies.
*
* When used to publish busy time, the "ORGANIZER" property specifies
* the calendar user associated with the published busy time; the
* "DTSTART" and "DTEND" properties specify an inclusive time window
* that surrounds the busy time information; the "FREEBUSY" property
* specifies the published busy time information; and the "DTSTAMP"
* property specifies the date/time that iCalendar object was created.
*
* The "VFREEBUSY" calendar component cannot be nested within another
* calendar component. Multiple "VFREEBUSY" calendar components can be
* specified within an iCalendar object. This permits the grouping of
* Free/Busy information into logical collections, such as monthly
* groups of busy time information.
*
* The "VFREEBUSY" calendar component is intended for use in iCalendar
* object methods involving requests for free time, requests for busy
* time, requests for both free and busy, and the associated replies.
*
* Free/Busy information is represented with the "FREEBUSY" property.
* This property provides a terse representation of time periods. One or
* more "FREEBUSY" properties can be specified in the "VFREEBUSY"
* calendar component.
*
* When present in a "VFREEBUSY" calendar component, the "DTSTART" and
* "DTEND" properties SHOULD be specified prior to any "FREEBUSY"
* properties. In a free time request, these properties can be used in
* combination with the "DURATION" property to represent a request for a
* duration of free time within a specified window of time.
*
* The recurrence properties ("RRULE", "EXRULE", "RDATE", "EXDATE") are
* not permitted within a "VFREEBUSY" calendar component. Any recurring
* events are resolved into their individual busy time periods using the
* "FREEBUSY" property.
*
* Example: The following is an example of a "VFREEBUSY" calendar
* component used to request free or busy time information:
*
* BEGIN:VFREEBUSY
* ORGANIZER:MAILTO:[email protected]
* ATTENDEE:MAILTO:[email protected]
* DTSTART:19971015T050000Z
* DTEND:19971016T050000Z
* DTSTAMP:19970901T083000Z
* END:VFREEBUSY
*
* The following is an example of a "VFREEBUSY" calendar component used
* to reply to the request with busy time information:
*
* BEGIN:VFREEBUSY
* ORGANIZER:MAILTO:[email protected]
* ATTENDEE:MAILTO:[email protected]
* DTSTAMP:19970901T100000Z
* FREEBUSY;VALUE=PERIOD:19971015T050000Z/PT8H30M,
* 19971015T160000Z/PT5H30M,19971015T223000Z/PT6H30M
* URL:http://host2.com/pub/busy/jpublic-01.ifb
* COMMENT:This iCalendar file contains busy time information for
* the next three months.
* END:VFREEBUSY
*
* The following is an example of a "VFREEBUSY" calendar component used
* to publish busy time information.
*
* BEGIN:VFREEBUSY
* ORGANIZER:[email protected]
* DTSTART:19980313T141711Z
* DTEND:19980410T141711Z
* FREEBUSY:19980314T233000Z/19980315T003000Z
* FREEBUSY:19980316T153000Z/19980316T163000Z
* FREEBUSY:19980318T030000Z/19980318T040000Z
* URL:http://www.host.com/calendar/busytime/jsmith.ifb
* END:VFREEBUSY
* </pre>
*
* Example 1 - Requesting all busy time slots for a given period:
*
* <pre><code>
* // request all busy times between today and 1 week from now..
* DateTime start = new DateTime();
* DateTime end = new DateTime(start.getTime() + 1000 * 60 * 60 * 24 * 7);
*
* VFreeBusy request = new VFreeBusy(start, end);
*
* VFreeBusy reply = new VFreeBusy(request, calendar.getComponents());
* </code></pre>
*
* Example 2 - Requesting all free time slots for a given period of at least the specified duration:
*
* <pre><code>
* // request all free time between today and 1 week from now of
* // duration 2 hours or more..
* DateTime start = new DateTime();
* DateTime end = new DateTime(start.getTime() + 1000 * 60 * 60 * 24 * 7);
*
* VFreeBusy request = new VFreeBusy(start, end, new Dur(0, 2, 0, 0));
*
* VFreeBusy response = new VFreeBusy(request, myCalendar.getComponents());
* </code></pre>
*
* @author Ben Fortuna
*/
public class VFreeBusy extends CalendarComponent {
private static final long serialVersionUID = 1046534053331139832L;
private transient Log log = LogFactory.getLog(VFreeBusy.class);
private final Map methodValidators = new HashMap();
{
methodValidators.put(Method.PUBLISH, new PublishValidator());
methodValidators.put(Method.REPLY, new ReplyValidator());
methodValidators.put(Method.REQUEST, new RequestValidator());
}
/**
* Default constructor.
*/
public VFreeBusy() {
super(VFREEBUSY);
getProperties().add(new DtStamp());
}
/**
* Constructor.
* @param properties a list of properties
*/
public VFreeBusy(final PropertyList properties) {
super(VFREEBUSY, properties);
}
/**
* Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used
* for requesting busy time for a specified period.
* @param start the starting boundary for the VFreeBusy
* @param end the ending boundary for the VFreeBusy
*/
public VFreeBusy(final DateTime start, final DateTime end) {
this();
// 4.8.2.4 Date/Time Start:
//
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start, true));
// 4.8.2.2 Date/Time End
//
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end, true));
}
/**
* Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used
* for requesting free time for a specified duration in given period defined by the start date and end date.
* @param start the starting boundary for the VFreeBusy
* @param end the ending boundary for the VFreeBusy
* @param duration the length of the period being requested
*/
public VFreeBusy(final DateTime start, final DateTime end, final Dur duration) {
this();
// 4.8.2.4 Date/Time Start:
//
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start, true));
// 4.8.2.2 Date/Time End
//
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end, true));
getProperties().add(new Duration(duration));
}
/**
* Constructs a new VFreeBusy instance representing a reply to the specified VFREEBUSY request according to the
* specified list of components.
* If the request argument has its duration set, then the result
* represents a list of <em>free</em> times (that is, parameter FBTYPE
* is set to FbType.FREE).
* If the request argument does not have its duration set, then the result
* represents a list of <em>busy</em> times.
* @param request a VFREEBUSY request
* @param components a component list used to initialise busy time
* @throws ValidationException
*/
public VFreeBusy(final VFreeBusy request, final ComponentList components) {
this();
DtStart start = (DtStart) request.getProperty(Property.DTSTART);
DtEnd end = (DtEnd) request.getProperty(Property.DTEND);
Duration duration = (Duration) request.getProperty(Property.DURATION);
// 4.8.2.4 Date/Time Start:
//
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start.getDate(), true));
// 4.8.2.2 Date/Time End
//
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end.getDate(), true));
if (duration != null) {
getProperties().add(new Duration(duration.getDuration()));
// Initialise with all free time of at least the specified duration..
DateTime freeStart = new DateTime(start.getDate());
DateTime freeEnd = new DateTime(end.getDate());
FreeBusy fb = new FreeTimeBuilder().start(freeStart)
.end(freeEnd)
.duration(duration.getDuration())
.components(components)
.build();
if (fb != null && !fb.getPeriods().isEmpty()) {
getProperties().add(fb);
}
}
else {
// initialise with all busy time for the specified period..
DateTime busyStart = new DateTime(start.getDate());
DateTime busyEnd = new DateTime(end.getDate());
FreeBusy fb = new BusyTimeBuilder().start(busyStart)
.end(busyEnd)
.components(components)
.build();
if (fb != null && !fb.getPeriods().isEmpty()) {
getProperties().add(fb);
}
}
}
/**
* Create a FREEBUSY property representing the busy time for the specified component list. If the component is not
* applicable to FREEBUSY time, or if the component is outside the bounds of the start and end dates, null is
* returned. If no valid busy periods are identified in the component an empty FREEBUSY property is returned (i.e.
* empty period list).
*/
private class BusyTimeBuilder {
private DateTime start;
private DateTime end;
private ComponentList components;
public BusyTimeBuilder start(DateTime start) {
this.start = start;
return this;
}
public BusyTimeBuilder end(DateTime end) {
this.end = end;
return this;
}
public BusyTimeBuilder components(ComponentList components) {
this.components = components;
return this;
}
public FreeBusy build() {
final PeriodList periods = getConsumedTime(components, start, end);
// periods must be in UTC time for freebusy..
periods.setUtc(true);
for (final Iterator i = periods.iterator(); i.hasNext();) {
final Period period = (Period) i.next();
// check if period outside bounds..
if (period.getStart().after(end) || period.getEnd().before(start)) {
periods.remove(period);
}
}
return new FreeBusy(periods);
}
}
/**
* Create a FREEBUSY property representing the free time available of the specified duration for the given list of
* components. component. If the component is not applicable to FREEBUSY time, or if the component is outside the
* bounds of the start and end dates, null is returned. If no valid busy periods are identified in the component an
* empty FREEBUSY property is returned (i.e. empty period list).
*/
private class FreeTimeBuilder {
private DateTime start;
private DateTime end;
private Dur duration;
private ComponentList components;
public FreeTimeBuilder start(DateTime start) {
this.start = start;
return this;
}
public FreeTimeBuilder end(DateTime end) {
this.end = end;
return this;
}
private FreeTimeBuilder duration(Dur duration) {
this.duration = duration;
return this;
}
public FreeTimeBuilder components(ComponentList components) {
this.components = components;
return this;
}
public FreeBusy build() {
final FreeBusy fb = new FreeBusy();
fb.getParameters().add(FbType.FREE);
final PeriodList periods = getConsumedTime(components, start, end);
// Add final consumed time to avoid special-case end-of-list processing
periods.add(new Period(end, end));
// debugging..
if (log.isDebugEnabled()) {
log.debug("Busy periods: " + periods);
}
DateTime lastPeriodEnd = new DateTime(start);
// where no time is consumed set the last period end as the range start..
for (final Iterator i = periods.iterator(); i.hasNext();) {
final Period period = (Period) i.next();
// check if period outside bounds..
if (period.getStart().after(end) || period.getEnd().before(start)) {
continue;
}
// calculate duration between this period start and last period end..
final Duration freeDuration = new Duration(lastPeriodEnd, period.getStart());
if (freeDuration.getDuration().compareTo(duration) >= 0) {
fb.getPeriods().add(new Period(lastPeriodEnd, freeDuration.getDuration()));
}
if (period.getEnd().after(lastPeriodEnd)) {
lastPeriodEnd = period.getEnd();
}
}
return fb;
}
}
/**
* Creates a list of periods representing the time consumed by the specified list of components.
* @param components
* @return
*/
private PeriodList getConsumedTime(final ComponentList components, final DateTime rangeStart,
final DateTime rangeEnd) {
PeriodList periods = new PeriodList();
// only events consume time..
for (Iterator i = components.getComponents(Component.VEVENT).iterator(); i.hasNext();) {
Component component = (Component) i.next();
periods.addAll(((VEvent) component).getConsumedTime(rangeStart, rangeEnd, false));
}
return periods.normalise();
}
/**
* {@inheritDoc}
*/
public final void validate(final boolean recurse) throws ValidationException {
if (!CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) {
// From "4.8.4.7 Unique Identifier":
// Conformance: The property MUST be specified in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.UID,
getProperties());
// From "4.8.7.2 Date/Time Stamp":
// Conformance: This property MUST be included in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.DTSTAMP,
getProperties());
}
PropertyValidator validator = PropertyValidator.getInstance();
/*
* ; the following are optional, ; but MUST NOT occur more than once contact / dtstart / dtend / duration /
* dtstamp / organizer / uid / url /
*/
validator.assertOneOrLess(Property.CONTACT, getProperties());
validator.assertOneOrLess(Property.DTSTART, getProperties());
validator.assertOneOrLess(Property.DTEND, getProperties());
validator.assertOneOrLess(Property.DURATION, getProperties());
validator.assertOneOrLess(Property.DTSTAMP, getProperties());
validator.assertOneOrLess(Property.ORGANIZER, getProperties());
validator.assertOneOrLess(Property.UID, getProperties());
validator.assertOneOrLess(Property.URL, getProperties());
/*
* ; the following are optional, ; and MAY occur more than once attendee / comment / freebusy / rstatus / x-prop
*/
/*
* The recurrence properties ("RRULE", "EXRULE", "RDATE", "EXDATE") are not permitted within a "VFREEBUSY"
* calendar component. Any recurring events are resolved into their individual busy time periods using the
* "FREEBUSY" property.
*/
validator.assertNone(Property.RRULE, getProperties());
validator.assertNone(Property.EXRULE, getProperties());
validator.assertNone(Property.RDATE, getProperties());
validator.assertNone(Property.EXDATE, getProperties());
// DtEnd value must be later in time that DtStart..
DtStart dtStart = (DtStart) getProperty(Property.DTSTART);
// 4.8.2.4 Date/Time Start:
//
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
if (dtStart != null && !dtStart.isUtc()) {
throw new ValidationException("DTSTART must be specified in UTC time");
}
DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND);
// 4.8.2.2 Date/Time End
//
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
if (dtEnd != null && !dtEnd.isUtc()) {
throw new ValidationException("DTEND must be specified in UTC time");
}
if (dtStart != null && dtEnd != null
&& !dtStart.getDate().before(dtEnd.getDate())) {
throw new ValidationException("Property [" + Property.DTEND
+ "] must be later in time than [" + Property.DTSTART + "]");
}
if (recurse) {
validateProperties();
}
}
/**
* {@inheritDoc}
*/
protected Validator getValidator(Method method) {
return (Validator) methodValidators.get(method);
}
/**
* <pre>
* Component/Property Presence
* ------------------- ----------------------------------------------
* METHOD 1 MUST be "PUBLISH"
*
* VFREEBUSY 1+
* DTSTAMP 1
* DTSTART 1 DateTime values must be in UTC
* DTEND 1 DateTime values must be in UTC
* FREEBUSY 1+ MUST be BUSYTIME. Multiple instances are
* allowed. Multiple instances must be sorted
* in ascending order
* ORGANIZER 1 MUST contain the address of originator of
* busy time data.
* UID 1
* COMMENT 0 or 1
* CONTACT 0+
* X-PROPERTY 0+
* URL 0 or 1 Specifies busy time URL
*
* ATTENDEE 0
* DURATION 0
* REQUEST-STATUS 0
*
* X-COMPONENT 0+
*
* VEVENT 0
* VTODO 0
* VJOURNAL 0
* VTIMEZONE 0
* VALARM 0
* </pre>
*
*/
private class PublishValidator implements Validator {
public void validate() throws ValidationException {
PropertyValidator.getInstance().assertOneOrMore(Property.FREEBUSY, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL, getProperties());
PropertyValidator.getInstance().assertNone(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.REQUEST_STATUS, getProperties());
}
}
/**
* <pre>
* Component/Property Presence
* ------------------- ----------------------------------------------
* METHOD 1 MUST be "REPLY"
*
* VFREEBUSY 1
* ATTENDEE 1 (address of recipient replying)
* DTSTAMP 1
* DTEND 1 DateTime values must be in UTC
* DTSTART 1 DateTime values must be in UTC
* FREEBUSY 0+ (values MUST all be of the same data
* type. Multiple instances are allowed.
* Multiple instances MUST be sorted in
* ascending order. Values MAY NOT overlap)
* ORGANIZER 1 MUST be the request originator's address
* UID 1
*
* COMMENT 0 or 1
* CONTACT 0+
* REQUEST-STATUS 0+
* URL 0 or 1 (specifies busy time URL)
* X-PROPERTY 0+
* DURATION 0
* SEQUENCE 0
*
* X-COMPONENT 0+
* VALARM 0
* VEVENT 0
* VTODO 0
* VJOURNAL 0
* VTIMEZONE 0
* </pre>
*
*/
private class ReplyValidator implements Validator {
public void validate() throws ValidationException {
// FREEBUSY is 1+ in RFC2446 but 0+ in Calsify
PropertyValidator.getInstance().assertOne(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.SEQUENCE, getProperties());
}
}
/**
* <pre>
* Component/Property Presence
* ------------------- ----------------------------------------------
* METHOD 1 MUST be "REQUEST"
*
* VFREEBUSY 1
* ATTENDEE 1+ contain the address of the calendar store
* DTEND 1 DateTime values must be in UTC
* DTSTAMP 1
* DTSTART 1 DateTime values must be in UTC
* ORGANIZER 1 MUST be the request originator's address
* UID 1
* COMMENT 0 or 1
* CONTACT 0+
* X-PROPERTY 0+
*
* FREEBUSY 0
* DURATION 0
* REQUEST-STATUS 0
* URL 0
*
* X-COMPONENT 0+
* VALARM 0
* VEVENT 0
* VTODO 0
* VJOURNAL 0
* VTIMEZONE 0
* </pre>
*
*/
private class RequestValidator implements Validator {
public void validate() throws ValidationException {
PropertyValidator.getInstance().assertOneOrMore(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertNone(Property.FREEBUSY, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.REQUEST_STATUS, getProperties());
PropertyValidator.getInstance().assertNone(Property.URL, getProperties());
}
}
/**
* @return the CONTACT property or null if not specified
*/
public final Contact getContact() {
return (Contact) getProperty(Property.CONTACT);
}
/**
* @return the DTSTART propery or null if not specified
*/
public final DtStart getStartDate() {
return (DtStart) getProperty(Property.DTSTART);
}
/**
* @return the DTEND property or null if not specified
*/
public final DtEnd getEndDate() {
return (DtEnd) getProperty(Property.DTEND);
}
/**
* @return the DURATION property or null if not specified
*/
public final Duration getDuration() {
return (Duration) getProperty(Property.DURATION);
}
/**
* @return the DTSTAMP property or null if not specified
*/
public final DtStamp getDateStamp() {
return (DtStamp) getProperty(Property.DTSTAMP);
}
/**
* @return the ORGANIZER property or null if not specified
*/
public final Organizer getOrganizer() {
return (Organizer) getProperty(Property.ORGANIZER);
}
/**
* @return the URL property or null if not specified
*/
public final Url getUrl() {
return (Url) getProperty(Property.URL);
}
/**
* Returns the UID property of this component if available.
* @return a Uid instance, or null if no UID property exists
*/
public final Uid getUid() {
return (Uid) getProperty(Property.UID);
}
/**
* @param stream
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(final java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
log = LogFactory.getLog(VFreeBusy.class);
}
}
| Use date range where possible to improve code re-use
| source/net/fortuna/ical4j/model/component/VFreeBusy.java | Use date range where possible to improve code re-use |
|
Java | mit | f6dcec03788ee221e5490ad37f5940f6b9c72a85 | 0 | facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.drawee.drawable;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.internal.VisibleForTesting;
import java.util.Arrays;
import javax.annotation.Nullable;
/** Drawable that draws underlying drawable with rounded corners. */
public class RoundedCornersDrawable extends ForwardingDrawable implements Rounded {
public enum Type {
/**
* Draws rounded corners on top of the underlying drawable by overlaying a solid color which is
* specified by {@code setOverlayColor}. This option should only be used when the background
* beneath the underlying drawable is static and of the same solid color.
*/
OVERLAY_COLOR,
/** Clips the drawing of the drawable to be rounded. */
CLIPPING
}
@VisibleForTesting Type mType = Type.OVERLAY_COLOR;
private final RectF mBounds = new RectF();
@Nullable private RectF mInsideBorderBounds;
@Nullable private Matrix mInsideBorderTransform;
private final float[] mRadii = new float[8];
@VisibleForTesting final float[] mBorderRadii = new float[8];
@VisibleForTesting final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean mIsCircle = false;
private float mBorderWidth = 0;
private int mBorderColor = Color.TRANSPARENT;
private int mOverlayColor = Color.TRANSPARENT;
private float mPadding = 0;
private boolean mScaleDownInsideBorders = false;
private boolean mPaintFilterBitmap = false;
private final Path mPath = new Path();
private final Path mBorderPath = new Path();
private final RectF mTempRectangle = new RectF();
/**
* Creates a new RoundedCornersDrawable with given underlying drawable.
*
* @param drawable underlying drawable
*/
public RoundedCornersDrawable(Drawable drawable) {
super(Preconditions.checkNotNull(drawable));
}
/**
* Sets the type of rounding process
*
* @param type type of rounding process
*/
public void setType(Type type) {
mType = type;
updatePath();
invalidateSelf();
}
/**
* Sets whether to round as circle.
*
* @param isCircle whether or not to round as circle
*/
@Override
public void setCircle(boolean isCircle) {
mIsCircle = isCircle;
updatePath();
invalidateSelf();
}
/** Returns whether or not this drawable rounds as circle. */
@Override
public boolean isCircle() {
return mIsCircle;
}
/**
* Sets radius to be used for rounding
*
* @param radius corner radius in pixels
*/
@Override
public void setRadius(float radius) {
Arrays.fill(mRadii, radius);
updatePath();
invalidateSelf();
}
/**
* Sets radii values to be used for rounding. Each corner receive two radius values [X, Y]. The
* corners are ordered top-left, top-right, bottom-right, bottom-left
*
* @param radii Array of 8 values, 4 pairs of [X,Y] radii
*/
@Override
public void setRadii(float[] radii) {
if (radii == null) {
Arrays.fill(mRadii, 0);
} else {
Preconditions.checkArgument(radii.length == 8, "radii should have exactly 8 values");
System.arraycopy(radii, 0, mRadii, 0, 8);
}
updatePath();
invalidateSelf();
}
/** Gets the radii. */
@Override
public float[] getRadii() {
return mRadii;
}
/**
* Sets the overlay color for corner type {@link Type#OVERLAY_COLOR}
*
* @param overlayColor the color to filled outside the rounded corners
*/
public void setOverlayColor(int overlayColor) {
mOverlayColor = overlayColor;
invalidateSelf();
}
/** Gets the overlay color. */
public int getOverlayColor() {
return mOverlayColor;
}
/**
* Sets the border
*
* @param color of the border
* @param width of the border
*/
@Override
public void setBorder(int color, float width) {
mBorderColor = color;
mBorderWidth = width;
updatePath();
invalidateSelf();
}
/** Gets the border color. */
@Override
public int getBorderColor() {
return mBorderColor;
}
/** Gets the border width. */
@Override
public float getBorderWidth() {
return mBorderWidth;
}
@Override
public void setPadding(float padding) {
mPadding = padding;
updatePath();
invalidateSelf();
}
/** Gets the padding. */
@Override
public float getPadding() {
return mPadding;
}
/**
* Sets whether image should be scaled down inside borders.
*
* @param scaleDownInsideBorders
*/
@Override
public void setScaleDownInsideBorders(boolean scaleDownInsideBorders) {
mScaleDownInsideBorders = scaleDownInsideBorders;
updatePath();
invalidateSelf();
}
/** Gets whether image should be scaled down inside borders. */
@Override
public boolean getScaleDownInsideBorders() {
return mScaleDownInsideBorders;
}
/**
* Sets FILTER_BITMAP_FLAG flag to Paint. {@link android.graphics.Paint#FILTER_BITMAP_FLAG}
*
* <p>This should generally be on when drawing bitmaps, unless performance-bound (rendering to
* software canvas) or preferring pixelation artifacts to blurriness when scaling significantly.
*
* @param paintFilterBitmap whether to set FILTER_BITMAP_FLAG flag to Paint.
*/
@Override
public void setPaintFilterBitmap(boolean paintFilterBitmap) {
if (mPaintFilterBitmap != paintFilterBitmap) {
mPaintFilterBitmap = paintFilterBitmap;
invalidateSelf();
}
}
/** Gets whether to set FILTER_BITMAP_FLAG flag to Paint. */
@Override
public boolean getPaintFilterBitmap() {
return mPaintFilterBitmap;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
updatePath();
}
private void updatePath() {
mPath.reset();
mBorderPath.reset();
mTempRectangle.set(getBounds());
mTempRectangle.inset(mPadding, mPadding);
if (mType == Type.OVERLAY_COLOR) {
mPath.addRect(mTempRectangle, Path.Direction.CW);
}
if (mIsCircle) {
mPath.addCircle(
mTempRectangle.centerX(),
mTempRectangle.centerY(),
Math.min(mTempRectangle.width(), mTempRectangle.height()) / 2,
Path.Direction.CW);
} else {
mPath.addRoundRect(mTempRectangle, mRadii, Path.Direction.CW);
}
mTempRectangle.inset(-mPadding, -mPadding);
mTempRectangle.inset(mBorderWidth / 2, mBorderWidth / 2);
if (mIsCircle) {
float radius = Math.min(mTempRectangle.width(), mTempRectangle.height()) / 2;
mBorderPath.addCircle(
mTempRectangle.centerX(), mTempRectangle.centerY(), radius, Path.Direction.CW);
} else {
for (int i = 0; i < mBorderRadii.length; i++) {
mBorderRadii[i] = mRadii[i] + mPadding - mBorderWidth / 2;
}
mBorderPath.addRoundRect(mTempRectangle, mBorderRadii, Path.Direction.CW);
}
mTempRectangle.inset(-mBorderWidth / 2, -mBorderWidth / 2);
}
@Override
public void draw(Canvas canvas) {
mBounds.set(getBounds());
switch (mType) {
case CLIPPING:
int saveCount = canvas.save();
canvas.clipPath(mPath);
super.draw(canvas);
canvas.restoreToCount(saveCount);
break;
case OVERLAY_COLOR:
if (mScaleDownInsideBorders) {
if (mInsideBorderBounds == null) {
mInsideBorderBounds = new RectF(mBounds);
mInsideBorderTransform = new Matrix();
} else {
mInsideBorderBounds.set(mBounds);
}
mInsideBorderBounds.inset(mBorderWidth, mBorderWidth);
mInsideBorderTransform.setRectToRect(
mBounds, mInsideBorderBounds, Matrix.ScaleToFit.FILL);
saveCount = canvas.save();
canvas.clipRect(mBounds);
canvas.concat(mInsideBorderTransform);
super.draw(canvas);
canvas.restoreToCount(saveCount);
} else {
super.draw(canvas);
}
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mOverlayColor);
mPaint.setStrokeWidth(0f);
mPaint.setFilterBitmap(getPaintFilterBitmap());
mPath.setFillType(Path.FillType.EVEN_ODD);
canvas.drawPath(mPath, mPaint);
if (mIsCircle) {
// INVERSE_EVEN_ODD will only draw inverse circle within its bounding box, so we need to
// fill the rest manually if the bounds are not square.
float paddingH = (mBounds.width() - mBounds.height() + mBorderWidth) / 2f;
float paddingV = (mBounds.height() - mBounds.width() + mBorderWidth) / 2f;
if (paddingH > 0) {
canvas.drawRect(
mBounds.left, mBounds.top, mBounds.left + paddingH, mBounds.bottom, mPaint);
canvas.drawRect(
mBounds.right - paddingH, mBounds.top, mBounds.right, mBounds.bottom, mPaint);
}
if (paddingV > 0) {
canvas.drawRect(
mBounds.left, mBounds.top, mBounds.right, mBounds.top + paddingV, mPaint);
canvas.drawRect(
mBounds.left, mBounds.bottom - paddingV, mBounds.right, mBounds.bottom, mPaint);
}
}
break;
}
if (mBorderColor != Color.TRANSPARENT) {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(mBorderColor);
mPaint.setStrokeWidth(mBorderWidth);
mPath.setFillType(Path.FillType.EVEN_ODD);
canvas.drawPath(mBorderPath, mPaint);
}
}
}
| drawee/src/main/java/com/facebook/drawee/drawable/RoundedCornersDrawable.java | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.drawee.drawable;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.internal.VisibleForTesting;
import java.util.Arrays;
import javax.annotation.Nullable;
/** Drawable that draws underlying drawable with rounded corners. */
public class RoundedCornersDrawable extends ForwardingDrawable implements Rounded {
public enum Type {
/**
* Draws rounded corners on top of the underlying drawable by overlaying a solid color which is
* specified by {@code setOverlayColor}. This option should only be used when the background
* beneath the underlying drawable is static and of the same solid color.
*/
OVERLAY_COLOR,
/**
* Clips the drawable to be rounded. This option is not supported right now but is expected to
* be made available in the future.
*/
CLIPPING
}
@VisibleForTesting Type mType = Type.OVERLAY_COLOR;
private final RectF mBounds = new RectF();
@Nullable private RectF mInsideBorderBounds;
@Nullable private Matrix mInsideBorderTransform;
private final float[] mRadii = new float[8];
@VisibleForTesting final float[] mBorderRadii = new float[8];
@VisibleForTesting final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean mIsCircle = false;
private float mBorderWidth = 0;
private int mBorderColor = Color.TRANSPARENT;
private int mOverlayColor = Color.TRANSPARENT;
private float mPadding = 0;
private boolean mScaleDownInsideBorders = false;
private boolean mPaintFilterBitmap = false;
private final Path mPath = new Path();
private final Path mBorderPath = new Path();
private final RectF mTempRectangle = new RectF();
/**
* Creates a new RoundedCornersDrawable with given underlying drawable.
*
* @param drawable underlying drawable
*/
public RoundedCornersDrawable(Drawable drawable) {
super(Preconditions.checkNotNull(drawable));
}
/**
* Sets the type of rounding process
*
* @param type type of rounding process
*/
public void setType(Type type) {
mType = type;
invalidateSelf();
}
/**
* Sets whether to round as circle.
*
* @param isCircle whether or not to round as circle
*/
@Override
public void setCircle(boolean isCircle) {
mIsCircle = isCircle;
updatePath();
invalidateSelf();
}
/** Returns whether or not this drawable rounds as circle. */
@Override
public boolean isCircle() {
return mIsCircle;
}
/**
* Sets radius to be used for rounding
*
* @param radius corner radius in pixels
*/
@Override
public void setRadius(float radius) {
Arrays.fill(mRadii, radius);
updatePath();
invalidateSelf();
}
/**
* Sets radii values to be used for rounding. Each corner receive two radius values [X, Y]. The
* corners are ordered top-left, top-right, bottom-right, bottom-left
*
* @param radii Array of 8 values, 4 pairs of [X,Y] radii
*/
@Override
public void setRadii(float[] radii) {
if (radii == null) {
Arrays.fill(mRadii, 0);
} else {
Preconditions.checkArgument(radii.length == 8, "radii should have exactly 8 values");
System.arraycopy(radii, 0, mRadii, 0, 8);
}
updatePath();
invalidateSelf();
}
/** Gets the radii. */
@Override
public float[] getRadii() {
return mRadii;
}
/**
* Sets the overlay color.
*
* @param overlayColor the color to filled outside the rounded corners
*/
public void setOverlayColor(int overlayColor) {
mOverlayColor = overlayColor;
invalidateSelf();
}
/** Gets the overlay color. */
public int getOverlayColor() {
return mOverlayColor;
}
/**
* Sets the border
*
* @param color of the border
* @param width of the border
*/
@Override
public void setBorder(int color, float width) {
mBorderColor = color;
mBorderWidth = width;
updatePath();
invalidateSelf();
}
/** Gets the border color. */
@Override
public int getBorderColor() {
return mBorderColor;
}
/** Gets the border width. */
@Override
public float getBorderWidth() {
return mBorderWidth;
}
@Override
public void setPadding(float padding) {
mPadding = padding;
updatePath();
invalidateSelf();
}
/** Gets the padding. */
@Override
public float getPadding() {
return mPadding;
}
/**
* Sets whether image should be scaled down inside borders.
*
* @param scaleDownInsideBorders
*/
@Override
public void setScaleDownInsideBorders(boolean scaleDownInsideBorders) {
mScaleDownInsideBorders = scaleDownInsideBorders;
updatePath();
invalidateSelf();
}
/** Gets whether image should be scaled down inside borders. */
@Override
public boolean getScaleDownInsideBorders() {
return mScaleDownInsideBorders;
}
/**
* Sets FILTER_BITMAP_FLAG flag to Paint. {@link android.graphics.Paint#FILTER_BITMAP_FLAG}
*
* <p>This should generally be on when drawing bitmaps, unless performance-bound (rendering to
* software canvas) or preferring pixelation artifacts to blurriness when scaling significantly.
*
* @param paintFilterBitmap whether to set FILTER_BITMAP_FLAG flag to Paint.
*/
@Override
public void setPaintFilterBitmap(boolean paintFilterBitmap) {
if (mPaintFilterBitmap != paintFilterBitmap) {
mPaintFilterBitmap = paintFilterBitmap;
invalidateSelf();
}
}
/** Gets whether to set FILTER_BITMAP_FLAG flag to Paint. */
@Override
public boolean getPaintFilterBitmap() {
return mPaintFilterBitmap;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
updatePath();
}
private void updatePath() {
mPath.reset();
mBorderPath.reset();
mTempRectangle.set(getBounds());
mTempRectangle.inset(mPadding, mPadding);
mPath.addRect(mTempRectangle, Path.Direction.CW);
if (mIsCircle) {
mPath.addCircle(
mTempRectangle.centerX(),
mTempRectangle.centerY(),
Math.min(mTempRectangle.width(), mTempRectangle.height()) / 2,
Path.Direction.CW);
} else {
mPath.addRoundRect(mTempRectangle, mRadii, Path.Direction.CW);
}
mTempRectangle.inset(-mPadding, -mPadding);
mTempRectangle.inset(mBorderWidth / 2, mBorderWidth / 2);
if (mIsCircle) {
float radius = Math.min(mTempRectangle.width(), mTempRectangle.height()) / 2;
mBorderPath.addCircle(
mTempRectangle.centerX(), mTempRectangle.centerY(), radius, Path.Direction.CW);
} else {
for (int i = 0; i < mBorderRadii.length; i++) {
mBorderRadii[i] = mRadii[i] + mPadding - mBorderWidth / 2;
}
mBorderPath.addRoundRect(mTempRectangle, mBorderRadii, Path.Direction.CW);
}
mTempRectangle.inset(-mBorderWidth / 2, -mBorderWidth / 2);
}
@Override
public void draw(Canvas canvas) {
mBounds.set(getBounds());
switch (mType) {
case CLIPPING:
int saveCount = canvas.save();
// clip, note: doesn't support anti-aliasing
mPath.setFillType(Path.FillType.EVEN_ODD);
canvas.clipPath(mPath);
super.draw(canvas);
canvas.restoreToCount(saveCount);
break;
case OVERLAY_COLOR:
if (mScaleDownInsideBorders) {
if (mInsideBorderBounds == null) {
mInsideBorderBounds = new RectF(mBounds);
mInsideBorderTransform = new Matrix();
} else {
mInsideBorderBounds.set(mBounds);
}
mInsideBorderBounds.inset(mBorderWidth, mBorderWidth);
mInsideBorderTransform.setRectToRect(
mBounds, mInsideBorderBounds, Matrix.ScaleToFit.FILL);
saveCount = canvas.save();
canvas.clipRect(mBounds);
canvas.concat(mInsideBorderTransform);
super.draw(canvas);
canvas.restoreToCount(saveCount);
} else {
super.draw(canvas);
}
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mOverlayColor);
mPaint.setStrokeWidth(0f);
mPaint.setFilterBitmap(getPaintFilterBitmap());
mPath.setFillType(Path.FillType.EVEN_ODD);
canvas.drawPath(mPath, mPaint);
if (mIsCircle) {
// INVERSE_EVEN_ODD will only draw inverse circle within its bounding box, so we need to
// fill the rest manually if the bounds are not square.
float paddingH = (mBounds.width() - mBounds.height() + mBorderWidth) / 2f;
float paddingV = (mBounds.height() - mBounds.width() + mBorderWidth) / 2f;
if (paddingH > 0) {
canvas.drawRect(
mBounds.left, mBounds.top, mBounds.left + paddingH, mBounds.bottom, mPaint);
canvas.drawRect(
mBounds.right - paddingH, mBounds.top, mBounds.right, mBounds.bottom, mPaint);
}
if (paddingV > 0) {
canvas.drawRect(
mBounds.left, mBounds.top, mBounds.right, mBounds.top + paddingV, mPaint);
canvas.drawRect(
mBounds.left, mBounds.bottom - paddingV, mBounds.right, mBounds.bottom, mPaint);
}
}
break;
}
if (mBorderColor != Color.TRANSPARENT) {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(mBorderColor);
mPaint.setStrokeWidth(mBorderWidth);
mPath.setFillType(Path.FillType.EVEN_ODD);
canvas.drawPath(mBorderPath, mPaint);
}
}
}
| Finish implementing "Clipping" in RoundedCornersDrawable
Reviewed By: oprisnik
Differential Revision: D17890039
fbshipit-source-id: cfb684efb7e5d929d0a2caf355c0ba0e09abaa40
| drawee/src/main/java/com/facebook/drawee/drawable/RoundedCornersDrawable.java | Finish implementing "Clipping" in RoundedCornersDrawable |
|
Java | mit | 45fd43a7f5bd329b054de0fbe080364a17600794 | 0 | KamranMackey/CommandHelper,Techcable/CommandHelper,Techcable/CommandHelper,sk89q/CommandHelper,KamranMackey/CommandHelper,dbuxo/CommandHelper,KamranMackey/CommandHelper,dbuxo/CommandHelper,sk89q/CommandHelper,dbuxo/CommandHelper,Techcable/CommandHelper,Techcable/CommandHelper,dbuxo/CommandHelper,sk89q/CommandHelper,sk89q/CommandHelper | package com.laytonsmith.PureUtilities;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Layton
*/
public class ReflectionUtils {
private ReflectionUtils() {
}
public static class ReflectionException extends RuntimeException {
public ReflectionException(Throwable cause) {
super(cause);
}
/**
* Returns the underlying checked exception that was thrown by the
* reflective operation.
*
* @return
*/
@Override
public Throwable getCause() {
return super.getCause();
}
}
/**
* Constructs a new instance of the specified object, assuming it has a no
* arg constructor. It will bypass access restrictions if possible.
*
* @param <T> The class type returned, specified by the class type requested
* @param clazz
* @return
* @throws com.laytonsmith.PureUtilities.ReflectionUtils.ReflectionException
*/
public static <T> T newInstance(Class<T> clazz) throws ReflectionException {
return newInstance(clazz, new Class[]{}, new Object[]{});
}
/**
* Constructs a new instance of the specified object, using the constructor
* that matches the argument types, and passes in the arguments specified.
* It will bypass access restrictions if possible.
*
* @param <T> The class type returned, specified by the class type requested
* @param clazz
* @param argTypes
* @param args
* @return
* @throws com.laytonsmith.PureUtilities.ReflectionUtils.ReflectionException
*/
public static <T> T newInstance(Class<T> clazz, Class[] argTypes, Object[] args) throws ReflectionException {
try {
Constructor<T> c = clazz.getDeclaredConstructor(argTypes);
c.setAccessible(true);
return c.newInstance(args);
} catch (InstantiationException ex) {
throw new ReflectionException(ex);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (InvocationTargetException ex) {
throw new ReflectionException(ex);
} catch (NoSuchMethodException ex) {
throw new ReflectionException(ex);
} catch (SecurityException ex) {
throw new ReflectionException(ex);
}
}
/**
* Gets the value from a static class member, disregarding the access
* restrictions.
*
* @param clazz
* @param variableName
* @return
*/
public static Object get(Class clazz, String variableName) throws ReflectionException {
return get(clazz, null, variableName);
}
/**
* Gets a member from a class, disregarding the access restrictions. If
* accessing a static variable, the instance may be null. If variableName
* contains a dot, then it recursively digs down and grabs that value. So,
* given the following class definitions:
* <pre>
* class A { B bObj; }
* class B { C cObj; }
* class C { String obj; }
* </pre> Then if clazz were A.class, and variableName were "bObj.cObj.obj",
* then C's String obj would be returned.
*
* @param clazz
* @param instance
* @param variableName
* @return
*/
public static Object get(Class clazz, Object instance, String variableName) throws ReflectionException {
try {
if (variableName.contains(".")) {
String split[] = variableName.split("\\.");
Object myInstance = instance;
Class myClazz = clazz;
for (String var : split) {
myInstance = get(myClazz, myInstance, var);
myClazz = myInstance.getClass();
}
return myInstance;
} else {
Field f = clazz.getDeclaredField(variableName);
f.setAccessible(true);
return f.get(instance);
}
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (NoSuchFieldException ex) {
throw new ReflectionException(ex);
} catch (SecurityException ex) {
throw new ReflectionException(ex);
}
}
/**
* Sets the value of a member in a static class, disregarding access
* restrictions and the final modifier.
*
* @param clazz
* @param variableName
* @param value
*/
public static void set(Class clazz, String variableName, Object value) throws ReflectionException {
set(clazz, null, variableName, value);
}
/**
* Sets the value of a member in a specific instance of an object,
* disregarding access restrictions and the final modifier.
*
* @param clazz
* @param instance
* @param variableName
* @param value
*/
public static void set(Class clazz, Object instance, String variableName, Object value) throws ReflectionException {
try {
if (variableName.contains(".")) {
String split[] = variableName.split("\\.");
Object myInstance = instance;
Class myClazz = clazz;
int count = 0;
for (String var : split) {
if (count == split.length - 1) {
//Only the last one needs to be set
break;
}
myInstance = get(myClazz, myInstance, var);
myClazz = myInstance.getClass();
count++;
}
set(myClazz, myInstance, split[split.length - 1], value);
} else {
Field f = clazz.getDeclaredField(variableName);
f.setAccessible(true);
//This is the really evil stuff here, this is what removes the final modifier.
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.set(instance, value);
}
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (NoSuchFieldException ex) {
throw new ReflectionException(ex);
} catch (SecurityException ex) {
throw new ReflectionException(ex);
}
}
/**
* Invokes a no argument method, disregarding access restrictions, and
* returns the result.
*
* @param clazz
* @param instance
* @param methodName
* @return
*/
public static Object invokeMethod(Class clazz, Object instance, String methodName) throws ReflectionException {
return invokeMethod(clazz, instance, methodName, new Class[]{}, new Object[]{});
}
/**
* Grabs the method from the instance object automatically. If multiple
* methods match the given name, the most appropriate one is selected based
* on the argument types. {@code instance} may not be null.
*
* @param instance
* @param methodName
* @throws com.laytonsmith.PureUtilities.ReflectionUtils.ReflectionException
*/
public static Object invokeMethod(Object instance, String methodName, Object... params) throws ReflectionException {
Class c = instance.getClass();
Class[] argTypes;
{
List<Class> cl = new ArrayList<Class>();
for (Object o : params) {
if (o != null) {
cl.add(o.getClass());
} else {
//If it's null, we'll just have to assume Object
cl.add(Object.class);
}
}
argTypes = cl.toArray(new Class[cl.size()]);
}
while (c != null) {
method:
for (Method m : c.getDeclaredMethods()) {
if (methodName.equals(m.getName())) {
try {
if (m.getParameterTypes().length == argTypes.length) {
Class[] args = m.getParameterTypes();
//Check to see that these arguments are subclasses
//of the method's parameters. If so, this is our method,
//otherwise, not.
for (int i = 0; i < argTypes.length; i++) {
if (!args[i].isAssignableFrom(argTypes[i])) {
continue method;
}
}
return m.invoke(instance, params);
}
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (InvocationTargetException ex) {
throw new ReflectionException(ex);
}
}
}
c = c.getSuperclass();
}
throw new ReflectionException(new NoSuchMethodException(methodName + " was not found in any of the searched classes."));
}
/**
* Grabs the method from the instance object automatically. {@code instance}
* may not be null.
*
* @param instance
* @param methodName
* @throws com.laytonsmith.PureUtilities.ReflectionUtils.ReflectionException
*/
public static Object invokeMethod(Object instance, String methodName) throws ReflectionException {
Class c = instance.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (methodName.equals(m.getName())) {
try {
return m.invoke(instance);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (InvocationTargetException ex) {
throw new ReflectionException(ex);
}
}
}
c = c.getSuperclass();
}
throw new ReflectionException(new NoSuchMethodException(methodName + " was not found in any of the searched classes."));
}
/**
* Invokes a method with the parameters specified, disregarding access
* restrictions, and returns the result.
*
* @param clazz
* @param instance
* @param methodName
* @param argTypes
* @param args
* @return
*/
public static Object invokeMethod(Class clazz, Object instance, String methodName, Class[] argTypes, Object[] args) throws ReflectionException {
try {
Method m = clazz.getDeclaredMethod(methodName, argTypes);
m.setAccessible(true);
return m.invoke(instance, args);
} catch (InvocationTargetException ex) {
throw new ReflectionException(ex);
} catch (NoSuchMethodException ex) {
throw new ReflectionException(ex);
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (SecurityException ex) {
throw new ReflectionException(ex);
}
}
/**
* Shorthand for {@link #PrintObjectTrace(instance, instanceOnly, null)}
*/
public static void PrintObjectTrace(Object instance, boolean instanceOnly) {
PrintObjectTrace(instance, instanceOnly, null);
}
/**
* Meant mostly as a debug tool, takes an object and prints out the object's
* non-static field information at this current point in time, to the
* specified PrintStream. This method will not throw any SecurityExceptions
* if a value cannot be reflectively accessed, but instead will print an
* error message for that single value.
*
* @param instance The object to explore. If this is null, "The object is
* null" is printed, and the method exits.
* @param instanceOnly If true, only the object's class members will be
* printed, otherwise, the method will recurse up the object's inheritance
* hierarchy, and prints everything.
* @param output The print stream to output to, or System.out if null.
*/
public static void PrintObjectTrace(Object instance, boolean instanceOnly, PrintStream output) {
if (output == null) {
output = System.out;
}
if (instance == null) {
output.println("The object is null");
return;
}
Class iClass = instance.getClass();
do {
for (Field f : iClass.getDeclaredFields()) {
if ((f.getModifiers() & Modifier.STATIC) > 0) {
continue;
}
String value = "null";
try {
f.setAccessible(true);
Object o = ReflectionUtils.get(iClass, instance, f.getName());
if (o != null) {
value = o.toString();
}
} catch (SecurityException e) {
value = "Could not access value due to a SecurityException";
}
output.println("(" + f.getType() + ") " + f.getName() + ": " + value);
}
} while (!instanceOnly && (iClass = iClass.getSuperclass()) != null);
}
}
| src/main/java/com/laytonsmith/PureUtilities/ReflectionUtils.java |
package com.laytonsmith.PureUtilities;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Layton
*/
public class ReflectionUtils {
private ReflectionUtils() {
}
public static class ReflectionException extends RuntimeException {
public ReflectionException(Throwable cause) {
super(cause);
}
/**
* Returns the underlying checked exception that was thrown
* by the reflective operation.
* @return
*/
@Override
public Throwable getCause(){
return super.getCause();
}
}
/**
* Constructs a new instance of the specified object, assuming it has a no
* arg constructor. It will bypass access restrictions if possible.
*
* @param <T> The class type returned, specified by the class type requested
* @param clazz
* @return
* @throws com.laytonsmith.PureUtilities.ReflectionUtils.ReflectionException
*/
public static <T> T newInstance(Class<T> clazz) throws ReflectionException {
return newInstance(clazz, new Class[]{}, new Object[]{});
}
/**
* Constructs a new instance of the specified object, using the constructor
* that matches the argument types, and passes in the arguments specified.
* It will bypass access restrictions if possible.
*
* @param <T> The class type returned, specified by the class type requested
* @param clazz
* @param argTypes
* @param args
* @return
* @throws com.laytonsmith.PureUtilities.ReflectionUtils.ReflectionException
*/
public static <T> T newInstance(Class<T> clazz, Class[] argTypes, Object[] args) throws ReflectionException {
try {
Constructor<T> c = clazz.getDeclaredConstructor(argTypes);
c.setAccessible(true);
return c.newInstance(args);
} catch (InstantiationException ex) {
throw new ReflectionException(ex);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (InvocationTargetException ex) {
throw new ReflectionException(ex);
} catch (NoSuchMethodException ex) {
throw new ReflectionException(ex);
} catch (SecurityException ex) {
throw new ReflectionException(ex);
}
}
/**
* Gets the value from a static class member, disregarding the access
* restrictions.
*
* @param clazz
* @param variableName
* @return
*/
public static Object get(Class clazz, String variableName) throws ReflectionException {
return get(clazz, null, variableName);
}
/**
* Gets a member from a class, disregarding the access restrictions. If
* accessing a static variable, the instance may be null. If variableName
* contains a dot, then it recursively digs down and grabs that value.
* So, given the following class definitions:
* <pre>
* class A { B bObj; }
* class B { C cObj; }
* class C { String obj; }
* </pre>
* Then if clazz were A.class, and variableName were "bObj.cObj.obj", then
* C's String obj would be returned.
*
* @param clazz
* @param instance
* @param variableName
* @return
*/
public static Object get(Class clazz, Object instance, String variableName) throws ReflectionException {
try {
if(variableName.contains(".")){
String split [] = variableName.split("\\.");
Object myInstance = instance;
Class myClazz = clazz;
for(String var : split){
myInstance = get(myClazz, myInstance, var);
myClazz = myInstance.getClass();
}
return myInstance;
} else {
Field f = clazz.getDeclaredField(variableName);
f.setAccessible(true);
return f.get(instance);
}
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (NoSuchFieldException ex) {
throw new ReflectionException(ex);
} catch (SecurityException ex) {
throw new ReflectionException(ex);
}
}
/**
* Sets the value of a member in a static class, disregarding access restrictions
* and the final modifier.
* @param clazz
* @param variableName
* @param value
*/
public static void set(Class clazz, String variableName, Object value) throws ReflectionException{
set(clazz, null, variableName, value);
}
/**
* Sets the value of a member in a specific instance of an object, disregarding access
* restrictions and the final modifier.
* @param clazz
* @param instance
* @param variableName
* @param value
*/
public static void set(Class clazz, Object instance, String variableName, Object value) throws ReflectionException {
try {
if(variableName.contains(".")){
String split [] = variableName.split("\\.");
Object myInstance = instance;
Class myClazz = clazz;
int count = 0;
for(String var : split){
if(count == split.length - 1){
//Only the last one needs to be set
break;
}
myInstance = get(myClazz, myInstance, var);
myClazz = myInstance.getClass();
count++;
}
set(myClazz, myInstance, split[split.length - 1], value);
} else {
Field f = clazz.getDeclaredField(variableName);
f.setAccessible(true);
//This is the really evil stuff here, this is what removes the final modifier.
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.set(instance, value);
}
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (NoSuchFieldException ex) {
throw new ReflectionException(ex);
} catch (SecurityException ex) {
throw new ReflectionException(ex);
}
}
/**
* Invokes a no argument method, disregarding access restrictions, and returns the
* result.
* @param clazz
* @param instance
* @param methodName
* @return
*/
public static Object invokeMethod(Class clazz, Object instance, String methodName) throws ReflectionException {
return invokeMethod(clazz, instance, methodName, new Class[]{}, new Object[]{});
}
/**
* Grabs the method from the instance object automatically. If multiple methods match the given name,
* the most appropriate one is selected based on the argument types. {@code instance} may not be null.
* @param instance
* @param methodName
* @throws com.laytonsmith.PureUtilities.ReflectionUtils.ReflectionException
*/
public static Object invokeMethod(Object instance, String methodName, Object ... params) throws ReflectionException{
Class c = instance.getClass();
Class [] argTypes;
{
List<Class> cl = new ArrayList<Class>();
for(Object o : params){
if(o != null){
cl.add(o.getClass());
} else {
//If it's null, we'll just have to assume Object
cl.add(Object.class);
}
}
argTypes = cl.toArray(new Class[cl.size()]);
}
while(c != null){
method: for(Method m : c.getDeclaredMethods()){
if(methodName.equals(m.getName())){
try {
if(m.getParameterTypes().length == argTypes.length){
Class [] args = m.getParameterTypes();
//Check to see that these arguments are subclasses
//of the method's parameters. If so, this is our method,
//otherwise, not.
for(int i = 0; i < argTypes.length; i++){
if(!args[i].isAssignableFrom(argTypes[i])){
continue method;
}
}
return m.invoke(instance, params);
}
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (InvocationTargetException ex) {
throw new ReflectionException(ex);
}
}
}
c = c.getSuperclass();
}
throw new ReflectionException(new NoSuchMethodException(methodName + " was not found in any of the searched classes."));
}
/**
* Grabs the method from the instance object automatically. {@code instance} may not be null.
* @param instance
* @param methodName
* @throws com.laytonsmith.PureUtilities.ReflectionUtils.ReflectionException
*/
public static Object invokeMethod(Object instance, String methodName) throws ReflectionException{
Class c = instance.getClass();
while(c != null){
for(Method m : c.getDeclaredMethods()){
if(methodName.equals(m.getName())){
try {
return m.invoke(instance);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (InvocationTargetException ex) {
throw new ReflectionException(ex);
}
}
}
c = c.getSuperclass();
}
throw new ReflectionException(new NoSuchMethodException(methodName + " was not found in any of the searched classes."));
}
/**
* Invokes a method with the parameters specified, disregarding access restrictions,
* and returns the result.
* @param clazz
* @param instance
* @param methodName
* @param argTypes
* @param args
* @return
*/
public static Object invokeMethod(Class clazz, Object instance, String methodName, Class[] argTypes, Object[] args) throws ReflectionException {
try {
Method m = clazz.getDeclaredMethod(methodName, argTypes);
m.setAccessible(true);
return m.invoke(instance, args);
} catch(InvocationTargetException ex){
throw new ReflectionException(ex);
} catch(NoSuchMethodException ex){
throw new ReflectionException(ex);
} catch (IllegalArgumentException ex) {
throw new ReflectionException(ex);
} catch (IllegalAccessException ex) {
throw new ReflectionException(ex);
} catch (SecurityException ex) {
throw new ReflectionException(ex);
}
}
}
| Added a debugging method to ReflectionUtils. | src/main/java/com/laytonsmith/PureUtilities/ReflectionUtils.java | Added a debugging method to ReflectionUtils. |
|
Java | mit | d52beae6d39a7a4080b66a620a8878723aff20ab | 0 | elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin | package com.elmakers.mine.bukkit.protection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredListener;
import com.elmakers.mine.bukkit.api.protection.BlockBreakManager;
import com.elmakers.mine.bukkit.api.protection.BlockBuildManager;
public class ProtectionManager implements BlockBreakManager, BlockBuildManager {
private Plugin owningPlugin;
private final Set<Plugin> plugins = new HashSet<>();
private final List<String> pluginNames = new ArrayList<>();
private boolean checkedListeners;
private final List<RegisteredListener> breakListeners = new ArrayList<>();
private final List<RegisteredListener> buildListeners = new ArrayList<>();
public boolean isEnabled() {
return plugins.size() > 0;
}
public void initialize(Plugin owner, List<String> pluginNames) {
owningPlugin = owner;
plugins.clear();
checkedListeners = false;
this.pluginNames.clear();
this.pluginNames.addAll(pluginNames);
}
public void check() {
for (String pluginName : pluginNames) {
Plugin plugin = owningPlugin.getServer().getPluginManager().getPlugin(pluginName);
if (plugin != null) {
plugins.add(plugin);
owningPlugin.getLogger().info("Integrating with " + pluginName + " using fake break/build events");
}
}
}
private void checkListeners() {
if (checkedListeners) return;
checkBreakListeners();
checkBuildListeners();
checkedListeners = true;
}
private void checkBreakListeners() {
breakListeners.clear();
HandlerList handlers = BlockBreakEvent.getHandlerList();
for (RegisteredListener listener : handlers.getRegisteredListeners()) {
if (plugins.contains(listener.getPlugin())) {
breakListeners.add(listener);
}
}
}
private void checkBuildListeners() {
buildListeners.clear();
HandlerList handlers = BlockPlaceEvent.getHandlerList();
for (RegisteredListener listener : handlers.getRegisteredListeners()) {
if (plugins.contains(listener.getPlugin())) {
buildListeners.add(listener);
}
}
}
@Override
public boolean hasBuildPermission(Player player, Block block) {
if (player == null || block == null) return true;
checkListeners();
BlockPlaceEvent placeEvent = new BlockPlaceEvent(block, block.getState(), block.getRelative(BlockFace.DOWN), player.getInventory().getItemInMainHand(), player, true, EquipmentSlot.HAND);
for (RegisteredListener listener : buildListeners) {
try {
listener.callEvent(placeEvent);
if (placeEvent.isCancelled()) {
return false;
}
} catch (Exception ex) {
owningPlugin.getLogger().log(Level.WARNING, "An error occurred sending a BlockPlaceEvent to " + listener.getPlugin().getName(), ex);
}
}
return true;
}
@Override
public boolean hasBreakPermission(Player player, Block block) {
if (player == null || block == null) return true;
checkListeners();
BlockBreakEvent breakEvent = new BlockBreakEvent(block, player);
for (RegisteredListener listener : breakListeners) {
try {
listener.callEvent(breakEvent);
if (breakEvent.isCancelled()) {
return false;
}
} catch (Exception ex) {
owningPlugin.getLogger().log(Level.WARNING, "An error occurred sending a BlockBreakEvent to " + listener.getPlugin().getName(), ex);
}
}
return true;
}
}
| Magic/src/main/java/com/elmakers/mine/bukkit/protection/ProtectionManager.java | package com.elmakers.mine.bukkit.protection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredListener;
import com.elmakers.mine.bukkit.api.protection.BlockBreakManager;
import com.elmakers.mine.bukkit.api.protection.BlockBuildManager;
public class ProtectionManager implements BlockBreakManager, BlockBuildManager {
private Plugin owningPlugin;
private final Set<Plugin> plugins = new HashSet<>();
private final List<String> pluginNames = new ArrayList<>();
private boolean checkedListeners;
private final List<RegisteredListener> breakListeners = new ArrayList<>();
private final List<RegisteredListener> buildListeners = new ArrayList<>();
public boolean isEnabled() {
return plugins.size() > 0;
}
public void initialize(Plugin owner, List<String> pluginNames) {
owningPlugin = owner;
plugins.clear();
checkedListeners = false;
this.pluginNames.clear();
this.pluginNames.addAll(pluginNames);
}
public void check() {
for (String pluginName : pluginNames) {
Plugin plugin = owningPlugin.getServer().getPluginManager().getPlugin(pluginName);
if (plugin != null && plugin.isEnabled()) {
plugins.add(plugin);
owningPlugin.getLogger().info("Integrating with " + pluginName + " using fake break/build events");
}
}
}
private void checkListeners() {
if (checkedListeners) return;
checkBreakListeners();
checkBuildListeners();
checkedListeners = true;
}
private void checkBreakListeners() {
breakListeners.clear();
HandlerList handlers = BlockBreakEvent.getHandlerList();
for (RegisteredListener listener : handlers.getRegisteredListeners()) {
if (plugins.contains(listener.getPlugin())) {
breakListeners.add(listener);
}
}
}
private void checkBuildListeners() {
buildListeners.clear();
HandlerList handlers = BlockPlaceEvent.getHandlerList();
for (RegisteredListener listener : handlers.getRegisteredListeners()) {
if (plugins.contains(listener.getPlugin())) {
buildListeners.add(listener);
}
}
}
@Override
public boolean hasBuildPermission(Player player, Block block) {
if (player == null || block == null) return true;
checkListeners();
BlockPlaceEvent placeEvent = new BlockPlaceEvent(block, block.getState(), block.getRelative(BlockFace.DOWN), player.getInventory().getItemInMainHand(), player, true, EquipmentSlot.HAND);
for (RegisteredListener listener : buildListeners) {
try {
listener.callEvent(placeEvent);
if (placeEvent.isCancelled()) {
return false;
}
} catch (Exception ex) {
owningPlugin.getLogger().log(Level.WARNING, "An error occurred sending a BlockPlaceEvent to " + listener.getPlugin().getName(), ex);
}
}
return true;
}
@Override
public boolean hasBreakPermission(Player player, Block block) {
if (player == null || block == null) return true;
checkListeners();
BlockBreakEvent breakEvent = new BlockBreakEvent(block, player);
for (RegisteredListener listener : breakListeners) {
try {
listener.callEvent(breakEvent);
if (breakEvent.isCancelled()) {
return false;
}
} catch (Exception ex) {
owningPlugin.getLogger().log(Level.WARNING, "An error occurred sending a BlockBreakEvent to " + listener.getPlugin().getName(), ex);
}
}
return true;
}
}
| Don't require generic_protection plugins to be enabled before Magic
| Magic/src/main/java/com/elmakers/mine/bukkit/protection/ProtectionManager.java | Don't require generic_protection plugins to be enabled before Magic |
|
Java | mit | 26515f20d874b5e5440d06de7db035f4fde21306 | 0 | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager | ///////////////////////////////////////////////////////////////////////////////
//FILE: AcquisitionPanel.java
//PROJECT: Micro-Manager
//SUBSYSTEM: ASIdiSPIM plugin
//-----------------------------------------------------------------------------
//
// AUTHOR: Nico Stuurman, Jon Daniels
//
// COPYRIGHT: University of California, San Francisco, & ASI, 2013
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.asidispim;
import org.micromanager.asidispim.Data.AcquisitionModes;
import org.micromanager.asidispim.Data.CameraModes;
import org.micromanager.asidispim.Data.Cameras;
import org.micromanager.asidispim.Data.Devices;
import org.micromanager.asidispim.Data.MultichannelModes;
import org.micromanager.asidispim.Data.MyStrings;
import org.micromanager.asidispim.Data.Positions;
import org.micromanager.asidispim.Data.Prefs;
import org.micromanager.asidispim.Data.Properties;
import org.micromanager.asidispim.Utils.DevicesListenerInterface;
import org.micromanager.asidispim.Utils.ListeningJPanel;
import org.micromanager.asidispim.Utils.MyDialogUtils;
import org.micromanager.asidispim.Utils.MyNumberUtils;
import org.micromanager.asidispim.Utils.PanelUtils;
import org.micromanager.asidispim.Utils.SliceTiming;
import org.micromanager.asidispim.Utils.StagePositionUpdater;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.ParseException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.DefaultFormatter;
import net.miginfocom.swing.MigLayout;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import mmcorej.CMMCore;
import mmcorej.StrVector;
import mmcorej.TaggedImage;
import org.micromanager.api.MultiStagePosition;
import org.micromanager.api.StagePosition;
import org.micromanager.api.PositionList;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.ImageCache;
import org.micromanager.api.MMTags;
import org.micromanager.MMStudio;
import org.micromanager.acquisition.ComponentTitledBorder;
import org.micromanager.acquisition.DefaultTaggedImageSink;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.TaggedImageQueue;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.TaggedImageStorageMultipageTiff;
import org.micromanager.imagedisplay.VirtualAcquisitionDisplay;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMFrame;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
import com.swtdesigner.SwingResourceManager;
import ij.IJ;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import org.micromanager.asidispim.Data.AcquisitionSettings;
import org.micromanager.asidispim.Data.ChannelSpec;
import org.micromanager.asidispim.Data.Devices.Sides;
import org.micromanager.asidispim.Data.Joystick.Directions;
import org.micromanager.asidispim.Utils.ControllerUtils;
import org.micromanager.asidispim.Utils.AutofocusUtils;
import org.micromanager.asidispim.api.ASIdiSPIMException;
/**
*
* @author nico
* @author Jon
*/
@SuppressWarnings("serial")
public class AcquisitionPanel extends ListeningJPanel implements DevicesListenerInterface {
private final Devices devices_;
private final Properties props_;
private final Cameras cameras_;
private final Prefs prefs_;
private final ControllerUtils controller_;
private final AutofocusUtils autofocus_;
private final Positions positions_;
private final CMMCore core_;
private final ScriptInterface gui_;
private final JCheckBox advancedSliceTimingCB_;
private final JSpinner numSlices_;
private final JComboBox numSides_;
private final JComboBox firstSide_;
private final JSpinner numScansPerSlice_;
private final JSpinner lineScanDuration_;
private final JSpinner delayScan_;
private final JSpinner delayLaser_;
private final JSpinner delayCamera_;
private final JSpinner durationCamera_; // NB: not the same as camera exposure
private final JSpinner exposureCamera_; // NB: only used in advanced timing mode
private JCheckBox alternateBeamScanCB_;
private final JSpinner durationLaser_;
private final JSpinner delaySide_;
private final JLabel actualSlicePeriodLabel_;
private final JLabel actualVolumeDurationLabel_;
private final JLabel actualTimeLapseDurationLabel_;
private final JSpinner numTimepoints_;
private final JSpinner acquisitionInterval_;
private final JToggleButton buttonStart_;
private final JButton buttonTestAcq_;
private final JPanel volPanel_;
private final JPanel slicePanel_;
private final JPanel timepointPanel_;
private final JPanel savePanel_;
private final JPanel durationPanel_;
private final JFormattedTextField rootField_;
private final JFormattedTextField prefixField_;
private final JLabel acquisitionStatusLabel_;
private int numTimePointsDone_;
private final AtomicBoolean cancelAcquisition_ = new AtomicBoolean(false); // true if we should stop acquisition
private final AtomicBoolean acquisitionRequested_ = new AtomicBoolean(false); // true if acquisition has been requested to start or is underway
private final AtomicBoolean acquisitionRunning_ = new AtomicBoolean(false); // true if the acquisition is actually underway
private final StagePositionUpdater posUpdater_;
private final JSpinner stepSize_;
private final JLabel desiredSlicePeriodLabel_;
private final JSpinner desiredSlicePeriod_;
private final JLabel desiredLightExposureLabel_;
private final JSpinner desiredLightExposure_;
private final JCheckBox minSlicePeriodCB_;
private final JCheckBox separateTimePointsCB_;
private final JCheckBox saveCB_;
private final JComboBox spimMode_;
private final JCheckBox navigationJoysticksCB_;
private final JCheckBox usePositionsCB_;
private final JSpinner positionDelay_;
private final JCheckBox useTimepointsCB_;
private final JCheckBox useAutofocusCB_;
private final JPanel leftColumnPanel_;
private final JPanel centerColumnPanel_;
private final JPanel rightColumnPanel_;
private final MMFrame sliceFrameAdvanced_;
private SliceTiming sliceTiming_;
private final MultiChannelSubPanel multiChannelPanel_;
private final Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA,
Color.PINK, Color.CYAN, Color.YELLOW, Color.ORANGE};
private String lastAcquisitionPath_;
private String lastAcquisitionName_;
private MMAcquisition acq_;
private String[] channelNames_;
private int nrRepeats_; // how many separate acquisitions to perform
public AcquisitionPanel(ScriptInterface gui,
Devices devices,
Properties props,
Cameras cameras,
Prefs prefs,
StagePositionUpdater posUpdater,
Positions positions,
ControllerUtils controller,
AutofocusUtils autofocus) {
super(MyStrings.PanelNames.ACQUSITION.toString(),
new MigLayout(
"",
"[center]0[center]0[center]",
"0[top]0"));
gui_ = gui;
devices_ = devices;
props_ = props;
cameras_ = cameras;
prefs_ = prefs;
posUpdater_ = posUpdater;
positions_ = positions;
controller_ = controller;
autofocus_ = autofocus;
core_ = gui_.getMMCore();
numTimePointsDone_ = 0;
sliceTiming_ = new SliceTiming();
lastAcquisitionPath_ = "";
lastAcquisitionName_ = "";
acq_ = null;
channelNames_ = null;
PanelUtils pu = new PanelUtils(prefs_, props_, devices_);
// added to spinner controls where we should re-calculate the displayed
// slice period, volume duration, and time lapse duration
ChangeListener recalculateTimingDisplayCL = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (advancedSliceTimingCB_.isSelected()) {
// need to update sliceTiming_ from property values
sliceTiming_ = getTimingFromAdvancedSettings();
}
updateDurationLabels();
}
};
// added to combobox controls where we should re-calculate the displayed
// slice period, volume duration, and time lapse duration
ActionListener recalculateTimingDisplayAL = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateDurationLabels();
}
};
// start volume (main) sub-panel
volPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"[]8[]"));
volPanel_.setBorder(PanelUtils.makeTitledBorder("Volume Settings"));
if (!ASIdiSPIM.oSPIM) {
} else {
props_.setPropValue(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SIDES, "1");
}
volPanel_.add(new JLabel("Number of sides:"));
String [] str12 = {"1", "2"};
numSides_ = pu.makeDropDownBox(str12, Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SIDES, str12[1]);
numSides_.addActionListener(recalculateTimingDisplayAL);
if (!ASIdiSPIM.oSPIM) {
} else {
numSides_.setEnabled(false);
}
volPanel_.add(numSides_, "wrap");
volPanel_.add(new JLabel("First side:"));
String[] ab = {Devices.Sides.A.toString(), Devices.Sides.B.toString()};
if (!ASIdiSPIM.oSPIM) {
} else {
props_.setPropValue(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString());
}
firstSide_ = pu.makeDropDownBox(ab, Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString());
if (!ASIdiSPIM.oSPIM) {
} else {
firstSide_.setEnabled(false);
}
volPanel_.add(firstSide_, "wrap");
volPanel_.add(new JLabel("Delay before side [ms]:"));
delaySide_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_SIDE, 0);
delaySide_.addChangeListener(recalculateTimingDisplayCL);
volPanel_.add(delaySide_, "wrap");
volPanel_.add(new JLabel("Slices per side:"));
numSlices_ = pu.makeSpinnerInteger(1, 65000,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SLICES, 20);
numSlices_.addChangeListener(recalculateTimingDisplayCL);
volPanel_.add(numSlices_, "wrap");
volPanel_.add(new JLabel("Slice step size [\u00B5m]:"));
stepSize_ = pu.makeSpinnerFloat(0, 100, 0.1,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_SLICE_STEP_SIZE,
1.0);
volPanel_.add(stepSize_, "wrap");
// out of order so we can reference it
desiredSlicePeriod_ = pu.makeSpinnerFloat(1, 1000, 0.25,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_SLICE_PERIOD, 30);
minSlicePeriodCB_ = pu.makeCheckBox("Minimize slice period",
Properties.Keys.PREFS_MINIMIZE_SLICE_PERIOD, panelName_, false);
minSlicePeriodCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean doMin = minSlicePeriodCB_.isSelected();
desiredSlicePeriod_.setEnabled(!doMin);
desiredSlicePeriodLabel_.setEnabled(!doMin);
recalculateSliceTiming(false);
}
});
volPanel_.add(minSlicePeriodCB_, "span 2, wrap");
// special field that is enabled/disabled depending on whether advanced timing is enabled
desiredSlicePeriodLabel_ = new JLabel("Slice period [ms]:");
volPanel_.add(desiredSlicePeriodLabel_);
volPanel_.add(desiredSlicePeriod_, "wrap");
desiredSlicePeriod_.addChangeListener(PanelUtils.coerceToQuarterIntegers(desiredSlicePeriod_));
desiredSlicePeriod_.addChangeListener(recalculateTimingDisplayCL);
// special field that is enabled/disabled depending on whether advanced timing is enabled
desiredLightExposureLabel_ = new JLabel("Sample exposure [ms]:");
volPanel_.add(desiredLightExposureLabel_);
desiredLightExposure_ = pu.makeSpinnerFloat(1.0, 1000, 0.25,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_EXPOSURE, 8.5);
desiredLightExposure_.addChangeListener(PanelUtils.coerceToQuarterIntegers(desiredLightExposure_));
desiredLightExposure_.addChangeListener(recalculateTimingDisplayCL);
volPanel_.add(desiredLightExposure_, "wrap");
// special checkbox to use the advanced timing settings
// action handler added below after defining components it enables/disables
advancedSliceTimingCB_ = pu.makeCheckBox("Use advanced timing settings",
Properties.Keys.PREFS_ADVANCED_SLICE_TIMING, panelName_, false);
volPanel_.add(advancedSliceTimingCB_, "left, span 2, wrap");
// end volume sub-panel
// start advanced slice timing frame
// visibility of this frame is controlled from advancedTiming checkbox
// this frame is separate from main plugin window
sliceFrameAdvanced_ = new MMFrame();
sliceFrameAdvanced_.setTitle("Advanced timing");
sliceFrameAdvanced_.loadPosition(100, 100);
slicePanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"[]8[]"));
sliceFrameAdvanced_.add(slicePanel_);
class SliceFrameAdapter extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
advancedSliceTimingCB_.setSelected(false);
sliceFrameAdvanced_.savePosition();
}
}
sliceFrameAdvanced_.addWindowListener(new SliceFrameAdapter());
JLabel scanDelayLabel = new JLabel("Delay before scan [ms]:");
slicePanel_.add(scanDelayLabel);
delayScan_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_SCAN, 0);
delayScan_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayScan_));
delayScan_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(delayScan_, "wrap");
JLabel lineScanLabel = new JLabel("Lines scans per slice:");
slicePanel_.add(lineScanLabel);
numScansPerSlice_ = pu.makeSpinnerInteger(1, 1000,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_NUM_SCANSPERSLICE, 1);
numScansPerSlice_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(numScansPerSlice_, "wrap");
JLabel lineScanPeriodLabel = new JLabel("Line scan duration [ms]:");
slicePanel_.add(lineScanPeriodLabel);
lineScanDuration_ = pu.makeSpinnerFloat(1, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_SCAN, 10);
lineScanDuration_.addChangeListener(PanelUtils.coerceToQuarterIntegers(lineScanDuration_));
lineScanDuration_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(lineScanDuration_, "wrap");
JLabel delayLaserLabel = new JLabel("Delay before laser [ms]:");
slicePanel_.add(delayLaserLabel);
delayLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_LASER, 0);
delayLaser_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayLaser_));
delayLaser_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(delayLaser_, "wrap");
JLabel durationLabel = new JLabel("Laser trig duration [ms]:");
slicePanel_.add(durationLabel);
durationLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_LASER, 1);
durationLaser_.addChangeListener(PanelUtils.coerceToQuarterIntegers(durationLaser_));
durationLaser_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(durationLaser_, "span 2, wrap");
JLabel delayLabel = new JLabel("Delay before camera [ms]:");
slicePanel_.add(delayLabel);
delayCamera_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_CAMERA, 0);
delayCamera_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayCamera_));
delayCamera_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(delayCamera_, "wrap");
JLabel cameraLabel = new JLabel("Camera trig duration [ms]:");
slicePanel_.add(cameraLabel);
durationCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_CAMERA, 0);
durationCamera_.addChangeListener(PanelUtils.coerceToQuarterIntegers(durationCamera_));
durationCamera_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(durationCamera_, "wrap");
JLabel exposureLabel = new JLabel("Camera exposure [ms]:");
slicePanel_.add(exposureLabel);
exposureCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_ADVANCED_CAMERA_EXPOSURE, 10f);
exposureCamera_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(exposureCamera_, "wrap");
alternateBeamScanCB_ = pu.makeCheckBox("Alternate scan direction",
Properties.Keys.PREFS_SCAN_OPPOSITE_DIRECTIONS, panelName_, false);
slicePanel_.add(alternateBeamScanCB_, "center, span 2, wrap");
final JComponent[] simpleTimingComponents = { desiredLightExposure_,
minSlicePeriodCB_, desiredSlicePeriodLabel_,
desiredLightExposureLabel_};
final JComponent[] advancedTimingComponents = {
delayScan_, numScansPerSlice_, lineScanDuration_,
delayLaser_, durationLaser_, delayCamera_,
durationCamera_, exposureCamera_, alternateBeamScanCB_};
PanelUtils.componentsSetEnabled(advancedTimingComponents, advancedSliceTimingCB_.isSelected());
PanelUtils.componentsSetEnabled(simpleTimingComponents, !advancedSliceTimingCB_.isSelected());
// this action listener takes care of enabling/disabling inputs
// of the advanced slice timing window
// we call this to get GUI looking right
ItemListener sliceTimingDisableGUIInputs = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean enabled = advancedSliceTimingCB_.isSelected();
// set other components in this advanced timing frame
PanelUtils.componentsSetEnabled(advancedTimingComponents, enabled);
// also control some components in main volume settings sub-panel
PanelUtils.componentsSetEnabled(simpleTimingComponents, !enabled);
desiredSlicePeriod_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected());
desiredSlicePeriodLabel_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected());
updateDurationLabels();
}
};
// this action listener shows/hides the advanced timing frame
ActionListener showAdvancedTimingFrame = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean enabled = advancedSliceTimingCB_.isSelected();
if (enabled) {
sliceFrameAdvanced_.setVisible(enabled);
}
}
};
sliceFrameAdvanced_.pack();
sliceFrameAdvanced_.setResizable(false);
// end slice Frame
// start repeat (time lapse) sub-panel
timepointPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"[]8[]"));
useTimepointsCB_ = pu.makeCheckBox("Time points",
Properties.Keys.PREFS_USE_TIMEPOINTS, panelName_, false);
useTimepointsCB_.setToolTipText("Perform a time-lapse acquisition");
useTimepointsCB_.setEnabled(true);
useTimepointsCB_.setFocusPainted(false);
ComponentTitledBorder componentBorder =
new ComponentTitledBorder(useTimepointsCB_, timepointPanel_,
BorderFactory.createLineBorder(ASIdiSPIM.borderColor));
timepointPanel_.setBorder(componentBorder);
ChangeListener recalculateTimeLapseDisplay = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
updateActualTimeLapseDurationLabel();
}
};
useTimepointsCB_.addChangeListener(recalculateTimeLapseDisplay);
timepointPanel_.add(new JLabel("Number:"));
numTimepoints_ = pu.makeSpinnerInteger(1, 100000,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_ACQUISITIONS, 1);
numTimepoints_.addChangeListener(recalculateTimeLapseDisplay);
numTimepoints_.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
// update nrRepeats_ variable so the acquisition can be extended or shortened
// as long as we have separate timepoints
if (acquisitionRunning_.get() && getSavingSeparateFile()) {
nrRepeats_ = getNumTimepoints();
}
}
});
timepointPanel_.add(numTimepoints_, "wrap");
timepointPanel_.add(new JLabel("Interval [s]:"));
acquisitionInterval_ = pu.makeSpinnerFloat(0.1, 32000, 0.1,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_ACQUISITION_INTERVAL, 60);
acquisitionInterval_.addChangeListener(recalculateTimeLapseDisplay);
timepointPanel_.add(acquisitionInterval_, "wrap");
// enable/disable panel elements depending on checkbox state
useTimepointsCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected());
}
});
PanelUtils.componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected()); // initialize
// end repeat sub-panel
// start savePanel
// TODO for now these settings aren't part of acquisition settings
// TODO consider whether that should be changed
final int textFieldWidth = 16;
savePanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]8[left]",
"[]4[]"));
savePanel_.setBorder(PanelUtils.makeTitledBorder("Data Saving Settings"));
separateTimePointsCB_ = pu.makeCheckBox("Separate viewer / file for each time point",
Properties.Keys.PREFS_SEPARATE_VIEWERS_FOR_TIMEPOINTS, panelName_, false);
saveCB_ = pu.makeCheckBox("Save while acquiring",
Properties.Keys.PREFS_SAVE_WHILE_ACQUIRING, panelName_, false);
// make sure that when separate viewer is enabled then saving gets enabled too
separateTimePointsCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (separateTimePointsCB_.isSelected() && !saveCB_.isSelected()) {
saveCB_.doClick(); // setSelected() won't work because need to call its listener
}
}
});
savePanel_.add(separateTimePointsCB_, "span 3, left, wrap");
savePanel_.add(saveCB_, "skip 1, span 2, center, wrap");
JLabel dirRootLabel = new JLabel ("Directory root:");
savePanel_.add(dirRootLabel);
DefaultFormatter formatter = new DefaultFormatter();
rootField_ = new JFormattedTextField(formatter);
rootField_.setText( prefs_.getString(panelName_,
Properties.Keys.PLUGIN_DIRECTORY_ROOT, "") );
rootField_.addPropertyChangeListener(new PropertyChangeListener() {
// will respond to commitEdit() as well as GUI edit on commit
@Override
public void propertyChange(PropertyChangeEvent evt) {
prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT,
rootField_.getText());
}
});
rootField_.setColumns(textFieldWidth);
savePanel_.add(rootField_, "span 2");
JButton browseRootButton = new JButton();
browseRootButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
setRootDirectory(rootField_);
prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT,
rootField_.getText());
}
});
browseRootButton.setMargin(new Insets(2, 5, 2, 5));
browseRootButton.setText("...");
savePanel_.add(browseRootButton, "wrap");
JLabel namePrefixLabel = new JLabel();
namePrefixLabel.setText("Name prefix:");
savePanel_.add(namePrefixLabel);
prefixField_ = new JFormattedTextField(formatter);
prefixField_.setText( prefs_.getString(panelName_,
Properties.Keys.PLUGIN_NAME_PREFIX, "acq"));
prefixField_.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
prefs_.putString(panelName_, Properties.Keys.PLUGIN_NAME_PREFIX,
prefixField_.getText());
}
});
prefixField_.setColumns(textFieldWidth);
savePanel_.add(prefixField_, "span 2, wrap");
// since we use the name field even for acquisitions in RAM,
// we only need to gray out the directory-related components
final JComponent[] saveComponents = { browseRootButton, rootField_,
dirRootLabel };
PanelUtils.componentsSetEnabled(saveComponents, saveCB_.isSelected());
saveCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(saveComponents, saveCB_.isSelected());
}
});
// end save panel
// start duration report panel
durationPanel_ = new JPanel(new MigLayout(
"",
"[right]6[left, 40%!]",
"[]5[]"));
durationPanel_.setBorder(PanelUtils.makeTitledBorder("Durations"));
durationPanel_.setPreferredSize(new Dimension(125, 0)); // fix width so it doesn't constantly change depending on text
durationPanel_.add(new JLabel("Slice:"));
actualSlicePeriodLabel_ = new JLabel();
durationPanel_.add(actualSlicePeriodLabel_, "wrap");
durationPanel_.add(new JLabel("Volume:"));
actualVolumeDurationLabel_ = new JLabel();
durationPanel_.add(actualVolumeDurationLabel_, "wrap");
durationPanel_.add(new JLabel("Total:"));
actualTimeLapseDurationLabel_ = new JLabel();
durationPanel_.add(actualTimeLapseDurationLabel_, "wrap");
// end duration report panel
buttonTestAcq_ = new JButton("Test Acquisition");
buttonTestAcq_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runTestAcquisition(Devices.Sides.NONE);
}
});
buttonStart_ = new JToggleButton();
buttonStart_.setIconTextGap(6);
buttonStart_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isAcquisitionRequested()) {
stopAcquisition();
} else {
runAcquisition();
}
}
});
updateStartButton(); // call once to initialize, isSelected() will be false
// make the size of the test button match the start button (easier on the eye)
Dimension sizeStart = buttonStart_.getPreferredSize();
Dimension sizeTest = buttonTestAcq_.getPreferredSize();
sizeTest.height = sizeStart.height;
buttonTestAcq_.setPreferredSize(sizeTest);
acquisitionStatusLabel_ = new JLabel("");
acquisitionStatusLabel_.setBackground(prefixField_.getBackground());
acquisitionStatusLabel_.setOpaque(true);
updateAcquisitionStatus(AcquisitionStatus.NONE);
// Channel Panel (separate file for code)
multiChannelPanel_ = new MultiChannelSubPanel(gui, devices_, props_, prefs_);
multiChannelPanel_.addDurationLabelListener(this);
// Position Panel
final JPanel positionPanel = new JPanel();
positionPanel.setLayout(new MigLayout("flowx, fillx","[right]10[left][10][]","[]8[]"));
usePositionsCB_ = pu.makeCheckBox("Multiple positions (XY)",
Properties.Keys.PREFS_USE_MULTIPOSITION, panelName_, false);
usePositionsCB_.setToolTipText("Acquire datasest at multiple postions");
usePositionsCB_.setEnabled(true);
usePositionsCB_.setFocusPainted(false);
componentBorder =
new ComponentTitledBorder(usePositionsCB_, positionPanel,
BorderFactory.createLineBorder(ASIdiSPIM.borderColor));
positionPanel.setBorder(componentBorder);
usePositionsCB_.addChangeListener(recalculateTimingDisplayCL);
final JButton editPositionListButton = new JButton("Edit position list...");
editPositionListButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gui_.showXYPositionList();
}
});
positionPanel.add(editPositionListButton, "span 2, center");
// add empty fill space on right side of panel
positionPanel.add(new JLabel(""), "wrap, growx");
positionPanel.add(new JLabel("Post-move delay [ms]:"));
positionDelay_ = pu.makeSpinnerFloat(0.0, 10000.0, 100.0,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_POSITION_DELAY,
0.0);
positionPanel.add(positionDelay_, "wrap");
// enable/disable panel elements depending on checkbox state
usePositionsCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(positionPanel, usePositionsCB_.isSelected());
}
});
PanelUtils.componentsSetEnabled(positionPanel, usePositionsCB_.isSelected()); // initialize
// end of Position panel
// checkbox to use navigation joystick settings or not
// an "orphan" UI element
navigationJoysticksCB_ = new JCheckBox("Use Navigation joystick settings");
navigationJoysticksCB_.setSelected(prefs_.getBoolean(panelName_,
Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS, false));
navigationJoysticksCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateJoysticks();
prefs_.putBoolean(panelName_, Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS,
navigationJoysticksCB_.isSelected());
}
});
// checkbox to signal that autofocus should be used during acquisition
// another orphan UI element
useAutofocusCB_ = new JCheckBox("Autofocus during acquisition");
useAutofocusCB_.setSelected(prefs_.getBoolean(panelName_,
Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS, false));
useAutofocusCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
prefs_.putBoolean(panelName_,
Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS,
useAutofocusCB_.isSelected());
}
});
// set up tabbed panels for GUI
// make 3 columns as own JPanels to get vertical space right
// in each column without dependencies on other columns
leftColumnPanel_ = new JPanel(new MigLayout(
"",
"[]",
"[]6[]10[]10[]"));
leftColumnPanel_.add(durationPanel_, "split 2");
leftColumnPanel_.add(timepointPanel_, "wrap, growx");
leftColumnPanel_.add(savePanel_, "wrap");
leftColumnPanel_.add(new JLabel("Acquisition mode: "), "split 2, right");
AcquisitionModes acqModes = new AcquisitionModes(devices_, prefs_);
spimMode_ = acqModes.getComboBox();
spimMode_.addActionListener(recalculateTimingDisplayAL);
leftColumnPanel_.add(spimMode_, "left, wrap");
leftColumnPanel_.add(buttonStart_, "split 3, left");
leftColumnPanel_.add(new JLabel(" "));
leftColumnPanel_.add(buttonTestAcq_, "wrap");
leftColumnPanel_.add(new JLabel("Status:"), "split 2, left");
leftColumnPanel_.add(acquisitionStatusLabel_);
centerColumnPanel_ = new JPanel(new MigLayout(
"",
"[]",
"[]"));
centerColumnPanel_.add(positionPanel, "growx, wrap");
centerColumnPanel_.add(multiChannelPanel_, "wrap");
centerColumnPanel_.add(navigationJoysticksCB_, "wrap");
centerColumnPanel_.add(useAutofocusCB_);
rightColumnPanel_ = new JPanel(new MigLayout(
"",
"[]",
"[]"));
rightColumnPanel_.add(volPanel_);
// add the column panels to the main panel
this.add(leftColumnPanel_);
this.add(centerColumnPanel_);
this.add(rightColumnPanel_);
// properly initialize the advanced slice timing
advancedSliceTimingCB_.addItemListener(sliceTimingDisableGUIInputs);
sliceTimingDisableGUIInputs.itemStateChanged(null);
advancedSliceTimingCB_.addActionListener(showAdvancedTimingFrame);
// included is calculating slice timing
updateDurationLabels();
}//end constructor
private void updateJoysticks() {
if (ASIdiSPIM.getFrame() != null) {
ASIdiSPIM.getFrame().getNavigationPanel().
doJoystickSettings(navigationJoysticksCB_.isSelected());
}
}
public final void updateDurationLabels() {
updateActualSlicePeriodLabel();
updateActualVolumeDurationLabel();
updateActualTimeLapseDurationLabel();
}
private void updateCalibrationOffset(final Sides side,
final AutofocusUtils.FocusResult score) {
if (score.getFocusSuccess()) {
double offsetDelta = score.getOffsetDelta();
double maxDelta = props_.getPropValueFloat(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_MAXOFFSETCHANGE);
if (Math.abs(offsetDelta) <= maxDelta) {
ASIdiSPIM.getFrame().getSetupPanel(side).updateCalibrationOffset(score);
} else {
ReportingUtils.logMessage("autofocus successful for side " + side + " but offset change too much to automatically update");
}
}
}
public SliceTiming getSliceTiming() {
return sliceTiming_;
}
/**
* Sets the acquisition name prefix programmatically.
* Added so that name prefix can be changed from a script.
* @param acqName
*/
public void setAcquisitionNamePrefix(String acqName) {
prefixField_.setText(acqName);
}
private void updateStartButton() {
boolean started = isAcquisitionRequested();
buttonStart_.setSelected(started);
buttonStart_.setText(started ? "Stop Acquisition!" : "Start Acquisition!");
buttonStart_.setBackground(started ? Color.red : Color.green);
buttonStart_.setIcon(started ?
SwingResourceManager.
getIcon(MMStudio.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudio.class,
"/org/micromanager/icons/arrow_right.png"));
buttonTestAcq_.setEnabled(!started);
}
/**
* @return CameraModes.Keys value from Settings panel
* (internal, edge, overlap, pseudo-overlap)
*/
private CameraModes.Keys getSPIMCameraMode() {
return CameraModes.getKeyFromPrefCode(
prefs_.getInt(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_MODE, 0));
}
/**
* convenience method to avoid having to regenerate acquisition settings
*/
private int getNumTimepoints() {
if (useTimepointsCB_.isSelected()) {
return (Integer) numTimepoints_.getValue();
} else {
return 1;
}
}
/**
* convenience method to avoid having to regenerate acquisition settings
* public for API use
*/
public int getNumSides() {
if (numSides_.getSelectedIndex() == 1) {
return 2;
} else {
return 1;
}
}
/**
* convenience method to avoid having to regenerate acquisition settings
* public for API use
*/
public boolean isFirstSideA() {
return ((String) firstSide_.getSelectedItem()).equals("A");
}
/**
* convenience method to avoid having to regenerate acquisition settings.
* public for API use
*/
public double getTimepointInterval() {
return PanelUtils.getSpinnerFloatValue(acquisitionInterval_);
}
/**
* Gathers all current acquisition settings into dedicated POD object
* @return
*/
public AcquisitionSettings getCurrentAcquisitionSettings() {
AcquisitionSettings acqSettings = new AcquisitionSettings();
acqSettings.spimMode = (AcquisitionModes.Keys) spimMode_.getSelectedItem();
acqSettings.isStageScanning = (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN
|| acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN_INTERLEAVED);
acqSettings.useTimepoints = useTimepointsCB_.isSelected();
acqSettings.numTimepoints = getNumTimepoints();
acqSettings.timepointInterval = getTimepointInterval();
acqSettings.useMultiPositions = usePositionsCB_.isSelected();
acqSettings.useChannels = multiChannelPanel_.isMultiChannel();
acqSettings.channelMode = multiChannelPanel_.getChannelMode();
acqSettings.numChannels = multiChannelPanel_.getNumChannels();
acqSettings.channels = multiChannelPanel_.getUsedChannels();
acqSettings.channelGroup = multiChannelPanel_.getChannelGroup();
acqSettings.useAutofocus = useAutofocusCB_.isSelected();
acqSettings.numSides = getNumSides();
acqSettings.firstSideIsA = isFirstSideA();
acqSettings.delayBeforeSide = PanelUtils.getSpinnerFloatValue(delaySide_);
acqSettings.numSlices = (Integer) numSlices_.getValue();
acqSettings.stepSizeUm = PanelUtils.getSpinnerFloatValue(stepSize_);
acqSettings.minimizeSlicePeriod = minSlicePeriodCB_.isSelected();
acqSettings.desiredSlicePeriod = PanelUtils.getSpinnerFloatValue(desiredSlicePeriod_);
acqSettings.desiredLightExposure = PanelUtils.getSpinnerFloatValue(desiredLightExposure_);
acqSettings.centerAtCurrentZ = false;
acqSettings.sliceTiming = sliceTiming_;
acqSettings.cameraMode = getSPIMCameraMode();
acqSettings.accelerationX = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_ACCEL);
acqSettings.hardwareTimepoints = false; // when running acquisition we check this and set to true if needed
acqSettings.separateTimepoints = getSavingSeparateFile();
return acqSettings;
}
/**
* gets the correct value for the slice timing's sliceDuration field
* based on other values of slice timing
* @param s
* @return
*/
private float getSliceDuration(final SliceTiming s) {
// slice duration is the max out of the scan time, laser time, and camera time
return Math.max(Math.max(
s.scanDelay +
(s.scanPeriod * s.scanNum), // scan time
s.laserDelay + s.laserDuration // laser time
),
s.cameraDelay + s.cameraDuration // camera time
);
}
/**
* gets the slice timing from advanced settings
* (normally these advanced settings are read-only and we populate them
* ourselves depending on the user's requests and our algorithm below)
* @return
*/
private SliceTiming getTimingFromAdvancedSettings() {
SliceTiming s = new SliceTiming();
s.scanDelay = PanelUtils.getSpinnerFloatValue(delayScan_);
s.scanNum = (Integer) numScansPerSlice_.getValue();
s.scanPeriod = PanelUtils.getSpinnerFloatValue(lineScanDuration_);
s.laserDelay = PanelUtils.getSpinnerFloatValue(delayLaser_);
s.laserDuration = PanelUtils.getSpinnerFloatValue(durationLaser_);
s.cameraDelay = PanelUtils.getSpinnerFloatValue(delayCamera_);
s.cameraDuration = PanelUtils.getSpinnerFloatValue(durationCamera_);
s.cameraExposure = PanelUtils.getSpinnerFloatValue(exposureCamera_);
s.sliceDuration = getSliceDuration(s);
return s;
}
/**
*
* @param showWarnings true to warn user about needing to change slice period
* @return
*/
private SliceTiming getTimingFromPeriodAndLightExposure(boolean showWarnings) {
// uses algorithm Jon worked out in Octave code; each slice period goes like this:
// 1. camera readout time (none if in overlap mode, 0.25ms in PCO pseudo-overlap)
// 2. any extra delay time
// 3. camera reset time
// 4. start scan 0.25ms before camera global exposure and shifted up in time to account for delay introduced by Bessel filter
// 5. turn on laser as soon as camera global exposure, leave laser on for desired light exposure time
// 7. end camera exposure in final 0.25ms, post-filter scan waveform also ends now
final float scanLaserBufferTime = MyNumberUtils.roundToQuarterMs(0.25f); // below assumed to be multiple of 0.25ms
final Color foregroundColorOK = Color.BLACK;
final Color foregroundColorError = Color.RED;
final Component elementToColor = desiredSlicePeriod_.getEditor().getComponent(0);
SliceTiming s = new SliceTiming();
final float cameraResetTime = computeCameraResetTime(); // recalculate for safety
final float cameraReadoutTime = computeCameraReadoutTime(); // recalculate for safety
// can we use acquisition settings directly? because they may be in flux
final AcquisitionSettings acqSettings = getCurrentAcquisitionSettings();
final float cameraReadout_max = MyNumberUtils.ceilToQuarterMs(cameraReadoutTime);
final float cameraReset_max = MyNumberUtils.ceilToQuarterMs(cameraResetTime);
// we will wait cameraReadout_max before triggering camera, then wait another cameraReset_max for global exposure
// this will also be in 0.25ms increment
final float globalExposureDelay_max = cameraReadout_max + cameraReset_max;
final float laserDuration = MyNumberUtils.roundToQuarterMs(acqSettings.desiredLightExposure);
final float scanDuration = laserDuration + 2*scanLaserBufferTime;
// scan will be longer than laser by 0.25ms at both start and end
// account for delay in scan position due to Bessel filter by starting the scan slightly earlier
// than we otherwise would (Bessel filter selected b/c stretches out pulse without any ripples)
// delay to start is (empirically) 0.07ms + 0.25/(freq in kHz)
// delay to midpoint is empirically 0.38/(freq in kHz)
// group delay for 5th-order bessel filter ~0.39/freq from theory and ~0.4/freq from IC datasheet
final float scanFilterFreq = Math.max(props_.getPropValueFloat(Devices.Keys.GALVOA, Properties.Keys.SCANNER_FILTER_X),
props_.getPropValueFloat(Devices.Keys.GALVOB, Properties.Keys.SCANNER_FILTER_X));
float scanDelayFilter = 0;
if (scanFilterFreq != 0) {
scanDelayFilter = MyNumberUtils.roundToQuarterMs(0.39f/scanFilterFreq);
}
// If the PLogic card is used, account for 0.25ms delay it introduces to
// the camera and laser trigger signals => subtract 0.25ms from the scanner delay
// (start scanner 0.25ms later than it would be otherwise)
// this time-shift opposes the Bessel filter delay
// scanDelayFilter won't be negative unless scanFilterFreq is more than 3kHz which shouldn't happen
if (devices_.isValidMMDevice(Devices.Keys.PLOGIC)) {
scanDelayFilter -= 0.25f;
}
s.scanDelay = globalExposureDelay_max - scanLaserBufferTime // start scan 0.25ms before camera's global exposure
- scanDelayFilter; // start galvo moving early due to card's Bessel filter and delay of TTL signals via PLC
s.scanNum = 1;
s.scanPeriod = scanDuration;
s.laserDelay = globalExposureDelay_max; // turn on laser as soon as camera's global exposure is reached
s.laserDuration = laserDuration;
s.cameraDelay = cameraReadout_max; // camera must readout last frame before triggering again
// figure out desired time for camera to be exposing (including reset time)
// because both camera trigger and laser on occur on 0.25ms intervals (i.e. we may not
// trigger the laser until 0.24ms after global exposure) use cameraReset_max
final float cameraExposure = cameraReset_max + laserDuration;
switch (acqSettings.cameraMode) {
case EDGE:
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = cameraExposure + 0.1f; // add 0.1ms as safety margin, may require adding an additional 0.25ms to slice
// slight delay between trigger and actual exposure start
// is included in exposure time for Hamamatsu and negligible for Andor and PCO cameras
// ensure not to miss triggers by not being done with readout in time for next trigger, add 0.25ms if needed
if (getSliceDuration(s) < (s.cameraExposure + cameraReadoutTime)) {
ReportingUtils.logDebugMessage("Added 0.25ms in edge-trigger mode to make sure camera exposure long enough without dropping frames");
s.cameraDelay += 0.25f;
s.laserDelay += 0.25f;
s.scanDelay += 0.25f;
}
break;
case LEVEL: // AKA "bulb mode", TTL rising starts exposure, TTL falling ends it
s.cameraDuration = MyNumberUtils.ceilToQuarterMs(cameraExposure);
s.cameraExposure = 1; // doesn't really matter, controlled by TTL
break;
case OVERLAP: // only Hamamatsu or Andor
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = 1; // doesn't really matter, controlled by interval between triggers
break;
case PSEUDO_OVERLAP: // only PCO, enforce 0.25ms between end exposure and start of next exposure by triggering camera 0.25ms into the slice
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = getSliceDuration(s) - s.cameraDelay; // s.cameraDelay should be 0.25ms
if (!MyNumberUtils.floatsEqual(s.cameraDelay, 0.25f)) {
MyDialogUtils.showError("Camera delay should be 0.25ms for pseudo-overlap mode.");
}
break;
case INTERNAL:
default:
MyDialogUtils.showError("Invalid camera mode");
break;
}
// fix corner case of negative calculated scanDelay
if (s.scanDelay < 0) {
s.cameraDelay -= s.scanDelay;
s.laserDelay -= s.scanDelay;
s.scanDelay = 0; // same as (-= s.scanDelay)
}
// if a specific slice period was requested, add corresponding delay to scan/laser/camera
elementToColor.setForeground(foregroundColorOK);
if (!acqSettings.minimizeSlicePeriod) {
float globalDelay = acqSettings.desiredSlicePeriod - getSliceDuration(s); // both should be in 0.25ms increments // TODO fix
if (globalDelay < 0) {
globalDelay = 0;
if (showWarnings) { // only true when user has specified period that is unattainable
MyDialogUtils.showError(
"Increasing slice period to meet laser exposure constraint\n"
+ "(time required for camera readout; readout time depends on ROI).");
elementToColor.setForeground(foregroundColorError);
}
}
s.scanDelay += globalDelay;
s.cameraDelay += globalDelay;
s.laserDelay += globalDelay;
}
// // Add 0.25ms to globalDelay if it is 0 and we are on overlap mode and scan has been shifted forward
// // basically the last 0.25ms of scan time that would have determined the slice period isn't
// // there any more because the scan time is moved up => add in the 0.25ms at the start of the slice
// // in edge or level trigger mode the camera trig falling edge marks the end of the slice period
// // not sure if PCO pseudo-overlap needs this, probably not because adding 0.25ms overhead in that case
// if (MyNumberUtils.floatsEqual(cameraReadout_max, 0f) // true iff overlap being used
// && (scanDelayFilter > 0.01f)) {
// globalDelay += 0.25f;
// }
// fix corner case of (exposure time + readout time) being greater than the slice duration
// most of the time the slice duration is already larger
float globalDelay = MyNumberUtils.ceilToQuarterMs((s.cameraExposure + cameraReadoutTime) - getSliceDuration(s));
if (globalDelay > 0) {
s.scanDelay += globalDelay;
s.cameraDelay += globalDelay;
s.laserDelay += globalDelay;
}
// update the slice duration based on our new values
s.sliceDuration = getSliceDuration(s);
return s;
}
/**
* Re-calculate the controller's timing settings for "easy timing" mode.
* Changes panel variable sliceTiming_.
* The controller's properties will be set as needed
* @param showWarnings will show warning if the user-specified slice period too short
* or if cameras aren't assigned
*/
private void recalculateSliceTiming(boolean showWarnings) {
if(!checkCamerasAssigned(showWarnings)) {
return;
}
// if user is providing his own slice timing don't change it
if (advancedSliceTimingCB_.isSelected()) {
return;
}
sliceTiming_ = getTimingFromPeriodAndLightExposure(showWarnings);
PanelUtils.setSpinnerFloatValue(delayScan_, sliceTiming_.scanDelay);
numScansPerSlice_.setValue(sliceTiming_.scanNum);
PanelUtils.setSpinnerFloatValue(lineScanDuration_, sliceTiming_.scanPeriod);
PanelUtils.setSpinnerFloatValue(delayLaser_, sliceTiming_.laserDelay);
PanelUtils.setSpinnerFloatValue(durationLaser_, sliceTiming_.laserDuration);
PanelUtils.setSpinnerFloatValue(delayCamera_, sliceTiming_.cameraDelay);
PanelUtils.setSpinnerFloatValue(durationCamera_, sliceTiming_.cameraDuration );
PanelUtils.setSpinnerFloatValue(exposureCamera_, sliceTiming_.cameraExposure );
}
/**
* Update the displayed slice period.
*/
private void updateActualSlicePeriodLabel() {
recalculateSliceTiming(false);
actualSlicePeriodLabel_.setText(
NumberUtils.doubleToDisplayString(
sliceTiming_.sliceDuration) +
" ms");
}
/**
* Compute the volume duration in ms based on controller's timing settings.
* Includes time for multiple channels. However, does not include for multiple positions.
* @return duration in ms
*/
public double computeActualVolumeDuration(AcquisitionSettings acqSettings) {
final MultichannelModes.Keys channelMode = acqSettings.channelMode;
final int numChannels = acqSettings.numChannels;
final int numSides = acqSettings.numSides;
final float delayBeforeSide = acqSettings.delayBeforeSide;
int numCameraTriggers = acqSettings.numSlices;
if (acqSettings.cameraMode == CameraModes.Keys.OVERLAP) {
numCameraTriggers += 1;
}
// stackDuration is per-side, per-channel, per-position
final double stackDuration = numCameraTriggers * acqSettings.sliceTiming.sliceDuration;
if (acqSettings.isStageScanning) {
final double rampDuration = delayBeforeSide + acqSettings.accelerationX;
// TODO double-check these calculations below, at least they are better than before ;-)
if (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN) {
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return (numSides * ((rampDuration * 2) + (stackDuration * numChannels)));
} else {
return (numSides * ((rampDuration * 2) + stackDuration) * numChannels);
}
} else { // interleaved mode
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return (rampDuration * 2 + stackDuration * numSides * numChannels);
} else {
return ((rampDuration * 2 + stackDuration * numSides) * numChannels);
}
}
} else { // piezo scan
double channelSwitchDelay = 0;
if (channelMode == MultichannelModes.Keys.VOLUME) {
channelSwitchDelay = 500; // estimate channel switching overhead time as 0.5s
// actual value will be hardware-dependent
}
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return numSides * (delayBeforeSide + stackDuration * numChannels); // channelSwitchDelay = 0
} else {
return numSides * numChannels
* (delayBeforeSide + stackDuration)
+ (numChannels - 1) * channelSwitchDelay;
}
}
}
/**
* Compute the timepoint duration in ms. Only difference from computeActualVolumeDuration()
* is that it also takes into account the multiple positions, if any.
* @return duration in ms
*/
private double computeTimepointDuration() {
AcquisitionSettings acqSettings = getCurrentAcquisitionSettings();
final double volumeDuration = computeActualVolumeDuration(acqSettings);
if (acqSettings.useMultiPositions) {
try {
// use 1.5 seconds motor move between positions
// (could be wildly off but was estimated using actual system
// and then slightly padded to be conservative to avoid errors
// where positions aren't completed in time for next position)
return gui_.getPositionList().getNumberOfPositions() *
(volumeDuration + 1500 + PanelUtils.getSpinnerFloatValue(positionDelay_));
} catch (MMScriptException ex) {
MyDialogUtils.showError(ex, "Error getting position list for multiple XY positions");
}
}
return volumeDuration;
}
/**
* Compute the volume duration in ms based on controller's timing settings.
* Includes time for multiple channels.
* @return duration in ms
*/
private double computeActualVolumeDuration() {
return computeActualVolumeDuration(getCurrentAcquisitionSettings());
}
/**
* Update the displayed volume duration.
*/
private void updateActualVolumeDurationLabel() {
actualVolumeDurationLabel_.setText(
NumberUtils.doubleToDisplayString(computeActualVolumeDuration()) +
" ms");
}
/**
* Compute the time lapse duration
* @return duration in s
*/
private double computeActualTimeLapseDuration() {
double duration = (getNumTimepoints() - 1) * getTimepointInterval()
+ computeTimepointDuration()/1000;
return duration;
}
/**
* Update the displayed time lapse duration.
*/
private void updateActualTimeLapseDurationLabel() {
String s = "";
double duration = computeActualTimeLapseDuration();
if (duration < 60) { // less than 1 min
s += NumberUtils.doubleToDisplayString(duration) + " s";
} else if (duration < 60*60) { // between 1 min and 1 hour
s += NumberUtils.doubleToDisplayString(Math.floor(duration/60)) + " min ";
s += NumberUtils.doubleToDisplayString(Math.round(duration % 60)) + " s";
} else { // longer than 1 hour
s += NumberUtils.doubleToDisplayString(Math.floor(duration/(60*60))) + " hr ";
s += NumberUtils.doubleToDisplayString(Math.round((duration % (60*60))/60)) + " min";
}
actualTimeLapseDurationLabel_.setText(s);
}
/**
* Computes the reset time of the SPIM cameras set on Devices panel.
* Handles single-side operation.
* Needed for computing (semi-)optimized slice timing in "easy timing" mode.
* @return
*/
private float computeCameraResetTime() {
float resetTime;
if (getNumSides() > 1) {
resetTime = Math.max(cameras_.computeCameraResetTime(Devices.Keys.CAMERAA),
cameras_.computeCameraResetTime(Devices.Keys.CAMERAB));
} else {
if (isFirstSideA()) {
resetTime = cameras_.computeCameraResetTime(Devices.Keys.CAMERAA);
} else {
resetTime = cameras_.computeCameraResetTime(Devices.Keys.CAMERAB);
}
}
return resetTime;
}
/**
* Computes the readout time of the SPIM cameras set on Devices panel.
* Handles single-side operation.
* Needed for computing (semi-)optimized slice timing in "easy timing" mode.
* @return
*/
private float computeCameraReadoutTime() {
CameraModes.Keys camMode = getSPIMCameraMode();
if (getNumSides() > 1) {
return Math.max(cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAA, camMode),
cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAB, camMode));
} else {
if (isFirstSideA()) {
return cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAA, camMode);
} else {
return cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAB, camMode);
}
}
}
/**
* Makes sure that cameras are assigned to the desired sides and display error message
* if not (e.g. if single-sided with side B first, then only checks camera for side B)
* @return true if cameras assigned, false if not
*/
private boolean checkCamerasAssigned(boolean showWarnings) {
String firstCamera, secondCamera;
final boolean firstSideA = isFirstSideA();
if (firstSideA) {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
} else {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
}
if (firstCamera == null) {
if (showWarnings) {
MyDialogUtils.showError("Please select a valid camera for the first side (Imaging Path " +
(firstSideA ? "A" : "B") + ") on the Devices Panel");
}
return false;
}
if (getNumSides()> 1 && secondCamera == null) {
if (showWarnings) {
MyDialogUtils.showError("Please select a valid camera for the second side (Imaging Path " +
(firstSideA ? "B" : "A") + ") on the Devices Panel.");
}
return false;
}
return true;
}
/**
* used for updateAcquisitionStatus() calls
*/
private static enum AcquisitionStatus {
NONE,
ACQUIRING,
WAITING,
DONE,
}
private void updateAcquisitionStatus(AcquisitionStatus phase) {
updateAcquisitionStatus(phase, 0);
}
private void updateAcquisitionStatus(AcquisitionStatus phase, int secsToNextAcquisition) {
String text = "";
switch(phase) {
case NONE:
text = "No acquisition in progress.";
break;
case ACQUIRING:
text = "Acquiring time point "
+ NumberUtils.intToDisplayString(numTimePointsDone_)
+ " of "
+ NumberUtils.intToDisplayString(getNumTimepoints());
// TODO make sure the number of timepoints can't change during an acquisition
// (or maybe we make a hidden feature where the acquisition can be terminated by changing)
break;
case WAITING:
text = "Next timepoint ("
+ NumberUtils.intToDisplayString(numTimePointsDone_+1)
+ " of "
+ NumberUtils.intToDisplayString(getNumTimepoints())
+ ") in "
+ NumberUtils.intToDisplayString(secsToNextAcquisition)
+ " s.";
break;
case DONE:
text = "Acquisition finished with "
+ NumberUtils.intToDisplayString(numTimePointsDone_)
+ " time points.";
break;
default:
break;
}
acquisitionStatusLabel_.setText(text);
}
/**
* runs a test acquisition with the following features:
* - not saved to disk
* - window can be closed without prompting to save
* - timepoints disabled
* - autofocus disabled
* @param side Devices.Sides.NONE to run as specified in acquisition tab,
* Devices.Side.A or B to run only that side
*/
public void runTestAcquisition(Devices.Sides side) {
cancelAcquisition_.set(false);
acquisitionRequested_.set(true);
updateStartButton();
boolean success = runAcquisitionPrivate(true, side);
if (!success) {
ReportingUtils.logError("Fatal error running test diSPIM acquisition.");
}
acquisitionRequested_.set(false);
acquisitionRunning_.set(false);
updateStartButton();
}
/**
* Implementation of acquisition that orchestrates image
* acquisition itself rather than using the acquisition engine.
*
* This methods is public so that the ScriptInterface can call it
* Please do not access this yourself directly, instead use the API, e.g.
* import org.micromanager.asidispim.api.*;
* ASIdiSPIMInterface diSPIM = new ASIdiSPIMImplementation();
* diSPIM.runAcquisition();
*/
public void runAcquisition() {
class acqThread extends Thread {
acqThread(String threadName) {
super(threadName);
}
@Override
public void run() {
ReportingUtils.logDebugMessage("User requested start of diSPIM acquisition.");
if (isAcquisitionRequested()) { // don't allow acquisition to be requested again, just return
ReportingUtils.logError("another acquisition already running");
return;
}
cancelAcquisition_.set(false);
acquisitionRequested_.set(true);
ASIdiSPIM.getFrame().tabsSetEnabled(false);
updateStartButton();
boolean success = runAcquisitionPrivate(false, Devices.Sides.NONE);
if (!success) {
ReportingUtils.logError("Fatal error running diSPIM acquisition.");
}
acquisitionRequested_.set(false);
updateStartButton();
ASIdiSPIM.getFrame().tabsSetEnabled(true);
}
}
acqThread acqt = new acqThread("diSPIM Acquisition");
acqt.start();
}
private Color getChannelColor(int channelIndex) {
return (colors[channelIndex % colors.length]);
}
/**
* Actually runs the acquisition; does the dirty work of setting
* up the controller, the circular buffer, starting the cameras,
* grabbing the images and putting them into the acquisition, etc.
* @param testAcq true if running test acquisition only (see runTestAcquisition() javadoc)
* @param testAcqSide only applies to test acquisition, passthrough from runTestAcquisition()
* @return true if ran without any fatal errors.
*/
private boolean runAcquisitionPrivate(boolean testAcq, Devices.Sides testAcqSide) {
// sanity check, shouldn't call this unless we aren't running an acquisition
if (gui_.isAcquisitionRunning()) {
MyDialogUtils.showError("An acquisition is already running");
return false;
}
if (ASIdiSPIM.getFrame().getHardwareInUse()) {
MyDialogUtils.showError("Hardware is being used by something else (maybe autofocus?)");
return false;
}
boolean liveModeOriginally = gui_.isLiveModeOn();
if (liveModeOriginally) {
gui_.enableLiveMode(false);
}
// stop the serial traffic for position updates during acquisition
posUpdater_.pauseUpdates(true);
// make sure slice timings are up to date
// do this automatically; we used to prompt user if they were out of date
// do this before getting snapshot of sliceTiming_ in acqSettings
recalculateSliceTiming(!minSlicePeriodCB_.isSelected());
AcquisitionSettings acqSettingsOrig = getCurrentAcquisitionSettings();
// if a test acquisition then only run single timpoint, no autofocus
if (testAcq) {
acqSettingsOrig.useTimepoints = false;
acqSettingsOrig.numTimepoints = 1;
acqSettingsOrig.useAutofocus = false;
// if called from the setup panels then the side will be specified
// so we can do an appropriate single-sided acquisition
// if called from the acquisition panel then NONE will be specified
// and run according to existing settings
if (testAcqSide != Devices.Sides.NONE) {
acqSettingsOrig.numSides = 1;
acqSettingsOrig.firstSideIsA = (testAcqSide == Devices.Sides.A);
}
// work around limitation of not being able to use PLogic per-volume switching with single side
// => do per-volume switching instead (only difference should be extra time to switch)
if (acqSettingsOrig.useChannels && acqSettingsOrig.channelMode == MultichannelModes.Keys.VOLUME_HW
&& acqSettingsOrig.numSides < 2) {
acqSettingsOrig.channelMode = MultichannelModes.Keys.VOLUME;
}
}
double volumeDuration = computeActualVolumeDuration(acqSettingsOrig);
double timepointDuration = computeTimepointDuration();
long timepointIntervalMs = Math.round(acqSettingsOrig.timepointInterval*1000);
// use hardware timing if < 1 second between timepoints
// experimentally need ~0.5 sec to set up acquisition, this gives a bit of cushion
// cannot do this in getCurrentAcquisitionSettings because of mutually recursive
// call with computeActualVolumeDuration()
if ( acqSettingsOrig.numTimepoints > 1
&& timepointIntervalMs < (timepointDuration + 750)
&& !acqSettingsOrig.isStageScanning) {
acqSettingsOrig.hardwareTimepoints = true;
}
if (acqSettingsOrig.useMultiPositions) {
if (acqSettingsOrig.hardwareTimepoints
|| ((acqSettingsOrig.numTimepoints > 1)
&& (timepointIntervalMs < timepointDuration*1.2))) {
// change to not hardwareTimepoints and warn user
// but allow acquisition to continue
acqSettingsOrig.hardwareTimepoints = false;
MyDialogUtils.showError("Timepoint interval may not be sufficient "
+ "depending on actual time required to change positions. "
+ "Proceed at your own risk.");
}
}
// now acqSettings should be read-only
final AcquisitionSettings acqSettings = acqSettingsOrig;
// generate string for log file
Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String acqSettingsJSON = gson.toJson(acqSettings);
// get MM device names for first/second cameras to acquire
String firstCamera, secondCamera;
boolean firstSideA = acqSettings.firstSideIsA;
if (firstSideA) {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
} else {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
}
boolean sideActiveA, sideActiveB;
boolean twoSided = acqSettings.numSides > 1;
if (twoSided) {
sideActiveA = true;
sideActiveB = true;
} else {
secondCamera = null;
if (firstSideA) {
sideActiveA = true;
sideActiveB = false;
} else {
sideActiveA = false;
sideActiveB = true;
}
}
boolean usingDemoCam = (devices_.getMMDeviceLibrary(Devices.Keys.CAMERAA).equals(Devices.Libraries.DEMOCAM) && sideActiveA)
|| (devices_.getMMDeviceLibrary(Devices.Keys.CAMERAB).equals(Devices.Libraries.DEMOCAM) && sideActiveB);
// set up channels
int nrChannelsSoftware = acqSettings.numChannels; // how many times we trigger the controller per stack
int nrSlicesSoftware = acqSettings.numSlices;
String originalChannelConfig = "";
boolean changeChannelPerVolumeSoftware = false;
if (acqSettings.useChannels) {
if (acqSettings.numChannels < 1) {
MyDialogUtils.showError("\"Channels\" is checked, but no channels are selected");
return false;
}
// get current channel so that we can restore it, then set channel appropriately
originalChannelConfig = multiChannelPanel_.getCurrentConfig();
switch (acqSettings.channelMode) {
case VOLUME:
changeChannelPerVolumeSoftware = true;
multiChannelPanel_.initializeChannelCycle();
break;
case VOLUME_HW:
case SLICE_HW:
if (acqSettings.numChannels == 1) { // only 1 channel selected so don't have to really use hardware switching
multiChannelPanel_.initializeChannelCycle();
multiChannelPanel_.selectNextChannel();
} else { // we have at least 2 channels
boolean success = controller_.setupHardwareChannelSwitching(acqSettings);
if (!success) {
MyDialogUtils.showError("Couldn't set up slice hardware channel switching.");
return false;
}
nrChannelsSoftware = 1;
nrSlicesSoftware = acqSettings.numSlices * acqSettings.numChannels;
}
break;
default:
MyDialogUtils.showError("Unsupported multichannel mode \"" + acqSettings.channelMode.toString() + "\"");
return false;
}
}
if (acqSettings.hardwareTimepoints) {
// in hardwareTimepoints case we trigger controller once for all timepoints => need to
// adjust number of frames we expect back from the camera during MM's SequenceAcquisition
if (acqSettings.cameraMode == CameraModes.Keys.OVERLAP) {
// For overlap mode we are send one extra trigger per side for PLogic slice-switching
// and one extra trigger be channel per side for volume-switching (both PLogic and not).
// Very last trigger won't ever return a frame so subtract 1.
if (acqSettings.channelMode == MultichannelModes.Keys.SLICE_HW) {
nrSlicesSoftware = (((acqSettings.numSlices * acqSettings.numChannels) + 1) * acqSettings.numTimepoints) - 1;
} else {
nrSlicesSoftware = ((acqSettings.numSlices + 1) * acqSettings.numChannels * acqSettings.numTimepoints) - 1;
}
} else {
// we get back one image per trigger for all trigger modes other than OVERLAP
// and we have already computed how many images that is (nrSlicesSoftware)
nrSlicesSoftware *= acqSettings.numTimepoints;
}
}
// set up XY positions
int nrPositions = 1;
PositionList positionList = new PositionList();
if (acqSettings.useMultiPositions) {
try {
positionList = gui_.getPositionList();
nrPositions = positionList.getNumberOfPositions();
} catch (MMScriptException ex) {
MyDialogUtils.showError(ex, "Error getting position list for multiple XY positions");
}
if (nrPositions < 1) {
MyDialogUtils.showError("\"Positions\" is checked, but no positions are in position list");
return false;
}
}
// make sure we have cameras selected
if (!checkCamerasAssigned(true)) {
return false;
}
float cameraReadoutTime = computeCameraReadoutTime();
double exposureTime = acqSettings.sliceTiming.cameraExposure;
final boolean save = saveCB_.isSelected() && !testAcq;
final String rootDir = rootField_.getText();
// make sure we have a valid directory to save in
final File dir = new File(rootDir);
if (save) {
try {
if (!dir.exists()) {
if (!dir.mkdir()) {
throw new Exception();
}
}
} catch (Exception ex) {
MyDialogUtils.showError("Could not create directory for saving acquisition data.");
return false;
}
}
if (acqSettings.separateTimepoints) {
// because separate timepoints closes windows when done, force the user to save data to disk to avoid confusion
if (!save) {
MyDialogUtils.showError("For separate timepoints, \"Save while acquiring\" must be enabled.");
return false;
}
// for separate timepoints, make sure the directory is empty to make sure naming pattern is "clean"
// this is an arbitrary choice to avoid confusion later on when looking at file names
if (dir != null && (dir.list().length > 0)) {
MyDialogUtils.showError("For separate timepoints the saving directory must be empty.");
return false;
}
}
int nrFrames; // how many Micro-manager "frames" = time points to take
if (acqSettings.separateTimepoints) {
nrFrames = 1;
nrRepeats_ = acqSettings.numTimepoints;
} else {
nrFrames = acqSettings.numTimepoints;
nrRepeats_ = 1;
}
AcquisitionModes.Keys spimMode = acqSettings.spimMode;
boolean autoShutter = core_.getAutoShutter();
boolean shutterOpen = false; // will read later
String originalCamera = core_.getCameraDevice();
// more sanity checks
// TODO move these checks earlier, before we set up channels and XY positions
// make sure stage scan is supported if selected
if (acqSettings.isStageScanning) {
if (!devices_.isTigerDevice(Devices.Keys.XYSTAGE)
|| !props_.hasProperty(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_NUMLINES)) {
MyDialogUtils.showError("Must have stage with scan-enabled firmware for stage scanning.");
return false;
}
}
double sliceDuration = acqSettings.sliceTiming.sliceDuration;
if (exposureTime + cameraReadoutTime > sliceDuration) {
// should only only possible to mess this up using advanced timing settings
// or if there are errors in our own calculations
MyDialogUtils.showError("Exposure time of " + exposureTime +
" is longer than time needed for a line scan with" +
" readout time of " + cameraReadoutTime + "\n" +
"This will result in dropped frames. " +
"Please change input");
return false;
}
// if we want to do hardware timepoints make sure there's not a problem
// lots of different situations where hardware timepoints can't be used...
if (acqSettings.hardwareTimepoints) {
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME_HW) {
// both hardware time points and volume channel switching use SPIMNumRepeats property
// TODO this seems a severe limitation, maybe this could be changed in the future via firmware change
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with hardware channel switching volume-by-volume.");
return false;
}
if (acqSettings.isStageScanning) {
// stage scanning needs to be triggered for each time point
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with stage scanning.");
return false;
}
if (acqSettings.separateTimepoints) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with separate viewers/file for each time point.");
return false;
}
if (acqSettings.useAutofocus) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with autofocus during acquisition.");
return false;
}
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with software channels (need to use PLogic channel switching).");
return false;
}
if (spimMode == AcquisitionModes.Keys.NO_SCAN) {
MyDialogUtils.showError("Cannot do hardware time points when no scan mode is used."
+ " Use the number of slices to set the number of images to acquire.");
return false;
}
}
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME_HW
&& acqSettings.numSides < 2) {
MyDialogUtils.showError("Cannot do PLogic channel switching of volume when only one"
+ " side is selected. Pester the developers if you need this.");
return false;
}
// make sure we aren't trying to collect timepoints faster than we can
if (!acqSettings.useMultiPositions && acqSettings.numTimepoints > 1) {
if (timepointIntervalMs < volumeDuration) {
MyDialogUtils.showError("Time point interval shorter than" +
" the time to collect a single volume.\n");
return false;
}
}
// Autofocus settings; only used if acqSettings.useAutofocus is true
boolean autofocusAtT0 = false;
int autofocusEachNFrames = 10;
String autofocusChannel = "";
if (acqSettings.useAutofocus) {
autofocusAtT0 = prefs_.getBoolean(MyStrings.PanelNames.AUTOFOCUS.toString(),
Properties.Keys.PLUGIN_AUTOFOCUS_ACQBEFORESTART, false);
autofocusEachNFrames = props_.getPropValueInteger(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_EACHNIMAGES);
autofocusChannel = props_.getPropValueString(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_CHANNEL);
// double-check that selected channel is valid if we are doing multi-channel
if (acqSettings.useChannels) {
String channelGroup = props_.getPropValueString(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_MULTICHANNEL_GROUP);
StrVector channels = gui_.getMMCore().getAvailableConfigs(channelGroup);
boolean found = false;
for (String channel : channels) {
if (channel.equals(autofocusChannel)) {
found = true;
break;
}
}
if (!found) {
MyDialogUtils.showError("Invalid autofocus channel selected on autofocus tab.");
return false;
}
}
}
// it appears the circular buffer, which is used by both cameras, can only have one
// image size setting => we require same image height and width for second camera if two-sided
if (twoSided) {
try {
Rectangle roi_1 = core_.getROI(firstCamera);
Rectangle roi_2 = core_.getROI(secondCamera);
if (roi_1.width != roi_2.width || roi_1.height != roi_2.height) {
MyDialogUtils.showError("Camera ROI height and width must be equal because of Micro-Manager's circular buffer");
return false;
}
} catch (Exception ex) {
MyDialogUtils.showError(ex, "Problem getting camera ROIs");
}
}
// seems to have a problem if the core's camera has been set to some other
// camera before we start doing things, so set to a SPIM camera
try {
core_.setCameraDevice(firstCamera);
} catch (Exception ex) {
MyDialogUtils.showError(ex, "could not set camera");
}
// empty out circular buffer
try {
core_.clearCircularBuffer();
} catch (Exception ex) {
MyDialogUtils.showError(ex, "Error emptying out the circular buffer");
return false;
}
// initialize stage scanning so we can restore state
Point2D.Double xyPosUm = new Point2D.Double();
float origXSpeed = 1f; // don't want 0 in case something goes wrong
if (acqSettings.isStageScanning) {
try {
xyPosUm = core_.getXYStagePosition(devices_.getMMDevice(Devices.Keys.XYSTAGE));
origXSpeed = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED);
} catch (Exception ex) {
MyDialogUtils.showError("Could not get XY stage position for stage scan initialization");
return false;
}
}
cameras_.setSPIMCamerasForAcquisition(true);
numTimePointsDone_ = 0;
// force saving as image stacks, not individual files
// implementation assumes just two options, either
// TaggedImageStorageDiskDefault.class or TaggedImageStorageMultipageTiff.class
boolean separateImageFilesOriginally =
ImageUtils.getImageStorageClass().equals(TaggedImageStorageDiskDefault.class);
ImageUtils.setImageStorageClass(TaggedImageStorageMultipageTiff.class);
// Set up controller SPIM parameters (including from Setup panel settings)
// want to do this, even with demo cameras, so we can test everything else
if (!controller_.prepareControllerForAquisition(acqSettings)) {
return false;
}
boolean nonfatalError = false;
long acqButtonStart = System.currentTimeMillis();
String acqName = "";
acq_ = null;
// do not want to return from within this loop => throw exception instead
// loop is executed once per acquisition (i.e. once if separate viewers isn't selected
// or once per timepoint if separate viewers is selected)
long repeatStart = System.currentTimeMillis();
for (int acqNum = 0; !cancelAcquisition_.get() && acqNum < nrRepeats_; acqNum++) {
// handle intervals between (software-timed) repeats
// only applies when doing separate viewers for each timepoint
// and have multiple timepoints
long repeatNow = System.currentTimeMillis();
long repeatdelay = repeatStart + acqNum * timepointIntervalMs - repeatNow;
while (repeatdelay > 0 && !cancelAcquisition_.get()) {
updateAcquisitionStatus(AcquisitionStatus.WAITING, (int) (repeatdelay / 1000));
long sleepTime = Math.min(1000, repeatdelay);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
repeatNow = System.currentTimeMillis();
repeatdelay = repeatStart + acqNum * timepointIntervalMs - repeatNow;
}
BlockingQueue<TaggedImage> bq = new LinkedBlockingQueue<TaggedImage>(10);
// try to close last acquisition viewer if there could be one open (only in single acquisition per timepoint mode)
if (acqSettings.separateTimepoints && (acq_!=null) && !cancelAcquisition_.get()) {
try {
// following line needed due to some arcane internal reason, otherwise
// call to closeAcquisitionWindow() fails silently.
// See http://sourceforge.net/p/micro-manager/mailman/message/32999320/
acq_.promptToSave(false);
gui_.closeAcquisitionWindow(acqName);
} catch (Exception ex) {
// do nothing if unsuccessful
}
}
if (acqSettings.separateTimepoints) {
// call to getUniqueAcquisitionName is extra safety net, we have checked that directory is empty before starting
acqName = gui_.getUniqueAcquisitionName(prefixField_.getText() + "_" + acqNum);
} else {
acqName = gui_.getUniqueAcquisitionName(prefixField_.getText());
}
VirtualAcquisitionDisplay vad = null;
WindowListener wl_acq = null;
WindowListener[] wls_orig = null;
try {
// check for stop button before each acquisition
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
// flag that we are actually running acquisition now
acquisitionRunning_.set(true);
ReportingUtils.logMessage("diSPIM plugin starting acquisition " + acqName + " with following settings: " + acqSettingsJSON);
if (spimMode == AcquisitionModes.Keys.NO_SCAN && !acqSettings.separateTimepoints) {
// swap nrFrames and numSlices
gui_.openAcquisition(acqName, rootDir, acqSettings.numSlices, acqSettings.numSides * acqSettings.numChannels,
nrFrames, nrPositions, true, save);
} else {
gui_.openAcquisition(acqName, rootDir, nrFrames, acqSettings.numSides * acqSettings.numChannels,
acqSettings.numSlices, nrPositions, true, save);
}
// save exposure time, will restore at end of acquisition
prefs_.putFloat(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_LIVE_EXPOSURE.toString(),
(float)core_.getExposure());
core_.setExposure(firstCamera, exposureTime);
if (twoSided) {
core_.setExposure(secondCamera, exposureTime);
}
channelNames_ = new String[acqSettings.numSides * acqSettings.numChannels];
// generate channel names and colors
// also builds viewString for MultiViewRegistration metadata
String viewString = "";
final String SEPARATOR = "_";
// set up channels (side A/B is treated as channel too)
if (acqSettings.useChannels) {
ChannelSpec[] channels = multiChannelPanel_.getUsedChannels();
for (int i = 0; i < channels.length; i++) {
String chName = "-" + channels[i].config_;
// same algorithm for channel index vs. specified channel and side as below
int channelIndex = i;
if (twoSided) {
channelIndex *= 2;
}
channelNames_[channelIndex] = firstCamera + chName;
viewString += NumberUtils.intToDisplayString(0) + SEPARATOR;
if (twoSided) {
channelNames_[channelIndex+1] = secondCamera + chName;
viewString += NumberUtils.intToDisplayString(90) + SEPARATOR;
}
}
} else {
channelNames_[0] = firstCamera;
viewString += NumberUtils.intToDisplayString(0) + SEPARATOR;
if (twoSided) {
channelNames_[1] = secondCamera;
viewString += NumberUtils.intToDisplayString(90) + SEPARATOR;
}
}
// strip last separator of viewString (for Multiview Reconstruction)
viewString = viewString.substring(0, viewString.length() - 1);
// assign channel names and colors
for (int i = 0; i < acqSettings.numSides * acqSettings.numChannels; i++) {
gui_.setChannelName(acqName, i, channelNames_[i]);
gui_.setChannelColor(acqName, i, getChannelColor(i));
}
// initialize acquisition
gui_.initializeAcquisition(acqName, (int) core_.getImageWidth(),
(int) core_.getImageHeight(), (int) core_.getBytesPerPixel(),
(int) core_.getImageBitDepth());
gui_.promptToSaveAcquisition(acqName, !testAcq);
// These metadata have to added after initialization, otherwise they will not be shown?!
gui_.setAcquisitionProperty(acqName, "NumberOfSides",
NumberUtils.doubleToDisplayString(acqSettings.numSides));
gui_.setAcquisitionProperty(acqName, "FirstSide", acqSettings.firstSideIsA ? "A" : "B");
gui_.setAcquisitionProperty(acqName, "SlicePeriod_ms",
actualSlicePeriodLabel_.getText());
gui_.setAcquisitionProperty(acqName, "LaserExposure_ms",
NumberUtils.doubleToDisplayString(acqSettings.desiredLightExposure));
gui_.setAcquisitionProperty(acqName, "VolumeDuration",
actualVolumeDurationLabel_.getText());
gui_.setAcquisitionProperty(acqName, "SPIMmode", spimMode.toString());
// Multi-page TIFF saving code wants this one (cameras are all 16-bits, so not much reason for anything else)
gui_.setAcquisitionProperty(acqName, "PixelType", "GRAY16");
gui_.setAcquisitionProperty(acqName, "UseAutofocus",
acqSettings.useAutofocus ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "HardwareTimepoints",
acqSettings.hardwareTimepoints ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "SeparateTimepoints",
acqSettings.separateTimepoints ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "CameraMode", acqSettings.cameraMode.toString());
gui_.setAcquisitionProperty(acqName, "z-step_um",
NumberUtils.doubleToDisplayString(acqSettings.stepSizeUm));
// Properties for use by MultiViewRegistration plugin
// Format is: x_y_z, set to 1 if we should rotate around this axis.
gui_.setAcquisitionProperty(acqName, "MVRotationAxis", "0_1_0");
gui_.setAcquisitionProperty(acqName, "MVRotations", viewString);
// save XY and SPIM head position in metadata
// update positions first at expense of two extra serial transactions
positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.X); // / will update cache for Y too
gui_.setAcquisitionProperty(acqName, "Position_X",
positions_.getPositionString(Devices.Keys.XYSTAGE, Directions.X));
gui_.setAcquisitionProperty(acqName, "Position_Y",
positions_.getPositionString(Devices.Keys.XYSTAGE, Directions.Y));
positions_.getUpdatedPosition(Devices.Keys.UPPERZDRIVE);
gui_.setAcquisitionProperty(acqName, "Position_SPIM_Head",
positions_.getPositionString(Devices.Keys.UPPERZDRIVE));
gui_.setAcquisitionProperty(acqName, "SPIMAcqSettings", acqSettingsJSON);
// get circular buffer ready
// do once here but not per-trigger; need to ensure ROI changes registered
core_.initializeCircularBuffer();
// TODO: use new acquisition interface that goes through the pipeline
//gui_.setAcquisitionAddImageAsynchronous(acqName);
acq_ = gui_.getAcquisition(acqName);
// Dive into MM internals since script interface does not support pipelines
ImageCache imageCache = acq_.getImageCache();
vad = acq_.getAcquisitionWindow();
imageCache.addImageCacheListener(vad);
// Start pumping images into the ImageCache
DefaultTaggedImageSink sink = new DefaultTaggedImageSink(bq, imageCache);
sink.start();
// remove usual window listener(s) and replace it with our own
// that will prompt before closing and cancel acquisition if confirmed
// this should be considered a hack, it may not work perfectly
// I have confirmed that there is only one windowListener and it seems to
// also be related to window closing
// Note that ImageJ's acquisition window is AWT instead of Swing
wls_orig = vad.getImagePlus().getWindow().getWindowListeners();
for (WindowListener l : wls_orig) {
vad.getImagePlus().getWindow().removeWindowListener(l);
}
wl_acq = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
// if running acquisition only close if user confirms
if (acquisitionRunning_.get()) {
boolean stop = MyDialogUtils.getConfirmDialogResult(
"Do you really want to abort the acquisition?",
JOptionPane.YES_NO_OPTION);
if (stop) {
cancelAcquisition_.set(true);
}
}
}
};
vad.getImagePlus().getWindow().addWindowListener(wl_acq);
// patterned after implementation in MMStudio.java
// will be null if not saving to disk
lastAcquisitionPath_ = acq_.getImageCache().getDiskLocation();
lastAcquisitionName_ = acqName;
// make sure all devices have arrived, e.g. a stage isn't still moving
try {
core_.waitForSystem();
} catch (Exception e) {
ReportingUtils.logError("error waiting for system");
}
// Loop over all the times we trigger the controller's acquisition
// (although if multi-channel with volume switching is selected there
// is inner loop to trigger once per channel)
// remember acquisition start time for software-timed timepoints
// For hardware-timed timepoints we only trigger the controller once
long acqStart = System.currentTimeMillis();
for (int trigNum = 0; trigNum < nrFrames; trigNum++) {
// handle intervals between (software-timed) time points
// when we are within the same acquisition
// (if separate viewer is selected then nothing bad happens here
// but waiting during interval handled elsewhere)
long acqNow = System.currentTimeMillis();
long delay = acqStart + trigNum * timepointIntervalMs - acqNow;
while (delay > 0 && !cancelAcquisition_.get()) {
updateAcquisitionStatus(AcquisitionStatus.WAITING, (int) (delay / 1000));
long sleepTime = Math.min(1000, delay);
Thread.sleep(sleepTime);
acqNow = System.currentTimeMillis();
delay = acqStart + trigNum * timepointIntervalMs - acqNow;
}
// check for stop button before each time point
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
int timePoint = acqSettings.separateTimepoints ? acqNum : trigNum ;
// this is where we autofocus if requested
if (acqSettings.useAutofocus) {
// Note that we will not autofocus as expected when using hardware
// timing. Seems OK, since hardware timing will result in short
// acquisition times that do not need autofocus. We have already
// ensured that we aren't doing both
if ( (autofocusAtT0 && timePoint == 0) || ( (timePoint > 0) &&
(timePoint % autofocusEachNFrames == 0 ) ) ) {
if (acqSettings.useChannels) {
multiChannelPanel_.selectChannel(autofocusChannel);
}
if (sideActiveA) {
AutofocusUtils.FocusResult score = autofocus_.runFocus(
this, Devices.Sides.A, false,
sliceTiming_, false);
updateCalibrationOffset(Devices.Sides.A, score);
}
if (sideActiveB) {
AutofocusUtils.FocusResult score = autofocus_.runFocus(
this, Devices.Sides.B, false,
sliceTiming_, false);
updateCalibrationOffset(Devices.Sides.B, score);
}
// Restore settings of the controller
controller_.prepareControllerForAquisition(acqSettings);
if (acqSettings.useChannels && acqSettings.channelMode != MultichannelModes.Keys.VOLUME) {
controller_.setupHardwareChannelSwitching(acqSettings);
}
}
}
numTimePointsDone_++;
updateAcquisitionStatus(AcquisitionStatus.ACQUIRING);
// loop over all positions
for (int positionNum = 0; positionNum < nrPositions; positionNum++) {
if (acqSettings.useMultiPositions) {
// make sure user didn't stop things
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
// want to move between positions move stage fast, so we
// will clobber stage scanning setting so need to restore it
float scanXSpeed = 1f;
if (acqSettings.isStageScanning) {
scanXSpeed = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, origXSpeed);
}
// blocking call; will wait for stages to move
MultiStagePosition.goToPosition(positionList.getPosition(positionNum), core_);
// restore speed for stage scanning
if (acqSettings.isStageScanning) {
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, scanXSpeed);
}
// setup stage scan at this position
if (acqSettings.isStageScanning) {
StagePosition pos = positionList.getPosition(positionNum).get(devices_.getMMDevice(Devices.Keys.XYSTAGE));
controller_.prepareStageScanForAcquisition(pos.x, pos.y);
}
// wait any extra time the user requests
Thread.sleep(Math.round(PanelUtils.getSpinnerFloatValue(positionDelay_)));
}
// loop over all the times we trigger the controller
// usually just once, but will be the number of channels if we have
// multiple channels and aren't using PLogic to change between them
for (int channelNum = 0; channelNum < nrChannelsSoftware; channelNum++) {
try {
// flag that we are using the cameras/controller
ASIdiSPIM.getFrame().setHardwareInUse(true);
// deal with shutter before starting acquisition
shutterOpen = core_.getShutterOpen();
if (autoShutter) {
core_.setAutoShutter(false);
if (!shutterOpen) {
core_.setShutterOpen(true);
}
}
// start the cameras
core_.startSequenceAcquisition(firstCamera, nrSlicesSoftware, 0, true);
if (twoSided) {
core_.startSequenceAcquisition(secondCamera, nrSlicesSoftware, 0, true);
}
// deal with channel if needed (hardware channel switching doesn't happen here)
if (changeChannelPerVolumeSoftware) {
multiChannelPanel_.selectNextChannel();
}
// trigger the state machine on the controller
// do this even with demo cameras to test everything else
boolean success = controller_.triggerControllerStartAcquisition(spimMode, firstSideA);
if (!success) {
throw new Exception("Controller triggering not successful");
}
ReportingUtils.logDebugMessage("Starting time point " + (timePoint+1) + " of " + nrFrames
+ " with (software) channel number " + channelNum);
// Wait for first image to create ImageWindow, so that we can be sure about image size
// Do not actually grab first image here, just make sure it is there
long start = System.currentTimeMillis();
long now = start;
final long timeout = Math.max(3000, Math.round(10*sliceDuration + 2*acqSettings.delayBeforeSide));
while (core_.getRemainingImageCount() == 0 && (now - start < timeout)
&& !cancelAcquisition_.get()) {
now = System.currentTimeMillis();
Thread.sleep(5);
}
if (now - start >= timeout) {
String msg = "Camera did not send first image within a reasonable time.\n";
if (acqSettings.isStageScanning) {
msg += "Make sure jumpers are correct on XY card and also micro-micromirror card.";
} else {
msg += "Make sure camera trigger cables are connected properly.";
}
throw new Exception(msg);
}
// grab all the images from the cameras, put them into the acquisition
int[] frNumber = new int[2*acqSettings.numChannels]; // keep track of how many frames we have received for each "channel" (MM channel is our channel * 2 for the 2 cameras)
int[] cameraFrNumber = new int[2]; // keep track of how many frames we have received from the camera
int[] tpNumber = new int[2*acqSettings.numChannels]; // keep track of which timepoint we are on for hardware timepoints
boolean skipNextImage = false; // hardware timepoints have to drop spurious images with overlap mode
final boolean checkForSkips = acqSettings.hardwareTimepoints && (acqSettings.cameraMode == CameraModes.Keys.OVERLAP);
final boolean skipPerSide = acqSettings.useChannels && (acqSettings.numChannels > 1)
&& (acqSettings.channelMode == MultichannelModes.Keys.SLICE_HW);
boolean done = false;
final long timeout2 = Math.max(1000, Math.round(5*sliceDuration));
start = System.currentTimeMillis();
long last = start;
try {
while ((core_.getRemainingImageCount() > 0
|| core_.isSequenceRunning(firstCamera)
|| (twoSided && core_.isSequenceRunning(secondCamera)))
&& !done) {
now = System.currentTimeMillis();
if (core_.getRemainingImageCount() > 0) { // we have an image to grab
TaggedImage timg = core_.popNextTaggedImage();
if (skipNextImage) {
skipNextImage = false;
continue; // goes to next iteration of this loop without doing anything else
}
// figure out which channel index this frame belongs to
// "channel index" is channel of MM acquisition
// channel indexes will go from 0 to (numSides * numChannels - 1)
// if double-sided then second camera gets odd channel indexes (1, 3, etc.)
// and adjacent pairs will be same color (e.g. 0 and 1 will be from first color, 2 and 3 from second, etc.)
String camera = (String) timg.tags.get("Camera");
int cameraIndex = camera.equals(firstCamera) ? 0: 1;
int channelIndex_tmp;
switch (acqSettings.channelMode) {
case NONE:
case VOLUME:
channelIndex_tmp = channelNum;
break;
case VOLUME_HW:
channelIndex_tmp = cameraFrNumber[cameraIndex] / acqSettings.numSlices; // want quotient only
break;
case SLICE_HW:
channelIndex_tmp = cameraFrNumber[cameraIndex] % acqSettings.numChannels; // want modulo arithmetic
break;
default:
// should never get here
throw new Exception("Undefined channel mode");
}
if (twoSided) {
channelIndex_tmp *= 2;
}
final int channelIndex = channelIndex_tmp + cameraIndex;
int actualTimePoint = timePoint;
if (acqSettings.hardwareTimepoints) {
actualTimePoint = tpNumber[channelIndex];
}
if (acqSettings.separateTimepoints) {
// if we are doing separate timepoints then frame is always 0
actualTimePoint = 0;
}
// note that hardwareTimepoints and separateTimepoints can never both be true
// add image to acquisition
if (spimMode == AcquisitionModes.Keys.NO_SCAN && !acqSettings.separateTimepoints) {
// create time series for no scan
addImageToAcquisition(acq_,
frNumber[channelIndex], channelIndex, actualTimePoint,
positionNum, now - acqStart, timg, bq);
} else { // standard, create Z-stacks
addImageToAcquisition(acq_, actualTimePoint, channelIndex,
frNumber[channelIndex], positionNum,
now - acqStart, timg, bq);
}
// update our counters to be ready for next image
frNumber[channelIndex]++;
cameraFrNumber[cameraIndex]++;
// if hardware timepoints then we only send one trigger and
// manually keep track of which channel/timepoint comes next
if (acqSettings.hardwareTimepoints
&& frNumber[channelIndex] >= acqSettings.numSlices) { // only do this if we are done with the slices in this MM channel
// we just finished filling one MM channel with all its slices so go to next timepoint for this channel
frNumber[channelIndex] = 0;
tpNumber[channelIndex]++;
// see if we are supposed to skip next image
if (checkForSkips) {
if (skipPerSide) { // one extra image per side, only happens with per-slice HW switching
if ((channelIndex == (acqSettings.numChannels - 1)) // final channel index is last one of side
|| (twoSided && (channelIndex == (acqSettings.numChannels - 2)))) { // 2nd-to-last channel index for two-sided is also last one of side
skipNextImage = true;
}
} else { // one extra image per MM channel, this includes case of only 1 color (either multi-channel disabled or else only 1 channel selected)
skipNextImage = true;
}
}
// update acquisition status message for hardware acquisition
// (for non-hardware acquisition message is updated elsewhere)
// Arbitrarily choose one possible channel to do this on.
if (channelIndex == 0 && (numTimePointsDone_ < acqSettings.numTimepoints)) {
numTimePointsDone_++;
updateAcquisitionStatus(AcquisitionStatus.ACQUIRING);
}
}
last = now; // keep track of last image timestamp
} else { // no image ready yet
done = cancelAcquisition_.get();
Thread.sleep(1);
if (now - last >= timeout2) {
ReportingUtils.logError("Camera did not send all expected images within" +
" a reasonable period for timepoint " + numTimePointsDone_ + ". Continuing anyway.");
nonfatalError = true;
done = true;
}
}
}
// update count if we stopped in the middle
if (cancelAcquisition_.get()) {
numTimePointsDone_--;
}
// if we are using demo camera then add some extra time to let controller finish
// since we got images without waiting for controller to actually send triggers
if (usingDemoCam) {
Thread.sleep(200); // for serial communication overhead
Thread.sleep((long)volumeDuration/nrChannelsSoftware); // estimate the time per channel, not ideal in case of software channel switching
}
} catch (InterruptedException iex) {
MyDialogUtils.showError(iex);
}
if (acqSettings.hardwareTimepoints) {
break; // only trigger controller once
}
} catch (Exception ex) {
MyDialogUtils.showError(ex);
} finally {
// cleanup at the end of each time we trigger the controller
ASIdiSPIM.getFrame().setHardwareInUse(false);
// put shutter back to original state
core_.setShutterOpen(shutterOpen);
core_.setAutoShutter(autoShutter);
// make sure cameras aren't running anymore
if (core_.isSequenceRunning(firstCamera)) {
core_.stopSequenceAcquisition(firstCamera);
}
if (twoSided && core_.isSequenceRunning(secondCamera)) {
core_.stopSequenceAcquisition(secondCamera);
}
}
}
}
if (acqSettings.hardwareTimepoints) {
break;
}
}
} catch (IllegalMonitorStateException ex) {
// do nothing, the acquisition was simply halted during its operation
// will log error message during finally clause
} catch (MMScriptException mex) {
MyDialogUtils.showError(mex);
} catch (Exception ex) {
MyDialogUtils.showError(ex);
} finally { // end of this acquisition (could be about to restart if separate viewers)
try {
// restore original window listeners
try {
vad.getImagePlus().getWindow().removeWindowListener(wl_acq);
for (WindowListener l : wls_orig) {
vad.getImagePlus().getWindow().addWindowListener(l);
}
} catch (Exception ex) {
// do nothing, window is probably gone
}
if (cancelAcquisition_.get()) {
ReportingUtils.logMessage("User stopped the acquisition");
}
bq.put(TaggedImageQueue.POISON);
// TODO: evaluate closeAcquisition call
// at the moment, the Micro-Manager api has a bug that causes
// a closed acquisition not be really closed, causing problems
// when the user closes a window of the previous acquisition
// changed r14705 (2014-11-24)
// gui_.closeAcquisition(acqName);
ReportingUtils.logMessage("diSPIM plugin acquisition " + acqName +
" took: " + (System.currentTimeMillis() - acqButtonStart) + "ms");
// flag that we are done with acquisition
acquisitionRunning_.set(false);
} catch (Exception ex) {
// exception while stopping sequence acquisition, not sure what to do...
MyDialogUtils.showError(ex, "Problem while finishing acquisition");
}
}
}// for loop over acquisitions
// cleanup after end of all acquisitions
// TODO be more careful and always do these if we actually started acquisition,
// even if exception happened
// restore camera
try {
core_.setCameraDevice(originalCamera);
} catch (Exception ex) {
MyDialogUtils.showError("Could not restore camera after acquisition");
}
// reset channel to original if we clobbered it
if (acqSettings.useChannels) {
multiChannelPanel_.setConfig(originalChannelConfig);
}
// clean up controller settings after acquisition
// want to do this, even with demo cameras, so we can test everything else
// TODO figure out if we really want to return piezos to 0 position (maybe center position,
// maybe not at all since we move when we switch to setup tab, something else??)
controller_.cleanUpControllerAfterAcquisition(acqSettings.numSides, acqSettings.firstSideIsA, true);
// if we did stage scanning restore its position and speed
if (acqSettings.isStageScanning) {
try {
// make sure stage scanning state machine is stopped, otherwise setting speed/position won't take
props_.setPropValue(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_STATE,
Properties.Values.SPIM_IDLE);
core_.setXYPosition(devices_.getMMDevice(Devices.Keys.XYSTAGE),
xyPosUm.x, xyPosUm.y);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, origXSpeed);
} catch (Exception ex) {
MyDialogUtils.showError("Could not restore XY stage position after acquisition");
}
}
updateAcquisitionStatus(AcquisitionStatus.DONE);
posUpdater_.pauseUpdates(false);
if (testAcq && prefs_.getBoolean(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_TESTACQ_SAVE, false)) {
String path = "";
try {
path = prefs_.getString(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_TESTACQ_PATH, "");
IJ.saveAs(acq_.getAcquisitionWindow().getImagePlus(), "raw", path);
// TODO consider generating a short metadata file to assist in interpretation
} catch (Exception ex) {
MyDialogUtils.showError("Could not save raw data from test acquisition to path " + path);
}
}
if (separateImageFilesOriginally) {
ImageUtils.setImageStorageClass(TaggedImageStorageDiskDefault.class);
}
cameras_.setSPIMCamerasForAcquisition(false);
if (liveModeOriginally) {
gui_.enableLiveMode(true);
}
if (nonfatalError) {
MyDialogUtils.showError("Missed some images during acquisition, see core log for details");
}
return true;
}
@Override
public void saveSettings() {
// save controller settings
props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.GALVOB, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.PLOGIC, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
}
/**
* Gets called when this tab gets focus. Refreshes values from properties.
*/
@Override
public void gotSelected() {
posUpdater_.pauseUpdates(true);
props_.callListeners();
// old joystick associations were cleared when leaving
// last tab so only do it if joystick settings need to be applied
if (navigationJoysticksCB_.isSelected()) {
updateJoysticks();
}
sliceFrameAdvanced_.setVisible(advancedSliceTimingCB_.isSelected());
posUpdater_.pauseUpdates(false);
}
/**
* called when tab looses focus.
*/
@Override
public void gotDeSelected() {
// if we have been using navigation panel's joysticks need to unset them
if (navigationJoysticksCB_.isSelected()) {
if (ASIdiSPIM.getFrame() != null) {
ASIdiSPIM.getFrame().getNavigationPanel().doJoystickSettings(false);
}
}
sliceFrameAdvanced_.setVisible(false);
}
@Override
public void devicesChangedAlert() {
devices_.callListeners();
}
/**
* Gets called when enclosing window closes
*/
@Override
public void windowClosing() {
if (acquisitionRequested_.get()) {
cancelAcquisition_.set(true);
while (acquisitionRunning_.get()) {
// spin wheels until we are done
}
}
sliceFrameAdvanced_.savePosition();
sliceFrameAdvanced_.dispose();
}
@Override
public void refreshDisplay() {
updateDurationLabels();
}
private void setRootDirectory(JTextField rootField) {
File result = FileDialogs.openDir(null,
"Please choose a directory root for image data",
MMStudio.MM_DATA_SET);
if (result != null) {
rootField.setText(result.getAbsolutePath());
}
}
/**
* The basic method for adding images to an existing data set. If the
* acquisition was not previously initialized, it will attempt to initialize
* it from the available image data. This version uses a blocking queue and is
* much faster than the one currently implemented in the ScriptInterface
* Eventually, this function should be replaced by the ScriptInterface version
* of the same.
* @param acq - MMAcquisition object to use (old way used acquisition name and then
* had to call deprecated function on every call, now just pass acquisition object
* @param frame - frame nr at which to insert the image
* @param channel - channel at which to insert image
* @param slice - (z) slice at which to insert image
* @param position - position at which to insert image
* @param ms - Time stamp to be added to the image metadata
* @param taggedImg - image + metadata to be added
* @param bq - Blocking queue to which the image should be added. This queue
* should be hooked up to the ImageCache belonging to this acquisitions
* @throws java.lang.InterruptedException
* @throws org.micromanager.utils.MMScriptException
*/
public void addImageToAcquisition(MMAcquisition acq,
int frame,
int channel,
int slice,
int position,
long ms,
TaggedImage taggedImg,
BlockingQueue<TaggedImage> bq) throws MMScriptException, InterruptedException {
// verify position number is allowed
if (acq.getPositions() <= position) {
throw new MMScriptException("The position number must not exceed declared"
+ " number of positions (" + acq.getPositions() + ")");
}
// verify that channel number is allowed
if (acq.getChannels() <= channel) {
throw new MMScriptException("The channel number must not exceed declared"
+ " number of channels (" + + acq.getChannels() + ")");
}
JSONObject tags = taggedImg.tags;
if (!acq.isInitialized()) {
throw new MMScriptException("Error in the ASIdiSPIM logic. Acquisition should have been initialized");
}
// create required coordinate tags
try {
MDUtils.setFrameIndex(tags, frame);
tags.put(MMTags.Image.FRAME, frame);
MDUtils.setChannelIndex(tags, channel);
MDUtils.setChannelName(tags, channelNames_[channel]);
MDUtils.setSliceIndex(tags, slice);
MDUtils.setPositionIndex(tags, position);
MDUtils.setElapsedTimeMs(tags, ms);
MDUtils.setImageTime(tags, MDUtils.getCurrentTime());
MDUtils.setZStepUm(tags, PanelUtils.getSpinnerFloatValue(stepSize_));
if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) {
// add default setting
tags.put(MMTags.Summary.SLICES_FIRST, true);
tags.put(MMTags.Summary.TIME_FIRST, false);
}
if (acq.getPositions() > 1) {
// if no position name is defined we need to insert a default one
if (tags.has(MMTags.Image.POS_NAME)) {
tags.put(MMTags.Image.POS_NAME, "Pos" + position);
}
}
// update frames if necessary
if (acq.getFrames() <= frame) {
acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame + 1));
}
} catch (JSONException e) {
throw new MMScriptException(e);
}
bq.put(taggedImg);
}
/***************** API *******************/
/**
* @return true if an acquisition is currently underway
* (e.g. all checks passed, controller set up, MM acquisition object created, etc.)
*/
public boolean isAcquisitionRunning() {
return acquisitionRunning_.get();
}
/**
* @return true if an acquisition has been requested by user. Will
* also return true if acquisition is running.
*/
public boolean isAcquisitionRequested() {
return acquisitionRequested_.get();
}
/**
* Stops the acquisition by setting an Atomic boolean indicating that we should
* halt. Does nothing if an acquisition isn't running.
*/
public void stopAcquisition() {
if (isAcquisitionRequested()) {
cancelAcquisition_.set(true);
}
}
/**
* @return pathname on filesystem to last completed acquisition
* (even if it was stopped pre-maturely). Null if not saved to disk.
*/
public String getLastAcquisitionPath() {
return lastAcquisitionPath_;
}
public String getLastAcquisitionName() {
return lastAcquisitionName_;
}
public ij.ImagePlus getLastAcquisitionImagePlus() throws ASIdiSPIMException {
try {
return gui_.getAcquisition(lastAcquisitionName_).getAcquisitionWindow().getImagePlus();
} catch (MMScriptException e) {
throw new ASIdiSPIMException(e);
}
}
public String getSavingDirectoryRoot() {
return rootField_.getText();
}
public void setSavingDirectoryRoot(String directory) throws ASIdiSPIMException {
rootField_.setText(directory);
try {
rootField_.commitEdit();
} catch (ParseException e) {
throw new ASIdiSPIMException(e);
}
}
public String getSavingNamePrefix() {
return prefixField_.getText();
}
public void setSavingNamePrefix(String acqPrefix) throws ASIdiSPIMException {
prefixField_.setText(acqPrefix);
try {
prefixField_.commitEdit();
} catch (ParseException e) {
throw new ASIdiSPIMException(e);
}
}
public boolean getSavingSeparateFile() {
return separateTimePointsCB_.isSelected();
}
public void setSavingSeparateFile(boolean separate) {
separateTimePointsCB_.setSelected(separate);
}
public boolean getSavingSaveWhileAcquiring() {
return saveCB_.isSelected();
}
public void setSavingSaveWhileAcquiring(boolean save) {
saveCB_.setSelected(save);
}
public org.micromanager.asidispim.Data.AcquisitionModes.Keys getAcquisitionMode() {
return (org.micromanager.asidispim.Data.AcquisitionModes.Keys) spimMode_.getSelectedItem();
}
public void setAcquisitionMode(org.micromanager.asidispim.Data.AcquisitionModes.Keys mode) {
spimMode_.setSelectedItem(mode);
}
public boolean getTimepointsEnabled() {
return useTimepointsCB_.isSelected();
}
public void setTimepointsEnabled(boolean enabled) {
useTimepointsCB_.setSelected(enabled);
}
public int getNumberOfTimepoints() {
return (Integer) numTimepoints_.getValue();
}
public void setNumberOfTimepoints(int numTimepoints) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(numTimepoints, 1, 100000)) {
throw new ASIdiSPIMException("illegal value for number of time points");
}
numTimepoints_.setValue(numTimepoints);
}
// getTimepointInterval already existed
public void setTimepointInterval(double intervalTimepoints) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(intervalTimepoints, 0.1, 32000)) {
throw new ASIdiSPIMException("illegal value for time point interval");
}
acquisitionInterval_.setValue(intervalTimepoints);
}
public boolean getMultiplePositionsEnabled() {
return usePositionsCB_.isSelected();
}
public void setMultiplePositionsEnabled(boolean enabled) {
usePositionsCB_.setSelected(enabled);
}
public double getMultiplePositionsPostMoveDelay() {
return PanelUtils.getSpinnerFloatValue(positionDelay_);
}
public void setMultiplePositionsDelay(double delayMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(delayMs, 0d, 10000d)) {
throw new ASIdiSPIMException("illegal value for post move delay");
}
positionDelay_.setValue(delayMs);
}
public boolean getChannelsEnabled() {
return multiChannelPanel_.isMultiChannel();
}
public void setChannelsEnabled(boolean enabled) {
multiChannelPanel_.setPanelEnabled(enabled);
}
public String[] getAvailableChannelGroups() {
return multiChannelPanel_.getAvailableGroups();
}
public String getChannelGroup() {
return multiChannelPanel_.getChannelGroup();
}
public void setChannelGroup(String channelGroup) {
String[] availableGroups = getAvailableChannelGroups();
for (String group : availableGroups) {
if (group.equals(channelGroup)) {
multiChannelPanel_.setChannelGroup(channelGroup);
}
}
}
public String[] getAvailableChannels() {
return multiChannelPanel_.getAvailableChannels();
}
public boolean getChannelEnabled(String channel) {
ChannelSpec[] usedChannels = multiChannelPanel_.getUsedChannels();
for (ChannelSpec spec : usedChannels) {
if (spec.config_.equals(channel)) {
return true;
}
}
return false;
}
public void setChannelEnabled(String channel, boolean enabled) {
multiChannelPanel_.setChannelEnabled(channel, enabled);
}
// getNumSides() already existed
public void setVolumeNumberOfSides(int numSides) {
if (numSides == 2) {
numSides_.setSelectedIndex(1);
} else {
numSides_.setSelectedIndex(0);
}
}
public void setFirstSideIsA(boolean firstSideIsA) {
if (firstSideIsA) {
firstSide_.setSelectedIndex(0);
} else {
firstSide_.setSelectedIndex(1);
}
}
public double getVolumeDelayBeforeSide() {
return PanelUtils.getSpinnerFloatValue(delaySide_);
}
public void setVolumeDelayBeforeSide(double delayMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(delayMs, 0d, 10000d)) {
throw new ASIdiSPIMException("illegal value for delay before side");
}
delaySide_.setValue(delayMs);
}
public int getVolumeSlicesPerVolume() {
return (Integer) numSlices_.getValue();
}
public void setVolumeSlicesPerVolume(int slices) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(slices, 1, 65000)) {
throw new ASIdiSPIMException("illegal value for number of slices");
}
numSlices_.setValue(slices);
}
public double getVolumeSliceStepSize() {
return PanelUtils.getSpinnerFloatValue(stepSize_);
}
public void setVolumeSliceStepSize(double stepSizeUm) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(stepSizeUm, 0d, 100d)) {
throw new ASIdiSPIMException("illegal value for slice step size");
}
stepSize_.setValue(stepSizeUm);
}
public boolean getVolumeMinimizeSlicePeriod() {
return minSlicePeriodCB_.isSelected();
}
public void setVolumeMinimizeSlicePeriod(boolean minimize) {
minSlicePeriodCB_.setSelected(minimize);
}
public double getVolumeSlicePeriod() {
return PanelUtils.getSpinnerFloatValue(desiredSlicePeriod_);
}
public void setVolumeSlicePeriod(double periodMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(periodMs, 1d, 1000d)) {
throw new ASIdiSPIMException("illegal value for slice period");
}
desiredSlicePeriod_.setValue(periodMs);
}
public double getVolumeSampleExposure() {
return PanelUtils.getSpinnerFloatValue(desiredLightExposure_);
}
public void setVolumeSampleExposure(double exposureMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(exposureMs, 1.0, 1000.0)) {
throw new ASIdiSPIMException("illegal value for sample exposure");
}
desiredLightExposure_.setValue(exposureMs);
}
public boolean getAutofocusDuringAcquisition() {
return useAutofocusCB_.isSelected();
}
public void setAutofocusDuringAcquisition(boolean enable) {
useAutofocusCB_.setSelected(enable);
}
public double getEstimatedSliceDuration() {
return sliceTiming_.sliceDuration;
}
public double getEstimatedVolumeDuration() {
return computeActualVolumeDuration();
}
public double getEstimatedAcquisitionDuration() {
return computeActualTimeLapseDuration();
}
} | plugins/ASIdiSPIM/src/org/micromanager/asidispim/AcquisitionPanel.java | ///////////////////////////////////////////////////////////////////////////////
//FILE: AcquisitionPanel.java
//PROJECT: Micro-Manager
//SUBSYSTEM: ASIdiSPIM plugin
//-----------------------------------------------------------------------------
//
// AUTHOR: Nico Stuurman, Jon Daniels
//
// COPYRIGHT: University of California, San Francisco, & ASI, 2013
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.asidispim;
import org.micromanager.asidispim.Data.AcquisitionModes;
import org.micromanager.asidispim.Data.CameraModes;
import org.micromanager.asidispim.Data.Cameras;
import org.micromanager.asidispim.Data.Devices;
import org.micromanager.asidispim.Data.MultichannelModes;
import org.micromanager.asidispim.Data.MyStrings;
import org.micromanager.asidispim.Data.Positions;
import org.micromanager.asidispim.Data.Prefs;
import org.micromanager.asidispim.Data.Properties;
import org.micromanager.asidispim.Utils.DevicesListenerInterface;
import org.micromanager.asidispim.Utils.ListeningJPanel;
import org.micromanager.asidispim.Utils.MyDialogUtils;
import org.micromanager.asidispim.Utils.MyNumberUtils;
import org.micromanager.asidispim.Utils.PanelUtils;
import org.micromanager.asidispim.Utils.SliceTiming;
import org.micromanager.asidispim.Utils.StagePositionUpdater;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.ParseException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.DefaultFormatter;
import net.miginfocom.swing.MigLayout;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import mmcorej.CMMCore;
import mmcorej.StrVector;
import mmcorej.TaggedImage;
import org.micromanager.api.MultiStagePosition;
import org.micromanager.api.StagePosition;
import org.micromanager.api.PositionList;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.ImageCache;
import org.micromanager.api.MMTags;
import org.micromanager.MMStudio;
import org.micromanager.acquisition.ComponentTitledBorder;
import org.micromanager.acquisition.DefaultTaggedImageSink;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.TaggedImageQueue;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.TaggedImageStorageMultipageTiff;
import org.micromanager.imagedisplay.VirtualAcquisitionDisplay;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMFrame;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
import com.swtdesigner.SwingResourceManager;
import ij.IJ;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import org.micromanager.asidispim.Data.AcquisitionSettings;
import org.micromanager.asidispim.Data.ChannelSpec;
import org.micromanager.asidispim.Data.Devices.Sides;
import org.micromanager.asidispim.Data.Joystick.Directions;
import org.micromanager.asidispim.Utils.ControllerUtils;
import org.micromanager.asidispim.Utils.AutofocusUtils;
import org.micromanager.asidispim.api.ASIdiSPIMException;
/**
*
* @author nico
* @author Jon
*/
@SuppressWarnings("serial")
public class AcquisitionPanel extends ListeningJPanel implements DevicesListenerInterface {
private final Devices devices_;
private final Properties props_;
private final Cameras cameras_;
private final Prefs prefs_;
private final ControllerUtils controller_;
private final AutofocusUtils autofocus_;
private final Positions positions_;
private final CMMCore core_;
private final ScriptInterface gui_;
private final JCheckBox advancedSliceTimingCB_;
private final JSpinner numSlices_;
private final JComboBox numSides_;
private final JComboBox firstSide_;
private final JSpinner numScansPerSlice_;
private final JSpinner lineScanDuration_;
private final JSpinner delayScan_;
private final JSpinner delayLaser_;
private final JSpinner delayCamera_;
private final JSpinner durationCamera_; // NB: not the same as camera exposure
private final JSpinner exposureCamera_; // NB: only used in advanced timing mode
private JCheckBox alternateBeamScanCB_;
private final JSpinner durationLaser_;
private final JSpinner delaySide_;
private final JLabel actualSlicePeriodLabel_;
private final JLabel actualVolumeDurationLabel_;
private final JLabel actualTimeLapseDurationLabel_;
private final JSpinner numTimepoints_;
private final JSpinner acquisitionInterval_;
private final JToggleButton buttonStart_;
private final JButton buttonTestAcq_;
private final JPanel volPanel_;
private final JPanel slicePanel_;
private final JPanel timepointPanel_;
private final JPanel savePanel_;
private final JPanel durationPanel_;
private final JFormattedTextField rootField_;
private final JFormattedTextField prefixField_;
private final JLabel acquisitionStatusLabel_;
private int numTimePointsDone_;
private final AtomicBoolean cancelAcquisition_ = new AtomicBoolean(false); // true if we should stop acquisition
private final AtomicBoolean acquisitionRequested_ = new AtomicBoolean(false); // true if acquisition has been requested to start or is underway
private final AtomicBoolean acquisitionRunning_ = new AtomicBoolean(false); // true if the acquisition is actually underway
private final StagePositionUpdater posUpdater_;
private final JSpinner stepSize_;
private final JLabel desiredSlicePeriodLabel_;
private final JSpinner desiredSlicePeriod_;
private final JLabel desiredLightExposureLabel_;
private final JSpinner desiredLightExposure_;
private final JCheckBox minSlicePeriodCB_;
private final JCheckBox separateTimePointsCB_;
private final JCheckBox saveCB_;
private final JComboBox spimMode_;
private final JCheckBox navigationJoysticksCB_;
private final JCheckBox usePositionsCB_;
private final JSpinner positionDelay_;
private final JCheckBox useTimepointsCB_;
private final JCheckBox useAutofocusCB_;
private final JPanel leftColumnPanel_;
private final JPanel centerColumnPanel_;
private final JPanel rightColumnPanel_;
private final MMFrame sliceFrameAdvanced_;
private SliceTiming sliceTiming_;
private final MultiChannelSubPanel multiChannelPanel_;
private final Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA,
Color.PINK, Color.CYAN, Color.YELLOW, Color.ORANGE};
private String lastAcquisitionPath_;
private String lastAcquisitionName_;
private MMAcquisition acq_;
private String[] channelNames_;
private int nrRepeats_; // how many separate acquisitions to perform
public AcquisitionPanel(ScriptInterface gui,
Devices devices,
Properties props,
Cameras cameras,
Prefs prefs,
StagePositionUpdater posUpdater,
Positions positions,
ControllerUtils controller,
AutofocusUtils autofocus) {
super(MyStrings.PanelNames.ACQUSITION.toString(),
new MigLayout(
"",
"[center]0[center]0[center]",
"0[top]0"));
gui_ = gui;
devices_ = devices;
props_ = props;
cameras_ = cameras;
prefs_ = prefs;
posUpdater_ = posUpdater;
positions_ = positions;
controller_ = controller;
autofocus_ = autofocus;
core_ = gui_.getMMCore();
numTimePointsDone_ = 0;
sliceTiming_ = new SliceTiming();
lastAcquisitionPath_ = "";
lastAcquisitionName_ = "";
acq_ = null;
channelNames_ = null;
PanelUtils pu = new PanelUtils(prefs_, props_, devices_);
// added to spinner controls where we should re-calculate the displayed
// slice period, volume duration, and time lapse duration
ChangeListener recalculateTimingDisplayCL = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (advancedSliceTimingCB_.isSelected()) {
// need to update sliceTiming_ from property values
sliceTiming_ = getTimingFromAdvancedSettings();
}
updateDurationLabels();
}
};
// added to combobox controls where we should re-calculate the displayed
// slice period, volume duration, and time lapse duration
ActionListener recalculateTimingDisplayAL = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateDurationLabels();
}
};
// start volume (main) sub-panel
volPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"[]8[]"));
volPanel_.setBorder(PanelUtils.makeTitledBorder("Volume Settings"));
if (!ASIdiSPIM.oSPIM) {
} else {
props_.setPropValue(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SIDES, "1");
}
volPanel_.add(new JLabel("Number of sides:"));
String [] str12 = {"1", "2"};
numSides_ = pu.makeDropDownBox(str12, Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SIDES, str12[1]);
numSides_.addActionListener(recalculateTimingDisplayAL);
if (!ASIdiSPIM.oSPIM) {
} else {
numSides_.setEnabled(false);
}
volPanel_.add(numSides_, "wrap");
volPanel_.add(new JLabel("First side:"));
String[] ab = {Devices.Sides.A.toString(), Devices.Sides.B.toString()};
if (!ASIdiSPIM.oSPIM) {
} else {
props_.setPropValue(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString());
}
firstSide_ = pu.makeDropDownBox(ab, Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString());
if (!ASIdiSPIM.oSPIM) {
} else {
firstSide_.setEnabled(false);
}
volPanel_.add(firstSide_, "wrap");
volPanel_.add(new JLabel("Delay before side [ms]:"));
delaySide_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_SIDE, 0);
delaySide_.addChangeListener(recalculateTimingDisplayCL);
volPanel_.add(delaySide_, "wrap");
volPanel_.add(new JLabel("Slices per side:"));
numSlices_ = pu.makeSpinnerInteger(1, 65000,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SLICES, 20);
numSlices_.addChangeListener(recalculateTimingDisplayCL);
volPanel_.add(numSlices_, "wrap");
volPanel_.add(new JLabel("Slice step size [\u00B5m]:"));
stepSize_ = pu.makeSpinnerFloat(0, 100, 0.1,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_SLICE_STEP_SIZE,
1.0);
volPanel_.add(stepSize_, "wrap");
// out of order so we can reference it
desiredSlicePeriod_ = pu.makeSpinnerFloat(1, 1000, 0.25,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_SLICE_PERIOD, 30);
minSlicePeriodCB_ = pu.makeCheckBox("Minimize slice period",
Properties.Keys.PREFS_MINIMIZE_SLICE_PERIOD, panelName_, false);
minSlicePeriodCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean doMin = minSlicePeriodCB_.isSelected();
desiredSlicePeriod_.setEnabled(!doMin);
desiredSlicePeriodLabel_.setEnabled(!doMin);
recalculateSliceTiming(false);
}
});
volPanel_.add(minSlicePeriodCB_, "span 2, wrap");
// special field that is enabled/disabled depending on whether advanced timing is enabled
desiredSlicePeriodLabel_ = new JLabel("Slice period [ms]:");
volPanel_.add(desiredSlicePeriodLabel_);
volPanel_.add(desiredSlicePeriod_, "wrap");
desiredSlicePeriod_.addChangeListener(PanelUtils.coerceToQuarterIntegers(desiredSlicePeriod_));
desiredSlicePeriod_.addChangeListener(recalculateTimingDisplayCL);
// special field that is enabled/disabled depending on whether advanced timing is enabled
desiredLightExposureLabel_ = new JLabel("Sample exposure [ms]:");
volPanel_.add(desiredLightExposureLabel_);
desiredLightExposure_ = pu.makeSpinnerFloat(1.0, 1000, 0.25,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_EXPOSURE, 8.5);
desiredLightExposure_.addChangeListener(PanelUtils.coerceToQuarterIntegers(desiredLightExposure_));
desiredLightExposure_.addChangeListener(recalculateTimingDisplayCL);
volPanel_.add(desiredLightExposure_, "wrap");
// special checkbox to use the advanced timing settings
// action handler added below after defining components it enables/disables
advancedSliceTimingCB_ = pu.makeCheckBox("Use advanced timing settings",
Properties.Keys.PREFS_ADVANCED_SLICE_TIMING, panelName_, false);
volPanel_.add(advancedSliceTimingCB_, "left, span 2, wrap");
// end volume sub-panel
// start advanced slice timing frame
// visibility of this frame is controlled from advancedTiming checkbox
// this frame is separate from main plugin window
sliceFrameAdvanced_ = new MMFrame();
sliceFrameAdvanced_.setTitle("Advanced timing");
sliceFrameAdvanced_.loadPosition(100, 100);
slicePanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"[]8[]"));
sliceFrameAdvanced_.add(slicePanel_);
class SliceFrameAdapter extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
advancedSliceTimingCB_.setSelected(false);
sliceFrameAdvanced_.savePosition();
}
}
sliceFrameAdvanced_.addWindowListener(new SliceFrameAdapter());
JLabel scanDelayLabel = new JLabel("Delay before scan [ms]:");
slicePanel_.add(scanDelayLabel);
delayScan_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_SCAN, 0);
delayScan_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayScan_));
delayScan_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(delayScan_, "wrap");
JLabel lineScanLabel = new JLabel("Lines scans per slice:");
slicePanel_.add(lineScanLabel);
numScansPerSlice_ = pu.makeSpinnerInteger(1, 1000,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_NUM_SCANSPERSLICE, 1);
numScansPerSlice_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(numScansPerSlice_, "wrap");
JLabel lineScanPeriodLabel = new JLabel("Line scan duration [ms]:");
slicePanel_.add(lineScanPeriodLabel);
lineScanDuration_ = pu.makeSpinnerFloat(1, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_SCAN, 10);
lineScanDuration_.addChangeListener(PanelUtils.coerceToQuarterIntegers(lineScanDuration_));
lineScanDuration_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(lineScanDuration_, "wrap");
JLabel delayLaserLabel = new JLabel("Delay before laser [ms]:");
slicePanel_.add(delayLaserLabel);
delayLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_LASER, 0);
delayLaser_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayLaser_));
delayLaser_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(delayLaser_, "wrap");
JLabel durationLabel = new JLabel("Laser trig duration [ms]:");
slicePanel_.add(durationLabel);
durationLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_LASER, 1);
durationLaser_.addChangeListener(PanelUtils.coerceToQuarterIntegers(durationLaser_));
durationLaser_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(durationLaser_, "span 2, wrap");
JLabel delayLabel = new JLabel("Delay before camera [ms]:");
slicePanel_.add(delayLabel);
delayCamera_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_CAMERA, 0);
delayCamera_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayCamera_));
delayCamera_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(delayCamera_, "wrap");
JLabel cameraLabel = new JLabel("Camera trig duration [ms]:");
slicePanel_.add(cameraLabel);
durationCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_CAMERA, 0);
durationCamera_.addChangeListener(PanelUtils.coerceToQuarterIntegers(durationCamera_));
durationCamera_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(durationCamera_, "wrap");
JLabel exposureLabel = new JLabel("Camera exposure [ms]:");
slicePanel_.add(exposureLabel);
exposureCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_ADVANCED_CAMERA_EXPOSURE, 10f);
exposureCamera_.addChangeListener(recalculateTimingDisplayCL);
slicePanel_.add(exposureCamera_, "wrap");
alternateBeamScanCB_ = pu.makeCheckBox("Alternate scan direction",
Properties.Keys.PREFS_SCAN_OPPOSITE_DIRECTIONS, panelName_, false);
slicePanel_.add(alternateBeamScanCB_, "center, span 2, wrap");
final JComponent[] simpleTimingComponents = { desiredLightExposure_,
minSlicePeriodCB_, desiredSlicePeriodLabel_,
desiredLightExposureLabel_};
final JComponent[] advancedTimingComponents = {
delayScan_, numScansPerSlice_, lineScanDuration_,
delayLaser_, durationLaser_, delayCamera_,
durationCamera_, exposureCamera_, alternateBeamScanCB_};
PanelUtils.componentsSetEnabled(advancedTimingComponents, advancedSliceTimingCB_.isSelected());
PanelUtils.componentsSetEnabled(simpleTimingComponents, !advancedSliceTimingCB_.isSelected());
// this action listener takes care of enabling/disabling inputs
// of the advanced slice timing window
// we call this to get GUI looking right
ItemListener sliceTimingDisableGUIInputs = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean enabled = advancedSliceTimingCB_.isSelected();
// set other components in this advanced timing frame
PanelUtils.componentsSetEnabled(advancedTimingComponents, enabled);
// also control some components in main volume settings sub-panel
PanelUtils.componentsSetEnabled(simpleTimingComponents, !enabled);
desiredSlicePeriod_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected());
desiredSlicePeriodLabel_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected());
updateDurationLabels();
}
};
// this action listener shows/hides the advanced timing frame
ActionListener showAdvancedTimingFrame = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean enabled = advancedSliceTimingCB_.isSelected();
if (enabled) {
sliceFrameAdvanced_.setVisible(enabled);
}
}
};
sliceFrameAdvanced_.pack();
sliceFrameAdvanced_.setResizable(false);
// end slice Frame
// start repeat (time lapse) sub-panel
timepointPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"[]8[]"));
useTimepointsCB_ = pu.makeCheckBox("Time points",
Properties.Keys.PREFS_USE_TIMEPOINTS, panelName_, false);
useTimepointsCB_.setToolTipText("Perform a time-lapse acquisition");
useTimepointsCB_.setEnabled(true);
useTimepointsCB_.setFocusPainted(false);
ComponentTitledBorder componentBorder =
new ComponentTitledBorder(useTimepointsCB_, timepointPanel_,
BorderFactory.createLineBorder(ASIdiSPIM.borderColor));
timepointPanel_.setBorder(componentBorder);
ChangeListener recalculateTimeLapseDisplay = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
updateActualTimeLapseDurationLabel();
}
};
useTimepointsCB_.addChangeListener(recalculateTimeLapseDisplay);
timepointPanel_.add(new JLabel("Number:"));
numTimepoints_ = pu.makeSpinnerInteger(1, 100000,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_ACQUISITIONS, 1);
numTimepoints_.addChangeListener(recalculateTimeLapseDisplay);
numTimepoints_.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
// update nrRepeats_ variable so the acquisition can be extended or shortened
// as long as we have separate timepoints
if (acquisitionRunning_.get() && getSavingSeparateFile()) {
nrRepeats_ = getNumTimepoints();
}
}
});
timepointPanel_.add(numTimepoints_, "wrap");
timepointPanel_.add(new JLabel("Interval [s]:"));
acquisitionInterval_ = pu.makeSpinnerFloat(0.1, 32000, 0.1,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_ACQUISITION_INTERVAL, 60);
acquisitionInterval_.addChangeListener(recalculateTimeLapseDisplay);
timepointPanel_.add(acquisitionInterval_, "wrap");
// enable/disable panel elements depending on checkbox state
useTimepointsCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected());
}
});
PanelUtils.componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected()); // initialize
// end repeat sub-panel
// start savePanel
// TODO for now these settings aren't part of acquisition settings
// TODO consider whether that should be changed
final int textFieldWidth = 16;
savePanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]8[left]",
"[]4[]"));
savePanel_.setBorder(PanelUtils.makeTitledBorder("Data Saving Settings"));
separateTimePointsCB_ = pu.makeCheckBox("Separate viewer / file for each time point",
Properties.Keys.PREFS_SEPARATE_VIEWERS_FOR_TIMEPOINTS, panelName_, false);
savePanel_.add(separateTimePointsCB_, "span 3, left, wrap");
saveCB_ = pu.makeCheckBox("Save while acquiring",
Properties.Keys.PREFS_SAVE_WHILE_ACQUIRING, panelName_, false);
// init the save while acquiring CB; could also do two doClick() calls
// TODO check that it's initialized now
savePanel_.add(saveCB_, "skip 1, span 2, center, wrap");
JLabel dirRootLabel = new JLabel ("Directory root:");
savePanel_.add(dirRootLabel);
DefaultFormatter formatter = new DefaultFormatter();
rootField_ = new JFormattedTextField(formatter);
rootField_.setText( prefs_.getString(panelName_,
Properties.Keys.PLUGIN_DIRECTORY_ROOT, "") );
rootField_.addPropertyChangeListener(new PropertyChangeListener() {
// will respond to commitEdit() as well as GUI edit on commit
@Override
public void propertyChange(PropertyChangeEvent evt) {
prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT,
rootField_.getText());
}
});
rootField_.setColumns(textFieldWidth);
savePanel_.add(rootField_, "span 2");
JButton browseRootButton = new JButton();
browseRootButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
setRootDirectory(rootField_);
prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT,
rootField_.getText());
}
});
browseRootButton.setMargin(new Insets(2, 5, 2, 5));
browseRootButton.setText("...");
savePanel_.add(browseRootButton, "wrap");
JLabel namePrefixLabel = new JLabel();
namePrefixLabel.setText("Name prefix:");
savePanel_.add(namePrefixLabel);
prefixField_ = new JFormattedTextField(formatter);
prefixField_.setText( prefs_.getString(panelName_,
Properties.Keys.PLUGIN_NAME_PREFIX, "acq"));
prefixField_.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
prefs_.putString(panelName_, Properties.Keys.PLUGIN_NAME_PREFIX,
prefixField_.getText());
}
});
prefixField_.setColumns(textFieldWidth);
savePanel_.add(prefixField_, "span 2, wrap");
// since we use the name field even for acquisitions in RAM,
// we only need to gray out the directory-related components
final JComponent[] saveComponents = { browseRootButton, rootField_,
dirRootLabel };
PanelUtils.componentsSetEnabled(saveComponents, saveCB_.isSelected());
saveCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(saveComponents, saveCB_.isSelected());
}
});
// end save panel
// start duration report panel
durationPanel_ = new JPanel(new MigLayout(
"",
"[right]6[left, 40%!]",
"[]5[]"));
durationPanel_.setBorder(PanelUtils.makeTitledBorder("Durations"));
durationPanel_.setPreferredSize(new Dimension(125, 0)); // fix width so it doesn't constantly change depending on text
durationPanel_.add(new JLabel("Slice:"));
actualSlicePeriodLabel_ = new JLabel();
durationPanel_.add(actualSlicePeriodLabel_, "wrap");
durationPanel_.add(new JLabel("Volume:"));
actualVolumeDurationLabel_ = new JLabel();
durationPanel_.add(actualVolumeDurationLabel_, "wrap");
durationPanel_.add(new JLabel("Total:"));
actualTimeLapseDurationLabel_ = new JLabel();
durationPanel_.add(actualTimeLapseDurationLabel_, "wrap");
// end duration report panel
buttonTestAcq_ = new JButton("Test Acquisition");
buttonTestAcq_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runTestAcquisition(Devices.Sides.NONE);
}
});
buttonStart_ = new JToggleButton();
buttonStart_.setIconTextGap(6);
buttonStart_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isAcquisitionRequested()) {
stopAcquisition();
} else {
runAcquisition();
}
}
});
updateStartButton(); // call once to initialize, isSelected() will be false
// make the size of the test button match the start button (easier on the eye)
Dimension sizeStart = buttonStart_.getPreferredSize();
Dimension sizeTest = buttonTestAcq_.getPreferredSize();
sizeTest.height = sizeStart.height;
buttonTestAcq_.setPreferredSize(sizeTest);
acquisitionStatusLabel_ = new JLabel("");
acquisitionStatusLabel_.setBackground(prefixField_.getBackground());
acquisitionStatusLabel_.setOpaque(true);
updateAcquisitionStatus(AcquisitionStatus.NONE);
// Channel Panel (separate file for code)
multiChannelPanel_ = new MultiChannelSubPanel(gui, devices_, props_, prefs_);
multiChannelPanel_.addDurationLabelListener(this);
// Position Panel
final JPanel positionPanel = new JPanel();
positionPanel.setLayout(new MigLayout("flowx, fillx","[right]10[left][10][]","[]8[]"));
usePositionsCB_ = pu.makeCheckBox("Multiple positions (XY)",
Properties.Keys.PREFS_USE_MULTIPOSITION, panelName_, false);
usePositionsCB_.setToolTipText("Acquire datasest at multiple postions");
usePositionsCB_.setEnabled(true);
usePositionsCB_.setFocusPainted(false);
componentBorder =
new ComponentTitledBorder(usePositionsCB_, positionPanel,
BorderFactory.createLineBorder(ASIdiSPIM.borderColor));
positionPanel.setBorder(componentBorder);
usePositionsCB_.addChangeListener(recalculateTimingDisplayCL);
final JButton editPositionListButton = new JButton("Edit position list...");
editPositionListButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gui_.showXYPositionList();
}
});
positionPanel.add(editPositionListButton, "span 2, center");
// add empty fill space on right side of panel
positionPanel.add(new JLabel(""), "wrap, growx");
positionPanel.add(new JLabel("Post-move delay [ms]:"));
positionDelay_ = pu.makeSpinnerFloat(0.0, 10000.0, 100.0,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_POSITION_DELAY,
0.0);
positionPanel.add(positionDelay_, "wrap");
// enable/disable panel elements depending on checkbox state
usePositionsCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(positionPanel, usePositionsCB_.isSelected());
}
});
PanelUtils.componentsSetEnabled(positionPanel, usePositionsCB_.isSelected()); // initialize
// end of Position panel
// checkbox to use navigation joystick settings or not
// an "orphan" UI element
navigationJoysticksCB_ = new JCheckBox("Use Navigation joystick settings");
navigationJoysticksCB_.setSelected(prefs_.getBoolean(panelName_,
Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS, false));
navigationJoysticksCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateJoysticks();
prefs_.putBoolean(panelName_, Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS,
navigationJoysticksCB_.isSelected());
}
});
// checkbox to signal that autofocus should be used during acquisition
// another orphan UI element
useAutofocusCB_ = new JCheckBox("Autofocus during acquisition");
useAutofocusCB_.setSelected(prefs_.getBoolean(panelName_,
Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS, false));
useAutofocusCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
prefs_.putBoolean(panelName_,
Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS,
useAutofocusCB_.isSelected());
}
});
// set up tabbed panels for GUI
// make 3 columns as own JPanels to get vertical space right
// in each column without dependencies on other columns
leftColumnPanel_ = new JPanel(new MigLayout(
"",
"[]",
"[]6[]10[]10[]"));
leftColumnPanel_.add(durationPanel_, "split 2");
leftColumnPanel_.add(timepointPanel_, "wrap, growx");
leftColumnPanel_.add(savePanel_, "wrap");
leftColumnPanel_.add(new JLabel("Acquisition mode: "), "split 2, right");
AcquisitionModes acqModes = new AcquisitionModes(devices_, prefs_);
spimMode_ = acqModes.getComboBox();
spimMode_.addActionListener(recalculateTimingDisplayAL);
leftColumnPanel_.add(spimMode_, "left, wrap");
leftColumnPanel_.add(buttonStart_, "split 3, left");
leftColumnPanel_.add(new JLabel(" "));
leftColumnPanel_.add(buttonTestAcq_, "wrap");
leftColumnPanel_.add(new JLabel("Status:"), "split 2, left");
leftColumnPanel_.add(acquisitionStatusLabel_);
centerColumnPanel_ = new JPanel(new MigLayout(
"",
"[]",
"[]"));
centerColumnPanel_.add(positionPanel, "growx, wrap");
centerColumnPanel_.add(multiChannelPanel_, "wrap");
centerColumnPanel_.add(navigationJoysticksCB_, "wrap");
centerColumnPanel_.add(useAutofocusCB_);
rightColumnPanel_ = new JPanel(new MigLayout(
"",
"[]",
"[]"));
rightColumnPanel_.add(volPanel_);
// add the column panels to the main panel
this.add(leftColumnPanel_);
this.add(centerColumnPanel_);
this.add(rightColumnPanel_);
// properly initialize the advanced slice timing
advancedSliceTimingCB_.addItemListener(sliceTimingDisableGUIInputs);
sliceTimingDisableGUIInputs.itemStateChanged(null);
advancedSliceTimingCB_.addActionListener(showAdvancedTimingFrame);
// included is calculating slice timing
updateDurationLabels();
}//end constructor
private void updateJoysticks() {
if (ASIdiSPIM.getFrame() != null) {
ASIdiSPIM.getFrame().getNavigationPanel().
doJoystickSettings(navigationJoysticksCB_.isSelected());
}
}
public final void updateDurationLabels() {
updateActualSlicePeriodLabel();
updateActualVolumeDurationLabel();
updateActualTimeLapseDurationLabel();
}
private void updateCalibrationOffset(final Sides side,
final AutofocusUtils.FocusResult score) {
if (score.getFocusSuccess()) {
double offsetDelta = score.getOffsetDelta();
double maxDelta = props_.getPropValueFloat(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_MAXOFFSETCHANGE);
if (Math.abs(offsetDelta) <= maxDelta) {
ASIdiSPIM.getFrame().getSetupPanel(side).updateCalibrationOffset(score);
} else {
ReportingUtils.logMessage("autofocus successful for side " + side + " but offset change too much to automatically update");
}
}
}
public SliceTiming getSliceTiming() {
return sliceTiming_;
}
/**
* Sets the acquisition name prefix programmatically.
* Added so that name prefix can be changed from a script.
* @param acqName
*/
public void setAcquisitionNamePrefix(String acqName) {
prefixField_.setText(acqName);
}
private void updateStartButton() {
boolean started = isAcquisitionRequested();
buttonStart_.setSelected(started);
buttonStart_.setText(started ? "Stop Acquisition!" : "Start Acquisition!");
buttonStart_.setBackground(started ? Color.red : Color.green);
buttonStart_.setIcon(started ?
SwingResourceManager.
getIcon(MMStudio.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudio.class,
"/org/micromanager/icons/arrow_right.png"));
buttonTestAcq_.setEnabled(!started);
}
/**
* @return CameraModes.Keys value from Settings panel
* (internal, edge, overlap, pseudo-overlap)
*/
private CameraModes.Keys getSPIMCameraMode() {
return CameraModes.getKeyFromPrefCode(
prefs_.getInt(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_MODE, 0));
}
/**
* convenience method to avoid having to regenerate acquisition settings
*/
private int getNumTimepoints() {
if (useTimepointsCB_.isSelected()) {
return (Integer) numTimepoints_.getValue();
} else {
return 1;
}
}
/**
* convenience method to avoid having to regenerate acquisition settings
* public for API use
*/
public int getNumSides() {
if (numSides_.getSelectedIndex() == 1) {
return 2;
} else {
return 1;
}
}
/**
* convenience method to avoid having to regenerate acquisition settings
* public for API use
*/
public boolean isFirstSideA() {
return ((String) firstSide_.getSelectedItem()).equals("A");
}
/**
* convenience method to avoid having to regenerate acquisition settings.
* public for API use
*/
public double getTimepointInterval() {
return PanelUtils.getSpinnerFloatValue(acquisitionInterval_);
}
/**
* Gathers all current acquisition settings into dedicated POD object
* @return
*/
public AcquisitionSettings getCurrentAcquisitionSettings() {
AcquisitionSettings acqSettings = new AcquisitionSettings();
acqSettings.spimMode = (AcquisitionModes.Keys) spimMode_.getSelectedItem();
acqSettings.isStageScanning = (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN
|| acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN_INTERLEAVED);
acqSettings.useTimepoints = useTimepointsCB_.isSelected();
acqSettings.numTimepoints = getNumTimepoints();
acqSettings.timepointInterval = getTimepointInterval();
acqSettings.useMultiPositions = usePositionsCB_.isSelected();
acqSettings.useChannels = multiChannelPanel_.isMultiChannel();
acqSettings.channelMode = multiChannelPanel_.getChannelMode();
acqSettings.numChannels = multiChannelPanel_.getNumChannels();
acqSettings.channels = multiChannelPanel_.getUsedChannels();
acqSettings.channelGroup = multiChannelPanel_.getChannelGroup();
acqSettings.useAutofocus = useAutofocusCB_.isSelected();
acqSettings.numSides = getNumSides();
acqSettings.firstSideIsA = isFirstSideA();
acqSettings.delayBeforeSide = PanelUtils.getSpinnerFloatValue(delaySide_);
acqSettings.numSlices = (Integer) numSlices_.getValue();
acqSettings.stepSizeUm = PanelUtils.getSpinnerFloatValue(stepSize_);
acqSettings.minimizeSlicePeriod = minSlicePeriodCB_.isSelected();
acqSettings.desiredSlicePeriod = PanelUtils.getSpinnerFloatValue(desiredSlicePeriod_);
acqSettings.desiredLightExposure = PanelUtils.getSpinnerFloatValue(desiredLightExposure_);
acqSettings.centerAtCurrentZ = false;
acqSettings.sliceTiming = sliceTiming_;
acqSettings.cameraMode = getSPIMCameraMode();
acqSettings.accelerationX = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_ACCEL);
acqSettings.hardwareTimepoints = false; // when running acquisition we check this and set to true if needed
acqSettings.separateTimepoints = getSavingSeparateFile();
return acqSettings;
}
/**
* gets the correct value for the slice timing's sliceDuration field
* based on other values of slice timing
* @param s
* @return
*/
private float getSliceDuration(final SliceTiming s) {
// slice duration is the max out of the scan time, laser time, and camera time
return Math.max(Math.max(
s.scanDelay +
(s.scanPeriod * s.scanNum), // scan time
s.laserDelay + s.laserDuration // laser time
),
s.cameraDelay + s.cameraDuration // camera time
);
}
/**
* gets the slice timing from advanced settings
* (normally these advanced settings are read-only and we populate them
* ourselves depending on the user's requests and our algorithm below)
* @return
*/
private SliceTiming getTimingFromAdvancedSettings() {
SliceTiming s = new SliceTiming();
s.scanDelay = PanelUtils.getSpinnerFloatValue(delayScan_);
s.scanNum = (Integer) numScansPerSlice_.getValue();
s.scanPeriod = PanelUtils.getSpinnerFloatValue(lineScanDuration_);
s.laserDelay = PanelUtils.getSpinnerFloatValue(delayLaser_);
s.laserDuration = PanelUtils.getSpinnerFloatValue(durationLaser_);
s.cameraDelay = PanelUtils.getSpinnerFloatValue(delayCamera_);
s.cameraDuration = PanelUtils.getSpinnerFloatValue(durationCamera_);
s.cameraExposure = PanelUtils.getSpinnerFloatValue(exposureCamera_);
s.sliceDuration = getSliceDuration(s);
return s;
}
/**
*
* @param showWarnings true to warn user about needing to change slice period
* @return
*/
private SliceTiming getTimingFromPeriodAndLightExposure(boolean showWarnings) {
// uses algorithm Jon worked out in Octave code; each slice period goes like this:
// 1. camera readout time (none if in overlap mode, 0.25ms in PCO pseudo-overlap)
// 2. any extra delay time
// 3. camera reset time
// 4. start scan 0.25ms before camera global exposure and shifted up in time to account for delay introduced by Bessel filter
// 5. turn on laser as soon as camera global exposure, leave laser on for desired light exposure time
// 7. end camera exposure in final 0.25ms, post-filter scan waveform also ends now
final float scanLaserBufferTime = MyNumberUtils.roundToQuarterMs(0.25f); // below assumed to be multiple of 0.25ms
final Color foregroundColorOK = Color.BLACK;
final Color foregroundColorError = Color.RED;
final Component elementToColor = desiredSlicePeriod_.getEditor().getComponent(0);
SliceTiming s = new SliceTiming();
final float cameraResetTime = computeCameraResetTime(); // recalculate for safety
final float cameraReadoutTime = computeCameraReadoutTime(); // recalculate for safety
// can we use acquisition settings directly? because they may be in flux
final AcquisitionSettings acqSettings = getCurrentAcquisitionSettings();
final float cameraReadout_max = MyNumberUtils.ceilToQuarterMs(cameraReadoutTime);
final float cameraReset_max = MyNumberUtils.ceilToQuarterMs(cameraResetTime);
// we will wait cameraReadout_max before triggering camera, then wait another cameraReset_max for global exposure
// this will also be in 0.25ms increment
final float globalExposureDelay_max = cameraReadout_max + cameraReset_max;
final float laserDuration = MyNumberUtils.roundToQuarterMs(acqSettings.desiredLightExposure);
final float scanDuration = laserDuration + 2*scanLaserBufferTime;
// scan will be longer than laser by 0.25ms at both start and end
// account for delay in scan position due to Bessel filter by starting the scan slightly earlier
// than we otherwise would (Bessel filter selected b/c stretches out pulse without any ripples)
// delay to start is (empirically) 0.07ms + 0.25/(freq in kHz)
// delay to midpoint is empirically 0.38/(freq in kHz)
// group delay for 5th-order bessel filter ~0.39/freq from theory and ~0.4/freq from IC datasheet
final float scanFilterFreq = Math.max(props_.getPropValueFloat(Devices.Keys.GALVOA, Properties.Keys.SCANNER_FILTER_X),
props_.getPropValueFloat(Devices.Keys.GALVOB, Properties.Keys.SCANNER_FILTER_X));
float scanDelayFilter = 0;
if (scanFilterFreq != 0) {
scanDelayFilter = MyNumberUtils.roundToQuarterMs(0.39f/scanFilterFreq);
}
// If the PLogic card is used, account for 0.25ms delay it introduces to
// the camera and laser trigger signals => subtract 0.25ms from the scanner delay
// (start scanner 0.25ms later than it would be otherwise)
// this time-shift opposes the Bessel filter delay
// scanDelayFilter won't be negative unless scanFilterFreq is more than 3kHz which shouldn't happen
if (devices_.isValidMMDevice(Devices.Keys.PLOGIC)) {
scanDelayFilter -= 0.25f;
}
s.scanDelay = globalExposureDelay_max - scanLaserBufferTime // start scan 0.25ms before camera's global exposure
- scanDelayFilter; // start galvo moving early due to card's Bessel filter and delay of TTL signals via PLC
s.scanNum = 1;
s.scanPeriod = scanDuration;
s.laserDelay = globalExposureDelay_max; // turn on laser as soon as camera's global exposure is reached
s.laserDuration = laserDuration;
s.cameraDelay = cameraReadout_max; // camera must readout last frame before triggering again
// figure out desired time for camera to be exposing (including reset time)
// because both camera trigger and laser on occur on 0.25ms intervals (i.e. we may not
// trigger the laser until 0.24ms after global exposure) use cameraReset_max
final float cameraExposure = cameraReset_max + laserDuration;
switch (acqSettings.cameraMode) {
case EDGE:
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = cameraExposure + 0.1f; // add 0.1ms as safety margin, may require adding an additional 0.25ms to slice
// slight delay between trigger and actual exposure start
// is included in exposure time for Hamamatsu and negligible for Andor and PCO cameras
// ensure not to miss triggers by not being done with readout in time for next trigger, add 0.25ms if needed
if (getSliceDuration(s) < (s.cameraExposure + cameraReadoutTime)) {
ReportingUtils.logDebugMessage("Added 0.25ms in edge-trigger mode to make sure camera exposure long enough without dropping frames");
s.cameraDelay += 0.25f;
s.laserDelay += 0.25f;
s.scanDelay += 0.25f;
}
break;
case LEVEL: // AKA "bulb mode", TTL rising starts exposure, TTL falling ends it
s.cameraDuration = MyNumberUtils.ceilToQuarterMs(cameraExposure);
s.cameraExposure = 1; // doesn't really matter, controlled by TTL
break;
case OVERLAP: // only Hamamatsu or Andor
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = 1; // doesn't really matter, controlled by interval between triggers
break;
case PSEUDO_OVERLAP: // only PCO, enforce 0.25ms between end exposure and start of next exposure by triggering camera 0.25ms into the slice
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = getSliceDuration(s) - s.cameraDelay; // s.cameraDelay should be 0.25ms
if (!MyNumberUtils.floatsEqual(s.cameraDelay, 0.25f)) {
MyDialogUtils.showError("Camera delay should be 0.25ms for pseudo-overlap mode.");
}
break;
case INTERNAL:
default:
MyDialogUtils.showError("Invalid camera mode");
break;
}
// fix corner case of negative calculated scanDelay
if (s.scanDelay < 0) {
s.cameraDelay -= s.scanDelay;
s.laserDelay -= s.scanDelay;
s.scanDelay = 0; // same as (-= s.scanDelay)
}
// if a specific slice period was requested, add corresponding delay to scan/laser/camera
elementToColor.setForeground(foregroundColorOK);
if (!acqSettings.minimizeSlicePeriod) {
float globalDelay = acqSettings.desiredSlicePeriod - getSliceDuration(s); // both should be in 0.25ms increments // TODO fix
if (globalDelay < 0) {
globalDelay = 0;
if (showWarnings) { // only true when user has specified period that is unattainable
MyDialogUtils.showError(
"Increasing slice period to meet laser exposure constraint\n"
+ "(time required for camera readout; readout time depends on ROI).");
elementToColor.setForeground(foregroundColorError);
}
}
s.scanDelay += globalDelay;
s.cameraDelay += globalDelay;
s.laserDelay += globalDelay;
}
// // Add 0.25ms to globalDelay if it is 0 and we are on overlap mode and scan has been shifted forward
// // basically the last 0.25ms of scan time that would have determined the slice period isn't
// // there any more because the scan time is moved up => add in the 0.25ms at the start of the slice
// // in edge or level trigger mode the camera trig falling edge marks the end of the slice period
// // not sure if PCO pseudo-overlap needs this, probably not because adding 0.25ms overhead in that case
// if (MyNumberUtils.floatsEqual(cameraReadout_max, 0f) // true iff overlap being used
// && (scanDelayFilter > 0.01f)) {
// globalDelay += 0.25f;
// }
// fix corner case of (exposure time + readout time) being greater than the slice duration
// most of the time the slice duration is already larger
float globalDelay = MyNumberUtils.ceilToQuarterMs((s.cameraExposure + cameraReadoutTime) - getSliceDuration(s));
if (globalDelay > 0) {
s.scanDelay += globalDelay;
s.cameraDelay += globalDelay;
s.laserDelay += globalDelay;
}
// update the slice duration based on our new values
s.sliceDuration = getSliceDuration(s);
return s;
}
/**
* Re-calculate the controller's timing settings for "easy timing" mode.
* Changes panel variable sliceTiming_.
* The controller's properties will be set as needed
* @param showWarnings will show warning if the user-specified slice period too short
* or if cameras aren't assigned
*/
private void recalculateSliceTiming(boolean showWarnings) {
if(!checkCamerasAssigned(showWarnings)) {
return;
}
// if user is providing his own slice timing don't change it
if (advancedSliceTimingCB_.isSelected()) {
return;
}
sliceTiming_ = getTimingFromPeriodAndLightExposure(showWarnings);
PanelUtils.setSpinnerFloatValue(delayScan_, sliceTiming_.scanDelay);
numScansPerSlice_.setValue(sliceTiming_.scanNum);
PanelUtils.setSpinnerFloatValue(lineScanDuration_, sliceTiming_.scanPeriod);
PanelUtils.setSpinnerFloatValue(delayLaser_, sliceTiming_.laserDelay);
PanelUtils.setSpinnerFloatValue(durationLaser_, sliceTiming_.laserDuration);
PanelUtils.setSpinnerFloatValue(delayCamera_, sliceTiming_.cameraDelay);
PanelUtils.setSpinnerFloatValue(durationCamera_, sliceTiming_.cameraDuration );
PanelUtils.setSpinnerFloatValue(exposureCamera_, sliceTiming_.cameraExposure );
}
/**
* Update the displayed slice period.
*/
private void updateActualSlicePeriodLabel() {
recalculateSliceTiming(false);
actualSlicePeriodLabel_.setText(
NumberUtils.doubleToDisplayString(
sliceTiming_.sliceDuration) +
" ms");
}
/**
* Compute the volume duration in ms based on controller's timing settings.
* Includes time for multiple channels. However, does not include for multiple positions.
* @return duration in ms
*/
public double computeActualVolumeDuration(AcquisitionSettings acqSettings) {
final MultichannelModes.Keys channelMode = acqSettings.channelMode;
final int numChannels = acqSettings.numChannels;
final int numSides = acqSettings.numSides;
final float delayBeforeSide = acqSettings.delayBeforeSide;
int numCameraTriggers = acqSettings.numSlices;
if (acqSettings.cameraMode == CameraModes.Keys.OVERLAP) {
numCameraTriggers += 1;
}
// stackDuration is per-side, per-channel, per-position
final double stackDuration = numCameraTriggers * acqSettings.sliceTiming.sliceDuration;
if (acqSettings.isStageScanning) {
final double rampDuration = delayBeforeSide + acqSettings.accelerationX;
// TODO double-check these calculations below, at least they are better than before ;-)
if (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN) {
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return (numSides * ((rampDuration * 2) + (stackDuration * numChannels)));
} else {
return (numSides * ((rampDuration * 2) + stackDuration) * numChannels);
}
} else { // interleaved mode
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return (rampDuration * 2 + stackDuration * numSides * numChannels);
} else {
return ((rampDuration * 2 + stackDuration * numSides) * numChannels);
}
}
} else { // piezo scan
double channelSwitchDelay = 0;
if (channelMode == MultichannelModes.Keys.VOLUME) {
channelSwitchDelay = 500; // estimate channel switching overhead time as 0.5s
// actual value will be hardware-dependent
}
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return numSides * (delayBeforeSide + stackDuration * numChannels); // channelSwitchDelay = 0
} else {
return numSides * numChannels
* (delayBeforeSide + stackDuration)
+ (numChannels - 1) * channelSwitchDelay;
}
}
}
/**
* Compute the timepoint duration in ms. Only difference from computeActualVolumeDuration()
* is that it also takes into account the multiple positions, if any.
* @return duration in ms
*/
private double computeTimepointDuration() {
AcquisitionSettings acqSettings = getCurrentAcquisitionSettings();
final double volumeDuration = computeActualVolumeDuration(acqSettings);
if (acqSettings.useMultiPositions) {
try {
// use 1.5 seconds motor move between positions
// (could be wildly off but was estimated using actual system
// and then slightly padded to be conservative to avoid errors
// where positions aren't completed in time for next position)
return gui_.getPositionList().getNumberOfPositions() *
(volumeDuration + 1500 + PanelUtils.getSpinnerFloatValue(positionDelay_));
} catch (MMScriptException ex) {
MyDialogUtils.showError(ex, "Error getting position list for multiple XY positions");
}
}
return volumeDuration;
}
/**
* Compute the volume duration in ms based on controller's timing settings.
* Includes time for multiple channels.
* @return duration in ms
*/
private double computeActualVolumeDuration() {
return computeActualVolumeDuration(getCurrentAcquisitionSettings());
}
/**
* Update the displayed volume duration.
*/
private void updateActualVolumeDurationLabel() {
actualVolumeDurationLabel_.setText(
NumberUtils.doubleToDisplayString(computeActualVolumeDuration()) +
" ms");
}
/**
* Compute the time lapse duration
* @return duration in s
*/
private double computeActualTimeLapseDuration() {
double duration = (getNumTimepoints() - 1) * getTimepointInterval()
+ computeTimepointDuration()/1000;
return duration;
}
/**
* Update the displayed time lapse duration.
*/
private void updateActualTimeLapseDurationLabel() {
String s = "";
double duration = computeActualTimeLapseDuration();
if (duration < 60) { // less than 1 min
s += NumberUtils.doubleToDisplayString(duration) + " s";
} else if (duration < 60*60) { // between 1 min and 1 hour
s += NumberUtils.doubleToDisplayString(Math.floor(duration/60)) + " min ";
s += NumberUtils.doubleToDisplayString(Math.round(duration % 60)) + " s";
} else { // longer than 1 hour
s += NumberUtils.doubleToDisplayString(Math.floor(duration/(60*60))) + " hr ";
s += NumberUtils.doubleToDisplayString(Math.round((duration % (60*60))/60)) + " min";
}
actualTimeLapseDurationLabel_.setText(s);
}
/**
* Computes the reset time of the SPIM cameras set on Devices panel.
* Handles single-side operation.
* Needed for computing (semi-)optimized slice timing in "easy timing" mode.
* @return
*/
private float computeCameraResetTime() {
float resetTime;
if (getNumSides() > 1) {
resetTime = Math.max(cameras_.computeCameraResetTime(Devices.Keys.CAMERAA),
cameras_.computeCameraResetTime(Devices.Keys.CAMERAB));
} else {
if (isFirstSideA()) {
resetTime = cameras_.computeCameraResetTime(Devices.Keys.CAMERAA);
} else {
resetTime = cameras_.computeCameraResetTime(Devices.Keys.CAMERAB);
}
}
return resetTime;
}
/**
* Computes the readout time of the SPIM cameras set on Devices panel.
* Handles single-side operation.
* Needed for computing (semi-)optimized slice timing in "easy timing" mode.
* @return
*/
private float computeCameraReadoutTime() {
CameraModes.Keys camMode = getSPIMCameraMode();
if (getNumSides() > 1) {
return Math.max(cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAA, camMode),
cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAB, camMode));
} else {
if (isFirstSideA()) {
return cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAA, camMode);
} else {
return cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAB, camMode);
}
}
}
/**
* Makes sure that cameras are assigned to the desired sides and display error message
* if not (e.g. if single-sided with side B first, then only checks camera for side B)
* @return true if cameras assigned, false if not
*/
private boolean checkCamerasAssigned(boolean showWarnings) {
String firstCamera, secondCamera;
final boolean firstSideA = isFirstSideA();
if (firstSideA) {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
} else {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
}
if (firstCamera == null) {
if (showWarnings) {
MyDialogUtils.showError("Please select a valid camera for the first side (Imaging Path " +
(firstSideA ? "A" : "B") + ") on the Devices Panel");
}
return false;
}
if (getNumSides()> 1 && secondCamera == null) {
if (showWarnings) {
MyDialogUtils.showError("Please select a valid camera for the second side (Imaging Path " +
(firstSideA ? "B" : "A") + ") on the Devices Panel.");
}
return false;
}
return true;
}
/**
* used for updateAcquisitionStatus() calls
*/
private static enum AcquisitionStatus {
NONE,
ACQUIRING,
WAITING,
DONE,
}
private void updateAcquisitionStatus(AcquisitionStatus phase) {
updateAcquisitionStatus(phase, 0);
}
private void updateAcquisitionStatus(AcquisitionStatus phase, int secsToNextAcquisition) {
String text = "";
switch(phase) {
case NONE:
text = "No acquisition in progress.";
break;
case ACQUIRING:
text = "Acquiring time point "
+ NumberUtils.intToDisplayString(numTimePointsDone_)
+ " of "
+ NumberUtils.intToDisplayString(getNumTimepoints());
// TODO make sure the number of timepoints can't change during an acquisition
// (or maybe we make a hidden feature where the acquisition can be terminated by changing)
break;
case WAITING:
text = "Next timepoint ("
+ NumberUtils.intToDisplayString(numTimePointsDone_+1)
+ " of "
+ NumberUtils.intToDisplayString(getNumTimepoints())
+ ") in "
+ NumberUtils.intToDisplayString(secsToNextAcquisition)
+ " s.";
break;
case DONE:
text = "Acquisition finished with "
+ NumberUtils.intToDisplayString(numTimePointsDone_)
+ " time points.";
break;
default:
break;
}
acquisitionStatusLabel_.setText(text);
}
/**
* runs a test acquisition with the following features:
* - not saved to disk
* - window can be closed without prompting to save
* - timepoints disabled
* - autofocus disabled
* @param side Devices.Sides.NONE to run as specified in acquisition tab,
* Devices.Side.A or B to run only that side
*/
public void runTestAcquisition(Devices.Sides side) {
cancelAcquisition_.set(false);
acquisitionRequested_.set(true);
updateStartButton();
boolean success = runAcquisitionPrivate(true, side);
if (!success) {
ReportingUtils.logError("Fatal error running test diSPIM acquisition.");
}
acquisitionRequested_.set(false);
acquisitionRunning_.set(false);
updateStartButton();
}
/**
* Implementation of acquisition that orchestrates image
* acquisition itself rather than using the acquisition engine.
*
* This methods is public so that the ScriptInterface can call it
* Please do not access this yourself directly, instead use the API, e.g.
* import org.micromanager.asidispim.api.*;
* ASIdiSPIMInterface diSPIM = new ASIdiSPIMImplementation();
* diSPIM.runAcquisition();
*/
public void runAcquisition() {
class acqThread extends Thread {
acqThread(String threadName) {
super(threadName);
}
@Override
public void run() {
ReportingUtils.logDebugMessage("User requested start of diSPIM acquisition.");
if (isAcquisitionRequested()) { // don't allow acquisition to be requested again, just return
ReportingUtils.logError("another acquisition already running");
return;
}
cancelAcquisition_.set(false);
acquisitionRequested_.set(true);
ASIdiSPIM.getFrame().tabsSetEnabled(false);
updateStartButton();
boolean success = runAcquisitionPrivate(false, Devices.Sides.NONE);
if (!success) {
ReportingUtils.logError("Fatal error running diSPIM acquisition.");
}
acquisitionRequested_.set(false);
updateStartButton();
ASIdiSPIM.getFrame().tabsSetEnabled(true);
}
}
acqThread acqt = new acqThread("diSPIM Acquisition");
acqt.start();
}
private Color getChannelColor(int channelIndex) {
return (colors[channelIndex % colors.length]);
}
/**
* Actually runs the acquisition; does the dirty work of setting
* up the controller, the circular buffer, starting the cameras,
* grabbing the images and putting them into the acquisition, etc.
* @param testAcq true if running test acquisition only (see runTestAcquisition() javadoc)
* @param testAcqSide only applies to test acquisition, passthrough from runTestAcquisition()
* @return true if ran without any fatal errors.
*/
private boolean runAcquisitionPrivate(boolean testAcq, Devices.Sides testAcqSide) {
// sanity check, shouldn't call this unless we aren't running an acquisition
if (gui_.isAcquisitionRunning()) {
MyDialogUtils.showError("An acquisition is already running");
return false;
}
if (ASIdiSPIM.getFrame().getHardwareInUse()) {
MyDialogUtils.showError("Hardware is being used by something else (maybe autofocus?)");
return false;
}
boolean liveModeOriginally = gui_.isLiveModeOn();
if (liveModeOriginally) {
gui_.enableLiveMode(false);
}
// stop the serial traffic for position updates during acquisition
posUpdater_.pauseUpdates(true);
// make sure slice timings are up to date
// do this automatically; we used to prompt user if they were out of date
// do this before getting snapshot of sliceTiming_ in acqSettings
recalculateSliceTiming(!minSlicePeriodCB_.isSelected());
AcquisitionSettings acqSettingsOrig = getCurrentAcquisitionSettings();
// if a test acquisition then only run single timpoint, no autofocus
if (testAcq) {
acqSettingsOrig.useTimepoints = false;
acqSettingsOrig.numTimepoints = 1;
acqSettingsOrig.useAutofocus = false;
// if called from the setup panels then the side will be specified
// so we can do an appropriate single-sided acquisition
// if called from the acquisition panel then NONE will be specified
// and run according to existing settings
if (testAcqSide != Devices.Sides.NONE) {
acqSettingsOrig.numSides = 1;
acqSettingsOrig.firstSideIsA = (testAcqSide == Devices.Sides.A);
}
// work around limitation of not being able to use PLogic per-volume switching with single side
// => do per-volume switching instead (only difference should be extra time to switch)
if (acqSettingsOrig.useChannels && acqSettingsOrig.channelMode == MultichannelModes.Keys.VOLUME_HW
&& acqSettingsOrig.numSides < 2) {
acqSettingsOrig.channelMode = MultichannelModes.Keys.VOLUME;
}
}
double volumeDuration = computeActualVolumeDuration(acqSettingsOrig);
double timepointDuration = computeTimepointDuration();
long timepointIntervalMs = Math.round(acqSettingsOrig.timepointInterval*1000);
// use hardware timing if < 1 second between timepoints
// experimentally need ~0.5 sec to set up acquisition, this gives a bit of cushion
// cannot do this in getCurrentAcquisitionSettings because of mutually recursive
// call with computeActualVolumeDuration()
if ( acqSettingsOrig.numTimepoints > 1
&& timepointIntervalMs < (timepointDuration + 750)
&& !acqSettingsOrig.isStageScanning) {
acqSettingsOrig.hardwareTimepoints = true;
}
if (acqSettingsOrig.useMultiPositions) {
if (acqSettingsOrig.hardwareTimepoints
|| ((acqSettingsOrig.numTimepoints > 1)
&& (timepointIntervalMs < timepointDuration*1.2))) {
// change to not hardwareTimepoints and warn user
// but allow acquisition to continue
acqSettingsOrig.hardwareTimepoints = false;
MyDialogUtils.showError("Timepoint interval may not be sufficient "
+ "depending on actual time required to change positions. "
+ "Proceed at your own risk.");
}
}
// now acqSettings should be read-only
final AcquisitionSettings acqSettings = acqSettingsOrig;
// generate string for log file
Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String acqSettingsJSON = gson.toJson(acqSettings);
// get MM device names for first/second cameras to acquire
String firstCamera, secondCamera;
boolean firstSideA = acqSettings.firstSideIsA;
if (firstSideA) {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
} else {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
}
boolean sideActiveA, sideActiveB;
boolean twoSided = acqSettings.numSides > 1;
if (twoSided) {
sideActiveA = true;
sideActiveB = true;
} else {
secondCamera = null;
if (firstSideA) {
sideActiveA = true;
sideActiveB = false;
} else {
sideActiveA = false;
sideActiveB = true;
}
}
boolean usingDemoCam = (devices_.getMMDeviceLibrary(Devices.Keys.CAMERAA).equals(Devices.Libraries.DEMOCAM) && sideActiveA)
|| (devices_.getMMDeviceLibrary(Devices.Keys.CAMERAB).equals(Devices.Libraries.DEMOCAM) && sideActiveB);
// set up channels
int nrChannelsSoftware = acqSettings.numChannels; // how many times we trigger the controller per stack
int nrSlicesSoftware = acqSettings.numSlices;
String originalChannelConfig = "";
boolean changeChannelPerVolumeSoftware = false;
if (acqSettings.useChannels) {
if (acqSettings.numChannels < 1) {
MyDialogUtils.showError("\"Channels\" is checked, but no channels are selected");
return false;
}
// get current channel so that we can restore it, then set channel appropriately
originalChannelConfig = multiChannelPanel_.getCurrentConfig();
switch (acqSettings.channelMode) {
case VOLUME:
changeChannelPerVolumeSoftware = true;
multiChannelPanel_.initializeChannelCycle();
break;
case VOLUME_HW:
case SLICE_HW:
if (acqSettings.numChannels == 1) { // only 1 channel selected so don't have to really use hardware switching
multiChannelPanel_.initializeChannelCycle();
multiChannelPanel_.selectNextChannel();
} else { // we have at least 2 channels
boolean success = controller_.setupHardwareChannelSwitching(acqSettings);
if (!success) {
MyDialogUtils.showError("Couldn't set up slice hardware channel switching.");
return false;
}
nrChannelsSoftware = 1;
nrSlicesSoftware = acqSettings.numSlices * acqSettings.numChannels;
}
break;
default:
MyDialogUtils.showError("Unsupported multichannel mode \"" + acqSettings.channelMode.toString() + "\"");
return false;
}
}
if (acqSettings.hardwareTimepoints) {
// in hardwareTimepoints case we trigger controller once for all timepoints => need to
// adjust number of frames we expect back from the camera during MM's SequenceAcquisition
if (acqSettings.cameraMode == CameraModes.Keys.OVERLAP) {
// For overlap mode we are send one extra trigger per side for PLogic slice-switching
// and one extra trigger be channel per side for volume-switching (both PLogic and not).
// Very last trigger won't ever return a frame so subtract 1.
if (acqSettings.channelMode == MultichannelModes.Keys.SLICE_HW) {
nrSlicesSoftware = (((acqSettings.numSlices * acqSettings.numChannels) + 1) * acqSettings.numTimepoints) - 1;
} else {
nrSlicesSoftware = ((acqSettings.numSlices + 1) * acqSettings.numChannels * acqSettings.numTimepoints) - 1;
}
} else {
// we get back one image per trigger for all trigger modes other than OVERLAP
// and we have already computed how many images that is (nrSlicesSoftware)
nrSlicesSoftware *= acqSettings.numTimepoints;
}
}
// set up XY positions
int nrPositions = 1;
PositionList positionList = new PositionList();
if (acqSettings.useMultiPositions) {
try {
positionList = gui_.getPositionList();
nrPositions = positionList.getNumberOfPositions();
} catch (MMScriptException ex) {
MyDialogUtils.showError(ex, "Error getting position list for multiple XY positions");
}
if (nrPositions < 1) {
MyDialogUtils.showError("\"Positions\" is checked, but no positions are in position list");
return false;
}
}
// make sure we have cameras selected
if (!checkCamerasAssigned(true)) {
return false;
}
float cameraReadoutTime = computeCameraReadoutTime();
double exposureTime = acqSettings.sliceTiming.cameraExposure;
boolean save = saveCB_.isSelected() && !testAcq;
String rootDir = rootField_.getText();
int nrFrames; // how many Micro-manager "frames" = time points to take
if (acqSettings.separateTimepoints) {
nrFrames = 1;
nrRepeats_ = acqSettings.numTimepoints;
} else {
nrFrames = acqSettings.numTimepoints;
nrRepeats_ = 1;
}
AcquisitionModes.Keys spimMode = acqSettings.spimMode;
boolean autoShutter = core_.getAutoShutter();
boolean shutterOpen = false; // will read later
String originalCamera = core_.getCameraDevice();
// more sanity checks
// TODO move these checks earlier, before we set up channels and XY positions
// make sure stage scan is supported if selected
if (acqSettings.isStageScanning) {
if (!devices_.isTigerDevice(Devices.Keys.XYSTAGE)
|| !props_.hasProperty(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_NUMLINES)) {
MyDialogUtils.showError("Must have stage with scan-enabled firmware for stage scanning.");
return false;
}
}
double sliceDuration = acqSettings.sliceTiming.sliceDuration;
if (exposureTime + cameraReadoutTime > sliceDuration) {
// should only only possible to mess this up using advanced timing settings
// or if there are errors in our own calculations
MyDialogUtils.showError("Exposure time of " + exposureTime +
" is longer than time needed for a line scan with" +
" readout time of " + cameraReadoutTime + "\n" +
"This will result in dropped frames. " +
"Please change input");
return false;
}
// if we want to do hardware timepoints make sure there's not a problem
// lots of different situations where hardware timepoints can't be used...
if (acqSettings.hardwareTimepoints) {
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME_HW) {
// both hardware time points and volume channel switching use SPIMNumRepeats property
// TODO this seems a severe limitation, maybe this could be changed in the future via firmware change
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with hardware channel switching volume-by-volume.");
return false;
}
if (acqSettings.isStageScanning) {
// stage scanning needs to be triggered for each time point
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with stage scanning.");
return false;
}
if (acqSettings.separateTimepoints) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with separate viewers/file for each time point.");
return false;
}
if (acqSettings.useAutofocus) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with autofocus during acquisition.");
return false;
}
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with software channels (need to use PLogic channel switching).");
return false;
}
if (spimMode == AcquisitionModes.Keys.NO_SCAN) {
MyDialogUtils.showError("Cannot do hardware time points when no scan mode is used."
+ " Use the number of slices to set the number of images to acquire.");
return false;
}
}
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME_HW
&& acqSettings.numSides < 2) {
MyDialogUtils.showError("Cannot do PLogic channel switching of volume when only one"
+ " side is selected. Pester the developers if you need this.");
return false;
}
// make sure we aren't trying to collect timepoints faster than we can
if (!acqSettings.useMultiPositions && acqSettings.numTimepoints > 1) {
if (timepointIntervalMs < volumeDuration) {
MyDialogUtils.showError("Time point interval shorter than" +
" the time to collect a single volume.\n");
return false;
}
}
// Autofocus settings; only used if acqSettings.useAutofocus is true
boolean autofocusAtT0 = false;
int autofocusEachNFrames = 10;
String autofocusChannel = "";
if (acqSettings.useAutofocus) {
autofocusAtT0 = prefs_.getBoolean(MyStrings.PanelNames.AUTOFOCUS.toString(),
Properties.Keys.PLUGIN_AUTOFOCUS_ACQBEFORESTART, false);
autofocusEachNFrames = props_.getPropValueInteger(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_EACHNIMAGES);
autofocusChannel = props_.getPropValueString(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_CHANNEL);
// double-check that selected channel is valid if we are doing multi-channel
if (acqSettings.useChannels) {
String channelGroup = props_.getPropValueString(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_MULTICHANNEL_GROUP);
StrVector channels = gui_.getMMCore().getAvailableConfigs(channelGroup);
boolean found = false;
for (String channel : channels) {
if (channel.equals(autofocusChannel)) {
found = true;
break;
}
}
if (!found) {
MyDialogUtils.showError("Invalid autofocus channel selected on autofocus tab.");
return false;
}
}
}
// it appears the circular buffer, which is used by both cameras, can only have one
// image size setting => we require same image height and width for second camera if two-sided
if (twoSided) {
try {
Rectangle roi_1 = core_.getROI(firstCamera);
Rectangle roi_2 = core_.getROI(secondCamera);
if (roi_1.width != roi_2.width || roi_1.height != roi_2.height) {
MyDialogUtils.showError("Camera ROI height and width must be equal because of Micro-Manager's circular buffer");
return false;
}
} catch (Exception ex) {
MyDialogUtils.showError(ex, "Problem getting camera ROIs");
}
}
// seems to have a problem if the core's camera has been set to some other
// camera before we start doing things, so set to a SPIM camera
try {
core_.setCameraDevice(firstCamera);
} catch (Exception ex) {
MyDialogUtils.showError(ex, "could not set camera");
}
// empty out circular buffer
try {
core_.clearCircularBuffer();
} catch (Exception ex) {
MyDialogUtils.showError(ex, "Error emptying out the circular buffer");
return false;
}
// initialize stage scanning so we can restore state
Point2D.Double xyPosUm = new Point2D.Double();
float origXSpeed = 1f; // don't want 0 in case something goes wrong
if (acqSettings.isStageScanning) {
try {
xyPosUm = core_.getXYStagePosition(devices_.getMMDevice(Devices.Keys.XYSTAGE));
origXSpeed = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED);
} catch (Exception ex) {
MyDialogUtils.showError("Could not get XY stage position for stage scan initialization");
return false;
}
}
cameras_.setSPIMCamerasForAcquisition(true);
numTimePointsDone_ = 0;
// force saving as image stacks, not individual files
// implementation assumes just two options, either
// TaggedImageStorageDiskDefault.class or TaggedImageStorageMultipageTiff.class
boolean separateImageFilesOriginally =
ImageUtils.getImageStorageClass().equals(TaggedImageStorageDiskDefault.class);
ImageUtils.setImageStorageClass(TaggedImageStorageMultipageTiff.class);
// Set up controller SPIM parameters (including from Setup panel settings)
// want to do this, even with demo cameras, so we can test everything else
if (!controller_.prepareControllerForAquisition(acqSettings)) {
return false;
}
boolean nonfatalError = false;
long acqButtonStart = System.currentTimeMillis();
String acqName = "";
acq_ = null;
// do not want to return from within this loop => throw exception instead
// loop is executed once per acquisition (i.e. once if separate viewers isn't selected
// or once per timepoint if separate viewers is selected)
long repeatStart = System.currentTimeMillis();
for (int acqNum = 0; !cancelAcquisition_.get() && acqNum < nrRepeats_; acqNum++) {
// handle intervals between (software-timed) repeats
// only applies when doing separate viewers for each timepoint
// and have multiple timepoints
long repeatNow = System.currentTimeMillis();
long repeatdelay = repeatStart + acqNum * timepointIntervalMs - repeatNow;
while (repeatdelay > 0 && !cancelAcquisition_.get()) {
updateAcquisitionStatus(AcquisitionStatus.WAITING, (int) (repeatdelay / 1000));
long sleepTime = Math.min(1000, repeatdelay);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
repeatNow = System.currentTimeMillis();
repeatdelay = repeatStart + acqNum * timepointIntervalMs - repeatNow;
}
BlockingQueue<TaggedImage> bq = new LinkedBlockingQueue<TaggedImage>(10);
// try to close last acquisition viewer if there could be one open (only in single acquisition per timepoint mode)
if (acqSettings.separateTimepoints && (acq_!=null) && !cancelAcquisition_.get()) {
try {
// following line needed due to some arcane internal reason, otherwise
// call to closeAcquisitionWindow() fails silently.
// See http://sourceforge.net/p/micro-manager/mailman/message/32999320/
acq_.promptToSave(false);
gui_.closeAcquisitionWindow(acqName);
} catch (Exception ex) {
// do nothing if unsuccessful
}
}
if (acqSettings.separateTimepoints) {
acqName = gui_.getUniqueAcquisitionName(prefixField_.getText() + "_" + acqNum);
} else {
acqName = gui_.getUniqueAcquisitionName(prefixField_.getText());
}
VirtualAcquisitionDisplay vad = null;
WindowListener wl_acq = null;
WindowListener[] wls_orig = null;
try {
// check for stop button before each acquisition
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
// flag that we are actually running acquisition now
acquisitionRunning_.set(true);
ReportingUtils.logMessage("diSPIM plugin starting acquisition " + acqName + " with following settings: " + acqSettingsJSON);
if (spimMode == AcquisitionModes.Keys.NO_SCAN && !acqSettings.separateTimepoints) {
// swap nrFrames and numSlices
gui_.openAcquisition(acqName, rootDir, acqSettings.numSlices, acqSettings.numSides * acqSettings.numChannels,
nrFrames, nrPositions, true, save);
} else {
gui_.openAcquisition(acqName, rootDir, nrFrames, acqSettings.numSides * acqSettings.numChannels,
acqSettings.numSlices, nrPositions, true, save);
}
// save exposure time, will restore at end of acquisition
prefs_.putFloat(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_LIVE_EXPOSURE.toString(),
(float)core_.getExposure());
core_.setExposure(firstCamera, exposureTime);
if (twoSided) {
core_.setExposure(secondCamera, exposureTime);
}
channelNames_ = new String[acqSettings.numSides * acqSettings.numChannels];
// generate channel names and colors
// also builds viewString for MultiViewRegistration metadata
String viewString = "";
final String SEPARATOR = "_";
// set up channels (side A/B is treated as channel too)
if (acqSettings.useChannels) {
ChannelSpec[] channels = multiChannelPanel_.getUsedChannels();
for (int i = 0; i < channels.length; i++) {
String chName = "-" + channels[i].config_;
// same algorithm for channel index vs. specified channel and side as below
int channelIndex = i;
if (twoSided) {
channelIndex *= 2;
}
channelNames_[channelIndex] = firstCamera + chName;
viewString += NumberUtils.intToDisplayString(0) + SEPARATOR;
if (twoSided) {
channelNames_[channelIndex+1] = secondCamera + chName;
viewString += NumberUtils.intToDisplayString(90) + SEPARATOR;
}
}
} else {
channelNames_[0] = firstCamera;
viewString += NumberUtils.intToDisplayString(0) + SEPARATOR;
if (twoSided) {
channelNames_[1] = secondCamera;
viewString += NumberUtils.intToDisplayString(90) + SEPARATOR;
}
}
// strip last separator of viewString (for Multiview Reconstruction)
viewString = viewString.substring(0, viewString.length() - 1);
// assign channel names and colors
for (int i = 0; i < acqSettings.numSides * acqSettings.numChannels; i++) {
gui_.setChannelName(acqName, i, channelNames_[i]);
gui_.setChannelColor(acqName, i, getChannelColor(i));
}
// initialize acquisition
gui_.initializeAcquisition(acqName, (int) core_.getImageWidth(),
(int) core_.getImageHeight(), (int) core_.getBytesPerPixel(),
(int) core_.getImageBitDepth());
gui_.promptToSaveAcquisition(acqName, !testAcq);
// These metadata have to added after initialization, otherwise they will not be shown?!
gui_.setAcquisitionProperty(acqName, "NumberOfSides",
NumberUtils.doubleToDisplayString(acqSettings.numSides));
gui_.setAcquisitionProperty(acqName, "FirstSide", acqSettings.firstSideIsA ? "A" : "B");
gui_.setAcquisitionProperty(acqName, "SlicePeriod_ms",
actualSlicePeriodLabel_.getText());
gui_.setAcquisitionProperty(acqName, "LaserExposure_ms",
NumberUtils.doubleToDisplayString(acqSettings.desiredLightExposure));
gui_.setAcquisitionProperty(acqName, "VolumeDuration",
actualVolumeDurationLabel_.getText());
gui_.setAcquisitionProperty(acqName, "SPIMmode", spimMode.toString());
// Multi-page TIFF saving code wants this one (cameras are all 16-bits, so not much reason for anything else)
gui_.setAcquisitionProperty(acqName, "PixelType", "GRAY16");
gui_.setAcquisitionProperty(acqName, "UseAutofocus",
acqSettings.useAutofocus ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "HardwareTimepoints",
acqSettings.hardwareTimepoints ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "SeparateTimepoints",
acqSettings.separateTimepoints ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "CameraMode", acqSettings.cameraMode.toString());
gui_.setAcquisitionProperty(acqName, "z-step_um",
NumberUtils.doubleToDisplayString(acqSettings.stepSizeUm));
// Properties for use by MultiViewRegistration plugin
// Format is: x_y_z, set to 1 if we should rotate around this axis.
gui_.setAcquisitionProperty(acqName, "MVRotationAxis", "0_1_0");
gui_.setAcquisitionProperty(acqName, "MVRotations", viewString);
// save XY and SPIM head position in metadata
// update positions first at expense of two extra serial transactions
positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.X); // / will update cache for Y too
gui_.setAcquisitionProperty(acqName, "Position_X",
positions_.getPositionString(Devices.Keys.XYSTAGE, Directions.X));
gui_.setAcquisitionProperty(acqName, "Position_Y",
positions_.getPositionString(Devices.Keys.XYSTAGE, Directions.Y));
positions_.getUpdatedPosition(Devices.Keys.UPPERZDRIVE);
gui_.setAcquisitionProperty(acqName, "Position_SPIM_Head",
positions_.getPositionString(Devices.Keys.UPPERZDRIVE));
gui_.setAcquisitionProperty(acqName, "SPIMAcqSettings", acqSettingsJSON);
// get circular buffer ready
// do once here but not per-trigger; need to ensure ROI changes registered
core_.initializeCircularBuffer();
// TODO: use new acquisition interface that goes through the pipeline
//gui_.setAcquisitionAddImageAsynchronous(acqName);
acq_ = gui_.getAcquisition(acqName);
// Dive into MM internals since script interface does not support pipelines
ImageCache imageCache = acq_.getImageCache();
vad = acq_.getAcquisitionWindow();
imageCache.addImageCacheListener(vad);
// Start pumping images into the ImageCache
DefaultTaggedImageSink sink = new DefaultTaggedImageSink(bq, imageCache);
sink.start();
// remove usual window listener(s) and replace it with our own
// that will prompt before closing and cancel acquisition if confirmed
// this should be considered a hack, it may not work perfectly
// I have confirmed that there is only one windowListener and it seems to
// also be related to window closing
// Note that ImageJ's acquisition window is AWT instead of Swing
wls_orig = vad.getImagePlus().getWindow().getWindowListeners();
for (WindowListener l : wls_orig) {
vad.getImagePlus().getWindow().removeWindowListener(l);
}
wl_acq = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
// if running acquisition only close if user confirms
if (acquisitionRunning_.get()) {
boolean stop = MyDialogUtils.getConfirmDialogResult(
"Do you really want to abort the acquisition?",
JOptionPane.YES_NO_OPTION);
if (stop) {
cancelAcquisition_.set(true);
}
}
}
};
vad.getImagePlus().getWindow().addWindowListener(wl_acq);
// patterned after implementation in MMStudio.java
// will be null if not saving to disk
lastAcquisitionPath_ = acq_.getImageCache().getDiskLocation();
lastAcquisitionName_ = acqName;
// make sure all devices have arrived, e.g. a stage isn't still moving
try {
core_.waitForSystem();
} catch (Exception e) {
ReportingUtils.logError("error waiting for system");
}
// Loop over all the times we trigger the controller's acquisition
// (although if multi-channel with volume switching is selected there
// is inner loop to trigger once per channel)
// remember acquisition start time for software-timed timepoints
// For hardware-timed timepoints we only trigger the controller once
long acqStart = System.currentTimeMillis();
for (int trigNum = 0; trigNum < nrFrames; trigNum++) {
// handle intervals between (software-timed) time points
// when we are within the same acquisition
// (if separate viewer is selected then nothing bad happens here
// but waiting during interval handled elsewhere)
long acqNow = System.currentTimeMillis();
long delay = acqStart + trigNum * timepointIntervalMs - acqNow;
while (delay > 0 && !cancelAcquisition_.get()) {
updateAcquisitionStatus(AcquisitionStatus.WAITING, (int) (delay / 1000));
long sleepTime = Math.min(1000, delay);
Thread.sleep(sleepTime);
acqNow = System.currentTimeMillis();
delay = acqStart + trigNum * timepointIntervalMs - acqNow;
}
// check for stop button before each time point
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
int timePoint = acqSettings.separateTimepoints ? acqNum : trigNum ;
// this is where we autofocus if requested
if (acqSettings.useAutofocus) {
// Note that we will not autofocus as expected when using hardware
// timing. Seems OK, since hardware timing will result in short
// acquisition times that do not need autofocus. We have already
// ensured that we aren't doing both
if ( (autofocusAtT0 && timePoint == 0) || ( (timePoint > 0) &&
(timePoint % autofocusEachNFrames == 0 ) ) ) {
if (acqSettings.useChannels) {
multiChannelPanel_.selectChannel(autofocusChannel);
}
if (sideActiveA) {
AutofocusUtils.FocusResult score = autofocus_.runFocus(
this, Devices.Sides.A, false,
sliceTiming_, false);
updateCalibrationOffset(Devices.Sides.A, score);
}
if (sideActiveB) {
AutofocusUtils.FocusResult score = autofocus_.runFocus(
this, Devices.Sides.B, false,
sliceTiming_, false);
updateCalibrationOffset(Devices.Sides.B, score);
}
// Restore settings of the controller
controller_.prepareControllerForAquisition(acqSettings);
if (acqSettings.useChannels && acqSettings.channelMode != MultichannelModes.Keys.VOLUME) {
controller_.setupHardwareChannelSwitching(acqSettings);
}
}
}
numTimePointsDone_++;
updateAcquisitionStatus(AcquisitionStatus.ACQUIRING);
// loop over all positions
for (int positionNum = 0; positionNum < nrPositions; positionNum++) {
if (acqSettings.useMultiPositions) {
// make sure user didn't stop things
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
// want to move between positions move stage fast, so we
// will clobber stage scanning setting so need to restore it
float scanXSpeed = 1f;
if (acqSettings.isStageScanning) {
scanXSpeed = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, origXSpeed);
}
// blocking call; will wait for stages to move
MultiStagePosition.goToPosition(positionList.getPosition(positionNum), core_);
// restore speed for stage scanning
if (acqSettings.isStageScanning) {
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, scanXSpeed);
}
// setup stage scan at this position
if (acqSettings.isStageScanning) {
StagePosition pos = positionList.getPosition(positionNum).get(devices_.getMMDevice(Devices.Keys.XYSTAGE));
controller_.prepareStageScanForAcquisition(pos.x, pos.y);
}
// wait any extra time the user requests
Thread.sleep(Math.round(PanelUtils.getSpinnerFloatValue(positionDelay_)));
}
// loop over all the times we trigger the controller
// usually just once, but will be the number of channels if we have
// multiple channels and aren't using PLogic to change between them
for (int channelNum = 0; channelNum < nrChannelsSoftware; channelNum++) {
try {
// flag that we are using the cameras/controller
ASIdiSPIM.getFrame().setHardwareInUse(true);
// deal with shutter before starting acquisition
shutterOpen = core_.getShutterOpen();
if (autoShutter) {
core_.setAutoShutter(false);
if (!shutterOpen) {
core_.setShutterOpen(true);
}
}
// start the cameras
core_.startSequenceAcquisition(firstCamera, nrSlicesSoftware, 0, true);
if (twoSided) {
core_.startSequenceAcquisition(secondCamera, nrSlicesSoftware, 0, true);
}
// deal with channel if needed (hardware channel switching doesn't happen here)
if (changeChannelPerVolumeSoftware) {
multiChannelPanel_.selectNextChannel();
}
// trigger the state machine on the controller
// do this even with demo cameras to test everything else
boolean success = controller_.triggerControllerStartAcquisition(spimMode, firstSideA);
if (!success) {
throw new Exception("Controller triggering not successful");
}
ReportingUtils.logDebugMessage("Starting time point " + (timePoint+1) + " of " + nrFrames
+ " with (software) channel number " + channelNum);
// Wait for first image to create ImageWindow, so that we can be sure about image size
// Do not actually grab first image here, just make sure it is there
long start = System.currentTimeMillis();
long now = start;
final long timeout = Math.max(3000, Math.round(10*sliceDuration + 2*acqSettings.delayBeforeSide));
while (core_.getRemainingImageCount() == 0 && (now - start < timeout)
&& !cancelAcquisition_.get()) {
now = System.currentTimeMillis();
Thread.sleep(5);
}
if (now - start >= timeout) {
String msg = "Camera did not send first image within a reasonable time.\n";
if (acqSettings.isStageScanning) {
msg += "Make sure jumpers are correct on XY card and also micro-micromirror card.";
} else {
msg += "Make sure camera trigger cables are connected properly.";
}
throw new Exception(msg);
}
// grab all the images from the cameras, put them into the acquisition
int[] frNumber = new int[2*acqSettings.numChannels]; // keep track of how many frames we have received for each "channel" (MM channel is our channel * 2 for the 2 cameras)
int[] cameraFrNumber = new int[2]; // keep track of how many frames we have received from the camera
int[] tpNumber = new int[2*acqSettings.numChannels]; // keep track of which timepoint we are on for hardware timepoints
boolean skipNextImage = false; // hardware timepoints have to drop spurious images with overlap mode
final boolean checkForSkips = acqSettings.hardwareTimepoints && (acqSettings.cameraMode == CameraModes.Keys.OVERLAP);
final boolean skipPerSide = acqSettings.useChannels && (acqSettings.numChannels > 1)
&& (acqSettings.channelMode == MultichannelModes.Keys.SLICE_HW);
boolean done = false;
final long timeout2 = Math.max(1000, Math.round(5*sliceDuration));
start = System.currentTimeMillis();
long last = start;
try {
while ((core_.getRemainingImageCount() > 0
|| core_.isSequenceRunning(firstCamera)
|| (twoSided && core_.isSequenceRunning(secondCamera)))
&& !done) {
now = System.currentTimeMillis();
if (core_.getRemainingImageCount() > 0) { // we have an image to grab
TaggedImage timg = core_.popNextTaggedImage();
if (skipNextImage) {
skipNextImage = false;
continue; // goes to next iteration of this loop without doing anything else
}
// figure out which channel index this frame belongs to
// "channel index" is channel of MM acquisition
// channel indexes will go from 0 to (numSides * numChannels - 1)
// if double-sided then second camera gets odd channel indexes (1, 3, etc.)
// and adjacent pairs will be same color (e.g. 0 and 1 will be from first color, 2 and 3 from second, etc.)
String camera = (String) timg.tags.get("Camera");
int cameraIndex = camera.equals(firstCamera) ? 0: 1;
int channelIndex_tmp;
switch (acqSettings.channelMode) {
case NONE:
case VOLUME:
channelIndex_tmp = channelNum;
break;
case VOLUME_HW:
channelIndex_tmp = cameraFrNumber[cameraIndex] / acqSettings.numSlices; // want quotient only
break;
case SLICE_HW:
channelIndex_tmp = cameraFrNumber[cameraIndex] % acqSettings.numChannels; // want modulo arithmetic
break;
default:
// should never get here
throw new Exception("Undefined channel mode");
}
if (twoSided) {
channelIndex_tmp *= 2;
}
final int channelIndex = channelIndex_tmp + cameraIndex;
int actualTimePoint = timePoint;
if (acqSettings.hardwareTimepoints) {
actualTimePoint = tpNumber[channelIndex];
}
if (acqSettings.separateTimepoints) {
// if we are doing separate timepoints then frame is always 0
actualTimePoint = 0;
}
// note that hardwareTimepoints and separateTimepoints can never both be true
// add image to acquisition
if (spimMode == AcquisitionModes.Keys.NO_SCAN && !acqSettings.separateTimepoints) {
// create time series for no scan
addImageToAcquisition(acq_,
frNumber[channelIndex], channelIndex, actualTimePoint,
positionNum, now - acqStart, timg, bq);
} else { // standard, create Z-stacks
addImageToAcquisition(acq_, actualTimePoint, channelIndex,
frNumber[channelIndex], positionNum,
now - acqStart, timg, bq);
}
// update our counters to be ready for next image
frNumber[channelIndex]++;
cameraFrNumber[cameraIndex]++;
// if hardware timepoints then we only send one trigger and
// manually keep track of which channel/timepoint comes next
if (acqSettings.hardwareTimepoints
&& frNumber[channelIndex] >= acqSettings.numSlices) { // only do this if we are done with the slices in this MM channel
// we just finished filling one MM channel with all its slices so go to next timepoint for this channel
frNumber[channelIndex] = 0;
tpNumber[channelIndex]++;
// see if we are supposed to skip next image
if (checkForSkips) {
if (skipPerSide) { // one extra image per side, only happens with per-slice HW switching
if ((channelIndex == (acqSettings.numChannels - 1)) // final channel index is last one of side
|| (twoSided && (channelIndex == (acqSettings.numChannels - 2)))) { // 2nd-to-last channel index for two-sided is also last one of side
skipNextImage = true;
}
} else { // one extra image per MM channel, this includes case of only 1 color (either multi-channel disabled or else only 1 channel selected)
skipNextImage = true;
}
}
// update acquisition status message for hardware acquisition
// (for non-hardware acquisition message is updated elsewhere)
// Arbitrarily choose one possible channel to do this on.
if (channelIndex == 0 && (numTimePointsDone_ < acqSettings.numTimepoints)) {
numTimePointsDone_++;
updateAcquisitionStatus(AcquisitionStatus.ACQUIRING);
}
}
last = now; // keep track of last image timestamp
} else { // no image ready yet
done = cancelAcquisition_.get();
Thread.sleep(1);
if (now - last >= timeout2) {
ReportingUtils.logError("Camera did not send all expected images within" +
" a reasonable period for timepoint " + numTimePointsDone_ + ". Continuing anyway.");
nonfatalError = true;
done = true;
}
}
}
// update count if we stopped in the middle
if (cancelAcquisition_.get()) {
numTimePointsDone_--;
}
// if we are using demo camera then add some extra time to let controller finish
// since we got images without waiting for controller to actually send triggers
if (usingDemoCam) {
Thread.sleep(200); // for serial communication overhead
Thread.sleep((long)volumeDuration/nrChannelsSoftware); // estimate the time per channel, not ideal in case of software channel switching
}
} catch (InterruptedException iex) {
MyDialogUtils.showError(iex);
}
if (acqSettings.hardwareTimepoints) {
break; // only trigger controller once
}
} catch (Exception ex) {
MyDialogUtils.showError(ex);
} finally {
// cleanup at the end of each time we trigger the controller
ASIdiSPIM.getFrame().setHardwareInUse(false);
// put shutter back to original state
core_.setShutterOpen(shutterOpen);
core_.setAutoShutter(autoShutter);
// make sure cameras aren't running anymore
if (core_.isSequenceRunning(firstCamera)) {
core_.stopSequenceAcquisition(firstCamera);
}
if (twoSided && core_.isSequenceRunning(secondCamera)) {
core_.stopSequenceAcquisition(secondCamera);
}
}
}
}
if (acqSettings.hardwareTimepoints) {
break;
}
}
} catch (IllegalMonitorStateException ex) {
// do nothing, the acquisition was simply halted during its operation
// will log error message during finally clause
} catch (MMScriptException mex) {
MyDialogUtils.showError(mex);
} catch (Exception ex) {
MyDialogUtils.showError(ex);
} finally { // end of this acquisition (could be about to restart if separate viewers)
try {
// restore original window listeners
try {
vad.getImagePlus().getWindow().removeWindowListener(wl_acq);
for (WindowListener l : wls_orig) {
vad.getImagePlus().getWindow().addWindowListener(l);
}
} catch (Exception ex) {
// do nothing, window is probably gone
}
if (cancelAcquisition_.get()) {
ReportingUtils.logMessage("User stopped the acquisition");
}
bq.put(TaggedImageQueue.POISON);
// TODO: evaluate closeAcquisition call
// at the moment, the Micro-Manager api has a bug that causes
// a closed acquisition not be really closed, causing problems
// when the user closes a window of the previous acquisition
// changed r14705 (2014-11-24)
// gui_.closeAcquisition(acqName);
ReportingUtils.logMessage("diSPIM plugin acquisition " + acqName +
" took: " + (System.currentTimeMillis() - acqButtonStart) + "ms");
// flag that we are done with acquisition
acquisitionRunning_.set(false);
} catch (Exception ex) {
// exception while stopping sequence acquisition, not sure what to do...
MyDialogUtils.showError(ex, "Problem while finishing acquisition");
}
}
}// for loop over acquisitions
// cleanup after end of all acquisitions
// TODO be more careful and always do these if we actually started acquisition,
// even if exception happened
// restore camera
try {
core_.setCameraDevice(originalCamera);
} catch (Exception ex) {
MyDialogUtils.showError("Could not restore camera after acquisition");
}
// reset channel to original if we clobbered it
if (acqSettings.useChannels) {
multiChannelPanel_.setConfig(originalChannelConfig);
}
// clean up controller settings after acquisition
// want to do this, even with demo cameras, so we can test everything else
// TODO figure out if we really want to return piezos to 0 position (maybe center position,
// maybe not at all since we move when we switch to setup tab, something else??)
controller_.cleanUpControllerAfterAcquisition(acqSettings.numSides, acqSettings.firstSideIsA, true);
// if we did stage scanning restore its position and speed
if (acqSettings.isStageScanning) {
try {
// make sure stage scanning state machine is stopped, otherwise setting speed/position won't take
props_.setPropValue(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_STATE,
Properties.Values.SPIM_IDLE);
core_.setXYPosition(devices_.getMMDevice(Devices.Keys.XYSTAGE),
xyPosUm.x, xyPosUm.y);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, origXSpeed);
} catch (Exception ex) {
MyDialogUtils.showError("Could not restore XY stage position after acquisition");
}
}
updateAcquisitionStatus(AcquisitionStatus.DONE);
posUpdater_.pauseUpdates(false);
if (testAcq && prefs_.getBoolean(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_TESTACQ_SAVE, false)) {
String path = "";
try {
path = prefs_.getString(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_TESTACQ_PATH, "");
IJ.saveAs(acq_.getAcquisitionWindow().getImagePlus(), "raw", path);
// TODO consider generating a short metadata file to assist in interpretation
} catch (Exception ex) {
MyDialogUtils.showError("Could not save raw data from test acquisition to path " + path);
}
}
if (separateImageFilesOriginally) {
ImageUtils.setImageStorageClass(TaggedImageStorageDiskDefault.class);
}
cameras_.setSPIMCamerasForAcquisition(false);
if (liveModeOriginally) {
gui_.enableLiveMode(true);
}
if (nonfatalError) {
MyDialogUtils.showError("Missed some images during acquisition, see core log for details");
}
return true;
}
@Override
public void saveSettings() {
// save controller settings
props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.GALVOB, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.PLOGIC, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
}
/**
* Gets called when this tab gets focus. Refreshes values from properties.
*/
@Override
public void gotSelected() {
posUpdater_.pauseUpdates(true);
props_.callListeners();
// old joystick associations were cleared when leaving
// last tab so only do it if joystick settings need to be applied
if (navigationJoysticksCB_.isSelected()) {
updateJoysticks();
}
sliceFrameAdvanced_.setVisible(advancedSliceTimingCB_.isSelected());
posUpdater_.pauseUpdates(false);
}
/**
* called when tab looses focus.
*/
@Override
public void gotDeSelected() {
// if we have been using navigation panel's joysticks need to unset them
if (navigationJoysticksCB_.isSelected()) {
if (ASIdiSPIM.getFrame() != null) {
ASIdiSPIM.getFrame().getNavigationPanel().doJoystickSettings(false);
}
}
sliceFrameAdvanced_.setVisible(false);
}
@Override
public void devicesChangedAlert() {
devices_.callListeners();
}
/**
* Gets called when enclosing window closes
*/
@Override
public void windowClosing() {
if (acquisitionRequested_.get()) {
cancelAcquisition_.set(true);
while (acquisitionRunning_.get()) {
// spin wheels until we are done
}
}
sliceFrameAdvanced_.savePosition();
sliceFrameAdvanced_.dispose();
}
@Override
public void refreshDisplay() {
updateDurationLabels();
}
private void setRootDirectory(JTextField rootField) {
File result = FileDialogs.openDir(null,
"Please choose a directory root for image data",
MMStudio.MM_DATA_SET);
if (result != null) {
rootField.setText(result.getAbsolutePath());
}
}
/**
* The basic method for adding images to an existing data set. If the
* acquisition was not previously initialized, it will attempt to initialize
* it from the available image data. This version uses a blocking queue and is
* much faster than the one currently implemented in the ScriptInterface
* Eventually, this function should be replaced by the ScriptInterface version
* of the same.
* @param acq - MMAcquisition object to use (old way used acquisition name and then
* had to call deprecated function on every call, now just pass acquisition object
* @param frame - frame nr at which to insert the image
* @param channel - channel at which to insert image
* @param slice - (z) slice at which to insert image
* @param position - position at which to insert image
* @param ms - Time stamp to be added to the image metadata
* @param taggedImg - image + metadata to be added
* @param bq - Blocking queue to which the image should be added. This queue
* should be hooked up to the ImageCache belonging to this acquisitions
* @throws java.lang.InterruptedException
* @throws org.micromanager.utils.MMScriptException
*/
public void addImageToAcquisition(MMAcquisition acq,
int frame,
int channel,
int slice,
int position,
long ms,
TaggedImage taggedImg,
BlockingQueue<TaggedImage> bq) throws MMScriptException, InterruptedException {
// verify position number is allowed
if (acq.getPositions() <= position) {
throw new MMScriptException("The position number must not exceed declared"
+ " number of positions (" + acq.getPositions() + ")");
}
// verify that channel number is allowed
if (acq.getChannels() <= channel) {
throw new MMScriptException("The channel number must not exceed declared"
+ " number of channels (" + + acq.getChannels() + ")");
}
JSONObject tags = taggedImg.tags;
if (!acq.isInitialized()) {
throw new MMScriptException("Error in the ASIdiSPIM logic. Acquisition should have been initialized");
}
// create required coordinate tags
try {
MDUtils.setFrameIndex(tags, frame);
tags.put(MMTags.Image.FRAME, frame);
MDUtils.setChannelIndex(tags, channel);
MDUtils.setChannelName(tags, channelNames_[channel]);
MDUtils.setSliceIndex(tags, slice);
MDUtils.setPositionIndex(tags, position);
MDUtils.setElapsedTimeMs(tags, ms);
MDUtils.setImageTime(tags, MDUtils.getCurrentTime());
MDUtils.setZStepUm(tags, PanelUtils.getSpinnerFloatValue(stepSize_));
if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) {
// add default setting
tags.put(MMTags.Summary.SLICES_FIRST, true);
tags.put(MMTags.Summary.TIME_FIRST, false);
}
if (acq.getPositions() > 1) {
// if no position name is defined we need to insert a default one
if (tags.has(MMTags.Image.POS_NAME)) {
tags.put(MMTags.Image.POS_NAME, "Pos" + position);
}
}
// update frames if necessary
if (acq.getFrames() <= frame) {
acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame + 1));
}
} catch (JSONException e) {
throw new MMScriptException(e);
}
bq.put(taggedImg);
}
/***************** API *******************/
/**
* @return true if an acquisition is currently underway
* (e.g. all checks passed, controller set up, MM acquisition object created, etc.)
*/
public boolean isAcquisitionRunning() {
return acquisitionRunning_.get();
}
/**
* @return true if an acquisition has been requested by user. Will
* also return true if acquisition is running.
*/
public boolean isAcquisitionRequested() {
return acquisitionRequested_.get();
}
/**
* Stops the acquisition by setting an Atomic boolean indicating that we should
* halt. Does nothing if an acquisition isn't running.
*/
public void stopAcquisition() {
if (isAcquisitionRequested()) {
cancelAcquisition_.set(true);
}
}
/**
* @return pathname on filesystem to last completed acquisition
* (even if it was stopped pre-maturely). Null if not saved to disk.
*/
public String getLastAcquisitionPath() {
return lastAcquisitionPath_;
}
public String getLastAcquisitionName() {
return lastAcquisitionName_;
}
public ij.ImagePlus getLastAcquisitionImagePlus() throws ASIdiSPIMException {
try {
return gui_.getAcquisition(lastAcquisitionName_).getAcquisitionWindow().getImagePlus();
} catch (MMScriptException e) {
throw new ASIdiSPIMException(e);
}
}
public String getSavingDirectoryRoot() {
return rootField_.getText();
}
public void setSavingDirectoryRoot(String directory) throws ASIdiSPIMException {
rootField_.setText(directory);
try {
rootField_.commitEdit();
} catch (ParseException e) {
throw new ASIdiSPIMException(e);
}
}
public String getSavingNamePrefix() {
return prefixField_.getText();
}
public void setSavingNamePrefix(String acqPrefix) throws ASIdiSPIMException {
prefixField_.setText(acqPrefix);
try {
prefixField_.commitEdit();
} catch (ParseException e) {
throw new ASIdiSPIMException(e);
}
}
public boolean getSavingSeparateFile() {
return separateTimePointsCB_.isSelected();
}
public void setSavingSeparateFile(boolean separate) {
separateTimePointsCB_.setSelected(separate);
}
public boolean getSavingSaveWhileAcquiring() {
return saveCB_.isSelected();
}
public void setSavingSaveWhileAcquiring(boolean save) {
saveCB_.setSelected(save);
}
public org.micromanager.asidispim.Data.AcquisitionModes.Keys getAcquisitionMode() {
return (org.micromanager.asidispim.Data.AcquisitionModes.Keys) spimMode_.getSelectedItem();
}
public void setAcquisitionMode(org.micromanager.asidispim.Data.AcquisitionModes.Keys mode) {
spimMode_.setSelectedItem(mode);
}
public boolean getTimepointsEnabled() {
return useTimepointsCB_.isSelected();
}
public void setTimepointsEnabled(boolean enabled) {
useTimepointsCB_.setSelected(enabled);
}
public int getNumberOfTimepoints() {
return (Integer) numTimepoints_.getValue();
}
public void setNumberOfTimepoints(int numTimepoints) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(numTimepoints, 1, 100000)) {
throw new ASIdiSPIMException("illegal value for number of time points");
}
numTimepoints_.setValue(numTimepoints);
}
// getTimepointInterval already existed
public void setTimepointInterval(double intervalTimepoints) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(intervalTimepoints, 0.1, 32000)) {
throw new ASIdiSPIMException("illegal value for time point interval");
}
acquisitionInterval_.setValue(intervalTimepoints);
}
public boolean getMultiplePositionsEnabled() {
return usePositionsCB_.isSelected();
}
public void setMultiplePositionsEnabled(boolean enabled) {
usePositionsCB_.setSelected(enabled);
}
public double getMultiplePositionsPostMoveDelay() {
return PanelUtils.getSpinnerFloatValue(positionDelay_);
}
public void setMultiplePositionsDelay(double delayMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(delayMs, 0d, 10000d)) {
throw new ASIdiSPIMException("illegal value for post move delay");
}
positionDelay_.setValue(delayMs);
}
public boolean getChannelsEnabled() {
return multiChannelPanel_.isMultiChannel();
}
public void setChannelsEnabled(boolean enabled) {
multiChannelPanel_.setPanelEnabled(enabled);
}
public String[] getAvailableChannelGroups() {
return multiChannelPanel_.getAvailableGroups();
}
public String getChannelGroup() {
return multiChannelPanel_.getChannelGroup();
}
public void setChannelGroup(String channelGroup) {
String[] availableGroups = getAvailableChannelGroups();
for (String group : availableGroups) {
if (group.equals(channelGroup)) {
multiChannelPanel_.setChannelGroup(channelGroup);
}
}
}
public String[] getAvailableChannels() {
return multiChannelPanel_.getAvailableChannels();
}
public boolean getChannelEnabled(String channel) {
ChannelSpec[] usedChannels = multiChannelPanel_.getUsedChannels();
for (ChannelSpec spec : usedChannels) {
if (spec.config_.equals(channel)) {
return true;
}
}
return false;
}
public void setChannelEnabled(String channel, boolean enabled) {
multiChannelPanel_.setChannelEnabled(channel, enabled);
}
// getNumSides() already existed
public void setVolumeNumberOfSides(int numSides) {
if (numSides == 2) {
numSides_.setSelectedIndex(1);
} else {
numSides_.setSelectedIndex(0);
}
}
public void setFirstSideIsA(boolean firstSideIsA) {
if (firstSideIsA) {
firstSide_.setSelectedIndex(0);
} else {
firstSide_.setSelectedIndex(1);
}
}
public double getVolumeDelayBeforeSide() {
return PanelUtils.getSpinnerFloatValue(delaySide_);
}
public void setVolumeDelayBeforeSide(double delayMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(delayMs, 0d, 10000d)) {
throw new ASIdiSPIMException("illegal value for delay before side");
}
delaySide_.setValue(delayMs);
}
public int getVolumeSlicesPerVolume() {
return (Integer) numSlices_.getValue();
}
public void setVolumeSlicesPerVolume(int slices) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(slices, 1, 65000)) {
throw new ASIdiSPIMException("illegal value for number of slices");
}
numSlices_.setValue(slices);
}
public double getVolumeSliceStepSize() {
return PanelUtils.getSpinnerFloatValue(stepSize_);
}
public void setVolumeSliceStepSize(double stepSizeUm) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(stepSizeUm, 0d, 100d)) {
throw new ASIdiSPIMException("illegal value for slice step size");
}
stepSize_.setValue(stepSizeUm);
}
public boolean getVolumeMinimizeSlicePeriod() {
return minSlicePeriodCB_.isSelected();
}
public void setVolumeMinimizeSlicePeriod(boolean minimize) {
minSlicePeriodCB_.setSelected(minimize);
}
public double getVolumeSlicePeriod() {
return PanelUtils.getSpinnerFloatValue(desiredSlicePeriod_);
}
public void setVolumeSlicePeriod(double periodMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(periodMs, 1d, 1000d)) {
throw new ASIdiSPIMException("illegal value for slice period");
}
desiredSlicePeriod_.setValue(periodMs);
}
public double getVolumeSampleExposure() {
return PanelUtils.getSpinnerFloatValue(desiredLightExposure_);
}
public void setVolumeSampleExposure(double exposureMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(exposureMs, 1.0, 1000.0)) {
throw new ASIdiSPIMException("illegal value for sample exposure");
}
desiredLightExposure_.setValue(exposureMs);
}
public boolean getAutofocusDuringAcquisition() {
return useAutofocusCB_.isSelected();
}
public void setAutofocusDuringAcquisition(boolean enable) {
useAutofocusCB_.setSelected(enable);
}
public double getEstimatedSliceDuration() {
return sliceTiming_.sliceDuration;
}
public double getEstimatedVolumeDuration() {
return computeActualVolumeDuration();
}
public double getEstimatedAcquisitionDuration() {
return computeActualTimeLapseDuration();
}
} | ASIdiSPIM: add some sanity checking to file saving, also force separate viewer mode to save to empty directory
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@16186 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
| plugins/ASIdiSPIM/src/org/micromanager/asidispim/AcquisitionPanel.java | ASIdiSPIM: add some sanity checking to file saving, also force separate viewer mode to save to empty directory |
|
Java | mit | 734a55cc82050af9597e1c9e1a5a5de1f6fa6479 | 0 | inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid | package org.inaturalist.android;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Typeface;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tinylog.Logger;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/** Various app-wide taxon-related utility functions */
public class TaxonUtils {
private static final Map<String, Float> RANK_NAME_TO_LEVEL;
private static final String TAG = "TaxonUtils";
static {
Map<String, Float> rankNameToLevel = new HashMap<>();
rankNameToLevel.put("root", 100f);
rankNameToLevel.put("kingdom", 70f);
rankNameToLevel.put("subkingdom", 67f);
rankNameToLevel.put("phylum", 60f);
rankNameToLevel.put("subphylum", 57f);
rankNameToLevel.put("superclass", 53f);
rankNameToLevel.put("class", 50f);
rankNameToLevel.put("subclass", 47f);
rankNameToLevel.put("infraclass", 45f);
rankNameToLevel.put("superorder", 43f);
rankNameToLevel.put("order", 40f);
rankNameToLevel.put("suborder", 37f);
rankNameToLevel.put("infraorder", 35f);
rankNameToLevel.put("parvorder", 34.5f);
rankNameToLevel.put("zoosection", 34f);
rankNameToLevel.put("zoosubsection", 33.5f);
rankNameToLevel.put("superfamily", 33f);
rankNameToLevel.put("epifamily", 32f);
rankNameToLevel.put("family", 30f);
rankNameToLevel.put("subfamily", 27f);
rankNameToLevel.put("supertribe", 26f);
rankNameToLevel.put("tribe", 25f);
rankNameToLevel.put("subtribe", 24f);
rankNameToLevel.put("genus", 20f);
rankNameToLevel.put("genushybrid", 20f);
rankNameToLevel.put("subgenus", 15f);
rankNameToLevel.put("section", 13f);
rankNameToLevel.put("subsection", 12f);
rankNameToLevel.put("species", 10f);
rankNameToLevel.put("hybrid", 10f);
rankNameToLevel.put("subspecies", 5f);
rankNameToLevel.put("variety", 5f);
rankNameToLevel.put("form", 5f);
rankNameToLevel.put("infrahybrid", 5f);
RANK_NAME_TO_LEVEL = Collections.unmodifiableMap(rankNameToLevel);
}
public static void setTaxonScientificName(INaturalistApp app, TextView textView, String taxonName, int rankLevel, String rank) {
JSONObject taxon = new JSONObject();
try {
taxon.put("rank", rank);
taxon.put("rank_level", rankLevel);
taxon.put("name", taxonName);
setTaxonScientificName(app, textView, taxon);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
public static void setTaxonScientificNameWithRank(INaturalistApp app, TextView textView, JSONObject item) {
textView.setText(Html.fromHtml(getTaxonScientificNameHtml(app, item, false, true)));
}
public static void setTaxonScientificName(INaturalistApp app, TextView textView, JSONObject item) {
setTaxonScientificName(app, textView, item, false);
}
public static void setTaxonScientificName(INaturalistApp app, TextView textView, JSONObject item, boolean bold) {
textView.setText(Html.fromHtml(getTaxonScientificNameHtml(app, item, bold, false)));
}
public static String getTaxonScientificNameHtml(INaturalistApp app, JSONObject item, boolean bold, boolean alwaysShowRank) {
String rankName = item.optString("name", "");
String rank = getTaxonRank(app, item);
double rankLevel = getTaxonRankLevel(item);
String name;
if ((alwaysShowRank) || (rankLevel <= 20)) {
name = (rank.equals("") ? "" : (rank + " "));
} else {
name = "";
}
if ((rankLevel <= 20) && (rankLevel != 11) /* 11 = complex */) {
name += "<i>" + rankName + "</i>";
} else {
name += rankName;
}
return bold ? "<b>" + name + "</b>" : name;
}
public static double getTaxonRankLevel(JSONObject item) {
if (item.has("rank_level")) return item.optDouble("rank_level");
// Try to deduce rank level from rank
if (item.has("rank")) {
if (RANK_NAME_TO_LEVEL.containsKey(item.optString("rank"))) {
return RANK_NAME_TO_LEVEL.get(item.optString("rank").toLowerCase());
} else {
return 0;
}
} else {
return 0;
}
}
public static String getTaxonRank(INaturalistApp app, JSONObject item) {
double rankLevel = getTaxonRankLevel(item);
if ((rankLevel < 15) && (rankLevel != 11)) {
// Lower than subgenus and not complex - don't return anything
return "";
} else {
return getTranslatedRank(app, item.optString("rank", ""));
}
}
/** Return the translated rank name (i.e. translated name of species/order/etc.) - if not found
* returns the rank as-is */
public static String getTranslatedRank(INaturalistApp app, String rank) {
String translated = app.getStringResourceByNameOrNull(String.format("rank_%s", toSnakeCase(rank)));
if (translated == null) {
// No translation found - return as-is
return rank;
}
return translated;
}
public static String getTaxonScientificName(INaturalistApp app, JSONObject item) {
String rank = getTaxonRank(app, item);
String scientificName = item.optString("name", "");
if (rank.equals("")) {
return scientificName;
} else {
return String.format("%s %s", rank, scientificName);
}
}
public static String getTaxonName(Context context, JSONObject item) {
JSONObject defaultName;
String displayName = null;
// Get the taxon display name according to device locale
Locale deviceLocale = context.getResources().getConfiguration().locale;
String deviceLexicon = deviceLocale.getLanguage();
try {
JSONArray taxonNames = item.getJSONArray("taxon_names");
for (int i = 0; i < taxonNames.length(); i++) {
JSONObject taxonName = taxonNames.getJSONObject(i);
String lexicon = taxonName.getString("lexicon");
if (lexicon.equals(deviceLexicon)) {
// Found the appropriate lexicon for the taxon
displayName = taxonName.getString("name");
break;
}
}
} catch (JSONException e) {
}
if (displayName == null) {
// Couldn't extract the display name from the taxon names list - use the default one
try {
defaultName = item.getJSONObject("default_name");
displayName = defaultName.getString("name");
} catch (JSONException e1) {
// alas
JSONObject commonName = item.optJSONObject("common_name");
if (commonName != null) {
displayName = commonName.optString("name");
} else {
displayName = item.optString("preferred_common_name");
if ((displayName == null) || (displayName.length() == 0)) {
displayName = item.optString("english_common_name");
if ((displayName == null) || (displayName.length() == 0)) {
displayName = item.optString("name");
}
}
}
}
}
if (displayName == null) {
displayName = context.getResources().getString(R.string.unknown);
}
return displayName;
}
public static int taxonicIconNameToResource(String iconicTaxonName) {
if (iconicTaxonName == null) {
return R.drawable.ic_taxa_unknown;
} else if (iconicTaxonName.equals("Animalia")) {
return R.drawable.animalia_large;
} else if (iconicTaxonName.equals("Plantae")) {
return R.drawable.plantae_large;
} else if (iconicTaxonName.equals("Chromista")) {
return R.drawable.chromista_large;
} else if (iconicTaxonName.equals("Fungi")) {
return R.drawable.fungi_large;
} else if (iconicTaxonName.equals("Protozoa")) {
return R.drawable.protozoa_large;
} else if (iconicTaxonName.equals("Actinopterygii")) {
return R.drawable.actinopterygii_large;
} else if (iconicTaxonName.equals("Amphibia")) {
return R.drawable.amphibia_large;
} else if (iconicTaxonName.equals("Reptilia")) {
return R.drawable.reptilia_large;
} else if (iconicTaxonName.equals("Aves")) {
return R.drawable.aves_large;
} else if (iconicTaxonName.equals("Mammalia")) {
return R.drawable.mammalia_large;
} else if (iconicTaxonName.equals("Mollusca")) {
return R.drawable.mollusca_large;
} else if (iconicTaxonName.equals("Insecta")) {
return R.drawable.insecta_large;
} else if (iconicTaxonName.equals("Arachnida")) {
return R.drawable.arachnida_large;
} else {
return R.drawable.ic_taxa_unknown;
}
}
public static int observationIcon(JSONObject o) {
if (o == null) return R.drawable.ic_taxa_unknown;
String iconicTaxonName = null;
if (o.has("iconic_taxon_name") && !o.isNull("iconic_taxon_name")) {
try {
iconicTaxonName = o.getString("iconic_taxon_name");
} catch (JSONException e) {
Logger.tag(TAG).error(e);
return R.drawable.ic_taxa_unknown;
}
} else if (o.has("taxon") && !o.isNull("taxon")) {
try {
iconicTaxonName = o.getJSONObject("taxon").optString("iconic_taxon_name");
} catch (JSONException e) {
Logger.tag(TAG).error(e);
return R.drawable.ic_taxa_unknown;
}
}
return taxonicIconNameToResource(iconicTaxonName);
}
public static BitmapDescriptor observationMarkerIcon(String iconic_taxon_name) {
return observationMarkerIcon(iconic_taxon_name, false);
}
public static BitmapDescriptor observationMarkerIcon(String iconic_taxon_name, boolean stemless) {
if (iconic_taxon_name == null) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_unknown : R.drawable.mm_34_unknown);
}
if (iconic_taxon_name.equals("Animalia") ||
iconic_taxon_name.equals("Actinopterygii") ||
iconic_taxon_name.equals("Amphibia") ||
iconic_taxon_name.equals("Reptilia") ||
iconic_taxon_name.equals("Aves") ||
iconic_taxon_name.equals("Mammalia")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_dodger_blue_no_dot : R.drawable.mm_34_dodger_blue);
} else if (iconic_taxon_name.equals("Insecta") ||
iconic_taxon_name.equals("Arachnida") ||
iconic_taxon_name.equals("Mollusca")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_orange_red_no_dot : R.drawable.mm_34_orange_red);
} else if (iconic_taxon_name.equals("Protozoa")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_dark_magenta_no_dot : R.drawable.mm_34_dark_magenta);
} else if (iconic_taxon_name.equals("Plantae")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_inat_green_no_dot : R.drawable.mm_34_inat_green);
} else if (iconic_taxon_name.equals("Fungi")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_hot_pink_no_dot : R.drawable.mm_34_hot_pink);
} else if (iconic_taxon_name.equals("Chromista")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_chromista_brown_no_dot : R.drawable.mm_34_chromista_brown);
} else {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_unknown : R.drawable.mm_34_unknown);
}
}
// Convert a string into snake case (e.g. "My String!!!" -> "my_string___"). Replaces any invalid character (non letter/digit) with an underscore.
public static String toSnakeCase(String string) {
StringBuilder builder = new StringBuilder(string);
final int len = builder.length();
for (int i = 0; i < len; i++) {
char c = builder.charAt(i);
if (!Character.isLetterOrDigit(c)) {
builder.setCharAt(i, '_');
} else {
builder.setCharAt(i, Character.toLowerCase(c));
}
}
return builder.toString();
}
}
| iNaturalist/src/main/java/org/inaturalist/android/TaxonUtils.java | package org.inaturalist.android;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Typeface;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tinylog.Logger;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/** Various app-wide taxon-related utility functions */
public class TaxonUtils {
private static final Map<String, Float> RANK_NAME_TO_LEVEL;
private static final String TAG = "TaxonUtils";
static {
Map<String, Float> rankNameToLevel = new HashMap<>();
rankNameToLevel.put("root", 100f);
rankNameToLevel.put("kingdom", 70f);
rankNameToLevel.put("subkingdom", 67f);
rankNameToLevel.put("phylum", 60f);
rankNameToLevel.put("subphylum", 57f);
rankNameToLevel.put("superclass", 53f);
rankNameToLevel.put("class", 50f);
rankNameToLevel.put("subclass", 47f);
rankNameToLevel.put("infraclass", 45f);
rankNameToLevel.put("superorder", 43f);
rankNameToLevel.put("order", 40f);
rankNameToLevel.put("suborder", 37f);
rankNameToLevel.put("infraorder", 35f);
rankNameToLevel.put("parvorder", 34.5f);
rankNameToLevel.put("zoosection", 34f);
rankNameToLevel.put("zoosubsection", 33.5f);
rankNameToLevel.put("superfamily", 33f);
rankNameToLevel.put("epifamily", 32f);
rankNameToLevel.put("family", 30f);
rankNameToLevel.put("subfamily", 27f);
rankNameToLevel.put("supertribe", 26f);
rankNameToLevel.put("tribe", 25f);
rankNameToLevel.put("subtribe", 24f);
rankNameToLevel.put("genus", 20f);
rankNameToLevel.put("genushybrid", 20f);
rankNameToLevel.put("subgenus", 15f);
rankNameToLevel.put("section", 13f);
rankNameToLevel.put("subsection", 12f);
rankNameToLevel.put("species", 10f);
rankNameToLevel.put("hybrid", 10f);
rankNameToLevel.put("subspecies", 5f);
rankNameToLevel.put("variety", 5f);
rankNameToLevel.put("form", 5f);
rankNameToLevel.put("infrahybrid", 5f);
RANK_NAME_TO_LEVEL = Collections.unmodifiableMap(rankNameToLevel);
}
public static void setTaxonScientificName(INaturalistApp app, TextView textView, String taxonName, int rankLevel, String rank) {
JSONObject taxon = new JSONObject();
try {
taxon.put("rank", rank);
taxon.put("rank_level", rankLevel);
taxon.put("name", taxonName);
setTaxonScientificName(app, textView, taxon);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
public static void setTaxonScientificNameWithRank(INaturalistApp app, TextView textView, JSONObject item) {
textView.setText(Html.fromHtml(getTaxonScientificNameHtml(app, item, false, true)));
}
public static void setTaxonScientificName(INaturalistApp app, TextView textView, JSONObject item) {
setTaxonScientificName(app, textView, item, false);
}
public static void setTaxonScientificName(INaturalistApp app, TextView textView, JSONObject item, boolean bold) {
textView.setText(Html.fromHtml(getTaxonScientificNameHtml(app, item, bold, false)));
}
public static String getTaxonScientificNameHtml(INaturalistApp app, JSONObject item, boolean bold, boolean alwaysShowRank) {
String rankName = item.optString("name", "");
String rank = getTaxonRank(app, item);
double rankLevel = getTaxonRankLevel(item);
String name;
if ((alwaysShowRank) || (rankLevel <= 20)) {
name = (rank.equals("") ? "" : (rank + " "));
} else {
name = "";
}
if ((rankLevel <= 20) && (rankLevel != 11) /* 11 = complex */) {
name += "<i>" + rankName + "</i>";
} else {
name += rankName;
}
return bold ? "<b>" + name + "</b>" : name;
}
public static double getTaxonRankLevel(JSONObject item) {
if (item.has("rank_level")) return item.optDouble("rank_level");
// Try to deduce rank level from rank
if (item.has("rank")) {
if (RANK_NAME_TO_LEVEL.containsKey(item.optString("rank"))) {
return RANK_NAME_TO_LEVEL.get(item.optString("rank").toLowerCase());
} else {
return 0;
}
} else {
return 0;
}
}
public static String getTaxonRank(INaturalistApp app, JSONObject item) {
double rankLevel = getTaxonRankLevel(item);
if ((rankLevel < 15) && (rankLevel != 11)) {
// Lower than subgenus and not complex - don't return anything
return "";
} else {
return getTranslatedRank(app, item.optString("rank", ""));
}
}
/** Return the translated rank name (i.e. translated name of species/order/etc.) - if not found
* returns the rank as-is */
public static String getTranslatedRank(INaturalistApp app, String rank) {
String translated = app.getStringResourceByNameOrNull(String.format("rank_%s", toSnakeCase(rank)));
Logger.tag(TAG).error("AAA - getTranslatedRank - " + rank + ":" + toSnakeCase(rank) + " => " + translated);
if (translated == null) {
// No translation found - return as-is
return rank;
}
return translated;
}
public static String getTaxonScientificName(INaturalistApp app, JSONObject item) {
String rank = getTaxonRank(app, item);
String scientificName = item.optString("name", "");
if (rank.equals("")) {
return scientificName;
} else {
return String.format("%s %s", rank, scientificName);
}
}
public static String getTaxonName(Context context, JSONObject item) {
JSONObject defaultName;
String displayName = null;
// Get the taxon display name according to device locale
Locale deviceLocale = context.getResources().getConfiguration().locale;
String deviceLexicon = deviceLocale.getLanguage();
try {
JSONArray taxonNames = item.getJSONArray("taxon_names");
for (int i = 0; i < taxonNames.length(); i++) {
JSONObject taxonName = taxonNames.getJSONObject(i);
String lexicon = taxonName.getString("lexicon");
if (lexicon.equals(deviceLexicon)) {
// Found the appropriate lexicon for the taxon
displayName = taxonName.getString("name");
break;
}
}
} catch (JSONException e) {
}
if (displayName == null) {
// Couldn't extract the display name from the taxon names list - use the default one
try {
defaultName = item.getJSONObject("default_name");
displayName = defaultName.getString("name");
} catch (JSONException e1) {
// alas
JSONObject commonName = item.optJSONObject("common_name");
if (commonName != null) {
displayName = commonName.optString("name");
} else {
displayName = item.optString("preferred_common_name");
if ((displayName == null) || (displayName.length() == 0)) {
displayName = item.optString("english_common_name");
if ((displayName == null) || (displayName.length() == 0)) {
displayName = item.optString("name");
}
}
}
}
}
if (displayName == null) {
displayName = context.getResources().getString(R.string.unknown);
}
return displayName;
}
public static int taxonicIconNameToResource(String iconicTaxonName) {
if (iconicTaxonName == null) {
return R.drawable.ic_taxa_unknown;
} else if (iconicTaxonName.equals("Animalia")) {
return R.drawable.animalia_large;
} else if (iconicTaxonName.equals("Plantae")) {
return R.drawable.plantae_large;
} else if (iconicTaxonName.equals("Chromista")) {
return R.drawable.chromista_large;
} else if (iconicTaxonName.equals("Fungi")) {
return R.drawable.fungi_large;
} else if (iconicTaxonName.equals("Protozoa")) {
return R.drawable.protozoa_large;
} else if (iconicTaxonName.equals("Actinopterygii")) {
return R.drawable.actinopterygii_large;
} else if (iconicTaxonName.equals("Amphibia")) {
return R.drawable.amphibia_large;
} else if (iconicTaxonName.equals("Reptilia")) {
return R.drawable.reptilia_large;
} else if (iconicTaxonName.equals("Aves")) {
return R.drawable.aves_large;
} else if (iconicTaxonName.equals("Mammalia")) {
return R.drawable.mammalia_large;
} else if (iconicTaxonName.equals("Mollusca")) {
return R.drawable.mollusca_large;
} else if (iconicTaxonName.equals("Insecta")) {
return R.drawable.insecta_large;
} else if (iconicTaxonName.equals("Arachnida")) {
return R.drawable.arachnida_large;
} else {
return R.drawable.ic_taxa_unknown;
}
}
public static int observationIcon(JSONObject o) {
if (o == null) return R.drawable.ic_taxa_unknown;
String iconicTaxonName = null;
if (o.has("iconic_taxon_name") && !o.isNull("iconic_taxon_name")) {
try {
iconicTaxonName = o.getString("iconic_taxon_name");
} catch (JSONException e) {
Logger.tag(TAG).error(e);
return R.drawable.ic_taxa_unknown;
}
} else if (o.has("taxon") && !o.isNull("taxon")) {
try {
iconicTaxonName = o.getJSONObject("taxon").optString("iconic_taxon_name");
} catch (JSONException e) {
Logger.tag(TAG).error(e);
return R.drawable.ic_taxa_unknown;
}
}
return taxonicIconNameToResource(iconicTaxonName);
}
public static BitmapDescriptor observationMarkerIcon(String iconic_taxon_name) {
return observationMarkerIcon(iconic_taxon_name, false);
}
public static BitmapDescriptor observationMarkerIcon(String iconic_taxon_name, boolean stemless) {
if (iconic_taxon_name == null) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_unknown : R.drawable.mm_34_unknown);
}
if (iconic_taxon_name.equals("Animalia") ||
iconic_taxon_name.equals("Actinopterygii") ||
iconic_taxon_name.equals("Amphibia") ||
iconic_taxon_name.equals("Reptilia") ||
iconic_taxon_name.equals("Aves") ||
iconic_taxon_name.equals("Mammalia")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_dodger_blue_no_dot : R.drawable.mm_34_dodger_blue);
} else if (iconic_taxon_name.equals("Insecta") ||
iconic_taxon_name.equals("Arachnida") ||
iconic_taxon_name.equals("Mollusca")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_orange_red_no_dot : R.drawable.mm_34_orange_red);
} else if (iconic_taxon_name.equals("Protozoa")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_dark_magenta_no_dot : R.drawable.mm_34_dark_magenta);
} else if (iconic_taxon_name.equals("Plantae")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_inat_green_no_dot : R.drawable.mm_34_inat_green);
} else if (iconic_taxon_name.equals("Fungi")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_hot_pink_no_dot : R.drawable.mm_34_hot_pink);
} else if (iconic_taxon_name.equals("Chromista")) {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_chromista_brown_no_dot : R.drawable.mm_34_chromista_brown);
} else {
return BitmapDescriptorFactory.fromResource(stemless ? R.drawable.mm_34_stemless_unknown : R.drawable.mm_34_unknown);
}
}
// Convert a string into snake case (e.g. "My String!!!" -> "my_string___"). Replaces any invalid character (non letter/digit) with an underscore.
public static String toSnakeCase(String string) {
StringBuilder builder = new StringBuilder(string);
final int len = builder.length();
for (int i = 0; i < len; i++) {
char c = builder.charAt(i);
if (!Character.isLetterOrDigit(c)) {
builder.setCharAt(i, '_');
} else {
builder.setCharAt(i, Character.toLowerCase(c));
}
}
return builder.toString();
}
}
| Removed debug prints
| iNaturalist/src/main/java/org/inaturalist/android/TaxonUtils.java | Removed debug prints |
|
Java | mit | 9c86144752363f0809621e9c6fcbdd6487e9bbc3 | 0 | Socialate/furry-sniffle | package com.socialteinc.socialate;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
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.typeText;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LoginActivityTest {
@Rule
public ActivityTestRule<LoginActivity> main = new ActivityTestRule<>(LoginActivity.class);
// @Before
// public void startActivity(){
// main.getActivity();
// }
//
// @Test
// public void isDisplayedTest() throws InterruptedException{
// Thread.sleep(2000);
// //main.getActivity();
// onView(withId(R.id.email_field)).check(matches(isDisplayed()));
// onView(withId(R.id.password_field)).check(matches(isDisplayed()));
// onView(withId(R.id.SinginButton)).check(matches(isDisplayed()));
//
// onView(withId(R.id.appNameTextView)).check(matches(isDisplayed()));
// onView(withId(R.id.orTextView)).check(matches(isDisplayed()));
//
// onView(withId(R.id.resetPasswordTextView)).check(matches(isDisplayed()));
// onView(withId(R.id.creatAccountTextView)).check(matches(isDisplayed()));
//
// onView(withId(R.id.facebookButton)).check(matches(isDisplayed()));
// onView(withId(R.id.googleButton)).check(matches(isDisplayed()));
//
// Thread.sleep(2000);
//
// }
//
@Test
public void noValidEmailTest() {
onView(withId(R.id.email_field)).perform(typeText("invalidsocialate.com"), closeSoftKeyboard());
onView(withId(R.id.password_field)).perform(typeText("furry"), closeSoftKeyboard());
onView(withId(R.id.SinginButton)).perform(click());
}
@Test
public void noValidPasswordTest(){
onView(withId(R.id.email_field)).perform(typeText("[email protected]"), closeSoftKeyboard());
onView(withId(R.id.password_field)).perform(typeText("furry"), closeSoftKeyboard());
onView(withId(R.id.password_field)).perform(clearText());
onView(withId(R.id.SinginButton)).perform(click());
}
//
// @Test
// public void loginTesting() throws InterruptedException {
// Thread.sleep(2000);
// onView(withId(R.id.email_field)).perform(typeText("[email protected]"), closeSoftKeyboard());
// onView(withId(R.id.password_field)).perform(typeText("sandile"), closeSoftKeyboard());
// onView(withId(R.id.SinginButton)).perform(click());
// Thread.sleep(2000);
// }
//
// @Test
// public void signUpTesting() throws InterruptedException {
// init();
// Thread.sleep(3000);
// onView(withId(R.id.creatAccountTextView)).perform(click());
// intended(hasComponent(RegisterActivity.class.getName()));
// release();
// //Thread.sleep(3000);
// }
//
// @Test
// public void resetPasswordTesting() throws InterruptedException {
// init();
// Thread.sleep(3000);
// onView(withId(R.id.resetPasswordTextView)).perform(click());
// intended(hasComponent(ResetPasswordActivity.class.getName()));
// release();
//
// }
}
| app/src/androidTest/java/com/socialteinc/socialate/LoginActivityTest.java | package com.socialteinc.socialate;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LoginActivityTest {
@Rule
public ActivityTestRule<LoginActivity> main = new ActivityTestRule<>(LoginActivity.class);
// @Before
// public void startActivity(){
// main.getActivity();
// }
//
// @Test
// public void isDisplayedTest() throws InterruptedException{
// Thread.sleep(2000);
// //main.getActivity();
// onView(withId(R.id.email_field)).check(matches(isDisplayed()));
// onView(withId(R.id.password_field)).check(matches(isDisplayed()));
// onView(withId(R.id.SinginButton)).check(matches(isDisplayed()));
//
// onView(withId(R.id.appNameTextView)).check(matches(isDisplayed()));
// onView(withId(R.id.orTextView)).check(matches(isDisplayed()));
//
// onView(withId(R.id.resetPasswordTextView)).check(matches(isDisplayed()));
// onView(withId(R.id.creatAccountTextView)).check(matches(isDisplayed()));
//
// onView(withId(R.id.facebookButton)).check(matches(isDisplayed()));
// onView(withId(R.id.googleButton)).check(matches(isDisplayed()));
//
// Thread.sleep(2000);
//
// }
//
@Test
public void noValidEmailTest() throws InterruptedException {
// Thread.sleep(2000);
// onView(withId(R.id.email_field)).perform(typeText("invalidsocialate.com"), closeSoftKeyboard());
// onView(withId(R.id.password_field)).perform(typeText("furry"), closeSoftKeyboard());
// onView(withId(R.id.SinginButton)).perform(click());
// Thread.sleep(2000);
}
//
// @Test
// public void noValidPasswordTest() throws InterruptedException {
// Thread.sleep(2000);
// onView(withId(R.id.email_field)).perform(typeText("[email protected]"), closeSoftKeyboard());
// onView(withId(R.id.password_field)).perform(typeText("furry"), closeSoftKeyboard());
// onView(withId(R.id.password_field)).perform(clearText());
// onView(withId(R.id.SinginButton)).perform(click());
// Thread.sleep(2000);
// }
//
// @Test
// public void loginTesting() throws InterruptedException {
// Thread.sleep(2000);
// onView(withId(R.id.email_field)).perform(typeText("[email protected]"), closeSoftKeyboard());
// onView(withId(R.id.password_field)).perform(typeText("sandile"), closeSoftKeyboard());
// onView(withId(R.id.SinginButton)).perform(click());
// Thread.sleep(2000);
// }
//
// @Test
// public void signUpTesting() throws InterruptedException {
// init();
// Thread.sleep(3000);
// onView(withId(R.id.creatAccountTextView)).perform(click());
// intended(hasComponent(RegisterActivity.class.getName()));
// release();
// //Thread.sleep(3000);
// }
//
// @Test
// public void resetPasswordTesting() throws InterruptedException {
// init();
// Thread.sleep(3000);
// onView(withId(R.id.resetPasswordTextView)).perform(click());
// intended(hasComponent(ResetPasswordActivity.class.getName()));
// release();
//
// }
}
| Login Tests update
| app/src/androidTest/java/com/socialteinc/socialate/LoginActivityTest.java | Login Tests update |
|
Java | mit | 5bb869aa98ff41a8fba5233ec03d7d6558eca407 | 0 | cs2103jan2015-w13-3j/main,cs2103jan2015-w13-3j/main | package udo.logic;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import udo.gui.GUI;
import udo.storage.Task;
import udo.util.Config;
public class Logic {
private GUI gui;
private static final String ERR_FORMAT = "Error: %s";
private static final String ERR_INVALID_CMD_NAME = "Invalid command";
private static final String ERR_UNSUPPORTED_CMD = "Unsupported command";
private static final String ERR_INVALID_CMD_ARG =
"Invalid command's argument";
private static final String ERR_UNSPECIFIED_INDEX =
"A valid task's index is required";
private static final String ERR_LATE_DEADLINE =
"Deadline has already passed";
private static final String ERR_NON_POSITIVE_DUR =
"Task's duration must be positive";
private static final String STATUS_ADDED = "Task: %s added sucessfully";
private static final String STATUS_DELETED =
"Task: %d deleted sucessfully";
private static final String STATUS_MODIFIED =
"Task: %d modified sucessfully";
private static final Integer MAX_STATUS_LENGTH = 40;
private InputParser parser;
private static String status;
public Logic(GUI gui) {
this.gui = gui;
parser = new InputParser();
/* TODO:
* Initialize Storage
* Initialize and start up passive thread for reminder
*/
}
/******************************
* Code for the active logics *
******************************/
/**
* Execute the command given in the command string
* @param command the command string
*/
public boolean executeCommand(String command) {
Command parsedCommand = parser.parseCommand(command);
if (parser.getErrorStatus() != null) {
// Syntax error
status = parser.getErrorStatus();
gui.displayStatus(status);
return false;
}
if (isCommandValid(parsedCommand)) {
switch (parsedCommand.commandName) {
case ADD:
executeAddCommand(parsedCommand);
break;
case MODIFY:
executeModifyCommand(parsedCommand);
break;
case DELETE:
executeDeleteCommand(parsedCommand);
break;
case DISPLAY:
executeDisplayCommand(parsedCommand);
break;
default:
status = ERR_UNSUPPORTED_CMD;
}
gui.displayStatus(status);
return true;
} else {
gui.displayStatus(status);
return false;
}
}
private void executeDisplayCommand(Command parsedCommand) {
// TODO fill in default values
// TODO fill in data structure and call storage apis
status = getDisplaySucessStatus(parsedCommand);
}
private String getDisplaySucessStatus(Command parsedCommand) {
return "";
}
private void executeDeleteCommand(Command parsedCommand) {
// TODO fill in default values
// TODO fill in data structure and call storage apis
status = getDeleteSucessStatus(parsedCommand);
// TODO retrieve and display all tasks
}
private String getDeleteSucessStatus(Command parsedCommand) {
return String.format(STATUS_DELETED, parsedCommand.argIndex);
}
private void executeModifyCommand(Command parsedCommand) {
// TODO fill in default values
// TODO fill in data structure and call storage apis
status = getModifySucessStatus(parsedCommand);
// TODO retrieve and display all tasks
}
private String getModifySucessStatus(Command parsedCommand) {
// TODO Auto-generated method stub
return String.format(STATUS_MODIFIED, parsedCommand.argIndex);
}
private void executeAddCommand(Command parsedCommand) {
Task task = fillAddedTask(parsedCommand);
// Call storage apis
status = getAddSucessStatus(parsedCommand);
// TODO retrieve and display all tasks
}
private Task fillAddedTask(Command parsedCommand) {
Task task = new Task();
task.setTaskType(getTaskType(parsedCommand));
task.setContent(parsedCommand.argStr);
fillDeadline(task, parsedCommand);
fillStartDate(task, parsedCommand);
fillEndDate(task, parsedCommand);
fillDuration(task, parsedCommand);
fillReminder(task, parsedCommand);
fillLabel(task, parsedCommand);
fillPriority(task, parsedCommand);
return task;
}
private void fillPriority(Task task, Command cmd) {
Command.Option priority = getOption(cmd, Config.OPT_PRIO);
if (priority != null) {
task.setPriority(true);
} else {
task.setPriority(false);
}
}
private void fillLabel(Task task, Command cmd) {
Command.Option label = getOption(cmd, Config.OPT_LABEL);
if (label != null) {
task.setLabel(label.strArgument);
}
}
private void fillReminder(Task task, Command cmd) {
Command.Option reminder = getOption(cmd, Config.OPT_START);
if (reminder != null) {
GregorianCalendar reminderCalendar = new GregorianCalendar();
reminderCalendar.setTime(reminder.dateArgument);
task.setReminder(reminderCalendar);
}
}
private void fillDuration(Task task, Command cmd) {
Command.Option duration = getOption(cmd, Config.OPT_DUR);
if (duration != null) {
task.setDuration(duration.timeArgument);
}
}
private void fillEndDate(Task task, Command cmd) {
Command.Option end = getOption(cmd, Config.OPT_START);
if (end != null) {
GregorianCalendar endCalendar = new GregorianCalendar();
endCalendar.setTime(end.dateArgument);
task.setEnd(endCalendar);
}
}
private void fillStartDate(Task task, Command cmd) {
Command.Option start = getOption(cmd, Config.OPT_START);
if (start != null) {
GregorianCalendar startCalendar = new GregorianCalendar();
startCalendar.setTime(start.dateArgument);
task.setStart(startCalendar);
}
}
private void fillDeadline(Task task, Command cmd) {
Command.Option deadline = getOption(cmd, Config.OPT_DEADLINE);
if (deadline != null) {
GregorianCalendar deadlineCalendar = new GregorianCalendar();
deadlineCalendar.setTime(deadline.dateArgument);
task.setDeadline(deadlineCalendar);
}
}
private Command.Option getOption(Command cmd, String[] option) {
return cmd.options.get(option[Config.OPT_LONG]);
}
/**
* Guess and return a task type from a command
* @param task
* @param options
*/
private Task.TaskType getTaskType(Command parsedCommand) {
Map<String, Command.Option> options = parsedCommand.options;
if (options.containsKey(Config.OPT_DEADLINE[Config.OPT_LONG]) ||
options.containsKey(Config.OPT_DEADLINE[Config.OPT_SHORT])) {
return Task.TaskType.DEADLINE;
} else if (options.containsKey(Config.OPT_START[Config.OPT_LONG]) ||
options.containsKey(Config.OPT_START[Config.OPT_SHORT]) ||
options.containsKey(Config.OPT_END[Config.OPT_LONG]) ||
options.containsKey(Config.OPT_END[Config.OPT_SHORT])) {
return Task.TaskType.EVENT;
} else {
return Task.TaskType.TODO;
}
}
private String getAddSucessStatus(Command parsedCommand) {
String taskContent = parsedCommand.argStr;
if (taskContent.length() > MAX_STATUS_LENGTH) {
taskContent = taskContent.substring(0, MAX_STATUS_LENGTH);
taskContent += "...";
}
return String.format(STATUS_ADDED, taskContent);
}
/**
* Check the semantics of a parsed command
* @param parsedCommand
* @return the command's correctness
*/
private boolean isCommandValid(Command parsedCommand) {
if (parsedCommand == null || parsedCommand.commandName == null) {
status = formatErrorStr(ERR_INVALID_CMD_NAME);
return false;
}
Config.CommandName cmdName = parsedCommand.commandName;
switch (cmdName) {
case ADD:
return isAddCmdValid(parsedCommand);
case DELETE:
return isDeleteCmdValid(parsedCommand);
case MODIFY:
return isModifyCmdValid(parsedCommand);
case DISPLAY:
return isDisplayCmdValid(parsedCommand);
default:
status = formatErrorStr(ERR_UNSUPPORTED_CMD);
return false;
}
}
private boolean isDisplayCmdValid(Command parsedCommand) {
return true;
}
private boolean isModifyCmdValid(Command parsedCommand) {
if (parsedCommand.argIndex == null) {
status = ERR_UNSPECIFIED_INDEX;
return false;
}
return true;
}
private boolean isDeleteCmdValid(Command parsedCommand) {
if (parsedCommand.argIndex == null) {
status = ERR_UNSPECIFIED_INDEX;
return false;
}
return true;
}
private boolean isAddCmdValid(Command parsedCommand) {
if (parsedCommand.argStr == null) {
status = ERR_INVALID_CMD_ARG;
return false;
}
return isStartBeforeEnd(parsedCommand) &&
isDurationValid(parsedCommand) &&
isDeadlineValid(parsedCommand);
}
private boolean isDeadlineValid(Command cmd) {
Command.Option deadline = getOption(cmd, Config.OPT_DEADLINE);
if (deadline != null) {
if (deadline.dateArgument.compareTo(new Date()) < 0) {
status = ERR_LATE_DEADLINE;
return false;
}
}
return true;
}
private boolean isDurationValid(Command cmd) {
Command.Option duration = getOption(cmd, Config.OPT_DUR);
if (duration != null) {
if (duration.timeArgument <= 0) {
status = ERR_NON_POSITIVE_DUR;
return false;
}
}
return true;
}
private boolean isStartBeforeEnd(Command cmd) {
Command.Option start = getOption(cmd, Config.OPT_DEADLINE);
Command.Option end = getOption(cmd, Config.OPT_END);
if (start != null && end != null) {
if (start.dateArgument.compareTo(end.dateArgument) >= 0) {
status = ERR_NON_POSITIVE_DUR;
return false;
}
}
return true;
}
private String formatErrorStr(String errorInvalidCmdName) {
return String.format(ERR_FORMAT, errorInvalidCmdName);
}
} | src/udo/logic/Logic.java | package udo.logic;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import udo.gui.GUI;
import udo.storage.Task;
import udo.util.Config;
public class Logic {
private GUI gui;
private static final String ERR_FORMAT = "Error: %s";
private static final String ERR_INVALID_CMD_NAME = "Invalid command";
private static final String ERR_UNSUPPORTED_CMD = "Unsupported command";
private static final String ERR_INVALID_CMD_ARG =
"Invalid command's argument";
private static final String ERR_UNSPECIFIED_INDEX =
"A valid task's index is required";
private static final String ERR_LATE_DEADLINE =
"Deadline has already passed";
private static final String ERR_NON_POSITIVE_DUR =
"Task's duration must be positive";
private static final String STATUS_ADDED = "Task: %s added sucessfully";
private static final String STATUS_DELETED =
"Task: %d deleted sucessfully";
private static final String STATUS_MODIFIED =
"Task: %d modified sucessfully";
private static final Integer MAX_STATUS_LENGTH = 40;
private InputParser parser;
private static String status;
public Logic(GUI gui) {
this.gui = gui;
parser = new InputParser();
/* TODO:
* Initialize Storage
* Initialize and start up passive thread for reminder
*/
}
/******************************
* Code for the active logics *
******************************/
/**
* Execute the command given in the command string
* @param command the command string
*/
public boolean executeCommand(String command) {
Command parsedCommand = parser.parseCommand(command);
if (parser.getErrorStatus() != null) {
// Syntax error
status = parser.getErrorStatus();
gui.displayStatus(status);
}
if (isCommandValid(parsedCommand)) {
switch (parsedCommand.commandName) {
case ADD:
executeAddCommand(parsedCommand);
break;
case MODIFY:
executeModifyCommand(parsedCommand);
break;
case DELETE:
executeDeleteCommand(parsedCommand);
break;
case DISPLAY:
executeDisplayCommand(parsedCommand);
break;
default:
status = ERR_UNSUPPORTED_CMD;
}
gui.displayStatus(status);
return true;
} else {
gui.displayStatus(status);
return false;
}
}
private void executeDisplayCommand(Command parsedCommand) {
// TODO fill in default values
// TODO fill in data structure and call storage apis
status = getDisplaySucessStatus(parsedCommand);
}
private String getDisplaySucessStatus(Command parsedCommand) {
return "";
}
private void executeDeleteCommand(Command parsedCommand) {
// TODO fill in default values
// TODO fill in data structure and call storage apis
status = getDeleteSucessStatus(parsedCommand);
// TODO retrieve and display all tasks
}
private String getDeleteSucessStatus(Command parsedCommand) {
return String.format(STATUS_DELETED, parsedCommand.argIndex);
}
private void executeModifyCommand(Command parsedCommand) {
// TODO fill in default values
// TODO fill in data structure and call storage apis
status = getModifySucessStatus(parsedCommand);
// TODO retrieve and display all tasks
}
private String getModifySucessStatus(Command parsedCommand) {
// TODO Auto-generated method stub
return String.format(STATUS_MODIFIED, parsedCommand.argIndex);
}
private void executeAddCommand(Command parsedCommand) {
Task task = fillAddedTask(parsedCommand);
// Call storage apis
status = getAddSucessStatus(parsedCommand);
// TODO retrieve and display all tasks
}
private Task fillAddedTask(Command parsedCommand) {
Task task = new Task();
task.setTaskType(getTaskType(parsedCommand));
task.setContent(parsedCommand.argStr);
fillDeadline(task, parsedCommand);
fillStartDate(task, parsedCommand);
fillEndDate(task, parsedCommand);
fillDuration(task, parsedCommand);
fillReminder(task, parsedCommand);
fillLabel(task, parsedCommand);
fillPriority(task, parsedCommand);
return task;
}
private void fillPriority(Task task, Command cmd) {
Command.Option priority = getOption(cmd, Config.OPT_PRIO);
if (priority != null) {
task.setPriority(true);
} else {
task.setPriority(false);
}
}
private void fillLabel(Task task, Command cmd) {
Command.Option label = getOption(cmd, Config.OPT_LABEL);
if (label != null) {
task.setLabel(label.strArgument);
}
}
private void fillReminder(Task task, Command cmd) {
Command.Option reminder = getOption(cmd, Config.OPT_START);
if (reminder != null) {
GregorianCalendar reminderCalendar = new GregorianCalendar();
reminderCalendar.setTime(reminder.dateArgument);
task.setReminder(reminderCalendar);
}
}
private void fillDuration(Task task, Command cmd) {
Command.Option duration = getOption(cmd, Config.OPT_DUR);
if (duration != null) {
task.setDuration(duration.timeArgument);
}
}
private void fillEndDate(Task task, Command cmd) {
Command.Option end = getOption(cmd, Config.OPT_START);
if (end != null) {
GregorianCalendar endCalendar = new GregorianCalendar();
endCalendar.setTime(end.dateArgument);
task.setEnd(endCalendar);
}
}
private void fillStartDate(Task task, Command cmd) {
Command.Option start = getOption(cmd, Config.OPT_START);
if (start != null) {
GregorianCalendar startCalendar = new GregorianCalendar();
startCalendar.setTime(start.dateArgument);
task.setStart(startCalendar);
}
}
private void fillDeadline(Task task, Command cmd) {
Command.Option deadline = getOption(cmd, Config.OPT_DEADLINE);
if (deadline != null) {
GregorianCalendar deadlineCalendar = new GregorianCalendar();
deadlineCalendar.setTime(deadline.dateArgument);
task.setDeadline(deadlineCalendar);
}
}
private Command.Option getOption(Command cmd, String[] option) {
return cmd.options.get(option[Config.OPT_LONG]);
}
/**
* Guess and return a task type from a command
* @param task
* @param options
*/
private Task.TaskType getTaskType(Command parsedCommand) {
Map<String, Command.Option> options = parsedCommand.options;
if (options.containsKey(Config.OPT_DEADLINE[Config.OPT_LONG]) ||
options.containsKey(Config.OPT_DEADLINE[Config.OPT_SHORT])) {
return Task.TaskType.DEADLINE;
} else if (options.containsKey(Config.OPT_START[Config.OPT_LONG]) ||
options.containsKey(Config.OPT_START[Config.OPT_SHORT]) ||
options.containsKey(Config.OPT_END[Config.OPT_LONG]) ||
options.containsKey(Config.OPT_END[Config.OPT_SHORT])) {
return Task.TaskType.EVENT;
} else {
return Task.TaskType.TODO;
}
}
private String getAddSucessStatus(Command parsedCommand) {
String taskContent = parsedCommand.argStr;
if (taskContent.length() > MAX_STATUS_LENGTH) {
taskContent = taskContent.substring(0, MAX_STATUS_LENGTH);
taskContent += "...";
}
return String.format(STATUS_ADDED, taskContent);
}
/**
* Check the semantics of a parsed command
* @param parsedCommand
* @return the command's correctness
*/
private boolean isCommandValid(Command parsedCommand) {
if (parsedCommand == null || parsedCommand.commandName == null) {
status = formatErrorStr(ERR_INVALID_CMD_NAME);
return false;
}
Config.CommandName cmdName = parsedCommand.commandName;
switch (cmdName) {
case ADD:
return isAddCmdValid(parsedCommand);
case DELETE:
return isDeleteCmdValid(parsedCommand);
case MODIFY:
return isModifyCmdValid(parsedCommand);
case DISPLAY:
return isDisplayCmdValid(parsedCommand);
default:
status = formatErrorStr(ERR_UNSUPPORTED_CMD);
return false;
}
}
private boolean isDisplayCmdValid(Command parsedCommand) {
return true;
}
private boolean isModifyCmdValid(Command parsedCommand) {
if (parsedCommand.argIndex == null) {
status = ERR_UNSPECIFIED_INDEX;
return false;
}
return true;
}
private boolean isDeleteCmdValid(Command parsedCommand) {
if (parsedCommand.argIndex == null) {
status = ERR_UNSPECIFIED_INDEX;
return false;
}
return true;
}
private boolean isAddCmdValid(Command parsedCommand) {
if (parsedCommand.argStr == null) {
status = ERR_INVALID_CMD_ARG;
return false;
}
return isStartBeforeEnd(parsedCommand) &&
isDurationValid(parsedCommand) &&
isDeadlineValid(parsedCommand);
}
private boolean isDeadlineValid(Command cmd) {
Command.Option deadline = getOption(cmd, Config.OPT_DEADLINE);
if (deadline != null) {
if (deadline.dateArgument.compareTo(new Date()) < 0) {
status = ERR_LATE_DEADLINE;
return false;
}
}
return true;
}
private boolean isDurationValid(Command cmd) {
Command.Option duration = getOption(cmd, Config.OPT_DUR);
if (duration != null) {
if (duration.timeArgument <= 0) {
status = ERR_NON_POSITIVE_DUR;
return false;
}
}
return true;
}
private boolean isStartBeforeEnd(Command cmd) {
Command.Option start = getOption(cmd, Config.OPT_DEADLINE);
Command.Option end = getOption(cmd, Config.OPT_END);
if (start != null && end != null) {
if (start.dateArgument.compareTo(end.dateArgument) >= 0) {
status = ERR_NON_POSITIVE_DUR;
return false;
}
}
return true;
}
private String formatErrorStr(String errorInvalidCmdName) {
return String.format(ERR_FORMAT, errorInvalidCmdName);
}
} | Change return type of executeCommand
| src/udo/logic/Logic.java | Change return type of executeCommand |
|
Java | mit | dc3ba10b0c7ddf478c70d2f3cb11120cc5a43046 | 0 | amymcgovern/spacesettlers,amymcgovern/spacesettlers | package spacesettlers.utilities;
import spacesettlers.simulator.Toroidal2DPhysics;
/**
* Position in space (x,y,orientation)
* @author amy
*
*/
public class Position {
double x, y, orientation, angularVelocity;
Vector2D velocity;
public Position(double x, double y) {
super();
this.x = x;
this.y = y;
velocity = new Vector2D();
}
public Position(double x, double y, double orientation) {
super();
this.x = x;
this.y = y;
this.orientation = orientation;
velocity = new Vector2D();
}
public Position(Vector2D vec) {
super();
this.x = vec.getXValue();
this.y = vec.getYValue();
orientation = 0;
velocity = new Vector2D();
}
public Position deepCopy() {
Position newPosition = new Position(x, y, orientation);
newPosition.velocity = new Vector2D(velocity);
newPosition.angularVelocity = angularVelocity;
return newPosition;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getOrientation() {
return orientation;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public double getTotalTranslationalVelocity() {
return velocity.getTotal();
}
public double getTranslationalVelocityX() {
return velocity.getXValue();
}
public double getTranslationalVelocityY() {
return velocity.getYValue();
}
public Vector2D getTranslationalVelocity() {
return velocity;
}
public void setTranslationalVelocity(Vector2D newVel) {
this.velocity = newVel;
}
public double getAngularVelocity() {
return angularVelocity;
}
public void setOrientation(double orientation) {
this.orientation = orientation;
}
public double getxVelocity() {
return velocity.getXValue();
}
public double getyVelocity() {
return velocity.getYValue();
}
public void setAngularVelocity(double angularVelocity) {
this.angularVelocity = angularVelocity;
}
public String toString() {
String str = "(" + x + " , " + y + ", " + orientation + ") velocity: " + velocity + ", " + angularVelocity;
return str;
}
/**
* Compares positions on location (x,y) only and ignores orientation and velocities
*
* @param newPosition
* @return
*/
public boolean equalsLocationOnly(Position newPosition) {
if (newPosition.getX() == x && newPosition.getY() == y) {
return true;
} else {
return false;
}
}
/**
* Verifies that all components of the position are finite and not NaN
* @return true if the position is valid (finite and a number, doesn't check world size) and false otherwise
*/
public boolean isValid() {
if (Double.isFinite(x) && Double.isFinite(y) &&
Double.isFinite(angularVelocity) && Double.isFinite(orientation) &&
velocity.isValid()) {
return true;
} else {
return false;
}
}
/**
* Compares positions on location (x,y) with comparing distance between two locations and ignores orientation and velocities
* For example, it can be used to check if ship's location matches up with the position passed.
* @param Toroidal2DPhysics object: space
* @param Position object: shipPosition
* @param Position object: currentPosition
* @return true if ship reached certain location or within the allowable difference distance i.e., between 0 and 4.
*/
public boolean equalsLocationOnlyWithDistance(Toroidal2DPhysics space, Position shipPosition, Position currentPosition) {
double differenceDistance = space.findShortestDistance(shipPosition, currentPosition);
if (differenceDistance > 0 && differenceDistance < 4) {
return true;
} else {
return false;
}
}
} | src/spacesettlers/utilities/Position.java | package spacesettlers.utilities;
/**
* Position in space (x,y,orientation)
* @author amy
*
*/
public class Position {
double x, y, orientation, angularVelocity;
Vector2D velocity;
public Position(double x, double y) {
super();
this.x = x;
this.y = y;
velocity = new Vector2D();
}
public Position(double x, double y, double orientation) {
super();
this.x = x;
this.y = y;
this.orientation = orientation;
velocity = new Vector2D();
}
public Position(Vector2D vec) {
super();
this.x = vec.getXValue();
this.y = vec.getYValue();
orientation = 0;
velocity = new Vector2D();
}
public Position deepCopy() {
Position newPosition = new Position(x, y, orientation);
newPosition.velocity = new Vector2D(velocity);
newPosition.angularVelocity = angularVelocity;
return newPosition;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getOrientation() {
return orientation;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public double getTotalTranslationalVelocity() {
return velocity.getTotal();
}
public double getTranslationalVelocityX() {
return velocity.getXValue();
}
public double getTranslationalVelocityY() {
return velocity.getYValue();
}
public Vector2D getTranslationalVelocity() {
return velocity;
}
public void setTranslationalVelocity(Vector2D newVel) {
this.velocity = newVel;
}
public double getAngularVelocity() {
return angularVelocity;
}
public void setOrientation(double orientation) {
this.orientation = orientation;
}
public double getxVelocity() {
return velocity.getXValue();
}
public double getyVelocity() {
return velocity.getYValue();
}
public void setAngularVelocity(double angularVelocity) {
this.angularVelocity = angularVelocity;
}
public String toString() {
String str = "(" + x + " , " + y + ", " + orientation + ") velocity: " + velocity + ", " + angularVelocity;
return str;
}
/**
* Compares positions on location (x,y) only and ignores orientation and velocities
*
* @param newPosition
* @return
*/
public boolean equalsLocationOnly(Position newPosition) {
if (newPosition.getX() == x && newPosition.getY() == y) {
return true;
} else {
return false;
}
}
/**
* Verifies that all components of the position are finite and not NaN
* @return true if the position is valid (finite and a number, doesn't check world size) and false otherwise
*/
public boolean isValid() {
if (Double.isFinite(x) && Double.isFinite(y) &&
Double.isFinite(angularVelocity) && Double.isFinite(orientation) &&
velocity.isValid()) {
return true;
} else {
return false;
}
}
} | Developed new method called: equalsLocationOnlyWithDistance | src/spacesettlers/utilities/Position.java | Developed new method called: equalsLocationOnlyWithDistance |
|
Java | mpl-2.0 | acb0b946142a7876916f186147fc403b71fc3beb | 0 | Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV | package org.helioviewer.gl3d.camera;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.ParseException;
import java.util.Date;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.helioviewer.base.logging.Log;
import org.helioviewer.basegui.components.TimeTextField;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.components.calendar.JHVCalendarDatePicker;
import org.helioviewer.jhv.gui.components.calendar.JHVCalendarEvent;
import org.helioviewer.jhv.gui.components.calendar.JHVCalendarListener;
import org.helioviewer.jhv.layers.LayersModel;
public class GL3DFollowObjectCameraOptionPanel extends GL3DCameraOptionPanel {
private final JLabel beginDateLabel;
private JPanel beginDatetimePanel;
JHVCalendarDatePicker beginDatePicker;
TimeTextField beginTimePicker;
private final JLabel endDateLabel;
private JPanel endDatetimePanel;
JHVCalendarDatePicker endDatePicker;
TimeTextField endTimePicker;
JComboBox objectCombobox;
private final GL3DFollowObjectCamera camera;
public GL3DFollowObjectCameraOptionPanel(GL3DFollowObjectCamera camera) {
this.camera = camera;
setLayout(new GridLayout(0, 1));
addObjectCombobox();
beginDateLabel = new JLabel("Begin date");
beginDatePicker = new JHVCalendarDatePicker();
beginTimePicker = new TimeTextField();
addBeginDatePanel();
endDateLabel = new JLabel("End date");
endDatePicker = new JHVCalendarDatePicker();
endTimePicker = new TimeTextField();
addEndDatePanel();
}
private void addObjectCombobox() {
objectCombobox = new JComboBox();
objectCombobox.addItem("Solar Orbiter");
objectCombobox.addItem("Venus");
objectCombobox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
String object = (String) event.getItem();
if (object != null) {
camera.setObservingObject(object);
revalidate();
}
}
}
});
add(objectCombobox);
}
private void addBeginDatePanel() {
add(beginDateLabel);
beginDatetimePanel = new JPanel();
beginDatetimePanel.setLayout(new GridLayout(0, 2));
beginDatePicker.addJHVCalendarListener(new JHVCalendarListener() {
@Override
public void actionPerformed(JHVCalendarEvent e) {
setBeginTime();
Displayer.getSingletonInstance().render();
}
});
Date startDate = null;
startDate = LayersModel.getSingletonInstance().getFirstDate();
beginDatePicker.setDate(startDate);
if (startDate == null) {
startDate = new Date(System.currentTimeMillis());
}
beginTimePicker.setText(TimeTextField.formatter.format(startDate));
beginTimePicker.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setEndTime();
Displayer.getSingletonInstance().render();
}
});
beginDatetimePanel.add(beginDatePicker);
beginDatetimePanel.add(beginTimePicker);
add(beginDatetimePanel);
}
protected void setEndTime() {
try {
Date dt = TimeTextField.formatter.parse(beginTimePicker.getText());
camera.setBeginDate(new Date(beginDatePicker.getDate().getTime() + dt.getTime()));
System.out.println(new Date(beginDatePicker.getDate().getTime() + dt.getTime()));
} catch (ParseException e) {
Log.error("Date parsing failed" + e);
}
}
protected void setBeginTime() {
try {
Date dt = TimeTextField.formatter.parse(beginTimePicker.getText());
camera.setBeginDate(new Date(beginDatePicker.getDate().getTime() + dt.getTime()));
System.out.println(new Date(beginDatePicker.getDate().getTime() + dt.getTime()));
} catch (ParseException e) {
Log.error("Date parsing failed" + e);
}
}
private void addEndDatePanel() {
add(endDateLabel);
endDatetimePanel = new JPanel();
endDatetimePanel.setLayout(new GridLayout(0, 2));
endDatePicker.addJHVCalendarListener(new JHVCalendarListener() {
@Override
public void actionPerformed(JHVCalendarEvent e) {
try {
Date dt = TimeTextField.formatter.parse(endTimePicker.getText());
camera.setEndDate(new Date(endDatePicker.getDate().getTime() + dt.getTime()));
} catch (ParseException e1) {
Log.error("Date parsing failed", e1);
}
Displayer.getSingletonInstance().render();
}
});
Date startDate = null;
startDate = LayersModel.getSingletonInstance().getLastDate();
endDatePicker.setDate(startDate);
if (startDate == null) {
startDate = new Date(System.currentTimeMillis());
}
endTimePicker.setText(TimeTextField.formatter.format(startDate));
endTimePicker.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Date dt = TimeTextField.formatter.parse(endTimePicker.getText());
camera.setBeginDate(new Date(endDatePicker.getDate().getTime() + dt.getTime()));
} catch (ParseException e1) {
Log.error("Date parsing failed", e1);
}
Displayer.getSingletonInstance().render();
}
});
endDatetimePanel.add(endDatePicker);
endDatetimePanel.add(endTimePicker);
add(endDatetimePanel);
}
}
| src/jhv/src/org/helioviewer/gl3d/camera/GL3DFollowObjectCameraOptionPanel.java | package org.helioviewer.gl3d.camera;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.ParseException;
import java.util.Date;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.helioviewer.base.logging.Log;
import org.helioviewer.basegui.components.TimeTextField;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.components.calendar.JHVCalendarDatePicker;
import org.helioviewer.jhv.gui.components.calendar.JHVCalendarEvent;
import org.helioviewer.jhv.gui.components.calendar.JHVCalendarListener;
import org.helioviewer.jhv.layers.LayersModel;
public class GL3DFollowObjectCameraOptionPanel extends GL3DCameraOptionPanel {
private final JLabel beginDateLabel;
private JPanel beginDatetimePanel;
JHVCalendarDatePicker beginDatePicker;
TimeTextField beginTimePicker;
private final JLabel endDateLabel;
private JPanel endDatetimePanel;
JHVCalendarDatePicker endDatePicker;
TimeTextField endTimePicker;
JComboBox objectCombobox;
private final GL3DFollowObjectCamera camera;
public GL3DFollowObjectCameraOptionPanel(GL3DFollowObjectCamera camera) {
this.camera = camera;
setLayout(new GridLayout(0, 1));
addObjectCombobox();
beginDateLabel = new JLabel("Begin date");
addBeginDatePanel(beginDateLabel, beginDatetimePanel, beginDatePicker, beginTimePicker);
endDateLabel = new JLabel("End date");
addEndDatePanel(endDateLabel, endDatetimePanel, endDatePicker, endTimePicker);
}
private void addObjectCombobox() {
objectCombobox = new JComboBox();
objectCombobox.addItem("Solar Orbiter");
objectCombobox.addItem("Venus");
objectCombobox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
String object = (String) event.getItem();
if (object != null) {
camera.setObservingObject(object);
revalidate();
}
}
}
});
add(objectCombobox);
}
private void addBeginDatePanel(JLabel dateLabel, JPanel datetimePanel, final JHVCalendarDatePicker datePicker, final TimeTextField timePicker) {
add(dateLabel);
datetimePanel = new JPanel();
datetimePanel.setLayout(new GridLayout(0, 2));
datePicker.addJHVCalendarListener(new JHVCalendarListener() {
@Override
public void actionPerformed(JHVCalendarEvent e) {
try {
Date dt = TimeTextField.formatter.parse(timePicker.getText());
camera.setBeginDate(new Date(datePicker.getDate().getTime() + dt.getTime()));
} catch (ParseException e1) {
Log.error("Date parsing failed", e1);
}
Displayer.getSingletonInstance().render();
}
});
Date startDate = null;
startDate = LayersModel.getSingletonInstance().getFirstDate();
datePicker.setDate(startDate);
if (startDate == null) {
startDate = new Date(System.currentTimeMillis());
}
timePicker.setText(TimeTextField.formatter.format(startDate));
timePicker.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Date dt = TimeTextField.formatter.parse(timePicker.getText());
camera.setBeginDate(new Date(datePicker.getDate().getTime() + dt.getTime()));
} catch (ParseException e1) {
Log.error("Date parsing failed", e1);
}
Displayer.getSingletonInstance().render();
}
});
datetimePanel.add(datePicker);
datetimePanel.add(timePicker);
add(datetimePanel);
}
private void addEndDatePanel(JLabel dateLabel, JPanel datetimePanel, final JHVCalendarDatePicker datePicker, final TimeTextField timePicker) {
add(dateLabel);
datetimePanel = new JPanel();
datetimePanel.setLayout(new GridLayout(0, 2));
datePicker.addJHVCalendarListener(new JHVCalendarListener() {
@Override
public void actionPerformed(JHVCalendarEvent e) {
try {
Date dt = TimeTextField.formatter.parse(timePicker.getText());
camera.setEndDate(new Date(datePicker.getDate().getTime() + dt.getTime()));
} catch (ParseException e1) {
Log.error("Date parsing failed", e1);
}
Displayer.getSingletonInstance().render();
}
});
Date startDate = null;
startDate = LayersModel.getSingletonInstance().getLastDate();
datePicker.setDate(startDate);
if (startDate == null) {
startDate = new Date(System.currentTimeMillis());
}
timePicker.setText(TimeTextField.formatter.format(startDate));
timePicker.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Date dt = TimeTextField.formatter.parse(timePicker.getText());
camera.setBeginDate(new Date(datePicker.getDate().getTime() + dt.getTime()));
} catch (ParseException e1) {
Log.error("Date parsing failed", e1);
}
Displayer.getSingletonInstance().render();
}
});
datetimePanel.add(datePicker);
datetimePanel.add(timePicker);
add(datetimePanel);
}
}
| Create separate functions to set time
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@1513 b4e469a2-07ce-4b26-9273-4d7d95a670c7
| src/jhv/src/org/helioviewer/gl3d/camera/GL3DFollowObjectCameraOptionPanel.java | Create separate functions to set time |
|
Java | lgpl-2.1 | 05a4cbe31390c647729620797c957fbdcf67a009 | 0 | open-eid/digidoc4j,keijokapp/digidoc4j,open-eid/digidoc4j,open-eid/digidoc4j,keijokapp/digidoc4j | /* DigiDoc4J library
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*/
package org.digidoc4j.impl.bdoc;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.util.List;
import org.apache.xml.security.signature.Reference;
import org.digidoc4j.Container;
import org.digidoc4j.ContainerBuilder;
import org.digidoc4j.Signature;
import org.digidoc4j.testutils.TestDataBuilder;
import org.digidoc4j.utils.AbstractSigningTests;
import org.digidoc4j.utils.CertificatesForTests;
import org.junit.Test;
/**
* This test is testing a "hack" feature that will probably be rolled back later.
*/
public class UriEncodingTest extends AbstractSigningTests {
@Test
public void signatureReferencesUseUriEncodingButManifestUsesPlainUtf8() throws InterruptedException {
Signature signature = sign();
List<Reference> referencesInSignature = ((BDocSignature)signature).getOrigin().getReferences();
assertEquals("dds_J%C3%9CRI%C3%96%C3%96%20%E2%82%AC%20%C5%BE%C5%A0%20p%C3%A4ev.txt", referencesInSignature.get(0).getURI());
// TODO: Also write an assertion to verify that the manifest file does NOT use URI encoding
}
protected Signature sign() {
Container container = ContainerBuilder.
aContainer().
withConfiguration(createDigiDoc4JConfiguration()).
withDataFile(new ByteArrayInputStream("file contents".getBytes()), "dds_JÜRIÖÖ € žŠ päev.txt", "application/octet-stream").
build();
Signature signature = TestDataBuilder.signContainer(container);
return signature;
}
}
| test/org/digidoc4j/impl/bdoc/UriEncodingTest.java | /* DigiDoc4J library
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*/
package org.digidoc4j.impl.bdoc;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.util.List;
import org.apache.xml.security.signature.Reference;
import org.digidoc4j.Container;
import org.digidoc4j.ContainerBuilder;
import org.digidoc4j.utils.AbstractSigningTests;
import org.digidoc4j.utils.CertificatesForTests;
import org.junit.Test;
/**
* This test is testing a "hack" feature that will probably be rolled back later.
*/
public class UriEncodingTest extends AbstractSigningTests {
@Test
public void signatureReferencesUseUriEncodingButManifestUsesPlainUtf8() throws InterruptedException {
Container container = sign();
List<Reference> referencesInSignature = ((BDocSignature)container.getSignature(0)).getOrigin().getReferences();
assertEquals("dds_J%C3%9CRI%C3%96%C3%96%20%E2%82%AC%20%C5%BE%C5%A0%20p%C3%A4ev.txt", referencesInSignature.get(0).getURI());
// TODO: Also write an assertion to verify that the manifest file does NOT use URI encoding
}
protected Container sign() {
Container container = ContainerBuilder.
aContainer().
withConfiguration(createDigiDoc4JConfiguration()).
withDataFile(new ByteArrayInputStream("file contents".getBytes()), "dds_JÜRIÖÖ € žŠ päev.txt", "application/octet-stream").
build();
byte[] hashToSign = prepareSigning(container, CertificatesForTests.SIGN_CERT, createSignatureParameters());
byte[] signatureValue = signWithRsa(CertificatesForTests.PRIVATE_KEY_FOR_SIGN_CERT, hashToSign);
container.signRaw(signatureValue);
return container;
}
}
| Fixed uri encoding test
| test/org/digidoc4j/impl/bdoc/UriEncodingTest.java | Fixed uri encoding test |
|
Java | apache-2.0 | 08c8071a18a84a371a1f686cf9a09c4089fcdb70 | 0 | mp911de/atsoundtrack,mp911de/atsoundtrack | package biz.paluch.atsoundtrack;
import static com.intellij.openapi.util.text.StringUtil.*;
import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiDocCommentBase;
import com.intellij.psi.xml.XmlComment;
import com.intellij.psi.xml.XmlToken;
/**
* @author <a href="mailto:[email protected]">Mark Paluch</a>
* @since 13.05.15 11:49
*/
public class AtSoundtrackContributor extends CompletionContributor {
@Override
public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {
String prefix = parameters.getOriginalPosition().getText();
if (!prefix.contains("soundtrack")) {
if (!isEmpty(AtSoundtrack.getName())) {
boolean qualified = false;
if (parameters.getOriginalPosition() instanceof PsiComment
|| parameters.getOriginalPosition().getContext() instanceof PsiDocCommentBase
|| parameters.getOriginalPosition().getClass().getName().contains("PsiDocToken")) {
qualified = true;
}
if (parameters.getOriginalPosition() instanceof XmlToken) {
XmlToken xmlToken = (XmlToken) parameters.getOriginalPosition();
if (xmlToken instanceof XmlComment || xmlToken.getContext() instanceof XmlComment) {
qualified = true;
}
}
if (qualified) {
if (!prefix.contains("@")) {
result.addElement(LookupElementBuilder.create("@soundtrack " + AtSoundtrack.getName()));
} else {
result.addElement(LookupElementBuilder.create("soundtrack " + AtSoundtrack.getName()));
}
}
}
}
super.fillCompletionVariants(parameters, result);
}
}
| src/biz/paluch/atsoundtrack/AtSoundtrackContributor.java | package biz.paluch.atsoundtrack;
import org.jetbrains.annotations.NotNull;
import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElement;
/**
* @author <a href="mailto:[email protected]">Mark Paluch</a>
* @since 13.05.15 11:49
*/
public class AtSoundtrackContributor extends CompletionContributor {
@Override
public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {
if (AtSoundtrack.getName() != null) {
result.addElement(new LookupElement() {
@NotNull
@Override
public String getLookupString() {
return "@soundtrack " + AtSoundtrack.getName();
}
});
}
super.fillCompletionVariants(parameters, result);
}
}
| Use code completion in multiple places and compatibility with PyCharm, RubyMine, PhpStorm
| src/biz/paluch/atsoundtrack/AtSoundtrackContributor.java | Use code completion in multiple places and compatibility with PyCharm, RubyMine, PhpStorm |
|
Java | apache-2.0 | cb68a4de94eea55bfcf7cce2569d454006e00757 | 0 | subclipse/svnclientadapter | /*******************************************************************************
* Copyright (c) 2003, 2006 svnClientAdapter project and others.
*
* 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.
*
* Contributors:
* svnClientAdapter project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.svnclientadapter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* High level API for Subversion
*
*/
public interface ISVNClientAdapter {
/** constant identifying the "bdb" repository type */
public final static String REPOSITORY_FSTYPE_BDB = "bdb";
/** constant identifying the "fsfs" repository type */
public final static String REPOSITORY_FSTYPE_FSFS = "fsfs";
/**
* Add a notification listener
* @param listener
*/
public abstract void addNotifyListener(ISVNNotifyListener listener);
/**
* Remove a notification listener
* @param listener
*/
public abstract void removeNotifyListener(ISVNNotifyListener listener);
/**
* @return the notification handler
*/
public abstract SVNNotificationHandler getNotificationHandler();
/**
* Sets the username.
* @param username
*/
public abstract void setUsername(String username);
/**
* Sets the password.
* @param password
*/
public abstract void setPassword(String password);
/**
* Add a callback for prompting for username, password SSL etc...
* @param callback
*/
public abstract void addPasswordCallback(ISVNPromptUserPassword callback);
/**
* Add a callback for resolving conflicts during up/sw/merge
* @param callback
*/
public abstract void addConflictResolutionCallback(ISVNConflictResolver callback);
/**
* Set a progress listener
* @param progressListener
*/
public abstract void setProgressListener(ISVNProgressListener progressListener);
/**
* Adds a file (or directory) to the repository.
* @param file
* @throws SVNClientException
*/
public abstract void addFile(File file) throws SVNClientException;
/**
* Adds a directory to the repository.
* @param dir
* @param recurse
* @throws SVNClientException
*/
public abstract void addDirectory(File dir, boolean recurse)
throws SVNClientException;
/**
* Adds a directory to the repository.
* @param dir
* @param recurse
* @param force
* @throws SVNClientException
*/
public abstract void addDirectory(File dir, boolean recurse, boolean force)
throws SVNClientException;
/**
* Executes a revision checkout.
* @param moduleName name of the module to checkout.
* @param destPath destination directory for checkout.
* @param revision the revision number to checkout. If the number is -1
* then it will checkout the latest revision.
* @param recurse whether you want it to checkout files recursively.
* @exception SVNClientException
*/
public abstract void checkout(
SVNUrl moduleName,
File destPath,
SVNRevision revision,
boolean recurse)
throws SVNClientException;
/**
* Executes a revision checkout.
* @param moduleName name of the module to checkout.
* @param destPath destination directory for checkout.
* @param revision the revision number to checkout. If the number is -1
* then it will checkout the latest revision.
* @param depth how deep to checkout files recursively.
* @param ignoreExternals if externals are ignored during checkout.
* @param force allow unversioned paths that obstruct adds.
* @exception SVNClientException
*/
public abstract void checkout(
SVNUrl moduleName,
File destPath,
SVNRevision revision,
int depth,
boolean ignoreExternals,
boolean force)
throws SVNClientException;
/**
* Commits changes to the repository. This usually requires
* authentication, see Auth.
* @return Returns a long representing the revision. It returns a
* -1 if the revision number is invalid.
* @param paths files to commit.
* @param message log message.
* @param recurse whether the operation should be done recursively.
* @exception SVNClientException
*/
public abstract long commit(File[] paths, String message, boolean recurse)
throws SVNClientException;
/**
* Commits changes to the repository. This usually requires
* authentication, see Auth.
* @return Returns a long representing the revision. It returns a
* -1 if the revision number is invalid.
* @param paths files to commit.
* @param message log message.
* @param recurse whether the operation should be done recursively.
* @param keepLocks
* @exception SVNClientException
*/
public abstract long commit(File[] paths, String message, boolean recurse, boolean keepLocks)
throws SVNClientException;
/**
* Commits changes to the repository. This usually requires
* authentication, see Auth.
*
* This differs from the normal commit method in that it can accept paths from
* more than one working copy.
*
* @return Returns an array of longs representing the revisions. It returns a
* -1 if the revision number is invalid.
* @param paths files to commit.
* @param message log message.
* @param recurse whether the operation should be done recursively.
* @param keepLocks whether to keep locks on files that are committed.
* @param atomic whether to attempt to perform the commit from multiple
* working copies atomically. Files from the same repository will be
* processed with one commit operation. If files span multiple repositories
* they will be processed in multiple commits.
* When atomic is false, you will get one commit per WC.
* @exception SVNClientException
*/
public abstract long[] commitAcrossWC(File[] paths, String message, boolean recurse, boolean keepLocks, boolean atomic)
throws SVNClientException;
/**
* List directory entries of a URL
* @param url
* @param revision
* @param recurse
* @return an array of ISVNDirEntries
* @throws SVNClientException
*/
public abstract ISVNDirEntry[] getList(
SVNUrl url,
SVNRevision revision,
boolean recurse)
throws SVNClientException;
/**
* List directory entries of a URL
* @param url
* @param revision
* @param pegRevision
* @param recurse
* @return an array of ISVNDirEntries
* @throws SVNClientException
*/
public abstract ISVNDirEntry[] getList(
SVNUrl url,
SVNRevision revision,
SVNRevision pegRevision,
boolean recurse)
throws SVNClientException;
/**
* List directory entries of a directory
* @param path
* @param revision
* @param recurse
* @return an array of ISVNDirEntries
* @throws SVNClientException
*/
public ISVNDirEntry[] getList(File path, SVNRevision revision, boolean recurse)
throws SVNClientException;
/**
* List directory entries of a directory
* @param path
* @param revision
* @param pegRevision
* @param recurse
* @return an array of ISVNDirEntries
* @throws SVNClientException
*/
public ISVNDirEntry[] getList(File path, SVNRevision revision, SVNRevision pegRevision, boolean recurse)
throws SVNClientException;
/**
* get the dirEntry for the given url
* @param url
* @param revision
* @return an ISVNDirEntry
* @throws SVNClientException
*/
public ISVNDirEntry getDirEntry(SVNUrl url, SVNRevision revision)
throws SVNClientException;
/**
* get the dirEntry for the given directory
* @param path
* @param revision
* @return an ISVNDirEntry
* @throws SVNClientException
*/
public ISVNDirEntry getDirEntry(File path, SVNRevision revision)
throws SVNClientException;
/**
* Returns the status of a single file in the path.
*
* @param path File to gather status.
* @return a Status
* @throws SVNClientException
*/
public abstract ISVNStatus getSingleStatus(File path)
throws SVNClientException;
/**
* Returns the status of given resources
* @param path
* @return the status of given resources
* @throws SVNClientException
*/
public abstract ISVNStatus[] getStatus(File[] path)
throws SVNClientException;
/**
* Returns the status of path and its children.
* If descend is true, recurse fully, else do only immediate children.
* If getAll is set, retrieve all entries; otherwise, retrieve only
* "interesting" entries (local mods and/or out-of-date).
*
* @param path File to gather status.
* @param descend get recursive status information
* @param getAll get status information for all files
* @return a Status
* @throws SVNClientException
*/
public abstract ISVNStatus[] getStatus(File path, boolean descend, boolean getAll)
throws SVNClientException;
/**
* Returns the status of path and its children.
* If descend is true, recurse fully, else do only immediate children.
* If getAll is set, retrieve all entries; otherwise, retrieve only
* "interesting" entries (local mods and/or out-of-date). Use the
* contactServer option to get server change information.
*
* @param path File to gather status.
* @param descend get recursive status information
* @param getAll get status information for all files
* @param contactServer contact server to get remote changes
* @return a Status
* @throws SVNClientException
*/
public abstract ISVNStatus[] getStatus(File path, boolean descend, boolean getAll, boolean contactServer)
throws SVNClientException;
/**
* Returns the status of path and its children.
* If descend is true, recurse fully, else do only immediate children.
* If getAll is set, retrieve all entries; otherwise, retrieve only
* "interesting" entries (local mods and/or out-of-date). Use the
* contactServer option to get server change information.
*
* @param path File to gather status.
* @param descend get recursive status information
* @param getAll get status information for all files
* @param contactServer contact server to get remote changes
* @param ignoreExternals if externals are ignored during status
* @return a Status
* @throws SVNClientException
*/
public abstract ISVNStatus[] getStatus(File path, boolean descend, boolean getAll, boolean contactServer, boolean ignoreExternals)
throws SVNClientException;
/**
* copy and schedule for addition (with history)
* @param srcPath
* @param destPath
* @throws SVNClientException
*/
public abstract void copy(File srcPath, File destPath)
throws SVNClientException;
/**
* immediately commit a copy of WC to URL
* @param srcPath
* @param destUrl
* @param message
* @throws SVNClientException
*/
public abstract void copy(File srcPath, SVNUrl destUrl, String message)
throws SVNClientException;
/**
* check out URL into WC, schedule for addition
* @param srcUrl
* @param destPath
* @param revision
* @throws SVNClientException
*/
public abstract void copy(SVNUrl srcUrl, File destPath, SVNRevision revision)
throws SVNClientException;
/**
* complete server-side copy; used to branch & tag
* @param srcUrl
* @param destUrl
* @param message
* @param revision
* @throws SVNClientException
*/
public abstract void copy(
SVNUrl srcUrl,
SVNUrl destUrl,
String message,
SVNRevision revision)
throws SVNClientException;
/**
* item is deleted from the repository via an immediate commit.
* @param url
* @param message
* @throws SVNClientException
*/
public abstract void remove(SVNUrl url[], String message)
throws SVNClientException;
/**
* the item is scheduled for deletion upon the next commit.
* Files, and directories that have not been committed, are immediately
* removed from the working copy. The command will not remove TARGETs
* that are, or contain, unversioned or modified items;
* use the force option to override this behaviour.
* @param file
* @param force
* @throws SVNClientException
*/
public abstract void remove(File file[], boolean force)
throws SVNClientException;
/**
* Exports a clean directory tree from the repository specified by
* srcUrl, at revision revision
* @param srcUrl
* @param destPath
* @param revision
* @param force
* @throws SVNClientException
*/
public abstract void doExport(
SVNUrl srcUrl,
File destPath,
SVNRevision revision,
boolean force)
throws SVNClientException;
/**
* Exports a clean directory tree from the working copy specified by
* PATH1 into PATH2. all local changes will be preserved, but files
* not under revision control will not be copied.
* @param srcPath
* @param destPath
* @param force
* @throws SVNClientException
*/
public abstract void doExport(File srcPath, File destPath, boolean force)
throws SVNClientException;
/**
* Import file or directory PATH into repository directory URL at head
* @param path
* @param url
* @param message
* @param recurse
* @throws SVNClientException
*/
public abstract void doImport(
File path,
SVNUrl url,
String message,
boolean recurse)
throws SVNClientException;
/**
* Creates a directory directly in a repository
* @param url
* @param message
* @throws SVNClientException
*/
public abstract void mkdir(SVNUrl url, String message)
throws SVNClientException;
/**
* Creates a directory directly in a repository
* @param url
* @param makeParents
* @param message
* @throws SVNClientException
*/
public abstract void mkdir(SVNUrl url, boolean makeParents, String message)
throws SVNClientException;
/**
* creates a directory on disk and schedules it for addition.
* @param file
* @throws SVNClientException
*/
public abstract void mkdir(File file) throws SVNClientException;
/**
* Moves or renames a file.
* @param srcPath
* @param destPath
* @param force
* @throws SVNClientException
*/
public abstract void move(File srcPath, File destPath, boolean force)
throws SVNClientException;
/**
* Moves or renames a file.
* @param srcUrl
* @param destUrl
* @param message
* @param revision
* @throws SVNClientException
*/
public abstract void move(
SVNUrl srcUrl,
SVNUrl destUrl,
String message,
SVNRevision revision)
throws SVNClientException;
/**
* Update a file or a directory
* @param path
* @param revision
* @param recurse
* @return Returns a long representing the revision. It returns a
* -1 if the revision number is invalid.
* @throws SVNClientException
*/
public abstract long update(File path, SVNRevision revision, boolean recurse)
throws SVNClientException;
/**
* Update a file or a directory
* @param path
* @param revision
* @param depth
* @param ignoreExternals
* @param force
* @return Returns a long representing the revision. It returns a
* -1 if the revision number is invalid.
* @throws SVNClientException
*/
public abstract long update(File path, SVNRevision revision, int depth, boolean ignoreExternals, boolean force)
throws SVNClientException;
/**
* Updates the directories or files from repository
* @param path array of target files.
* @param revision the revision number to update.
* @param recurse recursively update.
* @param ignoreExternals if externals are ignored during update
* @return Returns an array of longs representing the revision. It returns a
* -1 if the revision number is invalid.
* @throws SVNClientException
* @since 1.2
*/
public abstract long[] update(
File[] path,
SVNRevision revision,
boolean recurse,
boolean ignoreExternals)
throws SVNClientException;
/**
* Updates the directories or files from repository
* @param path array of target files.
* @param revision the revision number to update.
* @param depth the depth to recursively update.
* @param ignoreExternals if externals are ignored during update.
* @param force allow unversioned paths that obstruct adds.
* @return Returns an array of longs representing the revision. It returns a
* -1 if the revision number is invalid.
* @throws SVNClientException
*/
public abstract long[] update(
File[] path,
SVNRevision revision,
int depth,
boolean ignoreExternals,
boolean force)
throws SVNClientException;
/**
* Restore pristine working copy file (undo all local edits)
* @param path
* @param recurse
* @throws SVNClientException
*/
public abstract void revert(File path, boolean recurse)
throws SVNClientException;
/**
* Get the log messages for a set of revision(s)
* @param url
* @param revisionStart
* @param revisionEnd
* @return The list of log messages.
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
SVNUrl url,
SVNRevision revisionStart,
SVNRevision revisionEnd)
throws SVNClientException;
/**
* Get the log messages for a set of revision(s)
* @param url
* @param revisionStart
* @param revisionEnd
* @param fetchChangePath Whether or not to interogate the
* repository for the verbose log information containing the list
* of paths touched by the delta specified by
* <code>revisionStart</code> and <code>revisionEnd</code>.
* Setting this to <code>false</code> results in a more performant
* and memory efficient operation.
* @return The list of log messages.
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
SVNUrl url,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean fetchChangePath)
throws SVNClientException;
/**
* Get the log messages for a set paths and revision(s)
* @param url
* @param paths
* @param revStart
* @param revEnd
* @param stopOnCopy
* @param fetchChangePath
* @return The list of log messages.
* @throws SVNClientException
*/
public ISVNLogMessage[] getLogMessages(final SVNUrl url, final String [] paths,
SVNRevision revStart, SVNRevision revEnd,
boolean stopOnCopy, boolean fetchChangePath)
throws SVNClientException;
/**
* Get the log messages for a set of revision(s)
* @param path
* @param revisionStart
* @param revisionEnd
* @return The list of log messages.
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision revisionStart,
SVNRevision revisionEnd)
throws SVNClientException;
/**
* Get the log messages for a set of revision(s)
* @param path
* @param revisionStart
* @param revisionEnd
* @param fetchChangePath Whether or not to interogate the
* repository for the verbose log information containing the list
* of paths touched by the delta specified by
* <code>revisionStart</code> and <code>revisionEnd</code>.
* Setting this to <code>false</code> results in a more performant
* and memory efficient operation.
* @return The list of log messages.
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean fetchChangePath)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param path path or url to get the log message for.
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param path path to get the log message for.
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @param limit limit the number of log messages (if 0 or less no
* limit)
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath,
long limit)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param path path to get the log message for.
* @param pegRevision peg revision for URL
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @param limit limit the number of log messages (if 0 or less no
* limit)
* @param includeMergedRevisions include revisions that were merged
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision pegRevision,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath,
long limit,
boolean includeMergedRevisions)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param url url to get the log message for.
* @param pegRevision peg revision for URL
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @param limit limit the number of log messages (if 0 or less no
* limit)
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
SVNUrl url,
SVNRevision pegRevision,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath,
long limit)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param url url to get the log message for.
* @param pegRevision peg revision for URL
* @param range range of revisions to retrieve
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessagesForRevisions(
SVNUrl url,
SVNRevision pegRevision,
SVNRevisionRange[] range,
boolean fetchChangePath, boolean includeMergedRevisions)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param url url to get the log message for.
* @param pegRevision peg revision for URL
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @param limit limit the number of log messages (if 0 or less no
* limit)
* @param includeMergedRevisions include revisions that were merged
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
SVNUrl url,
SVNRevision pegRevision,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath,
long limit,
boolean includeMergedRevisions)
throws SVNClientException;
/**
* get the content of a file
* @param url
* @param revision
* @return the input stream with a content of the file
* @throws SVNClientException
*/
public abstract InputStream getContent(SVNUrl url, SVNRevision revision)
throws SVNClientException;
/**
* get the content of a file
* @param path
* @param revision
* @return the input stream with a content of the file
* @throws SVNClientException
*/
public InputStream getContent(File path, SVNRevision revision)
throws SVNClientException;
/**
* set a property
* @param path
* @param propertyName
* @param propertyValue
* @param recurse
* @throws SVNClientException
*/
public abstract void propertySet(
File path,
String propertyName,
String propertyValue,
boolean recurse)
throws SVNClientException;
/**
* set a property using the content of a file
* @param path
* @param propertyName
* @param propertyFile
* @param recurse
* @throws SVNClientException
* @throws IOException
*/
public abstract void propertySet(
File path,
String propertyName,
File propertyFile,
boolean recurse)
throws SVNClientException, IOException;
/**
* get a property or null if property is not found
* @param path
* @param propertyName
* @return a property or null
* @throws SVNClientException
*/
public abstract ISVNProperty propertyGet(File path, String propertyName)
throws SVNClientException;
/**
* get a property or null if property is not found
* @param url
* @param propertyName
* @return a property or null
* @throws SVNClientException
*/
public abstract ISVNProperty propertyGet(SVNUrl url, String propertyName)
throws SVNClientException;
/**
* get a property or null if property is not found
* @param url
* @param revision
* @param peg
* @param propertyName
* @return a property or null
* @throws SVNClientException
*/
public abstract ISVNProperty propertyGet(SVNUrl url, SVNRevision revision,
SVNRevision peg, String propertyName)
throws SVNClientException;
/**
* delete a property
* @param path
* @param propertyName
* @param recurse
* @throws SVNClientException
*/
public abstract void propertyDel(
File path,
String propertyName,
boolean recurse)
throws SVNClientException;
/**
* set the revision property for a given revision
* @param path
* @param revisionNo
* @param propName
* @param propertyData
* @param force
* @throws SVNClientException
*/
public abstract void setRevProperty(SVNUrl path,
SVNRevision.Number revisionNo, String propName,
String propertyData, boolean force) throws SVNClientException;
/**
* get the ignored patterns for the given directory
* if path is not a directory, returns null
* @param path
* @return list of ignored patterns
* @throws SVNClientException
*/
public abstract List getIgnoredPatterns(File path)
throws SVNClientException;
/**
* add a pattern to svn:ignore property
* @param path
* @param pattern
* @throws SVNClientException
*/
public abstract void addToIgnoredPatterns(File path, String pattern)
throws SVNClientException;
/**
* set the ignored patterns for the given directory
* @param path
* @param patterns
* @throws SVNClientException
*/
public abstract void setIgnoredPatterns(File path, List patterns)
throws SVNClientException;
/**
* display the differences between two paths.
* @param oldPath
* @param oldPathRevision
* @param newPath
* @param newPathRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
File oldPath,
SVNRevision oldPathRevision,
File newPath,
SVNRevision newPathRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between two paths.
* @param oldPath
* @param oldPathRevision
* @param newPath
* @param newPathRevision
* @param outFile
* @param recurse
* @param ignoreAncestry
* @param noDiffDeleted
* @param force
* @throws SVNClientException
*/
public abstract void diff(
File oldPath,
SVNRevision oldPathRevision,
File newPath,
SVNRevision newPathRevision,
File outFile,
boolean recurse,
boolean ignoreAncestry,
boolean noDiffDeleted,
boolean force)
throws SVNClientException;
/**
* display the differences between two paths.
* @param path
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
File path,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the combined differences for an array of paths.
* @param paths
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
File[] paths,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* create a patch from local differences.
* @param paths
* @param relativeToPath - create patch relative to this location
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void createPatch(
File[] paths,
File relativeToPath,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between two urls.
* @param oldUrl
* @param oldUrlRevision
* @param newUrl
* @param newUrlRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl oldUrl,
SVNRevision oldUrlRevision,
SVNUrl newUrl,
SVNRevision newUrlRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between two urls.
* @param oldUrl
* @param oldUrlRevision
* @param newUrl
* @param newUrlRevision
* @param outFile
* @param recurse
* @param ignoreAncestry
* @param noDiffDeleted
* @param force
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl oldUrl,
SVNRevision oldUrlRevision,
SVNUrl newUrl,
SVNRevision newUrlRevision,
File outFile,
boolean recurse,
boolean ignoreAncestry,
boolean noDiffDeleted,
boolean force)
throws SVNClientException;
/**
* Display the differences between two paths.
* @param target
* @param pegRevision
* @param startRevision
* @param endRevision
* @param outFile
* @param depth
* @param ignoreAncestry
* @param noDiffDeleted
* @param force
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl target,
SVNRevision pegRevision,
SVNRevision startRevision,
SVNRevision endRevision,
File outFile,
int depth,
boolean ignoreAncestry,
boolean noDiffDeleted,
boolean force)
throws SVNClientException;
/**
* Display the differences between two paths.
* @param target
* @param pegRevision
* @param startRevision
* @param endRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl target,
SVNRevision pegRevision,
SVNRevision startRevision,
SVNRevision endRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between two urls.
* @param url
* @param oldUrlRevision
* @param newUrlRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl url,
SVNRevision oldUrlRevision,
SVNRevision newUrlRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between WC and url.
* @param path
* @param url
* @param urlRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
File path,
SVNUrl url,
SVNRevision urlRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* returns the keywords used for substitution for the given resource
* @param path
* @return the keywords used for substitution
* @throws SVNClientException
*/
public abstract SVNKeywords getKeywords(File path) throws SVNClientException;
/**
* set the keywords substitution for the given resource
* @param path
* @param keywords
* @param recurse
* @throws SVNClientException
*/
public abstract void setKeywords(File path, SVNKeywords keywords, boolean recurse) throws SVNClientException;
/**
* add some keyword to the keywords substitution list
* @param path
* @param keywords
* @return keywords valid after this method call
* @throws SVNClientException
*/
public abstract SVNKeywords addKeywords(File path, SVNKeywords keywords) throws SVNClientException;
/**
* remove some keywords to the keywords substitution list
* @param path
* @param keywords
* @return keywords valid after this method call
* @throws SVNClientException
*/
public SVNKeywords removeKeywords(File path, SVNKeywords keywords) throws SVNClientException;
/**
* Output the content of specified url with revision and
* author information in-line.
* @param url
* @param revisionStart
* @param revisionEnd
* @return annotations for the given url
* @throws SVNClientException
*/
public ISVNAnnotations annotate(SVNUrl url, SVNRevision revisionStart, SVNRevision revisionEnd)
throws SVNClientException;
/**
* Output the content of specified file with revision and
* author information in-line.
* @param file
* @param revisionStart
* @param revisionEnd
* @return annotations for the given file
* @throws SVNClientException
*/
public ISVNAnnotations annotate(File file, SVNRevision revisionStart, SVNRevision revisionEnd)
throws SVNClientException;
/**
* Output the content of specified url with revision and
* author information in-line.
* @param url
* @param revisionStart
* @param revisionEnd
* @param ignoreMimeType
* @param includeMergedRevisons
* @return annotations for the given url
* @throws SVNClientException
*/
public ISVNAnnotations annotate(SVNUrl url, SVNRevision revisionStart, SVNRevision revisionEnd,
boolean ignoreMimeType, boolean includeMergedRevisions)
throws SVNClientException;
/**
* Output the content of specified file with revision and
* author information in-line.
* @param file
* @param revisionStart
* @param revisionEnd
* @param ignoreMimeType
* @param includeMergedRevisons
* @return annotations for the given file
* @throws SVNClientException
*/
public ISVNAnnotations annotate(File file, SVNRevision revisionStart, SVNRevision revisionEnd,
boolean ignoreMimeType, boolean includeMergedRevisions)
throws SVNClientException;
/**
* Get all the properties for the given file or dir
* @param path
* @return the properties for the given url
* @throws SVNClientException
*/
public abstract ISVNProperty[] getProperties(File path) throws SVNClientException;
/**
* Get all the properties for the given url
* @param url
* @return the properties for the given url
* @throws SVNClientException
*/
public abstract ISVNProperty[] getProperties(SVNUrl url) throws SVNClientException;
/**
* Remove 'conflicted' state on working copy files or directories
* @param path
* @throws SVNClientException
*/
public abstract void resolved(File path) throws SVNClientException;
/**
* Remove 'conflicted' state on working copy files or directories
* @param path
* @param result - choose resolve option - {@link ISVNConflictResolver.Choice}
* @throws SVNClientException
*/
public abstract void resolved(File path, int result) throws SVNClientException;
/**
* Create a new, empty repository at path
*
* @param path
* @param repositoryType either {@link ISVNClientAdapter#REPOSITORY_FSTYPE_BDB} or
* {@link ISVNClientAdapter#REPOSITORY_FSTYPE_FSFS} or null (will use svnadmin default)
* @throws SVNClientException
*/
public abstract void createRepository(File path, String repositoryType) throws SVNClientException;
/**
* Cancel the current operation
*
* @throws SVNClientException
*/
public void cancelOperation() throws SVNClientException;
/**
* Get information about a file or directory from working copy.
* Uses info() call which does NOT contact the repository
* @param file
* @return information about a file or directory from working copy.
* @throws SVNClientException
*/
public ISVNInfo getInfoFromWorkingCopy(File file) throws SVNClientException;
/**
* Get information about a file or directory.
* Uses info2() call which contacts the repository
* @param file
* @return information about a file or directory.
* @throws SVNClientException
*/
public ISVNInfo getInfo(File file) throws SVNClientException;
/**
* Get information about an URL.
* Uses info2() call which contacts the repository
* @param url
* @return information about an URL.
* @throws SVNClientException
*/
public ISVNInfo getInfo(SVNUrl url) throws SVNClientException;
/**
* Get information about an URL.
* Uses info2() call which contacts the repository
* @param url
* @param revision
* @param peg
* @return information about an URL.
* @throws SVNClientException
*/
public ISVNInfo getInfo(SVNUrl url, SVNRevision revision, SVNRevision peg) throws SVNClientException;
/**
* Update the working copy to mirror a new URL within the repository.
* This behaviour is similar to 'svn update', and is the way to
* move a working copy to a branch or tag within the same repository.
* @param url
* @param path
* @param revision
* @param recurse
* @throws SVNClientException
*/
public void switchToUrl(File path, SVNUrl url, SVNRevision revision, boolean recurse) throws SVNClientException;
/**
* Update the working copy to mirror a new URL within the repository.
* This behaviour is similar to 'svn update', and is the way to
* move a working copy to a branch or tag within the same repository.
* @param url
* @param path
* @param revision
* @param depth
* @param ignoreExternals
* @param force
* @throws SVNClientException
*/
public void switchToUrl(File path, SVNUrl url, SVNRevision revision, int depth, boolean ignoreExternals, boolean force) throws SVNClientException;
/**
* Update the working copy to mirror a new URL within the repository.
* This behaviour is similar to 'svn update', and is the way to
* move a working copy to a branch or tag within the same repository.
* @param url
* @param path
* @param revision
* @param pegRevision
* @param depth
* @param ignoreExternals
* @param force
* @throws SVNClientException
*/
public void switchToUrl(File path, SVNUrl url, SVNRevision revision, SVNRevision pegRevision, int depth, boolean ignoreExternals, boolean force) throws SVNClientException;
/**
* Set the configuration directory.
* @param dir
* @throws SVNClientException
*/
public void setConfigDirectory(File dir) throws SVNClientException;
/**
* Perform a clanup on the working copy. This will remove any stale transactions
* @param dir
* @throws SVNClientException
*/
public abstract void cleanup(File dir) throws SVNClientException;
/**
* Merge changes from two paths into a new local path.
* @param path1 first path or url
* @param revision1 first revision
* @param path2 second path or url
* @param revision2 second revision
* @param localPath target local path
* @param force overwrite local changes
* @param recurse traverse into subdirectories
* @exception SVNClientException
*/
public abstract void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
boolean recurse) throws SVNClientException;
/**
* Merge changes from two paths into a new local path.
* @param path1 first path or url
* @param revision1 first revision
* @param path2 second path or url
* @param revision2 second revision
* @param localPath target local path
* @param force overwrite local changes
* @param recurse traverse into subdirectories
* @param dryRun do not update working copy
* @exception SVNClientException
*/
public abstract void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
boolean recurse, boolean dryRun) throws SVNClientException;
/**
* Merge changes from two paths into a new local path.
* @param path1 first path or url
* @param revision1 first revision
* @param path2 second path or url
* @param revision2 second revision
* @param localPath target local path
* @param force overwrite local changes
* @param recurse traverse into subdirectories
* @param dryRun do not update working copy
* @param ignoreAncestry ignore ancestry when calculating merges
* @exception SVNClientException
*/
public abstract void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
boolean recurse, boolean dryRun, boolean ignoreAncestry) throws SVNClientException;
/**
* Merge changes from two paths into a new local path.
* @param path1 first path or url
* @param revision1 first revision
* @param path2 second path or url
* @param revision2 second revision
* @param localPath target local path
* @param force overwrite local changes
* @param int depth
* @param dryRun do not update working copy
* @param ignoreAncestry ignore ancestry when calculating merges
* @exception SVNClientException
*/
public abstract void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
int depth, boolean dryRun, boolean ignoreAncestry) throws SVNClientException;
/**
* Lock a working copy item
* @param paths path of the items to lock
* @param comment
* @param force break an existing lock
* @throws SVNClientException
*/
public abstract void lock(SVNUrl[] paths, String comment, boolean force)
throws SVNClientException;
/**
* Unlock a working copy item
* @param paths path of the items to unlock
* @param force break an existing lock
* @throws SVNClientException
*/
public abstract void unlock(SVNUrl[] paths, boolean force)
throws SVNClientException;
/**
* Lock a working copy item
* @param paths path of the items to lock
* @param comment
* @param force break an existing lock
* @throws SVNClientException
*/
public abstract void lock(File[] paths, String comment, boolean force)
throws SVNClientException;
/**
* Unlock a working copy item
* @param paths path of the items to unlock
* @param force break an existing lock
* @throws SVNClientException
*/
public abstract void unlock(File[] paths, boolean force)
throws SVNClientException;
/**
* Indicates whether a status call that contacts the
* server includes the remote info in the status object
* @return true when the client adapter implementation delivers remote info within status
*/
public abstract boolean statusReturnsRemoteInfo();
/**
* Indicates whether the commitAcrossWC method is
* supported in the adapter
* @return true when the client adapter implementation supports commitAcrossWC
*/
public abstract boolean canCommitAcrossWC();
/**
* Returns the name of the Subversion administrative
* working copy directory. Typically will be ".svn".
* @return the name of the Subversion administrative wc dir
*/
public abstract String getAdminDirectoryName();
/**
* Returns whether the passed folder name is a Subversion
* administrative working copy directory. Will always return
* true if ".svn" is passed. Otherwise, will be based on the
* Subversion runtime
* @param name
* @return true whether the folder is a Subversion administrative dir
*/
public abstract boolean isAdminDirectory(String name);
/**
* Rewrite the url's in the working copy
* @param from old url
* @param to new url
* @param path working copy path
* @param recurse recurse into subdirectories
* @throws SVNClientException
*/
public abstract void relocate(String from, String to, String path, boolean recurse)
throws SVNClientException;
/**
* Merge set of revisions into a new local path.
* @param url url
* @param pegRevision revision to interpret path
* @param revisions revisions to merge (must be in the form N-1:M)
* @param localPath target local path
* @param force overwrite local changes
* @param depth how deep to traverse into subdirectories
* @param ignoreAncestry ignore if files are not related
* @param dryRun do not change anything
* @throws SVNClientException
*/
public abstract void merge(SVNUrl url, SVNRevision pegRevision, SVNRevisionRange[] revisions,
File localPath, boolean force, int depth,
boolean ignoreAncestry, boolean dryRun) throws SVNClientException;
/**
* Get merge info for <code>path</code> at <code>revision</code>.
* @param path Local Path.
* @param revision SVNRevision at which to get the merge info for
* <code>path</code>.
* @throws SVNClientException
*/
public abstract ISVNMergeInfo getMergeInfo(File path, SVNRevision revision)
throws SVNClientException;
/**
* Get merge info for <code>url</code> at <code>revision</code>.
* @param url URL.
* @param revision SVNRevision at which to get the merge info for
* <code>path</code>.
* @throws SVNClientException
*/
public abstract ISVNMergeInfo getMergeInfo(SVNUrl url, SVNRevision revision)
throws SVNClientException;
/**
* Produce a diff summary which lists the items changed between
* path and revision pairs.
*
* @param target1 URL.
* @param revision1 Revision of <code>target1</code>.
* @param target2 URL.
* @param revision2 Revision of <code>target2</code>.
* @param depth how deep to recurse.
* @param ignoreAncestry Whether to ignore unrelated files during
* comparison. False positives may potentially be reported if
* this parameter <code>false</code>, since a file might have been
* modified between two revisions, but still have the same
* contents.
* @return the list of differences
*
* @throws SVNClientException
*/
public abstract SVNDiffSummary[] diffSummarize(SVNUrl target1, SVNRevision revision1,
SVNUrl target2, SVNRevision revision2,
int depth, boolean ignoreAncestry)
throws SVNClientException;
/**
* Produce a diff summary which lists the items changed between
* path and revision pairs.
*
* @param target URL.
* @param pegRevision Revision at which to interpret
* <code>target</code>. If {@link RevisionKind#unspecified} or
* <code>null</code>, behave identically to {@link
* diffSummarize(String, Revision, String, Revision, boolean,
* boolean, DiffSummaryReceiver)}, using <code>path</code> for
* both of that method's targets.
* @param startRevision Beginning of range for comparsion of
* <code>target</code>.
* @param endRevision End of range for comparsion of
* <code>target</code>.
* @param depth how deep to recurse.
* @param ignoreAncestry Whether to ignore unrelated files during
* comparison. False positives may potentially be reported if
* this parameter <code>false</code>, since a file might have been
* modified between two revisions, but still have the same
* contents.
* @return the list of differences
*
* @throws SVNClientException
*/
public abstract SVNDiffSummary[] diffSummarize(SVNUrl target, SVNRevision pegRevision,
SVNRevision startRevision, SVNRevision endRevision,
int depth, boolean ignoreAncestry)
throws SVNClientException;
/**
* Return an ordered list of suggested merge source URLs.
* @param path The merge target path for which to suggest sources.
* @return The list of URLs, empty if there are no suggestions.
* @throws SVNClientException If an error occurs.
*/
public abstract String[] suggestMergeSources(File path)
throws SVNClientException;
/**
* Return an ordered list of suggested merge source URLs.
* @param url The merge target path for which to suggest sources.
* @param peg The peg revision for the URL
* @return The list of URLs, empty if there are no suggestions.
* @throws SVNClientException If an error occurs.
*/
public abstract String[] suggestMergeSources(SVNUrl url, SVNRevision peg)
throws SVNClientException;
/**
* Get merge info for <code>path</code> at <code>pegRevision</code>.
* @param path WC path
* @param pegRevision Revision at which to get the merge info for
* <code>path</code>.
* @param mergeSource The merge source for which the list of
* revisions is available.
* @return The list of revisions available for merge from
* <code>mergeSource</code>, or <code>null</code> if all eligible
* revisions have been merged.
* @throws SVNClientException
*/
public abstract SVNRevisionRange[] getAvailableMerges(File path, SVNRevision pegRevision,
SVNUrl mergeSource)
throws SVNClientException;
/**
* Get merge info for <code>url</code> at <code>pegRevision</code>.
* @param url URL
* @param pegRevision Revision at which to get the merge info for
* <code>path</code>.
* @param mergeSource The merge source for which the list of
* revisions is available.
* @return The list of revisions available for merge from
* <code>mergeSource</code>, or <code>null</code> if all eligible
* revisions have been merged.
* @throws SVNClientException
*/
public abstract SVNRevisionRange[] getAvailableMerges(SVNUrl url, SVNRevision pegRevision,
SVNUrl mergeSource)
throws SVNClientException;
}
| src/main/org/tigris/subversion/svnclientadapter/ISVNClientAdapter.java | /*******************************************************************************
* Copyright (c) 2003, 2006 svnClientAdapter project and others.
*
* 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.
*
* Contributors:
* svnClientAdapter project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.svnclientadapter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* High level API for Subversion
*
*/
public interface ISVNClientAdapter {
/** constant identifying the "bdb" repository type */
public final static String REPOSITORY_FSTYPE_BDB = "bdb";
/** constant identifying the "fsfs" repository type */
public final static String REPOSITORY_FSTYPE_FSFS = "fsfs";
/**
* Add a notification listener
* @param listener
*/
public abstract void addNotifyListener(ISVNNotifyListener listener);
/**
* Remove a notification listener
* @param listener
*/
public abstract void removeNotifyListener(ISVNNotifyListener listener);
/**
* @return the notification handler
*/
public abstract SVNNotificationHandler getNotificationHandler();
/**
* Sets the username.
* @param username
*/
public abstract void setUsername(String username);
/**
* Sets the password.
* @param password
*/
public abstract void setPassword(String password);
/**
* Add a callback for prompting for username, password SSL etc...
* @param callback
*/
public abstract void addPasswordCallback(ISVNPromptUserPassword callback);
/**
* Add a callback for resolving conflicts during up/sw/merge
* @param callback
*/
public abstract void addConflictResolutionCallback(ISVNConflictResolver callback);
/**
* Set a progress listener
* @param progressListener
*/
public abstract void setProgressListener(ISVNProgressListener progressListener);
/**
* Adds a file (or directory) to the repository.
* @param file
* @throws SVNClientException
*/
public abstract void addFile(File file) throws SVNClientException;
/**
* Adds a directory to the repository.
* @param dir
* @param recurse
* @throws SVNClientException
*/
public abstract void addDirectory(File dir, boolean recurse)
throws SVNClientException;
/**
* Adds a directory to the repository.
* @param dir
* @param recurse
* @param force
* @throws SVNClientException
*/
public abstract void addDirectory(File dir, boolean recurse, boolean force)
throws SVNClientException;
/**
* Executes a revision checkout.
* @param moduleName name of the module to checkout.
* @param destPath destination directory for checkout.
* @param revision the revision number to checkout. If the number is -1
* then it will checkout the latest revision.
* @param recurse whether you want it to checkout files recursively.
* @exception SVNClientException
*/
public abstract void checkout(
SVNUrl moduleName,
File destPath,
SVNRevision revision,
boolean recurse)
throws SVNClientException;
/**
* Executes a revision checkout.
* @param moduleName name of the module to checkout.
* @param destPath destination directory for checkout.
* @param revision the revision number to checkout. If the number is -1
* then it will checkout the latest revision.
* @param depth how deep to checkout files recursively.
* @param ignoreExternals if externals are ignored during checkout.
* @param force allow unversioned paths that obstruct adds.
* @exception SVNClientException
*/
public abstract void checkout(
SVNUrl moduleName,
File destPath,
SVNRevision revision,
int depth,
boolean ignoreExternals,
boolean force)
throws SVNClientException;
/**
* Commits changes to the repository. This usually requires
* authentication, see Auth.
* @return Returns a long representing the revision. It returns a
* -1 if the revision number is invalid.
* @param paths files to commit.
* @param message log message.
* @param recurse whether the operation should be done recursively.
* @exception SVNClientException
*/
public abstract long commit(File[] paths, String message, boolean recurse)
throws SVNClientException;
/**
* Commits changes to the repository. This usually requires
* authentication, see Auth.
* @return Returns a long representing the revision. It returns a
* -1 if the revision number is invalid.
* @param paths files to commit.
* @param message log message.
* @param recurse whether the operation should be done recursively.
* @param keepLocks
* @exception SVNClientException
*/
public abstract long commit(File[] paths, String message, boolean recurse, boolean keepLocks)
throws SVNClientException;
/**
* Commits changes to the repository. This usually requires
* authentication, see Auth.
*
* This differs from the normal commit method in that it can accept paths from
* more than one working copy.
*
* @return Returns an array of longs representing the revisions. It returns a
* -1 if the revision number is invalid.
* @param paths files to commit.
* @param message log message.
* @param recurse whether the operation should be done recursively.
* @param keepLocks whether to keep locks on files that are committed.
* @param atomic whether to attempt to perform the commit from multiple
* working copies atomically. Files from the same repository will be
* processed with one commit operation. If files span multiple repositories
* they will be processed in multiple commits.
* When atomic is false, you will get one commit per WC.
* @exception SVNClientException
*/
public abstract long[] commitAcrossWC(File[] paths, String message, boolean recurse, boolean keepLocks, boolean atomic)
throws SVNClientException;
/**
* List directory entries of a URL
* @param url
* @param revision
* @param recurse
* @return an array of ISVNDirEntries
* @throws SVNClientException
*/
public abstract ISVNDirEntry[] getList(
SVNUrl url,
SVNRevision revision,
boolean recurse)
throws SVNClientException;
/**
* List directory entries of a URL
* @param url
* @param revision
* @param pegRevision
* @param recurse
* @return an array of ISVNDirEntries
* @throws SVNClientException
*/
public abstract ISVNDirEntry[] getList(
SVNUrl url,
SVNRevision revision,
SVNRevision pegRevision,
boolean recurse)
throws SVNClientException;
/**
* List directory entries of a directory
* @param path
* @param revision
* @param recurse
* @return an array of ISVNDirEntries
* @throws SVNClientException
*/
public ISVNDirEntry[] getList(File path, SVNRevision revision, boolean recurse)
throws SVNClientException;
/**
* List directory entries of a directory
* @param path
* @param revision
* @param pegRevision
* @param recurse
* @return an array of ISVNDirEntries
* @throws SVNClientException
*/
public ISVNDirEntry[] getList(File path, SVNRevision revision, SVNRevision pegRevision, boolean recurse)
throws SVNClientException;
/**
* get the dirEntry for the given url
* @param url
* @param revision
* @return an ISVNDirEntry
* @throws SVNClientException
*/
public ISVNDirEntry getDirEntry(SVNUrl url, SVNRevision revision)
throws SVNClientException;
/**
* get the dirEntry for the given directory
* @param path
* @param revision
* @return an ISVNDirEntry
* @throws SVNClientException
*/
public ISVNDirEntry getDirEntry(File path, SVNRevision revision)
throws SVNClientException;
/**
* Returns the status of a single file in the path.
*
* @param path File to gather status.
* @return a Status
* @throws SVNClientException
*/
public abstract ISVNStatus getSingleStatus(File path)
throws SVNClientException;
/**
* Returns the status of given resources
* @param path
* @return the status of given resources
* @throws SVNClientException
*/
public abstract ISVNStatus[] getStatus(File[] path)
throws SVNClientException;
/**
* Returns the status of path and its children.
* If descend is true, recurse fully, else do only immediate children.
* If getAll is set, retrieve all entries; otherwise, retrieve only
* "interesting" entries (local mods and/or out-of-date).
*
* @param path File to gather status.
* @param descend get recursive status information
* @param getAll get status information for all files
* @return a Status
* @throws SVNClientException
*/
public abstract ISVNStatus[] getStatus(File path, boolean descend, boolean getAll)
throws SVNClientException;
/**
* Returns the status of path and its children.
* If descend is true, recurse fully, else do only immediate children.
* If getAll is set, retrieve all entries; otherwise, retrieve only
* "interesting" entries (local mods and/or out-of-date). Use the
* contactServer option to get server change information.
*
* @param path File to gather status.
* @param descend get recursive status information
* @param getAll get status information for all files
* @param contactServer contact server to get remote changes
* @return a Status
* @throws SVNClientException
*/
public abstract ISVNStatus[] getStatus(File path, boolean descend, boolean getAll, boolean contactServer)
throws SVNClientException;
/**
* Returns the status of path and its children.
* If descend is true, recurse fully, else do only immediate children.
* If getAll is set, retrieve all entries; otherwise, retrieve only
* "interesting" entries (local mods and/or out-of-date). Use the
* contactServer option to get server change information.
*
* @param path File to gather status.
* @param descend get recursive status information
* @param getAll get status information for all files
* @param contactServer contact server to get remote changes
* @param ignoreExternals if externals are ignored during status
* @return a Status
* @throws SVNClientException
*/
public abstract ISVNStatus[] getStatus(File path, boolean descend, boolean getAll, boolean contactServer, boolean ignoreExternals)
throws SVNClientException;
/**
* copy and schedule for addition (with history)
* @param srcPath
* @param destPath
* @throws SVNClientException
*/
public abstract void copy(File srcPath, File destPath)
throws SVNClientException;
/**
* immediately commit a copy of WC to URL
* @param srcPath
* @param destUrl
* @param message
* @throws SVNClientException
*/
public abstract void copy(File srcPath, SVNUrl destUrl, String message)
throws SVNClientException;
/**
* check out URL into WC, schedule for addition
* @param srcUrl
* @param destPath
* @param revision
* @throws SVNClientException
*/
public abstract void copy(SVNUrl srcUrl, File destPath, SVNRevision revision)
throws SVNClientException;
/**
* complete server-side copy; used to branch & tag
* @param srcUrl
* @param destUrl
* @param message
* @param revision
* @throws SVNClientException
*/
public abstract void copy(
SVNUrl srcUrl,
SVNUrl destUrl,
String message,
SVNRevision revision)
throws SVNClientException;
/**
* item is deleted from the repository via an immediate commit.
* @param url
* @param message
* @throws SVNClientException
*/
public abstract void remove(SVNUrl url[], String message)
throws SVNClientException;
/**
* the item is scheduled for deletion upon the next commit.
* Files, and directories that have not been committed, are immediately
* removed from the working copy. The command will not remove TARGETs
* that are, or contain, unversioned or modified items;
* use the force option to override this behaviour.
* @param file
* @param force
* @throws SVNClientException
*/
public abstract void remove(File file[], boolean force)
throws SVNClientException;
/**
* Exports a clean directory tree from the repository specified by
* srcUrl, at revision revision
* @param srcUrl
* @param destPath
* @param revision
* @param force
* @throws SVNClientException
*/
public abstract void doExport(
SVNUrl srcUrl,
File destPath,
SVNRevision revision,
boolean force)
throws SVNClientException;
/**
* Exports a clean directory tree from the working copy specified by
* PATH1 into PATH2. all local changes will be preserved, but files
* not under revision control will not be copied.
* @param srcPath
* @param destPath
* @param force
* @throws SVNClientException
*/
public abstract void doExport(File srcPath, File destPath, boolean force)
throws SVNClientException;
/**
* Import file or directory PATH into repository directory URL at head
* @param path
* @param url
* @param message
* @param recurse
* @throws SVNClientException
*/
public abstract void doImport(
File path,
SVNUrl url,
String message,
boolean recurse)
throws SVNClientException;
/**
* Creates a directory directly in a repository
* @param url
* @param message
* @throws SVNClientException
*/
public abstract void mkdir(SVNUrl url, String message)
throws SVNClientException;
/**
* Creates a directory directly in a repository
* @param url
* @param makeParents
* @param message
* @throws SVNClientException
*/
public abstract void mkdir(SVNUrl url, boolean makeParents, String message)
throws SVNClientException;
/**
* creates a directory on disk and schedules it for addition.
* @param file
* @throws SVNClientException
*/
public abstract void mkdir(File file) throws SVNClientException;
/**
* Moves or renames a file.
* @param srcPath
* @param destPath
* @param force
* @throws SVNClientException
*/
public abstract void move(File srcPath, File destPath, boolean force)
throws SVNClientException;
/**
* Moves or renames a file.
* @param srcUrl
* @param destUrl
* @param message
* @param revision
* @throws SVNClientException
*/
public abstract void move(
SVNUrl srcUrl,
SVNUrl destUrl,
String message,
SVNRevision revision)
throws SVNClientException;
/**
* Update a file or a directory
* @param path
* @param revision
* @param recurse
* @return Returns a long representing the revision. It returns a
* -1 if the revision number is invalid.
* @throws SVNClientException
*/
public abstract long update(File path, SVNRevision revision, boolean recurse)
throws SVNClientException;
/**
* Update a file or a directory
* @param path
* @param revision
* @param depth
* @param ignoreExternals
* @param force
* @return Returns a long representing the revision. It returns a
* -1 if the revision number is invalid.
* @throws SVNClientException
*/
public abstract long update(File path, SVNRevision revision, int depth, boolean ignoreExternals, boolean force)
throws SVNClientException;
/**
* Updates the directories or files from repository
* @param path array of target files.
* @param revision the revision number to update.
* @param recurse recursively update.
* @param ignoreExternals if externals are ignored during update
* @return Returns an array of longs representing the revision. It returns a
* -1 if the revision number is invalid.
* @throws SVNClientException
* @since 1.2
*/
public abstract long[] update(
File[] path,
SVNRevision revision,
boolean recurse,
boolean ignoreExternals)
throws SVNClientException;
/**
* Updates the directories or files from repository
* @param path array of target files.
* @param revision the revision number to update.
* @param depth the depth to recursively update.
* @param ignoreExternals if externals are ignored during update.
* @param force allow unversioned paths that obstruct adds.
* @return Returns an array of longs representing the revision. It returns a
* -1 if the revision number is invalid.
* @throws SVNClientException
*/
public abstract long[] update(
File[] path,
SVNRevision revision,
int depth,
boolean ignoreExternals,
boolean force)
throws SVNClientException;
/**
* Restore pristine working copy file (undo all local edits)
* @param path
* @param recurse
* @throws SVNClientException
*/
public abstract void revert(File path, boolean recurse)
throws SVNClientException;
/**
* Get the log messages for a set of revision(s)
* @param url
* @param revisionStart
* @param revisionEnd
* @return The list of log messages.
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
SVNUrl url,
SVNRevision revisionStart,
SVNRevision revisionEnd)
throws SVNClientException;
/**
* Get the log messages for a set of revision(s)
* @param url
* @param revisionStart
* @param revisionEnd
* @param fetchChangePath Whether or not to interogate the
* repository for the verbose log information containing the list
* of paths touched by the delta specified by
* <code>revisionStart</code> and <code>revisionEnd</code>.
* Setting this to <code>false</code> results in a more performant
* and memory efficient operation.
* @return The list of log messages.
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
SVNUrl url,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean fetchChangePath)
throws SVNClientException;
/**
* Get the log messages for a set paths and revision(s)
* @param url
* @param paths
* @param revStart
* @param revEnd
* @param stopOnCopy
* @param fetchChangePath
* @return The list of log messages.
* @throws SVNClientException
*/
public ISVNLogMessage[] getLogMessages(final SVNUrl url, final String [] paths,
SVNRevision revStart, SVNRevision revEnd,
boolean stopOnCopy, boolean fetchChangePath)
throws SVNClientException;
/**
* Get the log messages for a set of revision(s)
* @param path
* @param revisionStart
* @param revisionEnd
* @return The list of log messages.
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision revisionStart,
SVNRevision revisionEnd)
throws SVNClientException;
/**
* Get the log messages for a set of revision(s)
* @param path
* @param revisionStart
* @param revisionEnd
* @param fetchChangePath Whether or not to interogate the
* repository for the verbose log information containing the list
* of paths touched by the delta specified by
* <code>revisionStart</code> and <code>revisionEnd</code>.
* Setting this to <code>false</code> results in a more performant
* and memory efficient operation.
* @return The list of log messages.
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean fetchChangePath)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param path path or url to get the log message for.
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param path path to get the log message for.
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @param limit limit the number of log messages (if 0 or less no
* limit)
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath,
long limit)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param path path to get the log message for.
* @param pegRevision peg revision for URL
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @param limit limit the number of log messages (if 0 or less no
* limit)
* @param includeMergedRevisions include revisions that were merged
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
File path,
SVNRevision pegRevision,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath,
long limit,
boolean includeMergedRevisions)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param url url to get the log message for.
* @param pegRevision peg revision for URL
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @param limit limit the number of log messages (if 0 or less no
* limit)
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
SVNUrl url,
SVNRevision pegRevision,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath,
long limit)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param url url to get the log message for.
* @param pegRevision peg revision for URL
* @param range range of revisions to retrieve
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessagesForRevisions(
SVNUrl url,
SVNRevision pegRevision,
SVNRevisionRange[] range,
boolean fetchChangePath, boolean includeMergedRevisions)
throws SVNClientException;
/**
* Retrieve the log messages for an item
* @param url url to get the log message for.
* @param pegRevision peg revision for URL
* @param revisionStart first revision to show
* @param revisionEnd last revision to show
* @param stopOnCopy do not continue on copy operations
* @param fetchChangePath returns the paths of the changed items in the
* returned objects
* @param limit limit the number of log messages (if 0 or less no
* limit)
* @param includeMergedRevisions include revisions that were merged
* @return array of LogMessages
* @throws SVNClientException
*/
public abstract ISVNLogMessage[] getLogMessages(
SVNUrl url,
SVNRevision pegRevision,
SVNRevision revisionStart,
SVNRevision revisionEnd,
boolean stopOnCopy,
boolean fetchChangePath,
long limit,
boolean includeMergedRevisions)
throws SVNClientException;
/**
* get the content of a file
* @param url
* @param revision
* @return the input stream with a content of the file
* @throws SVNClientException
*/
public abstract InputStream getContent(SVNUrl url, SVNRevision revision)
throws SVNClientException;
/**
* get the content of a file
* @param path
* @param revision
* @return the input stream with a content of the file
* @throws SVNClientException
*/
public InputStream getContent(File path, SVNRevision revision)
throws SVNClientException;
/**
* set a property
* @param path
* @param propertyName
* @param propertyValue
* @param recurse
* @throws SVNClientException
*/
public abstract void propertySet(
File path,
String propertyName,
String propertyValue,
boolean recurse)
throws SVNClientException;
/**
* set a property using the content of a file
* @param path
* @param propertyName
* @param propertyFile
* @param recurse
* @throws SVNClientException
* @throws IOException
*/
public abstract void propertySet(
File path,
String propertyName,
File propertyFile,
boolean recurse)
throws SVNClientException, IOException;
/**
* get a property or null if property is not found
* @param path
* @param propertyName
* @return a property or null
* @throws SVNClientException
*/
public abstract ISVNProperty propertyGet(File path, String propertyName)
throws SVNClientException;
/**
* get a property or null if property is not found
* @param url
* @param propertyName
* @return a property or null
* @throws SVNClientException
*/
public abstract ISVNProperty propertyGet(SVNUrl url, String propertyName)
throws SVNClientException;
/**
* get a property or null if property is not found
* @param url
* @param revision
* @param peg
* @param propertyName
* @return a property or null
* @throws SVNClientException
*/
public abstract ISVNProperty propertyGet(SVNUrl url, SVNRevision revision,
SVNRevision peg, String propertyName)
throws SVNClientException;
/**
* delete a property
* @param path
* @param propertyName
* @param recurse
* @throws SVNClientException
*/
public abstract void propertyDel(
File path,
String propertyName,
boolean recurse)
throws SVNClientException;
/**
* set the revision property for a given revision
* @param path
* @param revisionNo
* @param propName
* @param propertyData
* @param force
* @throws SVNClientException
*/
public abstract void setRevProperty(SVNUrl path,
SVNRevision.Number revisionNo, String propName,
String propertyData, boolean force) throws SVNClientException;
/**
* get the ignored patterns for the given directory
* if path is not a directory, returns null
* @param path
* @return list of ignored patterns
* @throws SVNClientException
*/
public abstract List getIgnoredPatterns(File path)
throws SVNClientException;
/**
* add a pattern to svn:ignore property
* @param path
* @param pattern
* @throws SVNClientException
*/
public abstract void addToIgnoredPatterns(File path, String pattern)
throws SVNClientException;
/**
* set the ignored patterns for the given directory
* @param path
* @param patterns
* @throws SVNClientException
*/
public abstract void setIgnoredPatterns(File path, List patterns)
throws SVNClientException;
/**
* display the differences between two paths.
* @param oldPath
* @param oldPathRevision
* @param newPath
* @param newPathRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
File oldPath,
SVNRevision oldPathRevision,
File newPath,
SVNRevision newPathRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between two paths.
* @param oldPath
* @param oldPathRevision
* @param newPath
* @param newPathRevision
* @param outFile
* @param recurse
* @param ignoreAncestry
* @param noDiffDeleted
* @param force
* @throws SVNClientException
*/
public abstract void diff(
File oldPath,
SVNRevision oldPathRevision,
File newPath,
SVNRevision newPathRevision,
File outFile,
boolean recurse,
boolean ignoreAncestry,
boolean noDiffDeleted,
boolean force)
throws SVNClientException;
/**
* display the differences between two paths.
* @param path
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
File path,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the combined differences for an array of paths.
* @param paths
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
File[] paths,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* create a patch from local differences.
* @param paths
* @param relativeToPath - create patch relative to this location
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void createPatch(
File[] paths,
File relativeToPath,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between two urls.
* @param oldUrl
* @param oldUrlRevision
* @param newUrl
* @param newUrlRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl oldUrl,
SVNRevision oldUrlRevision,
SVNUrl newUrl,
SVNRevision newUrlRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between two urls.
* @param oldUrl
* @param oldUrlRevision
* @param newUrl
* @param newUrlRevision
* @param outFile
* @param recurse
* @param ignoreAncestry
* @param noDiffDeleted
* @param force
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl oldUrl,
SVNRevision oldUrlRevision,
SVNUrl newUrl,
SVNRevision newUrlRevision,
File outFile,
boolean recurse,
boolean ignoreAncestry,
boolean noDiffDeleted,
boolean force)
throws SVNClientException;
/**
* Display the differences between two paths.
* @param target
* @param pegRevision
* @param startRevision
* @param endRevision
* @param outFile
* @param depth
* @param ignoreAncestry
* @param noDiffDeleted
* @param force
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl target,
SVNRevision pegRevision,
SVNRevision startRevision,
SVNRevision endRevision,
File outFile,
int depth,
boolean ignoreAncestry,
boolean noDiffDeleted,
boolean force)
throws SVNClientException;
/**
* Display the differences between two paths.
* @param target
* @param pegRevision
* @param startRevision
* @param endRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl target,
SVNRevision pegRevision,
SVNRevision startRevision,
SVNRevision endRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between two urls.
* @param url
* @param oldUrlRevision
* @param newUrlRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
SVNUrl url,
SVNRevision oldUrlRevision,
SVNRevision newUrlRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* display the differences between WC and url.
* @param path
* @param url
* @param urlRevision
* @param outFile
* @param recurse
* @throws SVNClientException
*/
public abstract void diff(
File path,
SVNUrl url,
SVNRevision urlRevision,
File outFile,
boolean recurse)
throws SVNClientException;
/**
* returns the keywords used for substitution for the given resource
* @param path
* @return the keywords used for substitution
* @throws SVNClientException
*/
public abstract SVNKeywords getKeywords(File path) throws SVNClientException;
/**
* set the keywords substitution for the given resource
* @param path
* @param keywords
* @param recurse
* @throws SVNClientException
*/
public abstract void setKeywords(File path, SVNKeywords keywords, boolean recurse) throws SVNClientException;
/**
* add some keyword to the keywords substitution list
* @param path
* @param keywords
* @return keywords valid after this method call
* @throws SVNClientException
*/
public abstract SVNKeywords addKeywords(File path, SVNKeywords keywords) throws SVNClientException;
/**
* remove some keywords to the keywords substitution list
* @param path
* @param keywords
* @return keywords valid after this method call
* @throws SVNClientException
*/
public SVNKeywords removeKeywords(File path, SVNKeywords keywords) throws SVNClientException;
/**
* Output the content of specified url with revision and
* author information in-line.
* @param url
* @param revisionStart
* @param revisionEnd
* @return annotations for the given url
* @throws SVNClientException
*/
public ISVNAnnotations annotate(SVNUrl url, SVNRevision revisionStart, SVNRevision revisionEnd)
throws SVNClientException;
/**
* Output the content of specified file with revision and
* author information in-line.
* @param file
* @param revisionStart
* @param revisionEnd
* @return annotations for the given file
* @throws SVNClientException
*/
public ISVNAnnotations annotate(File file, SVNRevision revisionStart, SVNRevision revisionEnd)
throws SVNClientException;
/**
* Output the content of specified url with revision and
* author information in-line.
* @param url
* @param revisionStart
* @param revisionEnd
* @param ignoreMimeType
* @param includeMergedRevisons
* @return annotations for the given url
* @throws SVNClientException
*/
public ISVNAnnotations annotate(SVNUrl url, SVNRevision revisionStart, SVNRevision revisionEnd,
boolean ignoreMimeType, boolean includeMergedRevisions)
throws SVNClientException;
/**
* Output the content of specified file with revision and
* author information in-line.
* @param file
* @param revisionStart
* @param revisionEnd
* @param ignoreMimeType
* @param includeMergedRevisons
* @return annotations for the given file
* @throws SVNClientException
*/
public ISVNAnnotations annotate(File file, SVNRevision revisionStart, SVNRevision revisionEnd,
boolean ignoreMimeType, boolean includeMergedRevisions)
throws SVNClientException;
/**
* Get all the properties for the given file or dir
* @param path
* @return the properties for the given url
* @throws SVNClientException
*/
public abstract ISVNProperty[] getProperties(File path) throws SVNClientException;
/**
* Get all the properties for the given url
* @param url
* @return the properties for the given url
* @throws SVNClientException
*/
public abstract ISVNProperty[] getProperties(SVNUrl url) throws SVNClientException;
/**
* Remove 'conflicted' state on working copy files or directories
* @param path
* @throws SVNClientException
*/
public abstract void resolved(File path) throws SVNClientException;
/**
* Remove 'conflicted' state on working copy files or directories
* @param path
* @param result - choose resolve option - {@link ISVNConflictResolver.Choice}
* @throws SVNClientException
*/
public abstract void resolved(File path, int result) throws SVNClientException;
/**
* Create a new, empty repository at path
*
* @param path
* @param repositoryType either {@link ISVNClientAdapter#REPOSITORY_FSTYPE_BDB} or
* {@link ISVNClientAdapter#REPOSITORY_FSTYPE_FSFS} or null (will use svnadmin default)
* @throws SVNClientException
*/
public abstract void createRepository(File path, String repositoryType) throws SVNClientException;
/**
* Cancel the current operation
*
* @throws SVNClientException
*/
public void cancelOperation() throws SVNClientException;
/**
* Get information about a file or directory from working copy.
* Uses info() call which does NOT contact the repository
* @param file
* @return information about a file or directory from working copy.
* @throws SVNClientException
*/
public ISVNInfo getInfoFromWorkingCopy(File file) throws SVNClientException;
/**
* Get information about a file or directory.
* Uses info2() call which contacts the repository
* @param file
* @return information about a file or directory.
* @throws SVNClientException
*/
public ISVNInfo getInfo(File file) throws SVNClientException;
/**
* Get information about an URL.
* Uses info2() call which contacts the repository
* @param url
* @return information about an URL.
* @throws SVNClientException
*/
public ISVNInfo getInfo(SVNUrl url) throws SVNClientException;
/**
* Get information about an URL.
* Uses info2() call which contacts the repository
* @param url
* @param revision
* @param peg
* @return information about an URL.
* @throws SVNClientException
*/
public ISVNInfo getInfo(SVNUrl url, SVNRevision revision, SVNRevision peg) throws SVNClientException;
/**
* Update the working copy to mirror a new URL within the repository.
* This behaviour is similar to 'svn update', and is the way to
* move a working copy to a branch or tag within the same repository.
* @param url
* @param path
* @param revision
* @param recurse
* @throws SVNClientException
*/
public void switchToUrl(File path, SVNUrl url, SVNRevision revision, boolean recurse) throws SVNClientException;
/**
* Update the working copy to mirror a new URL within the repository.
* This behaviour is similar to 'svn update', and is the way to
* move a working copy to a branch or tag within the same repository.
* @param url
* @param path
* @param revision
* @param depth
* @param ignoreExternals
* @param force
* @throws SVNClientException
*/
public void switchToUrl(File path, SVNUrl url, SVNRevision revision, int depth, boolean ignoreExternals, boolean force) throws SVNClientException;
/**
* Set the configuration directory.
* @param dir
* @throws SVNClientException
*/
public void setConfigDirectory(File dir) throws SVNClientException;
/**
* Perform a clanup on the working copy. This will remove any stale transactions
* @param dir
* @throws SVNClientException
*/
public abstract void cleanup(File dir) throws SVNClientException;
/**
* Merge changes from two paths into a new local path.
* @param path1 first path or url
* @param revision1 first revision
* @param path2 second path or url
* @param revision2 second revision
* @param localPath target local path
* @param force overwrite local changes
* @param recurse traverse into subdirectories
* @exception SVNClientException
*/
public abstract void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
boolean recurse) throws SVNClientException;
/**
* Merge changes from two paths into a new local path.
* @param path1 first path or url
* @param revision1 first revision
* @param path2 second path or url
* @param revision2 second revision
* @param localPath target local path
* @param force overwrite local changes
* @param recurse traverse into subdirectories
* @param dryRun do not update working copy
* @exception SVNClientException
*/
public abstract void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
boolean recurse, boolean dryRun) throws SVNClientException;
/**
* Merge changes from two paths into a new local path.
* @param path1 first path or url
* @param revision1 first revision
* @param path2 second path or url
* @param revision2 second revision
* @param localPath target local path
* @param force overwrite local changes
* @param recurse traverse into subdirectories
* @param dryRun do not update working copy
* @param ignoreAncestry ignore ancestry when calculating merges
* @exception SVNClientException
*/
public abstract void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
boolean recurse, boolean dryRun, boolean ignoreAncestry) throws SVNClientException;
/**
* Merge changes from two paths into a new local path.
* @param path1 first path or url
* @param revision1 first revision
* @param path2 second path or url
* @param revision2 second revision
* @param localPath target local path
* @param force overwrite local changes
* @param int depth
* @param dryRun do not update working copy
* @param ignoreAncestry ignore ancestry when calculating merges
* @exception SVNClientException
*/
public abstract void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
int depth, boolean dryRun, boolean ignoreAncestry) throws SVNClientException;
/**
* Lock a working copy item
* @param paths path of the items to lock
* @param comment
* @param force break an existing lock
* @throws SVNClientException
*/
public abstract void lock(SVNUrl[] paths, String comment, boolean force)
throws SVNClientException;
/**
* Unlock a working copy item
* @param paths path of the items to unlock
* @param force break an existing lock
* @throws SVNClientException
*/
public abstract void unlock(SVNUrl[] paths, boolean force)
throws SVNClientException;
/**
* Lock a working copy item
* @param paths path of the items to lock
* @param comment
* @param force break an existing lock
* @throws SVNClientException
*/
public abstract void lock(File[] paths, String comment, boolean force)
throws SVNClientException;
/**
* Unlock a working copy item
* @param paths path of the items to unlock
* @param force break an existing lock
* @throws SVNClientException
*/
public abstract void unlock(File[] paths, boolean force)
throws SVNClientException;
/**
* Indicates whether a status call that contacts the
* server includes the remote info in the status object
* @return true when the client adapter implementation delivers remote info within status
*/
public abstract boolean statusReturnsRemoteInfo();
/**
* Indicates whether the commitAcrossWC method is
* supported in the adapter
* @return true when the client adapter implementation supports commitAcrossWC
*/
public abstract boolean canCommitAcrossWC();
/**
* Returns the name of the Subversion administrative
* working copy directory. Typically will be ".svn".
* @return the name of the Subversion administrative wc dir
*/
public abstract String getAdminDirectoryName();
/**
* Returns whether the passed folder name is a Subversion
* administrative working copy directory. Will always return
* true if ".svn" is passed. Otherwise, will be based on the
* Subversion runtime
* @param name
* @return true whether the folder is a Subversion administrative dir
*/
public abstract boolean isAdminDirectory(String name);
/**
* Rewrite the url's in the working copy
* @param from old url
* @param to new url
* @param path working copy path
* @param recurse recurse into subdirectories
* @throws SVNClientException
*/
public abstract void relocate(String from, String to, String path, boolean recurse)
throws SVNClientException;
/**
* Merge set of revisions into a new local path.
* @param url url
* @param pegRevision revision to interpret path
* @param revisions revisions to merge (must be in the form N-1:M)
* @param localPath target local path
* @param force overwrite local changes
* @param depth how deep to traverse into subdirectories
* @param ignoreAncestry ignore if files are not related
* @param dryRun do not change anything
* @throws SVNClientException
*/
public abstract void merge(SVNUrl url, SVNRevision pegRevision, SVNRevisionRange[] revisions,
File localPath, boolean force, int depth,
boolean ignoreAncestry, boolean dryRun) throws SVNClientException;
/**
* Get merge info for <code>path</code> at <code>revision</code>.
* @param path Local Path.
* @param revision SVNRevision at which to get the merge info for
* <code>path</code>.
* @throws SVNClientException
*/
public abstract ISVNMergeInfo getMergeInfo(File path, SVNRevision revision)
throws SVNClientException;
/**
* Get merge info for <code>url</code> at <code>revision</code>.
* @param url URL.
* @param revision SVNRevision at which to get the merge info for
* <code>path</code>.
* @throws SVNClientException
*/
public abstract ISVNMergeInfo getMergeInfo(SVNUrl url, SVNRevision revision)
throws SVNClientException;
/**
* Produce a diff summary which lists the items changed between
* path and revision pairs.
*
* @param target1 URL.
* @param revision1 Revision of <code>target1</code>.
* @param target2 URL.
* @param revision2 Revision of <code>target2</code>.
* @param depth how deep to recurse.
* @param ignoreAncestry Whether to ignore unrelated files during
* comparison. False positives may potentially be reported if
* this parameter <code>false</code>, since a file might have been
* modified between two revisions, but still have the same
* contents.
* @return the list of differences
*
* @throws SVNClientException
*/
public abstract SVNDiffSummary[] diffSummarize(SVNUrl target1, SVNRevision revision1,
SVNUrl target2, SVNRevision revision2,
int depth, boolean ignoreAncestry)
throws SVNClientException;
/**
* Produce a diff summary which lists the items changed between
* path and revision pairs.
*
* @param target URL.
* @param pegRevision Revision at which to interpret
* <code>target</code>. If {@link RevisionKind#unspecified} or
* <code>null</code>, behave identically to {@link
* diffSummarize(String, Revision, String, Revision, boolean,
* boolean, DiffSummaryReceiver)}, using <code>path</code> for
* both of that method's targets.
* @param startRevision Beginning of range for comparsion of
* <code>target</code>.
* @param endRevision End of range for comparsion of
* <code>target</code>.
* @param depth how deep to recurse.
* @param ignoreAncestry Whether to ignore unrelated files during
* comparison. False positives may potentially be reported if
* this parameter <code>false</code>, since a file might have been
* modified between two revisions, but still have the same
* contents.
* @return the list of differences
*
* @throws SVNClientException
*/
public abstract SVNDiffSummary[] diffSummarize(SVNUrl target, SVNRevision pegRevision,
SVNRevision startRevision, SVNRevision endRevision,
int depth, boolean ignoreAncestry)
throws SVNClientException;
/**
* Return an ordered list of suggested merge source URLs.
* @param path The merge target path for which to suggest sources.
* @return The list of URLs, empty if there are no suggestions.
* @throws SVNClientException If an error occurs.
*/
public abstract String[] suggestMergeSources(File path)
throws SVNClientException;
/**
* Return an ordered list of suggested merge source URLs.
* @param url The merge target path for which to suggest sources.
* @param peg The peg revision for the URL
* @return The list of URLs, empty if there are no suggestions.
* @throws SVNClientException If an error occurs.
*/
public abstract String[] suggestMergeSources(SVNUrl url, SVNRevision peg)
throws SVNClientException;
/**
* Get merge info for <code>path</code> at <code>pegRevision</code>.
* @param path WC path
* @param pegRevision Revision at which to get the merge info for
* <code>path</code>.
* @param mergeSource The merge source for which the list of
* revisions is available.
* @return The list of revisions available for merge from
* <code>mergeSource</code>, or <code>null</code> if all eligible
* revisions have been merged.
* @throws SVNClientException
*/
public abstract SVNRevisionRange[] getAvailableMerges(File path, SVNRevision pegRevision,
SVNUrl mergeSource)
throws SVNClientException;
/**
* Get merge info for <code>url</code> at <code>pegRevision</code>.
* @param url URL
* @param pegRevision Revision at which to get the merge info for
* <code>path</code>.
* @param mergeSource The merge source for which the list of
* revisions is available.
* @return The list of revisions available for merge from
* <code>mergeSource</code>, or <code>null</code> if all eligible
* revisions have been merged.
* @throws SVNClientException
*/
public abstract SVNRevisionRange[] getAvailableMerges(SVNUrl url, SVNRevision pegRevision,
SVNUrl mergeSource)
throws SVNClientException;
}
| Use peg revision for switch.
| src/main/org/tigris/subversion/svnclientadapter/ISVNClientAdapter.java | Use peg revision for switch. |
|
Java | apache-2.0 | be1cc577e97a248703b72b6282fc90f003967c13 | 0 | googlesamples/android-testdpc,googlesamples/android-testdpc | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.afwsamples.testdpc.policy;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.admin.DevicePolicyManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.MediaStore;
import android.provider.Settings;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.support.v14.preference.SwitchPreference;
import android.support.v4.content.FileProvider;
import android.support.v7.preference.EditTextPreference;
import android.support.v7.preference.Preference;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.afwsamples.testdpc.DeviceAdminReceiver;
import com.afwsamples.testdpc.R;
import com.afwsamples.testdpc.common.AppInfoArrayAdapter;
import com.afwsamples.testdpc.common.CertificateUtil;
import com.afwsamples.testdpc.common.MediaDisplayFragment;
import com.afwsamples.testdpc.common.BaseSearchablePolicyPreferenceFragment;
import com.afwsamples.testdpc.common.Util;
import com.afwsamples.testdpc.policy.blockuninstallation.BlockUninstallationInfoArrayAdapter;
import com.afwsamples.testdpc.policy.certificate.DelegatedCertInstallerFragment;
import com.afwsamples.testdpc.policy.keyguard.LockScreenPolicyFragment;
import com.afwsamples.testdpc.policy.keyguard.PasswordConstraintsFragment;
import com.afwsamples.testdpc.policy.locktask.KioskModeActivity;
import com.afwsamples.testdpc.policy.locktask.LockTaskAppInfoArrayAdapter;
import com.afwsamples.testdpc.policy.networking.AlwaysOnVpnFragment;
import com.afwsamples.testdpc.policy.networking.NetworkUsageStatsFragment;
import com.afwsamples.testdpc.policy.systemupdatepolicy.SystemUpdatePolicyFragment;
import com.afwsamples.testdpc.policy.wifimanagement.WifiConfigCreationDialog;
import com.afwsamples.testdpc.policy.wifimanagement.WifiEapTlsCreateDialogFragment;
import com.afwsamples.testdpc.policy.wifimanagement.WifiModificationFragment;
import com.afwsamples.testdpc.profilepolicy.ProfilePolicyManagementFragment;
import com.afwsamples.testdpc.profilepolicy.addsystemapps.EnableSystemAppsByIntentFragment;
import com.afwsamples.testdpc.profilepolicy.apprestrictions.AppRestrictionsManagingPackageFragment;
import com.afwsamples.testdpc.profilepolicy.apprestrictions.ManageAppRestrictionsFragment;
import com.afwsamples.testdpc.profilepolicy.permission.ManageAppPermissionsFragment;
import com.afwsamples.testdpc.safetynet.SafetyNetFragment;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static android.os.UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
/**
* Provides several device management functions.
*
* These include:
* <ul>
* <li> {@link DevicePolicyManager#setLockTaskPackages(android.content.ComponentName, String[])} </li>
* <li> {@link DevicePolicyManager#isLockTaskPermitted(String)} </li>
* <li> {@link UserManager#DISALLOW_DEBUGGING_FEATURES} </li>
* <li> {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} </li>
* <li> {@link UserManager#DISALLOW_REMOVE_USER} </li>
* <li> {@link UserManager#DISALLOW_ADD_USER} </li>
* <li> {@link UserManager#DISALLOW_FACTORY_RESET} </li>
* <li> {@link UserManager#DISALLOW_CONFIG_CREDENTIALS} </li>
* <li> {@link UserManager#DISALLOW_SHARE_LOCATION} </li>
* <li> {@link UserManager#DISALLOW_CONFIG_TETHERING} </li>
* <li> {@link UserManager#DISALLOW_ADJUST_VOLUME} </li>
* <li> {@link UserManager#DISALLOW_UNMUTE_MICROPHONE} </li>
* <li> {@link UserManager#DISALLOW_MODIFY_ACCOUNTS} </li>
* <li> {@link UserManager#DISALLOW_SAFE_BOOT} </li>
* <li> {@link UserManager#DISALLOW_OUTGOING_BEAM}} </li>
* <li> {@link UserManager#DISALLOW_CREATE_WINDOWS}} </li>
* <li> {@link DevicePolicyManager#clearDeviceOwnerApp(String)} </li>
* <li> {@link DevicePolicyManager#getPermittedAccessibilityServices(android.content.ComponentName)}
* </li>
* <li> {@link DevicePolicyManager#getPermittedInputMethods(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#setAccountManagementDisabled(android.content.ComponentName,
* String, boolean)} </li>
* <li> {@link DevicePolicyManager#getAccountTypesWithManagementDisabled()} </li>
* <li> {@link DevicePolicyManager#removeUser(android.content.ComponentName,
android.os.UserHandle)} </li>
* <li> {@link DevicePolicyManager#setUninstallBlocked(android.content.ComponentName, String,
* boolean)} </li>
* <li> {@link DevicePolicyManager#isUninstallBlocked(android.content.ComponentName, String)} </li>
* <li> {@link DevicePolicyManager#setCameraDisabled(android.content.ComponentName, boolean)} </li>
* <li> {@link DevicePolicyManager#getCameraDisabled(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#enableSystemApp(android.content.ComponentName,
* android.content.Intent)} </li>
* <li> {@link DevicePolicyManager#enableSystemApp(android.content.ComponentName, String)} </li>
* <li> {@link DevicePolicyManager#setApplicationRestrictions(android.content.ComponentName, String,
* android.os.Bundle)} </li>
* <li> {@link DevicePolicyManager#installKeyPair(android.content.ComponentName,
* java.security.PrivateKey, java.security.cert.Certificate, String)} </li>
* <li> {@link DevicePolicyManager#removeKeyPair(android.content.ComponentName, String)} </li>
* <li> {@link DevicePolicyManager#installCaCert(android.content.ComponentName, byte[])} </li>
* <li> {@link DevicePolicyManager#uninstallAllUserCaCerts(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#getInstalledCaCerts(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#setStatusBarDisabled(ComponentName, boolean)} </li>
* <li> {@link DevicePolicyManager#setKeyguardDisabled(ComponentName, boolean)} </li>
* <li> {@link DevicePolicyManager#setPermissionPolicy(android.content.ComponentName, int)} </li>
* <li> {@link DevicePolicyManager#getPermissionPolicy(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#setPermissionGrantState(ComponentName, String, String, int) (
* android.content.ComponentName, String, String, boolean)} </li>
* <li> {@link DevicePolicyManager#setScreenCaptureDisabled(ComponentName, boolean)} </li>
* <li> {@link DevicePolicyManager#getScreenCaptureDisabled(ComponentName)} </li>
* <li> {@link DevicePolicyManager#setMaximumTimeToLock(ComponentName, long)} </li>
* <li> {@link DevicePolicyManager#setMaximumFailedPasswordsForWipe(ComponentName, int)} </li>
* <li> {@link DevicePolicyManager#setApplicationHidden(ComponentName, String, boolean)} </li>
* <li> {@link DevicePolicyManager#setShortSupportMessage(ComponentName, String)} </li>
* <li> {@link DevicePolicyManager#setLongSupportMessage(ComponentName, String)} </li>
* <li> {@link UserManager#DISALLOW_CONFIG_WIFI} </li>
* </ul>
*/
public class PolicyManagementFragment extends BaseSearchablePolicyPreferenceFragment implements
Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
// Tag for creating this fragment. This tag can be used to retrieve this fragment.
public static final String FRAGMENT_TAG = "PolicyManagementFragment";
private static final int INSTALL_KEY_CERTIFICATE_REQUEST_CODE = 7689;
private static final int INSTALL_CA_CERTIFICATE_REQUEST_CODE = 7690;
private static final int CAPTURE_IMAGE_REQUEST_CODE = 7691;
private static final int CAPTURE_VIDEO_REQUEST_CODE = 7692;
public static final int DEFAULT_BUFFER_SIZE = 4096;
public static final String X509_CERT_TYPE = "X.509";
public static final String TAG = "PolicyManagement";
public static final String OVERRIDE_KEY_SELECTION_KEY = "override_key_selection";
private static final String APP_RESTRICTIONS_MANAGING_PACKAGE_KEY
= "app_restrictions_managing_package";
private static final String BLOCK_UNINSTALLATION_BY_PKG_KEY = "block_uninstallation_by_pkg";
private static final String BLOCK_UNINSTALLATION_LIST_KEY = "block_uninstallation_list";
private static final String CAPTURE_IMAGE_KEY = "capture_image";
private static final String CAPTURE_VIDEO_KEY = "capture_video";
private static final String CHECK_LOCK_TASK_PERMITTED_KEY = "check_lock_task_permitted";
private static final String CREATE_AND_MANAGE_USER_KEY = "create_and_manage_user";
private static final String DELEGATED_CERT_INSTALLER_KEY = "manage_cert_installer";
private static final String DEVICE_OWNER_STATUS_KEY = "device_owner_status";
private static final String DISABLE_CAMERA_KEY = "disable_camera";
private static final String DISABLE_KEYGUARD = "disable_keyguard";
private static final String DISABLE_SCREEN_CAPTURE_KEY = "disable_screen_capture";
private static final String DISABLE_STATUS_BAR = "disable_status_bar";
private static final String ENABLE_PROCESS_LOGGING = "enable_process_logging";
private static final String ENABLE_SYSTEM_APPS_BY_INTENT_KEY = "enable_system_apps_by_intent";
private static final String ENABLE_SYSTEM_APPS_BY_PACKAGE_NAME_KEY
= "enable_system_apps_by_package_name";
private static final String ENABLE_SYSTEM_APPS_KEY = "enable_system_apps";
private static final String GET_CA_CERTIFICATES_KEY = "get_ca_certificates";
private static final String GET_DISABLE_ACCOUNT_MANAGEMENT_KEY
= "get_disable_account_management";
private static final String HIDE_APPS_KEY = "hide_apps";
private static final String INSTALL_CA_CERTIFICATE_KEY = "install_ca_certificate";
private static final String INSTALL_KEY_CERTIFICATE_KEY = "install_key_certificate";
private static final String INSTALL_NONMARKET_APPS_KEY
= "install_nonmarket_apps";
private static final String LOCK_SCREEN_POLICY_KEY = "lock_screen_policy";
private static final String MANAGE_APP_PERMISSIONS_KEY = "manage_app_permissions";
private static final String MANAGE_APP_RESTRICTIONS_KEY = "manage_app_restrictions";
private static final String MANAGED_PROFILE_SPECIFIC_POLICIES_KEY = "managed_profile_policies";
private static final String MANAGE_LOCK_TASK_LIST_KEY = "manage_lock_task";
private static final String MUTE_AUDIO_KEY = "mute_audio";
private static final String NETWORK_STATS_KEY = "network_stats";
private static final String PASSWORD_CONSTRAINTS_KEY = "password_constraints";
private static final String REBOOT_KEY = "reboot";
private static final String REENABLE_KEYGUARD = "reenable_keyguard";
private static final String REENABLE_STATUS_BAR = "reenable_status_bar";
private static final String REMOVE_ALL_CERTIFICATES_KEY = "remove_all_ca_certificates";
private static final String REMOVE_DEVICE_OWNER_KEY = "remove_device_owner";
private static final String REMOVE_KEY_CERTIFICATE_KEY = "remove_key_certificate";
private static final String REMOVE_USER_KEY = "remove_user";
private static final String REQUEST_BUGREPORT_KEY = "request_bugreport";
private static final String REQUEST_PROCESS_LOGS = "request_process_logs";
private static final String RESET_PASSWORD_KEY = "reset_password";
private static final String LOCK_NOW_KEY = "lock_now";
private static final String SET_ACCESSIBILITY_SERVICES_KEY = "set_accessibility_services";
private static final String SET_ALWAYS_ON_VPN_KEY = "set_always_on_vpn";
private static final String SET_AUTO_TIME_REQUIRED_KEY = "set_auto_time_required";
private static final String SET_DISABLE_ACCOUNT_MANAGEMENT_KEY
= "set_disable_account_management";
private static final String SET_INPUT_METHODS_KEY = "set_input_methods";
private static final String SET_LONG_SUPPORT_MESSAGE_KEY = "set_long_support_message";
private static final String SET_PERMISSION_POLICY_KEY = "set_permission_policy";
private static final String SET_SHORT_SUPPORT_MESSAGE_KEY = "set_short_support_message";
private static final String SET_USER_RESTRICTIONS_KEY = "set_user_restrictions";
private static final String SHOW_WIFI_MAC_ADDRESS_KEY = "show_wifi_mac_address";
private static final String START_KIOSK_MODE = "start_kiosk_mode";
private static final String START_LOCK_TASK = "start_lock_task";
private static final String STAY_ON_WHILE_PLUGGED_IN = "stay_on_while_plugged_in";
private static final String STOP_LOCK_TASK = "stop_lock_task";
private static final String SUSPEND_APPS_KEY = "suspend_apps";
private static final String SYSTEM_UPDATE_POLICY_KEY = "system_update_policy";
private static final String UNHIDE_APPS_KEY = "unhide_apps";
private static final String UNSUSPEND_APPS_KEY = "unsuspend_apps";
private static final String WIPE_DATA_KEY = "wipe_data";
private static final String CREATE_WIFI_CONFIGURATION_KEY = "create_wifi_configuration";
private static final String CREATE_EAP_TLS_WIFI_CONFIGURATION_KEY
= "create_eap_tls_wifi_configuration";
private static final String WIFI_CONFIG_LOCKDOWN_ENABLE_KEY = "enable_wifi_config_lockdown";
private static final String MODIFY_WIFI_CONFIGURATION_KEY = "modify_wifi_configuration";
private static final String TAG_WIFI_CONFIG_CREATION = "wifi_config_creation";
private static final String WIFI_CONFIG_LOCKDOWN_ON = "1";
private static final String WIFI_CONFIG_LOCKDOWN_OFF = "0";
private static final String SAFETYNET_ATTEST = "safetynet_attest";
private static final String BATTERY_PLUGGED_ANY = Integer.toString(
BatteryManager.BATTERY_PLUGGED_AC |
BatteryManager.BATTERY_PLUGGED_USB |
BatteryManager.BATTERY_PLUGGED_WIRELESS);
private static final String DONT_STAY_ON = "0";
private static final String[] PRIMARY_USER_ONLY_PREFERENCES = {
WIPE_DATA_KEY, REMOVE_DEVICE_OWNER_KEY, REMOVE_USER_KEY,
MANAGE_LOCK_TASK_LIST_KEY, CHECK_LOCK_TASK_PERMITTED_KEY, START_LOCK_TASK,
STOP_LOCK_TASK, DISABLE_STATUS_BAR, REENABLE_STATUS_BAR, DISABLE_KEYGUARD,
REENABLE_KEYGUARD, START_KIOSK_MODE, SYSTEM_UPDATE_POLICY_KEY, STAY_ON_WHILE_PLUGGED_IN,
SHOW_WIFI_MAC_ADDRESS_KEY, REBOOT_KEY, REQUEST_BUGREPORT_KEY, ENABLE_PROCESS_LOGGING,
REQUEST_PROCESS_LOGS, SET_AUTO_TIME_REQUIRED_KEY, CREATE_AND_MANAGE_USER_KEY
};
private static String[] MNC_PLUS_PREFERENCES = {
OVERRIDE_KEY_SELECTION_KEY, START_LOCK_TASK, STOP_LOCK_TASK, SYSTEM_UPDATE_POLICY_KEY,
NETWORK_STATS_KEY, DELEGATED_CERT_INSTALLER_KEY, DISABLE_STATUS_BAR,
REENABLE_STATUS_BAR, DISABLE_KEYGUARD, REENABLE_KEYGUARD, START_KIOSK_MODE,
SET_PERMISSION_POLICY_KEY, MANAGE_APP_PERMISSIONS_KEY,STAY_ON_WHILE_PLUGGED_IN,
WIFI_CONFIG_LOCKDOWN_ENABLE_KEY
};
private static String[] NYC_PLUS_PREFERENCES = {
APP_RESTRICTIONS_MANAGING_PACKAGE_KEY, REBOOT_KEY, REMOVE_KEY_CERTIFICATE_KEY,
SET_ALWAYS_ON_VPN_KEY, SHOW_WIFI_MAC_ADDRESS_KEY, SUSPEND_APPS_KEY, UNSUSPEND_APPS_KEY,
SET_SHORT_SUPPORT_MESSAGE_KEY, SET_LONG_SUPPORT_MESSAGE_KEY, REQUEST_BUGREPORT_KEY,
ENABLE_PROCESS_LOGGING, REQUEST_PROCESS_LOGS, CREATE_AND_MANAGE_USER_KEY
};
/**
* Preferences that are allowed only in NYC+ if it is profile owner. This does not restrict
* device owner.
*/
private static String[] PROFILE_OWNER_NYC_PLUS_PREFERENCES = {
RESET_PASSWORD_KEY
};
private static final String[] MANAGED_PROFILE_SPECIFIC_OPTIONS = {
MANAGED_PROFILE_SPECIFIC_POLICIES_KEY
};
private DevicePolicyManager mDevicePolicyManager;
private PackageManager mPackageManager;
private String mPackageName;
private ComponentName mAdminComponentName;
private UserManager mUserManager;
private TelephonyManager mTelephonyManager;
private SwitchPreference mDisableCameraSwitchPreference;
private SwitchPreference mDisableScreenCaptureSwitchPreference;
private SwitchPreference mMuteAudioSwitchPreference;
private SwitchPreference mStayOnWhilePluggedInSwitchPreference;
private SwitchPreference mInstallNonMarketAppsPreference;
private SwitchPreference mEnableProcessLoggingPreference;
private SwitchPreference mSetAutoTimeRequiredPreference;
private GetAccessibilityServicesTask mGetAccessibilityServicesTask = null;
private GetInputMethodsTask mGetInputMethodsTask = null;
private ShowCaCertificateListTask mShowCaCertificateListTask = null;
private Uri mImageUri;
private Uri mVideoUri;
@Override
public void onCreate(Bundle savedInstanceState) {
mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity());
mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(
Context.DEVICE_POLICY_SERVICE);
mUserManager = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
mTelephonyManager = (TelephonyManager) getActivity()
.getSystemService(Context.TELEPHONY_SERVICE);
mPackageManager = getActivity().getPackageManager();
mPackageName = getActivity().getPackageName();
mImageUri = getStorageUri("image.jpg");
mVideoUri = getStorageUri("video.mp4");
super.onCreate(savedInstanceState);
}
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(getPreferenceXml());
EditTextPreference overrideKeySelectionPreference =
(EditTextPreference) findPreference(OVERRIDE_KEY_SELECTION_KEY);
overrideKeySelectionPreference.setOnPreferenceChangeListener(this);
overrideKeySelectionPreference.setSummary(overrideKeySelectionPreference.getText());
findPreference(MANAGE_LOCK_TASK_LIST_KEY).setOnPreferenceClickListener(this);
findPreference(CHECK_LOCK_TASK_PERMITTED_KEY).setOnPreferenceClickListener(this);
findPreference(START_LOCK_TASK).setOnPreferenceClickListener(this);
findPreference(STOP_LOCK_TASK).setOnPreferenceClickListener(this);
findPreference(CREATE_AND_MANAGE_USER_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_USER_KEY).setOnPreferenceClickListener(this);
mDisableCameraSwitchPreference = (SwitchPreference) findPreference(DISABLE_CAMERA_KEY);
findPreference(CAPTURE_IMAGE_KEY).setOnPreferenceClickListener(this);
findPreference(CAPTURE_VIDEO_KEY).setOnPreferenceClickListener(this);
mDisableCameraSwitchPreference.setOnPreferenceChangeListener(this);
mDisableScreenCaptureSwitchPreference = (SwitchPreference) findPreference(
DISABLE_SCREEN_CAPTURE_KEY);
mDisableScreenCaptureSwitchPreference.setOnPreferenceChangeListener(this);
mMuteAudioSwitchPreference = (SwitchPreference) findPreference(
MUTE_AUDIO_KEY);
mMuteAudioSwitchPreference.setOnPreferenceChangeListener(this);
findPreference(LOCK_SCREEN_POLICY_KEY).setOnPreferenceClickListener(this);
findPreference(PASSWORD_CONSTRAINTS_KEY).setOnPreferenceClickListener(this);
findPreference(RESET_PASSWORD_KEY).setOnPreferenceClickListener(this);
findPreference(LOCK_NOW_KEY).setOnPreferenceClickListener(this);
findPreference(SYSTEM_UPDATE_POLICY_KEY).setOnPreferenceClickListener(this);
findPreference(SET_ALWAYS_ON_VPN_KEY).setOnPreferenceClickListener(this);
findPreference(NETWORK_STATS_KEY).setOnPreferenceClickListener(this);
findPreference(DELEGATED_CERT_INSTALLER_KEY).setOnPreferenceClickListener(this);
findPreference(DISABLE_STATUS_BAR).setOnPreferenceClickListener(this);
findPreference(REENABLE_STATUS_BAR).setOnPreferenceClickListener(this);
findPreference(DISABLE_KEYGUARD).setOnPreferenceClickListener(this);
findPreference(REENABLE_KEYGUARD).setOnPreferenceClickListener(this);
findPreference(START_KIOSK_MODE).setOnPreferenceClickListener(this);
mStayOnWhilePluggedInSwitchPreference = (SwitchPreference) findPreference(
STAY_ON_WHILE_PLUGGED_IN);
mStayOnWhilePluggedInSwitchPreference.setOnPreferenceChangeListener(this);
findPreference(WIPE_DATA_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_DEVICE_OWNER_KEY).setOnPreferenceClickListener(this);
findPreference(REQUEST_BUGREPORT_KEY).setOnPreferenceClickListener(this);
mEnableProcessLoggingPreference = (SwitchPreference) findPreference(
ENABLE_PROCESS_LOGGING);
mEnableProcessLoggingPreference.setOnPreferenceChangeListener(this);
findPreference(REQUEST_PROCESS_LOGS).setOnPreferenceClickListener(this);
findPreference(SET_ACCESSIBILITY_SERVICES_KEY).setOnPreferenceClickListener(this);
findPreference(SET_INPUT_METHODS_KEY).setOnPreferenceClickListener(this);
findPreference(SET_DISABLE_ACCOUNT_MANAGEMENT_KEY).setOnPreferenceClickListener(this);
findPreference(GET_DISABLE_ACCOUNT_MANAGEMENT_KEY).setOnPreferenceClickListener(this);
findPreference(BLOCK_UNINSTALLATION_BY_PKG_KEY).setOnPreferenceClickListener(this);
findPreference(BLOCK_UNINSTALLATION_LIST_KEY).setOnPreferenceClickListener(this);
findPreference(ENABLE_SYSTEM_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(ENABLE_SYSTEM_APPS_BY_PACKAGE_NAME_KEY).setOnPreferenceClickListener(this);
findPreference(ENABLE_SYSTEM_APPS_BY_INTENT_KEY).setOnPreferenceClickListener(this);
findPreference(HIDE_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(UNHIDE_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(SUSPEND_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(UNSUSPEND_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(MANAGE_APP_RESTRICTIONS_KEY).setOnPreferenceClickListener(this);
findPreference(APP_RESTRICTIONS_MANAGING_PACKAGE_KEY).setOnPreferenceClickListener(this);
findPreference(INSTALL_KEY_CERTIFICATE_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_KEY_CERTIFICATE_KEY).setOnPreferenceClickListener(this);
findPreference(INSTALL_CA_CERTIFICATE_KEY).setOnPreferenceClickListener(this);
findPreference(GET_CA_CERTIFICATES_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_ALL_CERTIFICATES_KEY).setOnPreferenceClickListener(this);
findPreference(MANAGED_PROFILE_SPECIFIC_POLICIES_KEY).setOnPreferenceClickListener(this);
findPreference(SET_PERMISSION_POLICY_KEY).setOnPreferenceClickListener(this);
findPreference(MANAGE_APP_PERMISSIONS_KEY).setOnPreferenceClickListener(this);
findPreference(CREATE_WIFI_CONFIGURATION_KEY).setOnPreferenceClickListener(this);
findPreference(CREATE_EAP_TLS_WIFI_CONFIGURATION_KEY).setOnPreferenceClickListener(this);
findPreference(WIFI_CONFIG_LOCKDOWN_ENABLE_KEY).setOnPreferenceChangeListener(this);
findPreference(MODIFY_WIFI_CONFIGURATION_KEY).setOnPreferenceClickListener(this);
findPreference(SHOW_WIFI_MAC_ADDRESS_KEY).setOnPreferenceClickListener(this);
mInstallNonMarketAppsPreference = (SwitchPreference) findPreference(
INSTALL_NONMARKET_APPS_KEY);
mInstallNonMarketAppsPreference.setOnPreferenceChangeListener(this);
findPreference(SET_USER_RESTRICTIONS_KEY).setOnPreferenceClickListener(this);
findPreference(REBOOT_KEY).setOnPreferenceClickListener(this);
findPreference(SET_SHORT_SUPPORT_MESSAGE_KEY).setOnPreferenceClickListener(this);
findPreference(SET_LONG_SUPPORT_MESSAGE_KEY).setOnPreferenceClickListener(this);
findPreference(SAFETYNET_ATTEST).setOnPreferenceClickListener(this);
mSetAutoTimeRequiredPreference = (SwitchPreference) findPreference(
SET_AUTO_TIME_REQUIRED_KEY);
mSetAutoTimeRequiredPreference.setOnPreferenceChangeListener(this);
disableIncompatibleManagementOptionsInCurrentProfile();
disableIncompatibleManagementOptionsByApiLevel();
reloadCameraDisableUi();
reloadScreenCaptureDisableUi();
reloadMuteAudioUi();
reloadEnableProcessLoggingUi();
reloadSetAutoTimeRequiredUi();
}
@Override
public int getPreferenceXml() {
return R.xml.device_policy_header;
}
@Override
public boolean isAvailable(Context context) {
DevicePolicyManager dpm =
(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
String packageName = context.getPackageName();
return dpm.isProfileOwnerApp(packageName) || dpm.isDeviceOwnerApp(packageName);
}
@Override
public void onResume() {
super.onResume();
getActivity().getActionBar().setTitle(R.string.policies_management);
if (!isAvailable(getActivity())) {
showToast(R.string.this_is_not_a_device_owner);
getActivity().finish();
}
// The settings might get changed outside the device policy app,
// so, we need to make sure the preference gets updated accordingly.
updateStayOnWhilePluggedInPreference();
updateInstallNonMarketAppsPreference();
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
switch (key) {
case MANAGE_LOCK_TASK_LIST_KEY:
showManageLockTaskListPrompt(R.string.lock_task_title,
new ManageLockTaskListCallback() {
@Override
public void onPositiveButtonClicked(String[] lockTaskArray) {
mDevicePolicyManager.setLockTaskPackages(
DeviceAdminReceiver.getComponentName(getActivity()),
lockTaskArray);
}
}
);
return true;
case CHECK_LOCK_TASK_PERMITTED_KEY:
showCheckLockTaskPermittedPrompt();
return true;
case RESET_PASSWORD_KEY:
showResetPasswordPrompt();
return false;
case LOCK_NOW_KEY:
lockNow();
return true;
case START_LOCK_TASK:
getActivity().startLockTask();
return true;
case STOP_LOCK_TASK:
try {
getActivity().stopLockTask();
} catch (IllegalStateException e) {
// no lock task present, ignore
}
return true;
case WIPE_DATA_KEY:
showWipeDataPrompt();
return true;
case REMOVE_DEVICE_OWNER_KEY:
showRemoveDeviceOwnerPrompt();
return true;
case REQUEST_BUGREPORT_KEY:
requestBugReport();
return true;
case REQUEST_PROCESS_LOGS:
showFragment(new ProcessLogsFragment());
return true;
case SET_ACCESSIBILITY_SERVICES_KEY:
// Avoid starting the same task twice.
if (mGetAccessibilityServicesTask != null && !mGetAccessibilityServicesTask
.isCancelled()) {
mGetAccessibilityServicesTask.cancel(true);
}
mGetAccessibilityServicesTask = new GetAccessibilityServicesTask();
mGetAccessibilityServicesTask.execute();
return true;
case SET_INPUT_METHODS_KEY:
// Avoid starting the same task twice.
if (mGetInputMethodsTask != null && !mGetInputMethodsTask.isCancelled()) {
mGetInputMethodsTask.cancel(true);
}
mGetInputMethodsTask = new GetInputMethodsTask();
mGetInputMethodsTask.execute();
return true;
case SET_DISABLE_ACCOUNT_MANAGEMENT_KEY:
showSetDisableAccountManagementPrompt();
return true;
case GET_DISABLE_ACCOUNT_MANAGEMENT_KEY:
showDisableAccountTypeList();
return true;
case CREATE_AND_MANAGE_USER_KEY:
showCreateAndManageUserPrompt();
return true;
case REMOVE_USER_KEY:
showRemoveUserPrompt();
return true;
case BLOCK_UNINSTALLATION_BY_PKG_KEY:
showBlockUninstallationByPackageNamePrompt();
return true;
case BLOCK_UNINSTALLATION_LIST_KEY:
showBlockUninstallationPrompt();
return true;
case ENABLE_SYSTEM_APPS_KEY:
showEnableSystemAppsPrompt();
return true;
case ENABLE_SYSTEM_APPS_BY_PACKAGE_NAME_KEY:
showEnableSystemAppByPackageNamePrompt();
return true;
case ENABLE_SYSTEM_APPS_BY_INTENT_KEY:
showFragment(new EnableSystemAppsByIntentFragment());
return true;
case HIDE_APPS_KEY:
showHideAppsPrompt(false);
return true;
case UNHIDE_APPS_KEY:
showHideAppsPrompt(true);
return true;
case SUSPEND_APPS_KEY:
showSuspendAppsPrompt(false);
return true;
case UNSUSPEND_APPS_KEY:
showSuspendAppsPrompt(true);
return true;
case MANAGE_APP_RESTRICTIONS_KEY:
showFragment(new ManageAppRestrictionsFragment());
return true;
case APP_RESTRICTIONS_MANAGING_PACKAGE_KEY:
showFragment(new AppRestrictionsManagingPackageFragment());
return true;
case SET_PERMISSION_POLICY_KEY:
showSetPermissionPolicyDialog();
return true;
case MANAGE_APP_PERMISSIONS_KEY:
showFragment(new ManageAppPermissionsFragment());
return true;
case INSTALL_KEY_CERTIFICATE_KEY:
showFileViewerForImportingCertificate(INSTALL_KEY_CERTIFICATE_REQUEST_CODE);
return true;
case REMOVE_KEY_CERTIFICATE_KEY:
choosePrivateKeyForRemoval();
return true;
case INSTALL_CA_CERTIFICATE_KEY:
showFileViewerForImportingCertificate(INSTALL_CA_CERTIFICATE_REQUEST_CODE);
return true;
case GET_CA_CERTIFICATES_KEY:
showCaCertificateList();
return true;
case REMOVE_ALL_CERTIFICATES_KEY:
mDevicePolicyManager.uninstallAllUserCaCerts(mAdminComponentName);
showToast(R.string.all_ca_certificates_removed);
return true;
case MANAGED_PROFILE_SPECIFIC_POLICIES_KEY:
showFragment(new ProfilePolicyManagementFragment(),
ProfilePolicyManagementFragment.FRAGMENT_TAG);
return true;
case LOCK_SCREEN_POLICY_KEY:
showFragment(new LockScreenPolicyFragment.Container());
return true;
case PASSWORD_CONSTRAINTS_KEY:
showFragment(new PasswordConstraintsFragment.Container());
return true;
case SYSTEM_UPDATE_POLICY_KEY:
showFragment(new SystemUpdatePolicyFragment());
return true;
case SET_ALWAYS_ON_VPN_KEY:
showFragment(new AlwaysOnVpnFragment());
return true;
case NETWORK_STATS_KEY:
showFragment(new NetworkUsageStatsFragment());
return true;
case DELEGATED_CERT_INSTALLER_KEY:
showFragment(new DelegatedCertInstallerFragment());
return true;
case DISABLE_STATUS_BAR:
setStatusBarDisabled(true);
return true;
case REENABLE_STATUS_BAR:
setStatusBarDisabled(false);
return true;
case DISABLE_KEYGUARD:
setKeyGuardDisabled(true);
return true;
case REENABLE_KEYGUARD:
setKeyGuardDisabled(false);
return true;
case START_KIOSK_MODE:
showManageLockTaskListPrompt(R.string.kiosk_select_title,
new ManageLockTaskListCallback() {
@Override
public void onPositiveButtonClicked(String[] lockTaskArray) {
startKioskMode(lockTaskArray);
}
}
);
return true;
case CAPTURE_IMAGE_KEY:
dispatchCaptureIntent(MediaStore.ACTION_IMAGE_CAPTURE,
CAPTURE_IMAGE_REQUEST_CODE, mImageUri);
return true;
case CAPTURE_VIDEO_KEY:
dispatchCaptureIntent(MediaStore.ACTION_VIDEO_CAPTURE,
CAPTURE_VIDEO_REQUEST_CODE, mVideoUri);
return true;
case CREATE_WIFI_CONFIGURATION_KEY:
showWifiConfigCreationDialog();
return true;
case CREATE_EAP_TLS_WIFI_CONFIGURATION_KEY:
showEapTlsWifiConfigCreationDialog();
return true;
case MODIFY_WIFI_CONFIGURATION_KEY:
showFragment(new WifiModificationFragment());
return true;
case SHOW_WIFI_MAC_ADDRESS_KEY:
showWifiMacAddress();
return true;
case SET_USER_RESTRICTIONS_KEY:
showFragment(new UserRestrictionsDisplayFragment());
return true;
case REBOOT_KEY:
reboot();
return true;
case SET_SHORT_SUPPORT_MESSAGE_KEY:
showFragment(SetSupportMessageFragment.newInstance(
SetSupportMessageFragment.TYPE_SHORT));
return true;
case SET_LONG_SUPPORT_MESSAGE_KEY:
showFragment(SetSupportMessageFragment.newInstance(
SetSupportMessageFragment.TYPE_LONG));
return true;
case SAFETYNET_ATTEST:
DialogFragment safetynetFragment = new SafetyNetFragment();
safetynetFragment.show(getFragmentManager(), SafetyNetFragment.class.getName());
return true;
}
return false;
}
@TargetApi(Build.VERSION_CODES.N)
private void lockNow() {
if (Util.isBeforeN() || !Util.isManagedProfile(getActivity(), mAdminComponentName)) {
mDevicePolicyManager.lockNow();
} else {
// In N for work profiles we should call lockNow on the parent instance to
// lock the device.
DevicePolicyManager parentDpm
= mDevicePolicyManager.getParentProfileInstance(mAdminComponentName);
parentDpm.lockNow();
}
}
@Override
@SuppressLint("NewApi")
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
switch (key) {
case OVERRIDE_KEY_SELECTION_KEY:
preference.setSummary((String) newValue);
return true;
case DISABLE_CAMERA_KEY:
setCameraDisabled((Boolean) newValue);
// Reload UI to verify the camera is enable / disable correctly.
reloadCameraDisableUi();
return true;
case ENABLE_PROCESS_LOGGING:
setSecurityLoggingEnabled((Boolean) newValue);
reloadEnableProcessLoggingUi();
return true;
case DISABLE_SCREEN_CAPTURE_KEY:
setScreenCaptureDisabled((Boolean) newValue);
// Reload UI to verify that screen capture was enabled / disabled correctly.
reloadScreenCaptureDisableUi();
return true;
case MUTE_AUDIO_KEY:
mDevicePolicyManager.setMasterVolumeMuted(mAdminComponentName,
(Boolean) newValue);
reloadMuteAudioUi();
return true;
case STAY_ON_WHILE_PLUGGED_IN:
mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
newValue.equals(true) ? BATTERY_PLUGGED_ANY : DONT_STAY_ON);
updateStayOnWhilePluggedInPreference();
return true;
case WIFI_CONFIG_LOCKDOWN_ENABLE_KEY:
mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN,
newValue.equals(Boolean.TRUE) ?
WIFI_CONFIG_LOCKDOWN_ON : WIFI_CONFIG_LOCKDOWN_OFF);
return true;
case INSTALL_NONMARKET_APPS_KEY:
mDevicePolicyManager.setSecureSetting(mAdminComponentName,
Settings.Secure.INSTALL_NON_MARKET_APPS,
newValue.equals(true) ? "1" : "0");
updateInstallNonMarketAppsPreference();
return true;
case SET_AUTO_TIME_REQUIRED_KEY:
mDevicePolicyManager.setAutoTimeRequired(mAdminComponentName,
newValue.equals(true));
reloadSetAutoTimeRequiredUi();
return true;
}
return false;
}
@TargetApi(Build.VERSION_CODES.M)
private void setCameraDisabled(boolean disabled) {
mDevicePolicyManager.setCameraDisabled(mAdminComponentName, disabled);
}
@TargetApi(Build.VERSION_CODES.N)
private void setSecurityLoggingEnabled(boolean enabled) {
mDevicePolicyManager.setSecurityLoggingEnabled(mAdminComponentName, enabled);
}
@TargetApi(Build.VERSION_CODES.M)
private void setKeyGuardDisabled(boolean disabled) {
if (!mDevicePolicyManager.setKeyguardDisabled(mAdminComponentName, disabled)) {
// this should not happen
if (disabled) {
showToast(R.string.unable_disable_keyguard);
} else {
showToast(R.string.unable_enable_keyguard);
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setScreenCaptureDisabled(boolean disabled) {
mDevicePolicyManager.setScreenCaptureDisabled(mAdminComponentName, disabled);
}
private void setMasterVolumeMuted(boolean muted) {
}
@TargetApi(Build.VERSION_CODES.N)
private void requestBugReport() {
boolean startedSuccessfully = mDevicePolicyManager.requestBugreport(
mAdminComponentName);
if (!startedSuccessfully) {
Context context = getActivity();
Util.showNotification(context, R.string.bugreport_title,
context.getString(R.string.bugreport_failure_throttled),
Util.BUGREPORT_NOTIFICATION_ID);
}
}
@TargetApi(Build.VERSION_CODES.M)
private void setStatusBarDisabled(boolean disable) {
if (!mDevicePolicyManager.setStatusBarDisabled(mAdminComponentName, disable)) {
if (disable) {
showToast("Unable to disable status bar when lock password is set.");
}
}
}
/**
* Dispatches an intent to capture image or video.
*/
private void dispatchCaptureIntent(String action, int requestCode, Uri storageUri) {
final Intent captureIntent = new Intent(action);
if (captureIntent.resolveActivity(mPackageManager) != null) {
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, storageUri);
startActivityForResult(captureIntent, requestCode);
} else {
showToast(R.string.camera_app_not_found);
}
}
/**
* Creates a content uri to be used with the capture intent.
*/
private Uri getStorageUri(String fileName) {
final String filePath = getActivity().getFilesDir() + File.separator + "media"
+ File.separator + fileName;
final File file = new File(filePath);
// Create the folder if it doesn't exist.
file.getParentFile().mkdirs();
return FileProvider.getUriForFile(getActivity(),
"com.afwsamples.testdpc.fileprovider", file);
}
/**
* Shows a list of primary user apps in a dialog.
*
* @param dialogTitle the title to show for the dialog
* @param callback will be called with the list apps that the user has selected when he closes
* the dialog. The callback is not fired if the user cancels.
*/
private void showManageLockTaskListPrompt(int dialogTitle,
final ManageLockTaskListCallback callback) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> primaryUserAppList = mPackageManager
.queryIntentActivities(launcherIntent, 0);
if (primaryUserAppList.isEmpty()) {
showToast(R.string.no_primary_app_available);
} else {
Collections.sort(primaryUserAppList,
new ResolveInfo.DisplayNameComparator(mPackageManager));
final LockTaskAppInfoArrayAdapter appInfoArrayAdapter = new LockTaskAppInfoArrayAdapter(
getActivity(), R.id.pkg_name, primaryUserAppList);
ListView listView = new ListView(getActivity());
listView.setAdapter(appInfoArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
appInfoArrayAdapter.onItemClick(parent, view, position, id);
}
});
new AlertDialog.Builder(getActivity())
.setTitle(getString(dialogTitle))
.setView(listView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] lockTaskEnabledArray = appInfoArrayAdapter.getLockTaskList();
callback.onPositiveButtonClicked(lockTaskEnabledArray);
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
}
/**
* Shows a prompt to collect a package name and checks whether the lock task for the
* corresponding app is permitted or not.
*/
private void showCheckLockTaskPermittedPrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View view = getActivity().getLayoutInflater().inflate(R.layout.simple_edittext, null);
final EditText input = (EditText) view.findViewById(R.id.input);
input.setHint(getString(R.string.input_package_name_hints));
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.check_lock_task_permitted))
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String packageName = input.getText().toString();
boolean isLockTaskPermitted = mDevicePolicyManager
.isLockTaskPermitted(packageName);
showToast(isLockTaskPermitted
? R.string.check_lock_task_permitted_result_permitted
: R.string.check_lock_task_permitted_result_not_permitted);
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
/**
* Shows a prompt to ask for a password to reset to and to set whether this requires
* re-entry before any further changes and/or whether the password needs to be entered during
* boot to start the user.
*/
private void showResetPasswordPrompt() {
View dialogView = getActivity().getLayoutInflater().inflate(
R.layout.reset_password_dialog, null);
final EditText passwordView = (EditText) dialogView.findViewById(
R.id.password);
final CheckBox requireEntry = (CheckBox) dialogView.findViewById(
R.id.require_password_entry_checkbox);
final CheckBox requireOnBoot = (CheckBox) dialogView.findViewById(
R.id.require_password_on_boot_checkbox);
DialogInterface.OnClickListener resetListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
String password = passwordView.getText().toString();
if (TextUtils.isEmpty(password)) {
password = null;
}
int flags = 0;
flags |= requireEntry.isChecked() ?
DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY : 0;
flags |= requireOnBoot.isChecked() ?
DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT : 0;
boolean ok = false;
try {
ok = mDevicePolicyManager.resetPassword(password, flags);
} catch (IllegalArgumentException iae) {
// Bad password, eg. 2 characters where system minimum length is 4.
Log.w(TAG, "Failed to reset password", iae);
}
showToast(ok ? R.string.password_reset_success : R.string.password_reset_failed);
}
};
new AlertDialog.Builder(getActivity())
.setTitle(R.string.reset_password)
.setView(dialogView)
.setPositiveButton(android.R.string.ok, resetListener)
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Shows a prompt to ask for confirmation on wiping the data and also provide an option
* to set if external storage and factory reset protection data also needs to wiped.
*/
private void showWipeDataPrompt() {
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.wipe_data_dialog_prompt, null);
final CheckBox externalStorageCheckBox = (CheckBox) dialogView.findViewById(
R.id.external_storage_checkbox);
final CheckBox resetProtectionCheckBox = (CheckBox) dialogView.findViewById(
R.id.reset_protection_checkbox);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.wipe_data_title)
.setView(dialogView)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
int flags = 0;
flags |= (externalStorageCheckBox.isChecked() ?
DevicePolicyManager.WIPE_EXTERNAL_STORAGE : 0);
flags |= (resetProtectionCheckBox.isChecked() ?
DevicePolicyManager.WIPE_RESET_PROTECTION_DATA : 0);
mDevicePolicyManager.wipeData(flags);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Shows a prompt to ask for confirmation on removing device owner.
*/
private void showRemoveDeviceOwnerPrompt() {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.remove_device_owner_title)
.setMessage(R.string.remove_device_owner_confirmation)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mDevicePolicyManager.clearDeviceOwnerApp(mPackageName);
if (getActivity() != null && !getActivity().isFinishing()) {
showToast(R.string.device_owner_removed);
getActivity().finish();
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Shows a message box with the device wifi mac address.
*/
@TargetApi(Build.VERSION_CODES.N)
private void showWifiMacAddress() {
final String macAddress = mDevicePolicyManager.getWifiMacAddress(mAdminComponentName);
final String message = macAddress != null ? macAddress
: getResources().getString(R.string.show_wifi_mac_address_not_available_msg);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.show_wifi_mac_address_title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, null)
.show();
}
private void setPreferenceChangeListeners(String[] preferenceKeys) {
for (String key : preferenceKeys) {
findPreference(key).setOnPreferenceChangeListener(this);
}
}
/**
* Update the preference switch for {@link Settings.Global#STAY_ON_WHILE_PLUGGED_IN} setting.
*
* <p>
* If either one of the {@link BatteryManager#BATTERY_PLUGGED_AC},
* {@link BatteryManager#BATTERY_PLUGGED_USB}, {@link BatteryManager#BATTERY_PLUGGED_WIRELESS}
* values is set, we toggle the preference to true and update the setting value to
* {@link #BATTERY_PLUGGED_ANY}
* </p>
*/
private void updateStayOnWhilePluggedInPreference() {
if (!mStayOnWhilePluggedInSwitchPreference.isEnabled()) {
return;
}
boolean checked = false;
final int currentState = Settings.Global.getInt(getActivity().getContentResolver(),
Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
checked = (currentState &
(BatteryManager.BATTERY_PLUGGED_AC |
BatteryManager.BATTERY_PLUGGED_USB |
BatteryManager.BATTERY_PLUGGED_WIRELESS)) != 0;
mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
checked ? BATTERY_PLUGGED_ANY : DONT_STAY_ON);
mStayOnWhilePluggedInSwitchPreference.setChecked(checked);
}
/**
* Update the preference switch for {@link Settings.Secure#INSTALL_NON_MARKET_APPS} setting.
*
* <p>
* If the user restriction {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} is set, then
* we disable this preference.
* </p>
*/
public void updateInstallNonMarketAppsPreference() {
mInstallNonMarketAppsPreference.setEnabled(
mUserManager.hasUserRestriction(DISALLOW_INSTALL_UNKNOWN_SOURCES) ? false : true);
int isInstallNonMarketAppsAllowed = Settings.Secure.getInt(
getActivity().getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS, 0);
mInstallNonMarketAppsPreference.setChecked(
isInstallNonMarketAppsAllowed == 0 ? false : true);
}
/**
* Some functionality only works if this app is device owner. Disable their UIs to avoid
* confusion.
*/
private void disableIncompatibleManagementOptionsInCurrentProfile() {
boolean isProfileOwner = mDevicePolicyManager.isProfileOwnerApp(mPackageName);
boolean isDeviceOwner = mDevicePolicyManager.isDeviceOwnerApp(mPackageName);
int deviceOwnerStatusStringId = R.string.this_is_not_a_device_owner;
if (isProfileOwner) {
// Some of the management options can only be applied in a primary profile.
for (String preference : PRIMARY_USER_ONLY_PREFERENCES) {
findPreference(preference).setEnabled(false);
}
if (Util.isBeforeN()) {
for (String preference : PROFILE_OWNER_NYC_PLUS_PREFERENCES) {
findPreference(preference).setEnabled(false);
}
}
deviceOwnerStatusStringId = R.string.this_is_a_profile_owner;
} else if (isDeviceOwner) {
// If it's a device owner and running in the primary profile.
deviceOwnerStatusStringId = R.string.this_is_a_device_owner;
}
findPreference(DEVICE_OWNER_STATUS_KEY).setSummary(deviceOwnerStatusStringId);
if (!isDeviceOwner) {
findPreference(WIFI_CONFIG_LOCKDOWN_ENABLE_KEY).setEnabled(false);
}
// Disable managed profile specific options if we are not running in managed profile.
if (!Util.isManagedProfile(getActivity(), mAdminComponentName)) {
for (String managedProfileSpecificOption : MANAGED_PROFILE_SPECIFIC_OPTIONS) {
findPreference(managedProfileSpecificOption).setEnabled(false);
}
}
}
private void disableIncompatibleManagementOptionsByApiLevel() {
if (Util.isBeforeM()) {
// The following options depend on MNC APIs.
for (String preference : MNC_PLUS_PREFERENCES) {
findPreference(preference).setEnabled(false);
}
}
if (Util.isBeforeN()) {
for (String preference : NYC_PLUS_PREFERENCES) {
findPreference(preference).setEnabled(false);
}
}
}
/**
* Shows the default response for future runtime permission requests by applications, and lets
* the user change the default value.
*/
@TargetApi(Build.VERSION_CODES.M)
private void showSetPermissionPolicyDialog() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View setPermissionPolicyView = getActivity().getLayoutInflater().inflate(
R.layout.set_permission_policy, null);
final RadioGroup permissionGroup =
(RadioGroup) setPermissionPolicyView.findViewById(R.id.set_permission_group);
int permissionPolicy = mDevicePolicyManager.getPermissionPolicy(mAdminComponentName);
switch (permissionPolicy) {
case DevicePolicyManager.PERMISSION_POLICY_PROMPT:
((RadioButton) permissionGroup.findViewById(R.id.prompt)).toggle();
break;
case DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT:
((RadioButton) permissionGroup.findViewById(R.id.accept)).toggle();
break;
case DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY:
((RadioButton) permissionGroup.findViewById(R.id.deny)).toggle();
break;
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.set_default_permission_policy))
.setView(setPermissionPolicyView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int policy = 0;
int checked = permissionGroup.getCheckedRadioButtonId();
switch (checked) {
case (R.id.prompt):
policy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
break;
case (R.id.accept):
policy = DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT;
break;
case (R.id.deny):
policy = DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY;
break;
}
mDevicePolicyManager.setPermissionPolicy(mAdminComponentName, policy);
dialog.dismiss();
}
})
.show();
}
/**
* Shows a prompt that allows entering the account type for which account management should be
* disabled or enabled.
*/
private void showSetDisableAccountManagementPrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View view = LayoutInflater.from(getActivity()).inflate(R.layout.simple_edittext, null);
final EditText input = (EditText) view.findViewById(R.id.input);
input.setHint(R.string.account_type_hint);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.set_disable_account_management)
.setView(view)
.setPositiveButton(R.string.disable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String accountType = input.getText().toString();
setDisableAccountManagement(accountType, true);
}
})
.setNeutralButton(R.string.enable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String accountType = input.getText().toString();
setDisableAccountManagement(accountType, false);
}
})
.setNegativeButton(android.R.string.cancel, null /* Nothing to do */)
.show();
}
private void setDisableAccountManagement(String accountType, boolean disabled) {
if (!TextUtils.isEmpty(accountType)) {
mDevicePolicyManager.setAccountManagementDisabled(mAdminComponentName, accountType,
disabled);
showToast(disabled
? R.string.account_management_disabled
: R.string.account_management_enabled,
accountType);
return;
}
showToast(R.string.fail_to_set_account_management);
}
/**
* Shows a list of account types that is disabled for account management.
*/
private void showDisableAccountTypeList() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
String[] disabledAccountTypeList = mDevicePolicyManager
.getAccountTypesWithManagementDisabled();
Arrays.sort(disabledAccountTypeList, String.CASE_INSENSITIVE_ORDER);
if (disabledAccountTypeList == null || disabledAccountTypeList.length == 0) {
showToast(R.string.no_disabled_account);
} else {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.list_of_disabled_account_types)
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1,
disabledAccountTypeList), null)
.setPositiveButton(android.R.string.ok, null)
.show();
}
}
/**
* For user creation:
* Shows a prompt asking for the username of the new user and whether the setup wizard should
* be skipped.
*/
@TargetApi(Build.VERSION_CODES.N)
private void showCreateAndManageUserPrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
final View dialogView = getActivity().getLayoutInflater().inflate(
R.layout.create_and_manage_user_dialog_prompt, null);
final EditText userNameEditText = (EditText) dialogView.findViewById(R.id.user_name);
userNameEditText.setHint(R.string.enter_username_hint);
final CheckBox skipSetupWizardCheckBox = (CheckBox) dialogView.findViewById(
R.id.skip_setup_wizard_checkbox);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.create_and_manage_user)
.setView(dialogView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String name = userNameEditText.getText().toString();
if (!TextUtils.isEmpty(name)) {
int flags = skipSetupWizardCheckBox.isChecked()
? DevicePolicyManager.SKIP_SETUP_WIZARD : 0;
UserHandle userHandle = mDevicePolicyManager.createAndManageUser(
mAdminComponentName,
name,
mAdminComponentName,
null,
flags);
if (userHandle != null) {
long serialNumber =
mUserManager.getSerialNumberForUser(userHandle);
showToast(R.string.user_created, serialNumber);
return;
}
showToast(R.string.failed_to_create_user);
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* For user removal:
* Shows a prompt for a user serial number. The associated user will be removed.
*/
private void showRemoveUserPrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View view = LayoutInflater.from(getActivity()).inflate(R.layout.simple_edittext, null);
final EditText input = (EditText) view.findViewById(R.id.input);
input.setHint(R.string.enter_user_id);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.remove_user)
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
boolean success = false;
long serialNumber = -1;
try {
serialNumber = Long.parseLong(input.getText().toString());
UserHandle userHandle = mUserManager
.getUserForSerialNumber(serialNumber);
if (userHandle != null) {
success = mDevicePolicyManager
.removeUser(mAdminComponentName, userHandle);
}
} catch (NumberFormatException e) {
// Error message is printed in the next line.
}
showToast(success ? R.string.user_removed : R.string.failed_to_remove_user);
}
})
.show();
}
/**
* Asks for the package name whose uninstallation should be blocked / unblocked.
*/
private void showBlockUninstallationByPackageNamePrompt() {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
View view = LayoutInflater.from(activity).inflate(R.layout.simple_edittext, null);
final EditText input = (EditText) view.findViewById(R.id.input);
input.setHint(getString(R.string.input_package_name_hints));
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.block_uninstallation_title)
.setView(view)
.setPositiveButton(R.string.block, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String pkgName = input.getText().toString();
if (!TextUtils.isEmpty(pkgName)) {
mDevicePolicyManager.setUninstallBlocked(mAdminComponentName, pkgName,
true);
showToast(R.string.uninstallation_blocked, pkgName);
} else {
showToast(R.string.block_uninstallation_failed_invalid_pkgname);
}
}
})
.setNeutralButton(R.string.unblock, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String pkgName = input.getText().toString();
if (!TextUtils.isEmpty(pkgName)) {
mDevicePolicyManager.setUninstallBlocked(mAdminComponentName, pkgName,
false);
showToast(R.string.uninstallation_allowed, pkgName);
} else {
showToast(R.string.block_uninstallation_failed_invalid_pkgname);
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void reloadCameraDisableUi() {
boolean isCameraDisabled = mDevicePolicyManager.getCameraDisabled(mAdminComponentName);
mDisableCameraSwitchPreference.setChecked(isCameraDisabled);
}
@TargetApi(Build.VERSION_CODES.N)
private void reloadEnableProcessLoggingUi() {
if (mEnableProcessLoggingPreference.isEnabled()) {
boolean isProcessLoggingEnabled = mDevicePolicyManager.isSecurityLoggingEnabled(
mAdminComponentName);
mEnableProcessLoggingPreference.setChecked(isProcessLoggingEnabled);
findPreference(REQUEST_PROCESS_LOGS).setEnabled(isProcessLoggingEnabled);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void reloadScreenCaptureDisableUi() {
boolean isScreenCaptureDisabled = mDevicePolicyManager.getScreenCaptureDisabled(
mAdminComponentName);
mDisableScreenCaptureSwitchPreference.setChecked(isScreenCaptureDisabled);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void reloadSetAutoTimeRequiredUi() {
if (mDevicePolicyManager.isDeviceOwnerApp(mPackageName)) {
boolean isAutoTimeRequired = mDevicePolicyManager.getAutoTimeRequired();
mSetAutoTimeRequiredPreference.setChecked(isAutoTimeRequired);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void reloadMuteAudioUi() {
final boolean isAudioMuted = mDevicePolicyManager.isMasterVolumeMuted(mAdminComponentName);
mMuteAudioSwitchPreference.setChecked(isAudioMuted);
}
/**
* Shows a prompt to ask for package name which is used to enable a system app.
*/
private void showEnableSystemAppByPackageNamePrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
LinearLayout inputContainer = (LinearLayout) getActivity().getLayoutInflater()
.inflate(R.layout.simple_edittext, null);
final EditText editText = (EditText) inputContainer.findViewById(R.id.input);
editText.setHint(getString(R.string.enable_system_apps_by_package_name_hints));
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.enable_system_apps_title))
.setView(inputContainer)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String packageName = editText.getText().toString();
try {
mDevicePolicyManager.enableSystemApp(mAdminComponentName, packageName);
showToast(R.string.enable_system_apps_by_package_name_success_msg,
packageName);
} catch (IllegalArgumentException e) {
showToast(R.string.enable_system_apps_by_package_name_error);
} finally {
dialog.dismiss();
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Shows the file viewer for importing a certificate.
*/
private void showFileViewerForImportingCertificate(int requestCode) {
Intent certIntent = new Intent(Intent.ACTION_GET_CONTENT);
certIntent.setTypeAndNormalize("*/*");
try {
startActivityForResult(certIntent, requestCode);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "showFileViewerForImportingCertificate: ", e);
}
}
/**
* Imports a certificate to the managed profile. If the provided password failed to decrypt the
* given certificate, shows a try again prompt. Otherwise, shows a prompt for the certificate
* alias.
*
* @param intent Intent that contains the certificate data uri.
* @param password The password to decrypt the certificate.
*/
private void importKeyCertificateFromIntent(Intent intent, String password) {
importKeyCertificateFromIntent(intent, password, 0 /* first try */);
}
/**
* Imports a certificate to the managed profile. If the provided decryption password is
* incorrect, shows a try again prompt. Otherwise, shows a prompt for the certificate alias.
*
* @param intent Intent that contains the certificate data uri.
* @param password The password to decrypt the certificate.
* @param attempts The number of times user entered incorrect password.
*/
private void importKeyCertificateFromIntent(Intent intent, String password, int attempts) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
Uri data = null;
if (intent != null && (data = intent.getData()) != null) {
// If the password is null, try to decrypt the certificate with an empty password.
if (password == null) {
password = "";
}
try {
CertificateUtil.PKCS12ParseInfo parseInfo = CertificateUtil
.parsePKCS12Certificate(getActivity().getContentResolver(), data, password);
showPromptForKeyCertificateAlias(parseInfo.privateKey, parseInfo.certificate,
parseInfo.alias);
} catch (KeyStoreException | FileNotFoundException | CertificateException |
UnrecoverableKeyException | NoSuchAlgorithmException e) {
Log.e(TAG, "Unable to load key", e);
} catch (IOException e) {
showPromptForCertificatePassword(intent, ++attempts);
} catch (ClassCastException e) {
showToast(R.string.not_a_key_certificate);
}
}
}
/**
* Shows a prompt to ask for the certificate password. If the certificate password is correct,
* import the private key and certificate.
*
* @param intent Intent that contains the certificate data uri.
* @param attempts The number of times user entered incorrect password.
*/
private void showPromptForCertificatePassword(final Intent intent, final int attempts) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View passwordInputView = getActivity().getLayoutInflater()
.inflate(R.layout.certificate_password_prompt, null);
final EditText input = (EditText) passwordInputView.findViewById(R.id.password_input);
if (attempts > 1) {
passwordInputView.findViewById(R.id.incorrect_password).setVisibility(View.VISIBLE);
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.certificate_password_prompt_title))
.setView(passwordInputView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String userPassword = input.getText().toString();
importKeyCertificateFromIntent(intent, userPassword, attempts);
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
/**
* Shows a prompt to ask for the certificate alias. This alias will be imported together with
* the private key and certificate.
*
* @param key The private key of a certificate.
* @param certificate The certificate will be imported.
* @param alias A name that represents the certificate in the profile.
*/
private void showPromptForKeyCertificateAlias(final PrivateKey key,
final Certificate certificate, String alias) {
if (getActivity() == null || getActivity().isFinishing() || key == null
|| certificate == null) {
return;
}
View passwordInputView = getActivity().getLayoutInflater().inflate(
R.layout.certificate_alias_prompt, null);
final EditText input = (EditText) passwordInputView.findViewById(R.id.alias_input);
if (!TextUtils.isEmpty(alias)) {
input.setText(alias);
input.selectAll();
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.certificate_alias_prompt_title))
.setView(passwordInputView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String alias = input.getText().toString();
if (mDevicePolicyManager.installKeyPair(mAdminComponentName, key,
certificate, alias) == true) {
showToast(R.string.certificate_added, alias);
} else {
showToast(R.string.certificate_add_failed, alias);
}
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
/**
* Selects a private/public key pair to uninstall, using the system dialog to choose
* an alias.
*
* Once the alias is chosen and deleted, a {@link Toast} shows status- success or failure.
*/
@TargetApi(Build.VERSION_CODES.N)
private void choosePrivateKeyForRemoval() {
KeyChain.choosePrivateKeyAlias(getActivity(), new KeyChainAliasCallback() {
@Override
public void alias(String alias) {
if (alias == null) {
// No value was chosen.
return;
}
final boolean removed =
mDevicePolicyManager.removeKeyPair(mAdminComponentName, alias);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (removed) {
showToast(R.string.remove_keypair_successfully);
} else {
showToast(R.string.remove_keypair_fail);
}
}
});
}
}, /* keyTypes[] */ null, /* issuers[] */ null, /* uri */ null, /* alias */ null);
}
/**
* Imports a CA certificate from the given data URI.
*
* @param intent Intent that contains the CA data URI.
*/
private void importCaCertificateFromIntent(Intent intent) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
Uri data = null;
if (intent != null && (data = intent.getData()) != null) {
boolean isCaInstalled = false;
try {
InputStream certificateInputStream = getActivity().getContentResolver()
.openInputStream(data);
if (certificateInputStream != null) {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int len = 0;
while ((len = certificateInputStream.read(buffer)) > 0) {
byteBuffer.write(buffer, 0, len);
}
isCaInstalled = mDevicePolicyManager.installCaCert(mAdminComponentName,
byteBuffer.toByteArray());
}
} catch (IOException e) {
Log.e(TAG, "importCaCertificateFromIntent: ", e);
}
showToast(isCaInstalled ? R.string.install_ca_successfully : R.string.install_ca_fail);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case INSTALL_KEY_CERTIFICATE_REQUEST_CODE:
importKeyCertificateFromIntent(data, "");
break;
case INSTALL_CA_CERTIFICATE_REQUEST_CODE:
importCaCertificateFromIntent(data);
break;
case CAPTURE_IMAGE_REQUEST_CODE:
showFragment(MediaDisplayFragment.newInstance(
MediaDisplayFragment.REQUEST_DISPLAY_IMAGE, mImageUri));
break;
case CAPTURE_VIDEO_REQUEST_CODE:
showFragment(MediaDisplayFragment.newInstance(
MediaDisplayFragment.REQUEST_DISPLAY_VIDEO, mVideoUri));
break;
}
}
}
/**
* Shows a list of installed CA certificates.
*/
private void showCaCertificateList() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
// Avoid starting the same task twice.
if (mShowCaCertificateListTask != null && !mShowCaCertificateListTask.isCancelled()) {
mShowCaCertificateListTask.cancel(true);
}
mShowCaCertificateListTask = new ShowCaCertificateListTask();
mShowCaCertificateListTask.execute();
}
/**
* Displays an alert dialog that allows the user to select applications from all non-system
* applications installed on the current profile. After the user selects an app, this app can't
* be uninstallation.
*/
private void showBlockUninstallationPrompt() {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
List<ApplicationInfo> applicationInfoList
= mPackageManager.getInstalledApplications(0 /* No flag */);
List<ResolveInfo> resolveInfoList = new ArrayList<ResolveInfo>();
Collections.sort(applicationInfoList,
new ApplicationInfo.DisplayNameComparator(mPackageManager));
for (ApplicationInfo applicationInfo : applicationInfoList) {
// Ignore system apps because they can't be uninstalled.
if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.resolvePackageName = applicationInfo.packageName;
resolveInfoList.add(resolveInfo);
}
}
final BlockUninstallationInfoArrayAdapter blockUninstallationInfoArrayAdapter
= new BlockUninstallationInfoArrayAdapter(getActivity(), R.id.pkg_name,
resolveInfoList);
ListView listview = new ListView(getActivity());
listview.setAdapter(blockUninstallationInfoArrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
blockUninstallationInfoArrayAdapter.onItemClick(parent, view, pos, id);
}
});
new AlertDialog.Builder(getActivity())
.setTitle(R.string.block_uninstallation_title)
.setView(listview)
.setPositiveButton(R.string.close, null /* Nothing to do */)
.show();
}
/**
* Shows an alert dialog which displays a list of disabled system apps. Clicking an app in the
* dialog enables the app.
*/
private void showEnableSystemAppsPrompt() {
// Disabled system apps list = {All system apps} - {Enabled system apps}
final List<String> disabledSystemApps = new ArrayList<String>();
// This list contains both enabled and disabled apps.
List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(
PackageManager.GET_UNINSTALLED_PACKAGES);
Collections.sort(allApps, new ApplicationInfo.DisplayNameComparator(mPackageManager));
// This list contains all enabled apps.
List<ApplicationInfo> enabledApps =
mPackageManager.getInstalledApplications(0 /* Default flags */);
Set<String> enabledAppsPkgNames = new HashSet<String>();
for (ApplicationInfo applicationInfo : enabledApps) {
enabledAppsPkgNames.add(applicationInfo.packageName);
}
for (ApplicationInfo applicationInfo : allApps) {
// Interested in disabled system apps only.
if (!enabledAppsPkgNames.contains(applicationInfo.packageName)
&& (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
disabledSystemApps.add(applicationInfo.packageName);
}
}
if (disabledSystemApps.isEmpty()) {
showToast(R.string.no_disabled_system_apps);
} else {
AppInfoArrayAdapter appInfoArrayAdapter = new AppInfoArrayAdapter(getActivity(),
R.id.pkg_name, disabledSystemApps, true);
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.enable_system_apps_title))
.setAdapter(appInfoArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
String packageName = disabledSystemApps.get(position);
mDevicePolicyManager.enableSystemApp(mAdminComponentName, packageName);
showToast(R.string.enable_system_apps_by_package_name_success_msg,
packageName);
}
})
.show();
}
}
/**
* Shows an alert dialog which displays a list hidden / non-hidden apps. Clicking an app in the
* dialog enables the app.
*/
private void showHideAppsPrompt(final boolean showHiddenApps) {
final List<String> showApps = new ArrayList<> ();
if (showHiddenApps) {
// Find all hidden packages using the GET_UNINSTALLED_PACKAGES flag
for (ApplicationInfo applicationInfo : getAllInstalledApplicationsSorted()) {
if (mDevicePolicyManager.isApplicationHidden(mAdminComponentName,
applicationInfo.packageName)) {
showApps.add(applicationInfo.packageName);
}
}
} else {
// Find all non-hidden apps with a launcher icon
for (ResolveInfo res : getAllLauncherIntentResolversSorted()) {
if (!showApps.contains(res.activityInfo.packageName)
&& !mDevicePolicyManager.isApplicationHidden(mAdminComponentName,
res.activityInfo.packageName)) {
showApps.add(res.activityInfo.packageName);
}
}
}
if (showApps.isEmpty()) {
showToast(showHiddenApps ? R.string.unhide_apps_empty : R.string.hide_apps_empty);
} else {
AppInfoArrayAdapter appInfoArrayAdapter = new AppInfoArrayAdapter(getActivity(),
R.id.pkg_name, showApps, true);
final int dialogTitleResId;
final int successResId;
final int failureResId;
if (showHiddenApps) {
// showing a dialog to unhide an app
dialogTitleResId = R.string.unhide_apps_title;
successResId = R.string.unhide_apps_success;
failureResId = R.string.unhide_apps_failure;
} else {
// showing a dialog to hide an app
dialogTitleResId = R.string.hide_apps_title;
successResId = R.string.hide_apps_success;
failureResId = R.string.hide_apps_failure;
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(dialogTitleResId))
.setAdapter(appInfoArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
String packageName = showApps.get(position);
if (mDevicePolicyManager.setApplicationHidden(mAdminComponentName,
packageName, !showHiddenApps)) {
showToast(successResId, packageName);
} else {
showToast(getString(failureResId, packageName), Toast.LENGTH_LONG);
}
}
})
.show();
}
}
/**
* Shows an alert dialog which displays a list of suspended/non-suspended apps.
*/
@TargetApi(Build.VERSION_CODES.N)
private void showSuspendAppsPrompt(final boolean forUnsuspending) {
final List<String> showApps = new ArrayList<>();
if (forUnsuspending) {
// Find all suspended packages using the GET_UNINSTALLED_PACKAGES flag.
for (ApplicationInfo applicationInfo : getAllInstalledApplicationsSorted()) {
if (isPackageSuspended(applicationInfo.packageName)) {
showApps.add(applicationInfo.packageName);
}
}
} else {
// Find all non-suspended apps with a launcher icon.
for (ResolveInfo res : getAllLauncherIntentResolversSorted()) {
if (!showApps.contains(res.activityInfo.packageName)
&& !isPackageSuspended(res.activityInfo.packageName)) {
showApps.add(res.activityInfo.packageName);
}
}
}
if (showApps.isEmpty()) {
showToast(forUnsuspending
? R.string.unsuspend_apps_empty
: R.string.suspend_apps_empty);
} else {
AppInfoArrayAdapter appInfoArrayAdapter = new AppInfoArrayAdapter(getActivity(),
R.id.pkg_name, showApps, true);
final int dialogTitleResId;
final int successResId;
final int failureResId;
if (forUnsuspending) {
// Showing a dialog to unsuspend an app.
dialogTitleResId = R.string.unsuspend_apps_title;
successResId = R.string.unsuspend_apps_success;
failureResId = R.string.unsuspend_apps_failure;
} else {
// Showing a dialog to suspend an app.
dialogTitleResId = R.string.suspend_apps_title;
successResId = R.string.suspend_apps_success;
failureResId = R.string.suspend_apps_failure;
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(dialogTitleResId))
.setAdapter(appInfoArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
String packageName = showApps.get(position);
if (mDevicePolicyManager.setPackagesSuspended(mAdminComponentName,
new String[] {packageName}, !forUnsuspending).length == 0) {
showToast(successResId, packageName);
} else {
showToast(getString(failureResId, packageName), Toast.LENGTH_LONG);
}
}
})
.show();
}
}
@TargetApi(Build.VERSION_CODES.N)
private boolean isPackageSuspended(String packageName) {
try {
return mDevicePolicyManager.isPackageSuspended(mAdminComponentName, packageName);
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Unable check if package is suspended", e);
return false;
}
}
private List<ResolveInfo> getAllLauncherIntentResolversSorted() {
final Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> launcherIntentResolvers = mPackageManager
.queryIntentActivities(launcherIntent, 0);
Collections.sort(launcherIntentResolvers,
new ResolveInfo.DisplayNameComparator(mPackageManager));
return launcherIntentResolvers;
}
private List<ApplicationInfo> getAllInstalledApplicationsSorted() {
List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(
PackageManager.GET_UNINSTALLED_PACKAGES);
Collections.sort(allApps, new ApplicationInfo.DisplayNameComparator(mPackageManager));
return allApps;
}
private void showToast(int msgId, Object... args) {
showToast(getString(msgId, args));
}
private void showToast(String msg) {
showToast(msg, Toast.LENGTH_SHORT);
}
private void showToast(String msg, int duration) {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
Toast.makeText(activity, msg, duration).show();
}
/**
* Gets all the accessibility services. After all the accessibility services are retrieved, the
* result is displayed in a popup.
*/
private class GetAccessibilityServicesTask
extends GetAvailableComponentsTask<AccessibilityServiceInfo> {
private AccessibilityManager mAccessibilityManager;
public GetAccessibilityServicesTask() {
super(getActivity(), R.string.set_accessibility_services);
mAccessibilityManager = (AccessibilityManager) getActivity().getSystemService(
Context.ACCESSIBILITY_SERVICE);
}
@Override
protected List<AccessibilityServiceInfo> doInBackground(Void... voids) {
return mAccessibilityManager.getInstalledAccessibilityServiceList();
}
@Override
protected List<ResolveInfo> getResolveInfoListFromAvailableComponents(
List<AccessibilityServiceInfo> accessibilityServiceInfoList) {
HashSet<String> packageSet = new HashSet<>();
List<ResolveInfo> resolveInfoList = new ArrayList<>();
for (AccessibilityServiceInfo accessibilityServiceInfo: accessibilityServiceInfoList) {
ResolveInfo resolveInfo = accessibilityServiceInfo.getResolveInfo();
// Some apps may contain multiple accessibility services. Make sure that the package
// name is unique in the return list.
if (!packageSet.contains(resolveInfo.serviceInfo.packageName)) {
resolveInfoList.add(resolveInfo);
packageSet.add(resolveInfo.serviceInfo.packageName);
}
}
return resolveInfoList;
}
@Override
protected List<String> getPermittedComponentsList() {
return mDevicePolicyManager.getPermittedAccessibilityServices(mAdminComponentName);
}
@Override
protected void setPermittedComponentsList(List<String> permittedAccessibilityServices) {
boolean result = mDevicePolicyManager.setPermittedAccessibilityServices(
mAdminComponentName, permittedAccessibilityServices);
int successMsgId = (permittedAccessibilityServices == null)
? R.string.all_accessibility_services_enabled
: R.string.set_accessibility_services_successful;
showToast(result ? successMsgId : R.string.set_accessibility_services_fail);
}
}
/**
* Gets all the input methods and displays them in a prompt.
*/
private class GetInputMethodsTask extends GetAvailableComponentsTask<InputMethodInfo> {
private InputMethodManager mInputMethodManager;
public GetInputMethodsTask() {
super(getActivity(), R.string.set_input_methods);
mInputMethodManager = (InputMethodManager) getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
}
@Override
protected List<InputMethodInfo> doInBackground(Void... voids) {
return mInputMethodManager.getInputMethodList();
}
@Override
protected List<ResolveInfo> getResolveInfoListFromAvailableComponents(
List<InputMethodInfo> inputMethodsInfoList) {
List<ResolveInfo> inputMethodsResolveInfoList = new ArrayList<>();
for (InputMethodInfo inputMethodInfo: inputMethodsInfoList) {
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = inputMethodInfo.getServiceInfo();
resolveInfo.resolvePackageName = inputMethodInfo.getPackageName();
inputMethodsResolveInfoList.add(resolveInfo);
}
return inputMethodsResolveInfoList;
}
@Override
protected List<String> getPermittedComponentsList() {
return mDevicePolicyManager.getPermittedInputMethods(mAdminComponentName);
}
@Override
protected void setPermittedComponentsList(List<String> permittedInputMethods) {
boolean result = mDevicePolicyManager.setPermittedInputMethods(mAdminComponentName,
permittedInputMethods);
int successMsgId = (permittedInputMethods == null)
? R.string.all_input_methods_enabled
: R.string.set_input_methods_successful;
showToast(result ? successMsgId : R.string.set_input_methods_fail);
}
}
/**
* Gets all CA certificates and displays them in a prompt.
*/
private class ShowCaCertificateListTask extends AsyncTask<Void, Void, String[]> {
@Override
protected String[] doInBackground(Void... params) {
return getCaCertificateSubjectDnList();
}
@Override
protected void onPostExecute(String[] installedCaCertificateDnList) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
if (installedCaCertificateDnList == null) {
showToast(R.string.no_ca_certificate);
} else {
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.installed_ca_title))
.setItems(installedCaCertificateDnList, null)
.show();
}
}
private String[] getCaCertificateSubjectDnList() {
List<byte[]> installedCaCerts = mDevicePolicyManager.getInstalledCaCerts(
mAdminComponentName);
String[] caSubjectDnList = null;
if (installedCaCerts.size() > 0) {
caSubjectDnList = new String[installedCaCerts.size()];
int i = 0;
for (byte[] installedCaCert : installedCaCerts) {
try {
X509Certificate certificate = (X509Certificate) CertificateFactory
.getInstance(X509_CERT_TYPE).generateCertificate(
new ByteArrayInputStream(installedCaCert));
caSubjectDnList[i++] = certificate.getSubjectDN().getName();
} catch (CertificateException e) {
Log.e(TAG, "getCaCertificateSubjectDnList: ", e);
}
}
}
return caSubjectDnList;
}
}
private void showFragment(final Fragment fragment) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().addToBackStack(PolicyManagementFragment.class.getName())
.replace(R.id.container, fragment).commit();
}
private void showFragment(final Fragment fragment, String tag) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().addToBackStack(PolicyManagementFragment.class.getName())
.replace(R.id.container, fragment, tag).commit();
}
private void startKioskMode(String[] lockTaskArray) {
// start locked activity
Intent launchIntent = new Intent(getActivity(), KioskModeActivity.class);
launchIntent.putExtra(KioskModeActivity.LOCKED_APP_PACKAGE_LIST, lockTaskArray);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mPackageManager.setComponentEnabledSetting(
new ComponentName(mPackageName, KioskModeActivity.class.getName()),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
startActivity(launchIntent);
getActivity().finish();
}
private void showWifiConfigCreationDialog() {
WifiConfigCreationDialog dialog = WifiConfigCreationDialog.newInstance();
dialog.show(getFragmentManager(), TAG_WIFI_CONFIG_CREATION);
}
private void showEapTlsWifiConfigCreationDialog() {
DialogFragment fragment = WifiEapTlsCreateDialogFragment.newInstance(null);
fragment.show(getFragmentManager(), WifiEapTlsCreateDialogFragment.class.getName());
}
@TargetApi(Build.VERSION_CODES.N)
private void reboot() {
if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
showToast(R.string.reboot_error_msg);
return;
}
mDevicePolicyManager.reboot(mAdminComponentName);
}
abstract class ManageLockTaskListCallback {
public abstract void onPositiveButtonClicked(String[] lockTaskArray);
}
}
| app/src/main/java/com/afwsamples/testdpc/policy/PolicyManagementFragment.java | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.afwsamples.testdpc.policy;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.admin.DevicePolicyManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.MediaStore;
import android.provider.Settings;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.support.v14.preference.SwitchPreference;
import android.support.v4.content.FileProvider;
import android.support.v7.preference.EditTextPreference;
import android.support.v7.preference.Preference;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.afwsamples.testdpc.DeviceAdminReceiver;
import com.afwsamples.testdpc.R;
import com.afwsamples.testdpc.common.AppInfoArrayAdapter;
import com.afwsamples.testdpc.common.CertificateUtil;
import com.afwsamples.testdpc.common.MediaDisplayFragment;
import com.afwsamples.testdpc.common.BaseSearchablePolicyPreferenceFragment;
import com.afwsamples.testdpc.common.Util;
import com.afwsamples.testdpc.policy.blockuninstallation.BlockUninstallationInfoArrayAdapter;
import com.afwsamples.testdpc.policy.certificate.DelegatedCertInstallerFragment;
import com.afwsamples.testdpc.policy.keyguard.LockScreenPolicyFragment;
import com.afwsamples.testdpc.policy.keyguard.PasswordConstraintsFragment;
import com.afwsamples.testdpc.policy.locktask.KioskModeActivity;
import com.afwsamples.testdpc.policy.locktask.LockTaskAppInfoArrayAdapter;
import com.afwsamples.testdpc.policy.networking.AlwaysOnVpnFragment;
import com.afwsamples.testdpc.policy.networking.NetworkUsageStatsFragment;
import com.afwsamples.testdpc.policy.systemupdatepolicy.SystemUpdatePolicyFragment;
import com.afwsamples.testdpc.policy.wifimanagement.WifiConfigCreationDialog;
import com.afwsamples.testdpc.policy.wifimanagement.WifiEapTlsCreateDialogFragment;
import com.afwsamples.testdpc.policy.wifimanagement.WifiModificationFragment;
import com.afwsamples.testdpc.profilepolicy.ProfilePolicyManagementFragment;
import com.afwsamples.testdpc.profilepolicy.addsystemapps.EnableSystemAppsByIntentFragment;
import com.afwsamples.testdpc.profilepolicy.apprestrictions.AppRestrictionsManagingPackageFragment;
import com.afwsamples.testdpc.profilepolicy.apprestrictions.ManageAppRestrictionsFragment;
import com.afwsamples.testdpc.profilepolicy.permission.ManageAppPermissionsFragment;
import com.afwsamples.testdpc.safetynet.SafetyNetFragment;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static android.os.UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
/**
* Provides several device management functions.
*
* These include:
* <ul>
* <li> {@link DevicePolicyManager#setLockTaskPackages(android.content.ComponentName, String[])} </li>
* <li> {@link DevicePolicyManager#isLockTaskPermitted(String)} </li>
* <li> {@link UserManager#DISALLOW_DEBUGGING_FEATURES} </li>
* <li> {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} </li>
* <li> {@link UserManager#DISALLOW_REMOVE_USER} </li>
* <li> {@link UserManager#DISALLOW_ADD_USER} </li>
* <li> {@link UserManager#DISALLOW_FACTORY_RESET} </li>
* <li> {@link UserManager#DISALLOW_CONFIG_CREDENTIALS} </li>
* <li> {@link UserManager#DISALLOW_SHARE_LOCATION} </li>
* <li> {@link UserManager#DISALLOW_CONFIG_TETHERING} </li>
* <li> {@link UserManager#DISALLOW_ADJUST_VOLUME} </li>
* <li> {@link UserManager#DISALLOW_UNMUTE_MICROPHONE} </li>
* <li> {@link UserManager#DISALLOW_MODIFY_ACCOUNTS} </li>
* <li> {@link UserManager#DISALLOW_SAFE_BOOT} </li>
* <li> {@link UserManager#DISALLOW_OUTGOING_BEAM}} </li>
* <li> {@link UserManager#DISALLOW_CREATE_WINDOWS}} </li>
* <li> {@link DevicePolicyManager#clearDeviceOwnerApp(String)} </li>
* <li> {@link DevicePolicyManager#getPermittedAccessibilityServices(android.content.ComponentName)}
* </li>
* <li> {@link DevicePolicyManager#getPermittedInputMethods(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#setAccountManagementDisabled(android.content.ComponentName,
* String, boolean)} </li>
* <li> {@link DevicePolicyManager#getAccountTypesWithManagementDisabled()} </li>
* <li> {@link DevicePolicyManager#removeUser(android.content.ComponentName,
android.os.UserHandle)} </li>
* <li> {@link DevicePolicyManager#setUninstallBlocked(android.content.ComponentName, String,
* boolean)} </li>
* <li> {@link DevicePolicyManager#isUninstallBlocked(android.content.ComponentName, String)} </li>
* <li> {@link DevicePolicyManager#setCameraDisabled(android.content.ComponentName, boolean)} </li>
* <li> {@link DevicePolicyManager#getCameraDisabled(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#enableSystemApp(android.content.ComponentName,
* android.content.Intent)} </li>
* <li> {@link DevicePolicyManager#enableSystemApp(android.content.ComponentName, String)} </li>
* <li> {@link DevicePolicyManager#setApplicationRestrictions(android.content.ComponentName, String,
* android.os.Bundle)} </li>
* <li> {@link DevicePolicyManager#installKeyPair(android.content.ComponentName,
* java.security.PrivateKey, java.security.cert.Certificate, String)} </li>
* <li> {@link DevicePolicyManager#removeKeyPair(android.content.ComponentName, String)} </li>
* <li> {@link DevicePolicyManager#installCaCert(android.content.ComponentName, byte[])} </li>
* <li> {@link DevicePolicyManager#uninstallAllUserCaCerts(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#getInstalledCaCerts(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#setStatusBarDisabled(ComponentName, boolean)} </li>
* <li> {@link DevicePolicyManager#setKeyguardDisabled(ComponentName, boolean)} </li>
* <li> {@link DevicePolicyManager#setPermissionPolicy(android.content.ComponentName, int)} </li>
* <li> {@link DevicePolicyManager#getPermissionPolicy(android.content.ComponentName)} </li>
* <li> {@link DevicePolicyManager#setPermissionGrantState(ComponentName, String, String, int) (
* android.content.ComponentName, String, String, boolean)} </li>
* <li> {@link DevicePolicyManager#setScreenCaptureDisabled(ComponentName, boolean)} </li>
* <li> {@link DevicePolicyManager#getScreenCaptureDisabled(ComponentName)} </li>
* <li> {@link DevicePolicyManager#setMaximumTimeToLock(ComponentName, long)} </li>
* <li> {@link DevicePolicyManager#setMaximumFailedPasswordsForWipe(ComponentName, int)} </li>
* <li> {@link DevicePolicyManager#setApplicationHidden(ComponentName, String, boolean)} </li>
* <li> {@link DevicePolicyManager#setShortSupportMessage(ComponentName, String)} </li>
* <li> {@link DevicePolicyManager#setLongSupportMessage(ComponentName, String)} </li>
* <li> {@link UserManager#DISALLOW_CONFIG_WIFI} </li>
* </ul>
*/
public class PolicyManagementFragment extends BaseSearchablePolicyPreferenceFragment implements
Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
// Tag for creating this fragment. This tag can be used to retrieve this fragment.
public static final String FRAGMENT_TAG = "PolicyManagementFragment";
private static final int INSTALL_KEY_CERTIFICATE_REQUEST_CODE = 7689;
private static final int INSTALL_CA_CERTIFICATE_REQUEST_CODE = 7690;
private static final int CAPTURE_IMAGE_REQUEST_CODE = 7691;
private static final int CAPTURE_VIDEO_REQUEST_CODE = 7692;
public static final int DEFAULT_BUFFER_SIZE = 4096;
public static final String X509_CERT_TYPE = "X.509";
public static final String TAG = "PolicyManagement";
public static final String OVERRIDE_KEY_SELECTION_KEY = "override_key_selection";
private static final String APP_RESTRICTIONS_MANAGING_PACKAGE_KEY
= "app_restrictions_managing_package";
private static final String BLOCK_UNINSTALLATION_BY_PKG_KEY = "block_uninstallation_by_pkg";
private static final String BLOCK_UNINSTALLATION_LIST_KEY = "block_uninstallation_list";
private static final String CAPTURE_IMAGE_KEY = "capture_image";
private static final String CAPTURE_VIDEO_KEY = "capture_video";
private static final String CHECK_LOCK_TASK_PERMITTED_KEY = "check_lock_task_permitted";
private static final String CREATE_AND_MANAGE_USER_KEY = "create_and_manage_user";
private static final String DELEGATED_CERT_INSTALLER_KEY = "manage_cert_installer";
private static final String DEVICE_OWNER_STATUS_KEY = "device_owner_status";
private static final String DISABLE_CAMERA_KEY = "disable_camera";
private static final String DISABLE_KEYGUARD = "disable_keyguard";
private static final String DISABLE_SCREEN_CAPTURE_KEY = "disable_screen_capture";
private static final String DISABLE_STATUS_BAR = "disable_status_bar";
private static final String ENABLE_PROCESS_LOGGING = "enable_process_logging";
private static final String ENABLE_SYSTEM_APPS_BY_INTENT_KEY = "enable_system_apps_by_intent";
private static final String ENABLE_SYSTEM_APPS_BY_PACKAGE_NAME_KEY
= "enable_system_apps_by_package_name";
private static final String ENABLE_SYSTEM_APPS_KEY = "enable_system_apps";
private static final String GET_CA_CERTIFICATES_KEY = "get_ca_certificates";
private static final String GET_DISABLE_ACCOUNT_MANAGEMENT_KEY
= "get_disable_account_management";
private static final String HIDE_APPS_KEY = "hide_apps";
private static final String INSTALL_CA_CERTIFICATE_KEY = "install_ca_certificate";
private static final String INSTALL_KEY_CERTIFICATE_KEY = "install_key_certificate";
private static final String INSTALL_NONMARKET_APPS_KEY
= "install_nonmarket_apps";
private static final String LOCK_SCREEN_POLICY_KEY = "lock_screen_policy";
private static final String MANAGE_APP_PERMISSIONS_KEY = "manage_app_permissions";
private static final String MANAGE_APP_RESTRICTIONS_KEY = "manage_app_restrictions";
private static final String MANAGED_PROFILE_SPECIFIC_POLICIES_KEY = "managed_profile_policies";
private static final String MANAGE_LOCK_TASK_LIST_KEY = "manage_lock_task";
private static final String MUTE_AUDIO_KEY = "mute_audio";
private static final String NETWORK_STATS_KEY = "network_stats";
private static final String PASSWORD_CONSTRAINTS_KEY = "password_constraints";
private static final String REBOOT_KEY = "reboot";
private static final String REENABLE_KEYGUARD = "reenable_keyguard";
private static final String REENABLE_STATUS_BAR = "reenable_status_bar";
private static final String REMOVE_ALL_CERTIFICATES_KEY = "remove_all_ca_certificates";
private static final String REMOVE_DEVICE_OWNER_KEY = "remove_device_owner";
private static final String REMOVE_KEY_CERTIFICATE_KEY = "remove_key_certificate";
private static final String REMOVE_USER_KEY = "remove_user";
private static final String REQUEST_BUGREPORT_KEY = "request_bugreport";
private static final String REQUEST_PROCESS_LOGS = "request_process_logs";
private static final String RESET_PASSWORD_KEY = "reset_password";
private static final String LOCK_NOW_KEY = "lock_now";
private static final String SET_ACCESSIBILITY_SERVICES_KEY = "set_accessibility_services";
private static final String SET_ALWAYS_ON_VPN_KEY = "set_always_on_vpn";
private static final String SET_AUTO_TIME_REQUIRED_KEY = "set_auto_time_required";
private static final String SET_DISABLE_ACCOUNT_MANAGEMENT_KEY
= "set_disable_account_management";
private static final String SET_INPUT_METHODS_KEY = "set_input_methods";
private static final String SET_LONG_SUPPORT_MESSAGE_KEY = "set_long_support_message";
private static final String SET_PERMISSION_POLICY_KEY = "set_permission_policy";
private static final String SET_SHORT_SUPPORT_MESSAGE_KEY = "set_short_support_message";
private static final String SET_USER_RESTRICTIONS_KEY = "set_user_restrictions";
private static final String SHOW_WIFI_MAC_ADDRESS_KEY = "show_wifi_mac_address";
private static final String START_KIOSK_MODE = "start_kiosk_mode";
private static final String START_LOCK_TASK = "start_lock_task";
private static final String STAY_ON_WHILE_PLUGGED_IN = "stay_on_while_plugged_in";
private static final String STOP_LOCK_TASK = "stop_lock_task";
private static final String SUSPEND_APPS_KEY = "suspend_apps";
private static final String SYSTEM_UPDATE_POLICY_KEY = "system_update_policy";
private static final String UNHIDE_APPS_KEY = "unhide_apps";
private static final String UNSUSPEND_APPS_KEY = "unsuspend_apps";
private static final String WIPE_DATA_KEY = "wipe_data";
private static final String CREATE_WIFI_CONFIGURATION_KEY = "create_wifi_configuration";
private static final String CREATE_EAP_TLS_WIFI_CONFIGURATION_KEY
= "create_eap_tls_wifi_configuration";
private static final String WIFI_CONFIG_LOCKDOWN_ENABLE_KEY = "enable_wifi_config_lockdown";
private static final String MODIFY_WIFI_CONFIGURATION_KEY = "modify_wifi_configuration";
private static final String TAG_WIFI_CONFIG_CREATION = "wifi_config_creation";
private static final String WIFI_CONFIG_LOCKDOWN_ON = "1";
private static final String WIFI_CONFIG_LOCKDOWN_OFF = "0";
private static final String SAFETYNET_ATTEST = "safetynet_attest";
private static final String BATTERY_PLUGGED_ANY = Integer.toString(
BatteryManager.BATTERY_PLUGGED_AC |
BatteryManager.BATTERY_PLUGGED_USB |
BatteryManager.BATTERY_PLUGGED_WIRELESS);
private static final String DONT_STAY_ON = "0";
private static final String[] PRIMARY_USER_ONLY_PREFERENCES = {
WIPE_DATA_KEY, REMOVE_DEVICE_OWNER_KEY, REMOVE_USER_KEY,
MANAGE_LOCK_TASK_LIST_KEY, CHECK_LOCK_TASK_PERMITTED_KEY, START_LOCK_TASK,
STOP_LOCK_TASK, DISABLE_STATUS_BAR, REENABLE_STATUS_BAR, DISABLE_KEYGUARD,
REENABLE_KEYGUARD, START_KIOSK_MODE, SYSTEM_UPDATE_POLICY_KEY, STAY_ON_WHILE_PLUGGED_IN,
SHOW_WIFI_MAC_ADDRESS_KEY, REBOOT_KEY, REQUEST_BUGREPORT_KEY, ENABLE_PROCESS_LOGGING,
REQUEST_PROCESS_LOGS, SET_AUTO_TIME_REQUIRED_KEY, CREATE_AND_MANAGE_USER_KEY
};
private static String[] MNC_PLUS_PREFERENCES = {
OVERRIDE_KEY_SELECTION_KEY, START_LOCK_TASK, STOP_LOCK_TASK, SYSTEM_UPDATE_POLICY_KEY,
NETWORK_STATS_KEY, DELEGATED_CERT_INSTALLER_KEY, DISABLE_STATUS_BAR,
REENABLE_STATUS_BAR, DISABLE_KEYGUARD, REENABLE_KEYGUARD, START_KIOSK_MODE,
SET_PERMISSION_POLICY_KEY, MANAGE_APP_PERMISSIONS_KEY,STAY_ON_WHILE_PLUGGED_IN,
WIFI_CONFIG_LOCKDOWN_ENABLE_KEY
};
private static String[] NYC_PLUS_PREFERENCES = {
APP_RESTRICTIONS_MANAGING_PACKAGE_KEY, REBOOT_KEY, REMOVE_KEY_CERTIFICATE_KEY,
SET_ALWAYS_ON_VPN_KEY, SHOW_WIFI_MAC_ADDRESS_KEY, SUSPEND_APPS_KEY, UNSUSPEND_APPS_KEY,
SET_SHORT_SUPPORT_MESSAGE_KEY, SET_LONG_SUPPORT_MESSAGE_KEY, REQUEST_BUGREPORT_KEY,
ENABLE_PROCESS_LOGGING, REQUEST_PROCESS_LOGS, CREATE_AND_MANAGE_USER_KEY
};
/**
* Preferences that are allowed only in NYC+ if it is profile owner. This does not restrict
* device owner.
*/
private static String[] PROFILE_OWNER_NYC_PLUS_PREFERENCES = {
RESET_PASSWORD_KEY
};
private static final String[] MANAGED_PROFILE_SPECIFIC_OPTIONS = {
MANAGED_PROFILE_SPECIFIC_POLICIES_KEY
};
private DevicePolicyManager mDevicePolicyManager;
private PackageManager mPackageManager;
private String mPackageName;
private ComponentName mAdminComponentName;
private UserManager mUserManager;
private TelephonyManager mTelephonyManager;
private SwitchPreference mDisableCameraSwitchPreference;
private SwitchPreference mDisableScreenCaptureSwitchPreference;
private SwitchPreference mMuteAudioSwitchPreference;
private SwitchPreference mStayOnWhilePluggedInSwitchPreference;
private SwitchPreference mInstallNonMarketAppsPreference;
private SwitchPreference mEnableProcessLoggingPreference;
private SwitchPreference mSetAutoTimeRequiredPreference;
private GetAccessibilityServicesTask mGetAccessibilityServicesTask = null;
private GetInputMethodsTask mGetInputMethodsTask = null;
private ShowCaCertificateListTask mShowCaCertificateListTask = null;
private Uri mImageUri;
private Uri mVideoUri;
@Override
public void onCreate(Bundle savedInstanceState) {
mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity());
mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(
Context.DEVICE_POLICY_SERVICE);
mUserManager = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
mTelephonyManager = (TelephonyManager) getActivity()
.getSystemService(Context.TELEPHONY_SERVICE);
mPackageManager = getActivity().getPackageManager();
mPackageName = getActivity().getPackageName();
mImageUri = getStorageUri("image.jpg");
mVideoUri = getStorageUri("video.mp4");
super.onCreate(savedInstanceState);
}
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(getPreferenceXml());
EditTextPreference overrideKeySelectionPreference =
(EditTextPreference) findPreference(OVERRIDE_KEY_SELECTION_KEY);
overrideKeySelectionPreference.setOnPreferenceChangeListener(this);
overrideKeySelectionPreference.setSummary(overrideKeySelectionPreference.getText());
findPreference(MANAGE_LOCK_TASK_LIST_KEY).setOnPreferenceClickListener(this);
findPreference(CHECK_LOCK_TASK_PERMITTED_KEY).setOnPreferenceClickListener(this);
findPreference(START_LOCK_TASK).setOnPreferenceClickListener(this);
findPreference(STOP_LOCK_TASK).setOnPreferenceClickListener(this);
findPreference(CREATE_AND_MANAGE_USER_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_USER_KEY).setOnPreferenceClickListener(this);
mDisableCameraSwitchPreference = (SwitchPreference) findPreference(DISABLE_CAMERA_KEY);
findPreference(CAPTURE_IMAGE_KEY).setOnPreferenceClickListener(this);
findPreference(CAPTURE_VIDEO_KEY).setOnPreferenceClickListener(this);
mDisableCameraSwitchPreference.setOnPreferenceChangeListener(this);
mDisableScreenCaptureSwitchPreference = (SwitchPreference) findPreference(
DISABLE_SCREEN_CAPTURE_KEY);
mDisableScreenCaptureSwitchPreference.setOnPreferenceChangeListener(this);
mMuteAudioSwitchPreference = (SwitchPreference) findPreference(
MUTE_AUDIO_KEY);
mMuteAudioSwitchPreference.setOnPreferenceChangeListener(this);
findPreference(LOCK_SCREEN_POLICY_KEY).setOnPreferenceClickListener(this);
findPreference(PASSWORD_CONSTRAINTS_KEY).setOnPreferenceClickListener(this);
findPreference(RESET_PASSWORD_KEY).setOnPreferenceClickListener(this);
findPreference(LOCK_NOW_KEY).setOnPreferenceClickListener(this);
findPreference(SYSTEM_UPDATE_POLICY_KEY).setOnPreferenceClickListener(this);
findPreference(SET_ALWAYS_ON_VPN_KEY).setOnPreferenceClickListener(this);
findPreference(NETWORK_STATS_KEY).setOnPreferenceClickListener(this);
findPreference(DELEGATED_CERT_INSTALLER_KEY).setOnPreferenceClickListener(this);
findPreference(DISABLE_STATUS_BAR).setOnPreferenceClickListener(this);
findPreference(REENABLE_STATUS_BAR).setOnPreferenceClickListener(this);
findPreference(DISABLE_KEYGUARD).setOnPreferenceClickListener(this);
findPreference(REENABLE_KEYGUARD).setOnPreferenceClickListener(this);
findPreference(START_KIOSK_MODE).setOnPreferenceClickListener(this);
mStayOnWhilePluggedInSwitchPreference = (SwitchPreference) findPreference(
STAY_ON_WHILE_PLUGGED_IN);
mStayOnWhilePluggedInSwitchPreference.setOnPreferenceChangeListener(this);
findPreference(WIPE_DATA_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_DEVICE_OWNER_KEY).setOnPreferenceClickListener(this);
findPreference(REQUEST_BUGREPORT_KEY).setOnPreferenceClickListener(this);
mEnableProcessLoggingPreference = (SwitchPreference) findPreference(
ENABLE_PROCESS_LOGGING);
mEnableProcessLoggingPreference.setOnPreferenceChangeListener(this);
findPreference(REQUEST_PROCESS_LOGS).setOnPreferenceClickListener(this);
findPreference(SET_ACCESSIBILITY_SERVICES_KEY).setOnPreferenceClickListener(this);
findPreference(SET_INPUT_METHODS_KEY).setOnPreferenceClickListener(this);
findPreference(SET_DISABLE_ACCOUNT_MANAGEMENT_KEY).setOnPreferenceClickListener(this);
findPreference(GET_DISABLE_ACCOUNT_MANAGEMENT_KEY).setOnPreferenceClickListener(this);
findPreference(BLOCK_UNINSTALLATION_BY_PKG_KEY).setOnPreferenceClickListener(this);
findPreference(BLOCK_UNINSTALLATION_LIST_KEY).setOnPreferenceClickListener(this);
findPreference(ENABLE_SYSTEM_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(ENABLE_SYSTEM_APPS_BY_PACKAGE_NAME_KEY).setOnPreferenceClickListener(this);
findPreference(ENABLE_SYSTEM_APPS_BY_INTENT_KEY).setOnPreferenceClickListener(this);
findPreference(HIDE_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(UNHIDE_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(SUSPEND_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(UNSUSPEND_APPS_KEY).setOnPreferenceClickListener(this);
findPreference(MANAGE_APP_RESTRICTIONS_KEY).setOnPreferenceClickListener(this);
findPreference(APP_RESTRICTIONS_MANAGING_PACKAGE_KEY).setOnPreferenceClickListener(this);
findPreference(INSTALL_KEY_CERTIFICATE_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_KEY_CERTIFICATE_KEY).setOnPreferenceClickListener(this);
findPreference(INSTALL_CA_CERTIFICATE_KEY).setOnPreferenceClickListener(this);
findPreference(GET_CA_CERTIFICATES_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_ALL_CERTIFICATES_KEY).setOnPreferenceClickListener(this);
findPreference(MANAGED_PROFILE_SPECIFIC_POLICIES_KEY).setOnPreferenceClickListener(this);
findPreference(SET_PERMISSION_POLICY_KEY).setOnPreferenceClickListener(this);
findPreference(MANAGE_APP_PERMISSIONS_KEY).setOnPreferenceClickListener(this);
findPreference(CREATE_WIFI_CONFIGURATION_KEY).setOnPreferenceClickListener(this);
findPreference(CREATE_EAP_TLS_WIFI_CONFIGURATION_KEY).setOnPreferenceClickListener(this);
findPreference(WIFI_CONFIG_LOCKDOWN_ENABLE_KEY).setOnPreferenceChangeListener(this);
findPreference(MODIFY_WIFI_CONFIGURATION_KEY).setOnPreferenceClickListener(this);
findPreference(SHOW_WIFI_MAC_ADDRESS_KEY).setOnPreferenceClickListener(this);
mInstallNonMarketAppsPreference = (SwitchPreference) findPreference(
INSTALL_NONMARKET_APPS_KEY);
mInstallNonMarketAppsPreference.setOnPreferenceChangeListener(this);
findPreference(SET_USER_RESTRICTIONS_KEY).setOnPreferenceClickListener(this);
findPreference(REBOOT_KEY).setOnPreferenceClickListener(this);
findPreference(SET_SHORT_SUPPORT_MESSAGE_KEY).setOnPreferenceClickListener(this);
findPreference(SET_LONG_SUPPORT_MESSAGE_KEY).setOnPreferenceClickListener(this);
findPreference(SAFETYNET_ATTEST).setOnPreferenceClickListener(this);
mSetAutoTimeRequiredPreference = (SwitchPreference) findPreference(
SET_AUTO_TIME_REQUIRED_KEY);
mSetAutoTimeRequiredPreference.setOnPreferenceChangeListener(this);
disableIncompatibleManagementOptionsInCurrentProfile();
disableIncompatibleManagementOptionsByApiLevel();
reloadCameraDisableUi();
reloadScreenCaptureDisableUi();
reloadMuteAudioUi();
reloadEnableProcessLoggingUi();
reloadSetAutoTimeRequiredUi();
}
@Override
public int getPreferenceXml() {
return R.xml.device_policy_header;
}
@Override
public boolean isAvailable(Context context) {
DevicePolicyManager dpm =
(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
String packageName = context.getPackageName();
return dpm.isProfileOwnerApp(packageName) || dpm.isDeviceOwnerApp(packageName);
}
@Override
public void onResume() {
super.onResume();
getActivity().getActionBar().setTitle(R.string.policies_management);
if (!isAvailable(getActivity())) {
showToast(R.string.this_is_not_a_device_owner);
getActivity().finish();
}
// The settings might get changed outside the device policy app,
// so, we need to make sure the preference gets updated accordingly.
updateStayOnWhilePluggedInPreference();
updateInstallNonMarketAppsPreference();
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
switch (key) {
case MANAGE_LOCK_TASK_LIST_KEY:
showManageLockTaskListPrompt(R.string.lock_task_title,
new ManageLockTaskListCallback() {
@Override
public void onPositiveButtonClicked(String[] lockTaskArray) {
mDevicePolicyManager.setLockTaskPackages(
DeviceAdminReceiver.getComponentName(getActivity()),
lockTaskArray);
}
}
);
return true;
case CHECK_LOCK_TASK_PERMITTED_KEY:
showCheckLockTaskPermittedPrompt();
return true;
case RESET_PASSWORD_KEY:
showResetPasswordPrompt();
return false;
case LOCK_NOW_KEY:
mDevicePolicyManager.lockNow();
return true;
case START_LOCK_TASK:
getActivity().startLockTask();
return true;
case STOP_LOCK_TASK:
try {
getActivity().stopLockTask();
} catch (IllegalStateException e) {
// no lock task present, ignore
}
return true;
case WIPE_DATA_KEY:
showWipeDataPrompt();
return true;
case REMOVE_DEVICE_OWNER_KEY:
showRemoveDeviceOwnerPrompt();
return true;
case REQUEST_BUGREPORT_KEY:
requestBugReport();
return true;
case REQUEST_PROCESS_LOGS:
showFragment(new ProcessLogsFragment());
return true;
case SET_ACCESSIBILITY_SERVICES_KEY:
// Avoid starting the same task twice.
if (mGetAccessibilityServicesTask != null && !mGetAccessibilityServicesTask
.isCancelled()) {
mGetAccessibilityServicesTask.cancel(true);
}
mGetAccessibilityServicesTask = new GetAccessibilityServicesTask();
mGetAccessibilityServicesTask.execute();
return true;
case SET_INPUT_METHODS_KEY:
// Avoid starting the same task twice.
if (mGetInputMethodsTask != null && !mGetInputMethodsTask.isCancelled()) {
mGetInputMethodsTask.cancel(true);
}
mGetInputMethodsTask = new GetInputMethodsTask();
mGetInputMethodsTask.execute();
return true;
case SET_DISABLE_ACCOUNT_MANAGEMENT_KEY:
showSetDisableAccountManagementPrompt();
return true;
case GET_DISABLE_ACCOUNT_MANAGEMENT_KEY:
showDisableAccountTypeList();
return true;
case CREATE_AND_MANAGE_USER_KEY:
showCreateAndManageUserPrompt();
return true;
case REMOVE_USER_KEY:
showRemoveUserPrompt();
return true;
case BLOCK_UNINSTALLATION_BY_PKG_KEY:
showBlockUninstallationByPackageNamePrompt();
return true;
case BLOCK_UNINSTALLATION_LIST_KEY:
showBlockUninstallationPrompt();
return true;
case ENABLE_SYSTEM_APPS_KEY:
showEnableSystemAppsPrompt();
return true;
case ENABLE_SYSTEM_APPS_BY_PACKAGE_NAME_KEY:
showEnableSystemAppByPackageNamePrompt();
return true;
case ENABLE_SYSTEM_APPS_BY_INTENT_KEY:
showFragment(new EnableSystemAppsByIntentFragment());
return true;
case HIDE_APPS_KEY:
showHideAppsPrompt(false);
return true;
case UNHIDE_APPS_KEY:
showHideAppsPrompt(true);
return true;
case SUSPEND_APPS_KEY:
showSuspendAppsPrompt(false);
return true;
case UNSUSPEND_APPS_KEY:
showSuspendAppsPrompt(true);
return true;
case MANAGE_APP_RESTRICTIONS_KEY:
showFragment(new ManageAppRestrictionsFragment());
return true;
case APP_RESTRICTIONS_MANAGING_PACKAGE_KEY:
showFragment(new AppRestrictionsManagingPackageFragment());
return true;
case SET_PERMISSION_POLICY_KEY:
showSetPermissionPolicyDialog();
return true;
case MANAGE_APP_PERMISSIONS_KEY:
showFragment(new ManageAppPermissionsFragment());
return true;
case INSTALL_KEY_CERTIFICATE_KEY:
showFileViewerForImportingCertificate(INSTALL_KEY_CERTIFICATE_REQUEST_CODE);
return true;
case REMOVE_KEY_CERTIFICATE_KEY:
choosePrivateKeyForRemoval();
return true;
case INSTALL_CA_CERTIFICATE_KEY:
showFileViewerForImportingCertificate(INSTALL_CA_CERTIFICATE_REQUEST_CODE);
return true;
case GET_CA_CERTIFICATES_KEY:
showCaCertificateList();
return true;
case REMOVE_ALL_CERTIFICATES_KEY:
mDevicePolicyManager.uninstallAllUserCaCerts(mAdminComponentName);
showToast(R.string.all_ca_certificates_removed);
return true;
case MANAGED_PROFILE_SPECIFIC_POLICIES_KEY:
showFragment(new ProfilePolicyManagementFragment(),
ProfilePolicyManagementFragment.FRAGMENT_TAG);
return true;
case LOCK_SCREEN_POLICY_KEY:
showFragment(new LockScreenPolicyFragment.Container());
return true;
case PASSWORD_CONSTRAINTS_KEY:
showFragment(new PasswordConstraintsFragment.Container());
return true;
case SYSTEM_UPDATE_POLICY_KEY:
showFragment(new SystemUpdatePolicyFragment());
return true;
case SET_ALWAYS_ON_VPN_KEY:
showFragment(new AlwaysOnVpnFragment());
return true;
case NETWORK_STATS_KEY:
showFragment(new NetworkUsageStatsFragment());
return true;
case DELEGATED_CERT_INSTALLER_KEY:
showFragment(new DelegatedCertInstallerFragment());
return true;
case DISABLE_STATUS_BAR:
setStatusBarDisabled(true);
return true;
case REENABLE_STATUS_BAR:
setStatusBarDisabled(false);
return true;
case DISABLE_KEYGUARD:
setKeyGuardDisabled(true);
return true;
case REENABLE_KEYGUARD:
setKeyGuardDisabled(false);
return true;
case START_KIOSK_MODE:
showManageLockTaskListPrompt(R.string.kiosk_select_title,
new ManageLockTaskListCallback() {
@Override
public void onPositiveButtonClicked(String[] lockTaskArray) {
startKioskMode(lockTaskArray);
}
}
);
return true;
case CAPTURE_IMAGE_KEY:
dispatchCaptureIntent(MediaStore.ACTION_IMAGE_CAPTURE,
CAPTURE_IMAGE_REQUEST_CODE, mImageUri);
return true;
case CAPTURE_VIDEO_KEY:
dispatchCaptureIntent(MediaStore.ACTION_VIDEO_CAPTURE,
CAPTURE_VIDEO_REQUEST_CODE, mVideoUri);
return true;
case CREATE_WIFI_CONFIGURATION_KEY:
showWifiConfigCreationDialog();
return true;
case CREATE_EAP_TLS_WIFI_CONFIGURATION_KEY:
showEapTlsWifiConfigCreationDialog();
return true;
case MODIFY_WIFI_CONFIGURATION_KEY:
showFragment(new WifiModificationFragment());
return true;
case SHOW_WIFI_MAC_ADDRESS_KEY:
showWifiMacAddress();
return true;
case SET_USER_RESTRICTIONS_KEY:
showFragment(new UserRestrictionsDisplayFragment());
return true;
case REBOOT_KEY:
reboot();
return true;
case SET_SHORT_SUPPORT_MESSAGE_KEY:
showFragment(SetSupportMessageFragment.newInstance(
SetSupportMessageFragment.TYPE_SHORT));
return true;
case SET_LONG_SUPPORT_MESSAGE_KEY:
showFragment(SetSupportMessageFragment.newInstance(
SetSupportMessageFragment.TYPE_LONG));
return true;
case SAFETYNET_ATTEST:
DialogFragment safetynetFragment = new SafetyNetFragment();
safetynetFragment.show(getFragmentManager(), SafetyNetFragment.class.getName());
return true;
}
return false;
}
@Override
@SuppressLint("NewApi")
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
switch (key) {
case OVERRIDE_KEY_SELECTION_KEY:
preference.setSummary((String) newValue);
return true;
case DISABLE_CAMERA_KEY:
setCameraDisabled((Boolean) newValue);
// Reload UI to verify the camera is enable / disable correctly.
reloadCameraDisableUi();
return true;
case ENABLE_PROCESS_LOGGING:
setSecurityLoggingEnabled((Boolean) newValue);
reloadEnableProcessLoggingUi();
return true;
case DISABLE_SCREEN_CAPTURE_KEY:
setScreenCaptureDisabled((Boolean) newValue);
// Reload UI to verify that screen capture was enabled / disabled correctly.
reloadScreenCaptureDisableUi();
return true;
case MUTE_AUDIO_KEY:
mDevicePolicyManager.setMasterVolumeMuted(mAdminComponentName,
(Boolean) newValue);
reloadMuteAudioUi();
return true;
case STAY_ON_WHILE_PLUGGED_IN:
mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
newValue.equals(true) ? BATTERY_PLUGGED_ANY : DONT_STAY_ON);
updateStayOnWhilePluggedInPreference();
return true;
case WIFI_CONFIG_LOCKDOWN_ENABLE_KEY:
mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN,
newValue.equals(Boolean.TRUE) ?
WIFI_CONFIG_LOCKDOWN_ON : WIFI_CONFIG_LOCKDOWN_OFF);
return true;
case INSTALL_NONMARKET_APPS_KEY:
mDevicePolicyManager.setSecureSetting(mAdminComponentName,
Settings.Secure.INSTALL_NON_MARKET_APPS,
newValue.equals(true) ? "1" : "0");
updateInstallNonMarketAppsPreference();
return true;
case SET_AUTO_TIME_REQUIRED_KEY:
mDevicePolicyManager.setAutoTimeRequired(mAdminComponentName,
newValue.equals(true));
reloadSetAutoTimeRequiredUi();
return true;
}
return false;
}
@TargetApi(Build.VERSION_CODES.M)
private void setCameraDisabled(boolean disabled) {
mDevicePolicyManager.setCameraDisabled(mAdminComponentName, disabled);
}
@TargetApi(Build.VERSION_CODES.N)
private void setSecurityLoggingEnabled(boolean enabled) {
mDevicePolicyManager.setSecurityLoggingEnabled(mAdminComponentName, enabled);
}
@TargetApi(Build.VERSION_CODES.M)
private void setKeyGuardDisabled(boolean disabled) {
if (!mDevicePolicyManager.setKeyguardDisabled(mAdminComponentName, disabled)) {
// this should not happen
if (disabled) {
showToast(R.string.unable_disable_keyguard);
} else {
showToast(R.string.unable_enable_keyguard);
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setScreenCaptureDisabled(boolean disabled) {
mDevicePolicyManager.setScreenCaptureDisabled(mAdminComponentName, disabled);
}
private void setMasterVolumeMuted(boolean muted) {
}
@TargetApi(Build.VERSION_CODES.N)
private void requestBugReport() {
boolean startedSuccessfully = mDevicePolicyManager.requestBugreport(
mAdminComponentName);
if (!startedSuccessfully) {
Context context = getActivity();
Util.showNotification(context, R.string.bugreport_title,
context.getString(R.string.bugreport_failure_throttled),
Util.BUGREPORT_NOTIFICATION_ID);
}
}
@TargetApi(Build.VERSION_CODES.M)
private void setStatusBarDisabled(boolean disable) {
if (!mDevicePolicyManager.setStatusBarDisabled(mAdminComponentName, disable)) {
if (disable) {
showToast("Unable to disable status bar when lock password is set.");
}
}
}
/**
* Dispatches an intent to capture image or video.
*/
private void dispatchCaptureIntent(String action, int requestCode, Uri storageUri) {
final Intent captureIntent = new Intent(action);
if (captureIntent.resolveActivity(mPackageManager) != null) {
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, storageUri);
startActivityForResult(captureIntent, requestCode);
} else {
showToast(R.string.camera_app_not_found);
}
}
/**
* Creates a content uri to be used with the capture intent.
*/
private Uri getStorageUri(String fileName) {
final String filePath = getActivity().getFilesDir() + File.separator + "media"
+ File.separator + fileName;
final File file = new File(filePath);
// Create the folder if it doesn't exist.
file.getParentFile().mkdirs();
return FileProvider.getUriForFile(getActivity(),
"com.afwsamples.testdpc.fileprovider", file);
}
/**
* Shows a list of primary user apps in a dialog.
*
* @param dialogTitle the title to show for the dialog
* @param callback will be called with the list apps that the user has selected when he closes
* the dialog. The callback is not fired if the user cancels.
*/
private void showManageLockTaskListPrompt(int dialogTitle,
final ManageLockTaskListCallback callback) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> primaryUserAppList = mPackageManager
.queryIntentActivities(launcherIntent, 0);
if (primaryUserAppList.isEmpty()) {
showToast(R.string.no_primary_app_available);
} else {
Collections.sort(primaryUserAppList,
new ResolveInfo.DisplayNameComparator(mPackageManager));
final LockTaskAppInfoArrayAdapter appInfoArrayAdapter = new LockTaskAppInfoArrayAdapter(
getActivity(), R.id.pkg_name, primaryUserAppList);
ListView listView = new ListView(getActivity());
listView.setAdapter(appInfoArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
appInfoArrayAdapter.onItemClick(parent, view, position, id);
}
});
new AlertDialog.Builder(getActivity())
.setTitle(getString(dialogTitle))
.setView(listView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] lockTaskEnabledArray = appInfoArrayAdapter.getLockTaskList();
callback.onPositiveButtonClicked(lockTaskEnabledArray);
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
}
/**
* Shows a prompt to collect a package name and checks whether the lock task for the
* corresponding app is permitted or not.
*/
private void showCheckLockTaskPermittedPrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View view = getActivity().getLayoutInflater().inflate(R.layout.simple_edittext, null);
final EditText input = (EditText) view.findViewById(R.id.input);
input.setHint(getString(R.string.input_package_name_hints));
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.check_lock_task_permitted))
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String packageName = input.getText().toString();
boolean isLockTaskPermitted = mDevicePolicyManager
.isLockTaskPermitted(packageName);
showToast(isLockTaskPermitted
? R.string.check_lock_task_permitted_result_permitted
: R.string.check_lock_task_permitted_result_not_permitted);
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
/**
* Shows a prompt to ask for a password to reset to and to set whether this requires
* re-entry before any further changes and/or whether the password needs to be entered during
* boot to start the user.
*/
private void showResetPasswordPrompt() {
View dialogView = getActivity().getLayoutInflater().inflate(
R.layout.reset_password_dialog, null);
final EditText passwordView = (EditText) dialogView.findViewById(
R.id.password);
final CheckBox requireEntry = (CheckBox) dialogView.findViewById(
R.id.require_password_entry_checkbox);
final CheckBox requireOnBoot = (CheckBox) dialogView.findViewById(
R.id.require_password_on_boot_checkbox);
DialogInterface.OnClickListener resetListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
String password = passwordView.getText().toString();
if (TextUtils.isEmpty(password)) {
password = null;
}
int flags = 0;
flags |= requireEntry.isChecked() ?
DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY : 0;
flags |= requireOnBoot.isChecked() ?
DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT : 0;
boolean ok = false;
try {
ok = mDevicePolicyManager.resetPassword(password, flags);
} catch (IllegalArgumentException iae) {
// Bad password, eg. 2 characters where system minimum length is 4.
Log.w(TAG, "Failed to reset password", iae);
}
showToast(ok ? R.string.password_reset_success : R.string.password_reset_failed);
}
};
new AlertDialog.Builder(getActivity())
.setTitle(R.string.reset_password)
.setView(dialogView)
.setPositiveButton(android.R.string.ok, resetListener)
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Shows a prompt to ask for confirmation on wiping the data and also provide an option
* to set if external storage and factory reset protection data also needs to wiped.
*/
private void showWipeDataPrompt() {
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.wipe_data_dialog_prompt, null);
final CheckBox externalStorageCheckBox = (CheckBox) dialogView.findViewById(
R.id.external_storage_checkbox);
final CheckBox resetProtectionCheckBox = (CheckBox) dialogView.findViewById(
R.id.reset_protection_checkbox);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.wipe_data_title)
.setView(dialogView)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
int flags = 0;
flags |= (externalStorageCheckBox.isChecked() ?
DevicePolicyManager.WIPE_EXTERNAL_STORAGE : 0);
flags |= (resetProtectionCheckBox.isChecked() ?
DevicePolicyManager.WIPE_RESET_PROTECTION_DATA : 0);
mDevicePolicyManager.wipeData(flags);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Shows a prompt to ask for confirmation on removing device owner.
*/
private void showRemoveDeviceOwnerPrompt() {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.remove_device_owner_title)
.setMessage(R.string.remove_device_owner_confirmation)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mDevicePolicyManager.clearDeviceOwnerApp(mPackageName);
if (getActivity() != null && !getActivity().isFinishing()) {
showToast(R.string.device_owner_removed);
getActivity().finish();
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Shows a message box with the device wifi mac address.
*/
@TargetApi(Build.VERSION_CODES.N)
private void showWifiMacAddress() {
final String macAddress = mDevicePolicyManager.getWifiMacAddress(mAdminComponentName);
final String message = macAddress != null ? macAddress
: getResources().getString(R.string.show_wifi_mac_address_not_available_msg);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.show_wifi_mac_address_title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, null)
.show();
}
private void setPreferenceChangeListeners(String[] preferenceKeys) {
for (String key : preferenceKeys) {
findPreference(key).setOnPreferenceChangeListener(this);
}
}
/**
* Update the preference switch for {@link Settings.Global#STAY_ON_WHILE_PLUGGED_IN} setting.
*
* <p>
* If either one of the {@link BatteryManager#BATTERY_PLUGGED_AC},
* {@link BatteryManager#BATTERY_PLUGGED_USB}, {@link BatteryManager#BATTERY_PLUGGED_WIRELESS}
* values is set, we toggle the preference to true and update the setting value to
* {@link #BATTERY_PLUGGED_ANY}
* </p>
*/
private void updateStayOnWhilePluggedInPreference() {
if (!mStayOnWhilePluggedInSwitchPreference.isEnabled()) {
return;
}
boolean checked = false;
final int currentState = Settings.Global.getInt(getActivity().getContentResolver(),
Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
checked = (currentState &
(BatteryManager.BATTERY_PLUGGED_AC |
BatteryManager.BATTERY_PLUGGED_USB |
BatteryManager.BATTERY_PLUGGED_WIRELESS)) != 0;
mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
checked ? BATTERY_PLUGGED_ANY : DONT_STAY_ON);
mStayOnWhilePluggedInSwitchPreference.setChecked(checked);
}
/**
* Update the preference switch for {@link Settings.Secure#INSTALL_NON_MARKET_APPS} setting.
*
* <p>
* If the user restriction {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} is set, then
* we disable this preference.
* </p>
*/
public void updateInstallNonMarketAppsPreference() {
mInstallNonMarketAppsPreference.setEnabled(
mUserManager.hasUserRestriction(DISALLOW_INSTALL_UNKNOWN_SOURCES) ? false : true);
int isInstallNonMarketAppsAllowed = Settings.Secure.getInt(
getActivity().getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS, 0);
mInstallNonMarketAppsPreference.setChecked(
isInstallNonMarketAppsAllowed == 0 ? false : true);
}
/**
* Some functionality only works if this app is device owner. Disable their UIs to avoid
* confusion.
*/
private void disableIncompatibleManagementOptionsInCurrentProfile() {
boolean isProfileOwner = mDevicePolicyManager.isProfileOwnerApp(mPackageName);
boolean isDeviceOwner = mDevicePolicyManager.isDeviceOwnerApp(mPackageName);
int deviceOwnerStatusStringId = R.string.this_is_not_a_device_owner;
if (isProfileOwner) {
// Some of the management options can only be applied in a primary profile.
for (String preference : PRIMARY_USER_ONLY_PREFERENCES) {
findPreference(preference).setEnabled(false);
}
if (Util.isBeforeN()) {
for (String preference : PROFILE_OWNER_NYC_PLUS_PREFERENCES) {
findPreference(preference).setEnabled(false);
}
}
deviceOwnerStatusStringId = R.string.this_is_a_profile_owner;
} else if (isDeviceOwner) {
// If it's a device owner and running in the primary profile.
deviceOwnerStatusStringId = R.string.this_is_a_device_owner;
}
findPreference(DEVICE_OWNER_STATUS_KEY).setSummary(deviceOwnerStatusStringId);
if (!isDeviceOwner) {
findPreference(WIFI_CONFIG_LOCKDOWN_ENABLE_KEY).setEnabled(false);
}
// Disable managed profile specific options if we are not running in managed profile.
if (!Util.isManagedProfile(getActivity(), mAdminComponentName)) {
for (String managedProfileSpecificOption : MANAGED_PROFILE_SPECIFIC_OPTIONS) {
findPreference(managedProfileSpecificOption).setEnabled(false);
}
}
}
private void disableIncompatibleManagementOptionsByApiLevel() {
if (Util.isBeforeM()) {
// The following options depend on MNC APIs.
for (String preference : MNC_PLUS_PREFERENCES) {
findPreference(preference).setEnabled(false);
}
}
if (Util.isBeforeN()) {
for (String preference : NYC_PLUS_PREFERENCES) {
findPreference(preference).setEnabled(false);
}
}
}
/**
* Shows the default response for future runtime permission requests by applications, and lets
* the user change the default value.
*/
@TargetApi(Build.VERSION_CODES.M)
private void showSetPermissionPolicyDialog() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View setPermissionPolicyView = getActivity().getLayoutInflater().inflate(
R.layout.set_permission_policy, null);
final RadioGroup permissionGroup =
(RadioGroup) setPermissionPolicyView.findViewById(R.id.set_permission_group);
int permissionPolicy = mDevicePolicyManager.getPermissionPolicy(mAdminComponentName);
switch (permissionPolicy) {
case DevicePolicyManager.PERMISSION_POLICY_PROMPT:
((RadioButton) permissionGroup.findViewById(R.id.prompt)).toggle();
break;
case DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT:
((RadioButton) permissionGroup.findViewById(R.id.accept)).toggle();
break;
case DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY:
((RadioButton) permissionGroup.findViewById(R.id.deny)).toggle();
break;
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.set_default_permission_policy))
.setView(setPermissionPolicyView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int policy = 0;
int checked = permissionGroup.getCheckedRadioButtonId();
switch (checked) {
case (R.id.prompt):
policy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
break;
case (R.id.accept):
policy = DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT;
break;
case (R.id.deny):
policy = DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY;
break;
}
mDevicePolicyManager.setPermissionPolicy(mAdminComponentName, policy);
dialog.dismiss();
}
})
.show();
}
/**
* Shows a prompt that allows entering the account type for which account management should be
* disabled or enabled.
*/
private void showSetDisableAccountManagementPrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View view = LayoutInflater.from(getActivity()).inflate(R.layout.simple_edittext, null);
final EditText input = (EditText) view.findViewById(R.id.input);
input.setHint(R.string.account_type_hint);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.set_disable_account_management)
.setView(view)
.setPositiveButton(R.string.disable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String accountType = input.getText().toString();
setDisableAccountManagement(accountType, true);
}
})
.setNeutralButton(R.string.enable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String accountType = input.getText().toString();
setDisableAccountManagement(accountType, false);
}
})
.setNegativeButton(android.R.string.cancel, null /* Nothing to do */)
.show();
}
private void setDisableAccountManagement(String accountType, boolean disabled) {
if (!TextUtils.isEmpty(accountType)) {
mDevicePolicyManager.setAccountManagementDisabled(mAdminComponentName, accountType,
disabled);
showToast(disabled
? R.string.account_management_disabled
: R.string.account_management_enabled,
accountType);
return;
}
showToast(R.string.fail_to_set_account_management);
}
/**
* Shows a list of account types that is disabled for account management.
*/
private void showDisableAccountTypeList() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
String[] disabledAccountTypeList = mDevicePolicyManager
.getAccountTypesWithManagementDisabled();
Arrays.sort(disabledAccountTypeList, String.CASE_INSENSITIVE_ORDER);
if (disabledAccountTypeList == null || disabledAccountTypeList.length == 0) {
showToast(R.string.no_disabled_account);
} else {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.list_of_disabled_account_types)
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1,
disabledAccountTypeList), null)
.setPositiveButton(android.R.string.ok, null)
.show();
}
}
/**
* For user creation:
* Shows a prompt asking for the username of the new user and whether the setup wizard should
* be skipped.
*/
@TargetApi(Build.VERSION_CODES.N)
private void showCreateAndManageUserPrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
final View dialogView = getActivity().getLayoutInflater().inflate(
R.layout.create_and_manage_user_dialog_prompt, null);
final EditText userNameEditText = (EditText) dialogView.findViewById(R.id.user_name);
userNameEditText.setHint(R.string.enter_username_hint);
final CheckBox skipSetupWizardCheckBox = (CheckBox) dialogView.findViewById(
R.id.skip_setup_wizard_checkbox);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.create_and_manage_user)
.setView(dialogView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String name = userNameEditText.getText().toString();
if (!TextUtils.isEmpty(name)) {
int flags = skipSetupWizardCheckBox.isChecked()
? DevicePolicyManager.SKIP_SETUP_WIZARD : 0;
UserHandle userHandle = mDevicePolicyManager.createAndManageUser(
mAdminComponentName,
name,
mAdminComponentName,
null,
flags);
if (userHandle != null) {
long serialNumber =
mUserManager.getSerialNumberForUser(userHandle);
showToast(R.string.user_created, serialNumber);
return;
}
showToast(R.string.failed_to_create_user);
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* For user removal:
* Shows a prompt for a user serial number. The associated user will be removed.
*/
private void showRemoveUserPrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View view = LayoutInflater.from(getActivity()).inflate(R.layout.simple_edittext, null);
final EditText input = (EditText) view.findViewById(R.id.input);
input.setHint(R.string.enter_user_id);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.remove_user)
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
boolean success = false;
long serialNumber = -1;
try {
serialNumber = Long.parseLong(input.getText().toString());
UserHandle userHandle = mUserManager
.getUserForSerialNumber(serialNumber);
if (userHandle != null) {
success = mDevicePolicyManager
.removeUser(mAdminComponentName, userHandle);
}
} catch (NumberFormatException e) {
// Error message is printed in the next line.
}
showToast(success ? R.string.user_removed : R.string.failed_to_remove_user);
}
})
.show();
}
/**
* Asks for the package name whose uninstallation should be blocked / unblocked.
*/
private void showBlockUninstallationByPackageNamePrompt() {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
View view = LayoutInflater.from(activity).inflate(R.layout.simple_edittext, null);
final EditText input = (EditText) view.findViewById(R.id.input);
input.setHint(getString(R.string.input_package_name_hints));
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.block_uninstallation_title)
.setView(view)
.setPositiveButton(R.string.block, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String pkgName = input.getText().toString();
if (!TextUtils.isEmpty(pkgName)) {
mDevicePolicyManager.setUninstallBlocked(mAdminComponentName, pkgName,
true);
showToast(R.string.uninstallation_blocked, pkgName);
} else {
showToast(R.string.block_uninstallation_failed_invalid_pkgname);
}
}
})
.setNeutralButton(R.string.unblock, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String pkgName = input.getText().toString();
if (!TextUtils.isEmpty(pkgName)) {
mDevicePolicyManager.setUninstallBlocked(mAdminComponentName, pkgName,
false);
showToast(R.string.uninstallation_allowed, pkgName);
} else {
showToast(R.string.block_uninstallation_failed_invalid_pkgname);
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void reloadCameraDisableUi() {
boolean isCameraDisabled = mDevicePolicyManager.getCameraDisabled(mAdminComponentName);
mDisableCameraSwitchPreference.setChecked(isCameraDisabled);
}
@TargetApi(Build.VERSION_CODES.N)
private void reloadEnableProcessLoggingUi() {
if (mEnableProcessLoggingPreference.isEnabled()) {
boolean isProcessLoggingEnabled = mDevicePolicyManager.isSecurityLoggingEnabled(
mAdminComponentName);
mEnableProcessLoggingPreference.setChecked(isProcessLoggingEnabled);
findPreference(REQUEST_PROCESS_LOGS).setEnabled(isProcessLoggingEnabled);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void reloadScreenCaptureDisableUi() {
boolean isScreenCaptureDisabled = mDevicePolicyManager.getScreenCaptureDisabled(
mAdminComponentName);
mDisableScreenCaptureSwitchPreference.setChecked(isScreenCaptureDisabled);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void reloadSetAutoTimeRequiredUi() {
if (mDevicePolicyManager.isDeviceOwnerApp(mPackageName)) {
boolean isAutoTimeRequired = mDevicePolicyManager.getAutoTimeRequired();
mSetAutoTimeRequiredPreference.setChecked(isAutoTimeRequired);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void reloadMuteAudioUi() {
final boolean isAudioMuted = mDevicePolicyManager.isMasterVolumeMuted(mAdminComponentName);
mMuteAudioSwitchPreference.setChecked(isAudioMuted);
}
/**
* Shows a prompt to ask for package name which is used to enable a system app.
*/
private void showEnableSystemAppByPackageNamePrompt() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
LinearLayout inputContainer = (LinearLayout) getActivity().getLayoutInflater()
.inflate(R.layout.simple_edittext, null);
final EditText editText = (EditText) inputContainer.findViewById(R.id.input);
editText.setHint(getString(R.string.enable_system_apps_by_package_name_hints));
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.enable_system_apps_title))
.setView(inputContainer)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String packageName = editText.getText().toString();
try {
mDevicePolicyManager.enableSystemApp(mAdminComponentName, packageName);
showToast(R.string.enable_system_apps_by_package_name_success_msg,
packageName);
} catch (IllegalArgumentException e) {
showToast(R.string.enable_system_apps_by_package_name_error);
} finally {
dialog.dismiss();
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Shows the file viewer for importing a certificate.
*/
private void showFileViewerForImportingCertificate(int requestCode) {
Intent certIntent = new Intent(Intent.ACTION_GET_CONTENT);
certIntent.setTypeAndNormalize("*/*");
try {
startActivityForResult(certIntent, requestCode);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "showFileViewerForImportingCertificate: ", e);
}
}
/**
* Imports a certificate to the managed profile. If the provided password failed to decrypt the
* given certificate, shows a try again prompt. Otherwise, shows a prompt for the certificate
* alias.
*
* @param intent Intent that contains the certificate data uri.
* @param password The password to decrypt the certificate.
*/
private void importKeyCertificateFromIntent(Intent intent, String password) {
importKeyCertificateFromIntent(intent, password, 0 /* first try */);
}
/**
* Imports a certificate to the managed profile. If the provided decryption password is
* incorrect, shows a try again prompt. Otherwise, shows a prompt for the certificate alias.
*
* @param intent Intent that contains the certificate data uri.
* @param password The password to decrypt the certificate.
* @param attempts The number of times user entered incorrect password.
*/
private void importKeyCertificateFromIntent(Intent intent, String password, int attempts) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
Uri data = null;
if (intent != null && (data = intent.getData()) != null) {
// If the password is null, try to decrypt the certificate with an empty password.
if (password == null) {
password = "";
}
try {
CertificateUtil.PKCS12ParseInfo parseInfo = CertificateUtil
.parsePKCS12Certificate(getActivity().getContentResolver(), data, password);
showPromptForKeyCertificateAlias(parseInfo.privateKey, parseInfo.certificate,
parseInfo.alias);
} catch (KeyStoreException | FileNotFoundException | CertificateException |
UnrecoverableKeyException | NoSuchAlgorithmException e) {
Log.e(TAG, "Unable to load key", e);
} catch (IOException e) {
showPromptForCertificatePassword(intent, ++attempts);
} catch (ClassCastException e) {
showToast(R.string.not_a_key_certificate);
}
}
}
/**
* Shows a prompt to ask for the certificate password. If the certificate password is correct,
* import the private key and certificate.
*
* @param intent Intent that contains the certificate data uri.
* @param attempts The number of times user entered incorrect password.
*/
private void showPromptForCertificatePassword(final Intent intent, final int attempts) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
View passwordInputView = getActivity().getLayoutInflater()
.inflate(R.layout.certificate_password_prompt, null);
final EditText input = (EditText) passwordInputView.findViewById(R.id.password_input);
if (attempts > 1) {
passwordInputView.findViewById(R.id.incorrect_password).setVisibility(View.VISIBLE);
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.certificate_password_prompt_title))
.setView(passwordInputView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String userPassword = input.getText().toString();
importKeyCertificateFromIntent(intent, userPassword, attempts);
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
/**
* Shows a prompt to ask for the certificate alias. This alias will be imported together with
* the private key and certificate.
*
* @param key The private key of a certificate.
* @param certificate The certificate will be imported.
* @param alias A name that represents the certificate in the profile.
*/
private void showPromptForKeyCertificateAlias(final PrivateKey key,
final Certificate certificate, String alias) {
if (getActivity() == null || getActivity().isFinishing() || key == null
|| certificate == null) {
return;
}
View passwordInputView = getActivity().getLayoutInflater().inflate(
R.layout.certificate_alias_prompt, null);
final EditText input = (EditText) passwordInputView.findViewById(R.id.alias_input);
if (!TextUtils.isEmpty(alias)) {
input.setText(alias);
input.selectAll();
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.certificate_alias_prompt_title))
.setView(passwordInputView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String alias = input.getText().toString();
if (mDevicePolicyManager.installKeyPair(mAdminComponentName, key,
certificate, alias) == true) {
showToast(R.string.certificate_added, alias);
} else {
showToast(R.string.certificate_add_failed, alias);
}
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
/**
* Selects a private/public key pair to uninstall, using the system dialog to choose
* an alias.
*
* Once the alias is chosen and deleted, a {@link Toast} shows status- success or failure.
*/
@TargetApi(Build.VERSION_CODES.N)
private void choosePrivateKeyForRemoval() {
KeyChain.choosePrivateKeyAlias(getActivity(), new KeyChainAliasCallback() {
@Override
public void alias(String alias) {
if (alias == null) {
// No value was chosen.
return;
}
final boolean removed =
mDevicePolicyManager.removeKeyPair(mAdminComponentName, alias);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (removed) {
showToast(R.string.remove_keypair_successfully);
} else {
showToast(R.string.remove_keypair_fail);
}
}
});
}
}, /* keyTypes[] */ null, /* issuers[] */ null, /* uri */ null, /* alias */ null);
}
/**
* Imports a CA certificate from the given data URI.
*
* @param intent Intent that contains the CA data URI.
*/
private void importCaCertificateFromIntent(Intent intent) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
Uri data = null;
if (intent != null && (data = intent.getData()) != null) {
boolean isCaInstalled = false;
try {
InputStream certificateInputStream = getActivity().getContentResolver()
.openInputStream(data);
if (certificateInputStream != null) {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int len = 0;
while ((len = certificateInputStream.read(buffer)) > 0) {
byteBuffer.write(buffer, 0, len);
}
isCaInstalled = mDevicePolicyManager.installCaCert(mAdminComponentName,
byteBuffer.toByteArray());
}
} catch (IOException e) {
Log.e(TAG, "importCaCertificateFromIntent: ", e);
}
showToast(isCaInstalled ? R.string.install_ca_successfully : R.string.install_ca_fail);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case INSTALL_KEY_CERTIFICATE_REQUEST_CODE:
importKeyCertificateFromIntent(data, "");
break;
case INSTALL_CA_CERTIFICATE_REQUEST_CODE:
importCaCertificateFromIntent(data);
break;
case CAPTURE_IMAGE_REQUEST_CODE:
showFragment(MediaDisplayFragment.newInstance(
MediaDisplayFragment.REQUEST_DISPLAY_IMAGE, mImageUri));
break;
case CAPTURE_VIDEO_REQUEST_CODE:
showFragment(MediaDisplayFragment.newInstance(
MediaDisplayFragment.REQUEST_DISPLAY_VIDEO, mVideoUri));
break;
}
}
}
/**
* Shows a list of installed CA certificates.
*/
private void showCaCertificateList() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
// Avoid starting the same task twice.
if (mShowCaCertificateListTask != null && !mShowCaCertificateListTask.isCancelled()) {
mShowCaCertificateListTask.cancel(true);
}
mShowCaCertificateListTask = new ShowCaCertificateListTask();
mShowCaCertificateListTask.execute();
}
/**
* Displays an alert dialog that allows the user to select applications from all non-system
* applications installed on the current profile. After the user selects an app, this app can't
* be uninstallation.
*/
private void showBlockUninstallationPrompt() {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
List<ApplicationInfo> applicationInfoList
= mPackageManager.getInstalledApplications(0 /* No flag */);
List<ResolveInfo> resolveInfoList = new ArrayList<ResolveInfo>();
Collections.sort(applicationInfoList,
new ApplicationInfo.DisplayNameComparator(mPackageManager));
for (ApplicationInfo applicationInfo : applicationInfoList) {
// Ignore system apps because they can't be uninstalled.
if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.resolvePackageName = applicationInfo.packageName;
resolveInfoList.add(resolveInfo);
}
}
final BlockUninstallationInfoArrayAdapter blockUninstallationInfoArrayAdapter
= new BlockUninstallationInfoArrayAdapter(getActivity(), R.id.pkg_name,
resolveInfoList);
ListView listview = new ListView(getActivity());
listview.setAdapter(blockUninstallationInfoArrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
blockUninstallationInfoArrayAdapter.onItemClick(parent, view, pos, id);
}
});
new AlertDialog.Builder(getActivity())
.setTitle(R.string.block_uninstallation_title)
.setView(listview)
.setPositiveButton(R.string.close, null /* Nothing to do */)
.show();
}
/**
* Shows an alert dialog which displays a list of disabled system apps. Clicking an app in the
* dialog enables the app.
*/
private void showEnableSystemAppsPrompt() {
// Disabled system apps list = {All system apps} - {Enabled system apps}
final List<String> disabledSystemApps = new ArrayList<String>();
// This list contains both enabled and disabled apps.
List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(
PackageManager.GET_UNINSTALLED_PACKAGES);
Collections.sort(allApps, new ApplicationInfo.DisplayNameComparator(mPackageManager));
// This list contains all enabled apps.
List<ApplicationInfo> enabledApps =
mPackageManager.getInstalledApplications(0 /* Default flags */);
Set<String> enabledAppsPkgNames = new HashSet<String>();
for (ApplicationInfo applicationInfo : enabledApps) {
enabledAppsPkgNames.add(applicationInfo.packageName);
}
for (ApplicationInfo applicationInfo : allApps) {
// Interested in disabled system apps only.
if (!enabledAppsPkgNames.contains(applicationInfo.packageName)
&& (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
disabledSystemApps.add(applicationInfo.packageName);
}
}
if (disabledSystemApps.isEmpty()) {
showToast(R.string.no_disabled_system_apps);
} else {
AppInfoArrayAdapter appInfoArrayAdapter = new AppInfoArrayAdapter(getActivity(),
R.id.pkg_name, disabledSystemApps, true);
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.enable_system_apps_title))
.setAdapter(appInfoArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
String packageName = disabledSystemApps.get(position);
mDevicePolicyManager.enableSystemApp(mAdminComponentName, packageName);
showToast(R.string.enable_system_apps_by_package_name_success_msg,
packageName);
}
})
.show();
}
}
/**
* Shows an alert dialog which displays a list hidden / non-hidden apps. Clicking an app in the
* dialog enables the app.
*/
private void showHideAppsPrompt(final boolean showHiddenApps) {
final List<String> showApps = new ArrayList<> ();
if (showHiddenApps) {
// Find all hidden packages using the GET_UNINSTALLED_PACKAGES flag
for (ApplicationInfo applicationInfo : getAllInstalledApplicationsSorted()) {
if (mDevicePolicyManager.isApplicationHidden(mAdminComponentName,
applicationInfo.packageName)) {
showApps.add(applicationInfo.packageName);
}
}
} else {
// Find all non-hidden apps with a launcher icon
for (ResolveInfo res : getAllLauncherIntentResolversSorted()) {
if (!showApps.contains(res.activityInfo.packageName)
&& !mDevicePolicyManager.isApplicationHidden(mAdminComponentName,
res.activityInfo.packageName)) {
showApps.add(res.activityInfo.packageName);
}
}
}
if (showApps.isEmpty()) {
showToast(showHiddenApps ? R.string.unhide_apps_empty : R.string.hide_apps_empty);
} else {
AppInfoArrayAdapter appInfoArrayAdapter = new AppInfoArrayAdapter(getActivity(),
R.id.pkg_name, showApps, true);
final int dialogTitleResId;
final int successResId;
final int failureResId;
if (showHiddenApps) {
// showing a dialog to unhide an app
dialogTitleResId = R.string.unhide_apps_title;
successResId = R.string.unhide_apps_success;
failureResId = R.string.unhide_apps_failure;
} else {
// showing a dialog to hide an app
dialogTitleResId = R.string.hide_apps_title;
successResId = R.string.hide_apps_success;
failureResId = R.string.hide_apps_failure;
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(dialogTitleResId))
.setAdapter(appInfoArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
String packageName = showApps.get(position);
if (mDevicePolicyManager.setApplicationHidden(mAdminComponentName,
packageName, !showHiddenApps)) {
showToast(successResId, packageName);
} else {
showToast(getString(failureResId, packageName), Toast.LENGTH_LONG);
}
}
})
.show();
}
}
/**
* Shows an alert dialog which displays a list of suspended/non-suspended apps.
*/
@TargetApi(Build.VERSION_CODES.N)
private void showSuspendAppsPrompt(final boolean forUnsuspending) {
final List<String> showApps = new ArrayList<>();
if (forUnsuspending) {
// Find all suspended packages using the GET_UNINSTALLED_PACKAGES flag.
for (ApplicationInfo applicationInfo : getAllInstalledApplicationsSorted()) {
if (isPackageSuspended(applicationInfo.packageName)) {
showApps.add(applicationInfo.packageName);
}
}
} else {
// Find all non-suspended apps with a launcher icon.
for (ResolveInfo res : getAllLauncherIntentResolversSorted()) {
if (!showApps.contains(res.activityInfo.packageName)
&& !isPackageSuspended(res.activityInfo.packageName)) {
showApps.add(res.activityInfo.packageName);
}
}
}
if (showApps.isEmpty()) {
showToast(forUnsuspending
? R.string.unsuspend_apps_empty
: R.string.suspend_apps_empty);
} else {
AppInfoArrayAdapter appInfoArrayAdapter = new AppInfoArrayAdapter(getActivity(),
R.id.pkg_name, showApps, true);
final int dialogTitleResId;
final int successResId;
final int failureResId;
if (forUnsuspending) {
// Showing a dialog to unsuspend an app.
dialogTitleResId = R.string.unsuspend_apps_title;
successResId = R.string.unsuspend_apps_success;
failureResId = R.string.unsuspend_apps_failure;
} else {
// Showing a dialog to suspend an app.
dialogTitleResId = R.string.suspend_apps_title;
successResId = R.string.suspend_apps_success;
failureResId = R.string.suspend_apps_failure;
}
new AlertDialog.Builder(getActivity())
.setTitle(getString(dialogTitleResId))
.setAdapter(appInfoArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
String packageName = showApps.get(position);
if (mDevicePolicyManager.setPackagesSuspended(mAdminComponentName,
new String[] {packageName}, !forUnsuspending).length == 0) {
showToast(successResId, packageName);
} else {
showToast(getString(failureResId, packageName), Toast.LENGTH_LONG);
}
}
})
.show();
}
}
@TargetApi(Build.VERSION_CODES.N)
private boolean isPackageSuspended(String packageName) {
try {
return mDevicePolicyManager.isPackageSuspended(mAdminComponentName, packageName);
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Unable check if package is suspended", e);
return false;
}
}
private List<ResolveInfo> getAllLauncherIntentResolversSorted() {
final Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> launcherIntentResolvers = mPackageManager
.queryIntentActivities(launcherIntent, 0);
Collections.sort(launcherIntentResolvers,
new ResolveInfo.DisplayNameComparator(mPackageManager));
return launcherIntentResolvers;
}
private List<ApplicationInfo> getAllInstalledApplicationsSorted() {
List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(
PackageManager.GET_UNINSTALLED_PACKAGES);
Collections.sort(allApps, new ApplicationInfo.DisplayNameComparator(mPackageManager));
return allApps;
}
private void showToast(int msgId, Object... args) {
showToast(getString(msgId, args));
}
private void showToast(String msg) {
showToast(msg, Toast.LENGTH_SHORT);
}
private void showToast(String msg, int duration) {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
Toast.makeText(activity, msg, duration).show();
}
/**
* Gets all the accessibility services. After all the accessibility services are retrieved, the
* result is displayed in a popup.
*/
private class GetAccessibilityServicesTask
extends GetAvailableComponentsTask<AccessibilityServiceInfo> {
private AccessibilityManager mAccessibilityManager;
public GetAccessibilityServicesTask() {
super(getActivity(), R.string.set_accessibility_services);
mAccessibilityManager = (AccessibilityManager) getActivity().getSystemService(
Context.ACCESSIBILITY_SERVICE);
}
@Override
protected List<AccessibilityServiceInfo> doInBackground(Void... voids) {
return mAccessibilityManager.getInstalledAccessibilityServiceList();
}
@Override
protected List<ResolveInfo> getResolveInfoListFromAvailableComponents(
List<AccessibilityServiceInfo> accessibilityServiceInfoList) {
HashSet<String> packageSet = new HashSet<>();
List<ResolveInfo> resolveInfoList = new ArrayList<>();
for (AccessibilityServiceInfo accessibilityServiceInfo: accessibilityServiceInfoList) {
ResolveInfo resolveInfo = accessibilityServiceInfo.getResolveInfo();
// Some apps may contain multiple accessibility services. Make sure that the package
// name is unique in the return list.
if (!packageSet.contains(resolveInfo.serviceInfo.packageName)) {
resolveInfoList.add(resolveInfo);
packageSet.add(resolveInfo.serviceInfo.packageName);
}
}
return resolveInfoList;
}
@Override
protected List<String> getPermittedComponentsList() {
return mDevicePolicyManager.getPermittedAccessibilityServices(mAdminComponentName);
}
@Override
protected void setPermittedComponentsList(List<String> permittedAccessibilityServices) {
boolean result = mDevicePolicyManager.setPermittedAccessibilityServices(
mAdminComponentName, permittedAccessibilityServices);
int successMsgId = (permittedAccessibilityServices == null)
? R.string.all_accessibility_services_enabled
: R.string.set_accessibility_services_successful;
showToast(result ? successMsgId : R.string.set_accessibility_services_fail);
}
}
/**
* Gets all the input methods and displays them in a prompt.
*/
private class GetInputMethodsTask extends GetAvailableComponentsTask<InputMethodInfo> {
private InputMethodManager mInputMethodManager;
public GetInputMethodsTask() {
super(getActivity(), R.string.set_input_methods);
mInputMethodManager = (InputMethodManager) getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
}
@Override
protected List<InputMethodInfo> doInBackground(Void... voids) {
return mInputMethodManager.getInputMethodList();
}
@Override
protected List<ResolveInfo> getResolveInfoListFromAvailableComponents(
List<InputMethodInfo> inputMethodsInfoList) {
List<ResolveInfo> inputMethodsResolveInfoList = new ArrayList<>();
for (InputMethodInfo inputMethodInfo: inputMethodsInfoList) {
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = inputMethodInfo.getServiceInfo();
resolveInfo.resolvePackageName = inputMethodInfo.getPackageName();
inputMethodsResolveInfoList.add(resolveInfo);
}
return inputMethodsResolveInfoList;
}
@Override
protected List<String> getPermittedComponentsList() {
return mDevicePolicyManager.getPermittedInputMethods(mAdminComponentName);
}
@Override
protected void setPermittedComponentsList(List<String> permittedInputMethods) {
boolean result = mDevicePolicyManager.setPermittedInputMethods(mAdminComponentName,
permittedInputMethods);
int successMsgId = (permittedInputMethods == null)
? R.string.all_input_methods_enabled
: R.string.set_input_methods_successful;
showToast(result ? successMsgId : R.string.set_input_methods_fail);
}
}
/**
* Gets all CA certificates and displays them in a prompt.
*/
private class ShowCaCertificateListTask extends AsyncTask<Void, Void, String[]> {
@Override
protected String[] doInBackground(Void... params) {
return getCaCertificateSubjectDnList();
}
@Override
protected void onPostExecute(String[] installedCaCertificateDnList) {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
if (installedCaCertificateDnList == null) {
showToast(R.string.no_ca_certificate);
} else {
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.installed_ca_title))
.setItems(installedCaCertificateDnList, null)
.show();
}
}
private String[] getCaCertificateSubjectDnList() {
List<byte[]> installedCaCerts = mDevicePolicyManager.getInstalledCaCerts(
mAdminComponentName);
String[] caSubjectDnList = null;
if (installedCaCerts.size() > 0) {
caSubjectDnList = new String[installedCaCerts.size()];
int i = 0;
for (byte[] installedCaCert : installedCaCerts) {
try {
X509Certificate certificate = (X509Certificate) CertificateFactory
.getInstance(X509_CERT_TYPE).generateCertificate(
new ByteArrayInputStream(installedCaCert));
caSubjectDnList[i++] = certificate.getSubjectDN().getName();
} catch (CertificateException e) {
Log.e(TAG, "getCaCertificateSubjectDnList: ", e);
}
}
}
return caSubjectDnList;
}
}
private void showFragment(final Fragment fragment) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().addToBackStack(PolicyManagementFragment.class.getName())
.replace(R.id.container, fragment).commit();
}
private void showFragment(final Fragment fragment, String tag) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().addToBackStack(PolicyManagementFragment.class.getName())
.replace(R.id.container, fragment, tag).commit();
}
private void startKioskMode(String[] lockTaskArray) {
// start locked activity
Intent launchIntent = new Intent(getActivity(), KioskModeActivity.class);
launchIntent.putExtra(KioskModeActivity.LOCKED_APP_PACKAGE_LIST, lockTaskArray);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mPackageManager.setComponentEnabledSetting(
new ComponentName(mPackageName, KioskModeActivity.class.getName()),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
startActivity(launchIntent);
getActivity().finish();
}
private void showWifiConfigCreationDialog() {
WifiConfigCreationDialog dialog = WifiConfigCreationDialog.newInstance();
dialog.show(getFragmentManager(), TAG_WIFI_CONFIG_CREATION);
}
private void showEapTlsWifiConfigCreationDialog() {
DialogFragment fragment = WifiEapTlsCreateDialogFragment.newInstance(null);
fragment.show(getFragmentManager(), WifiEapTlsCreateDialogFragment.class.getName());
}
@TargetApi(Build.VERSION_CODES.N)
private void reboot() {
if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
showToast(R.string.reboot_error_msg);
return;
}
mDevicePolicyManager.reboot(mAdminComponentName);
}
abstract class ManageLockTaskListCallback {
public abstract void onPositiveButtonClicked(String[] lockTaskArray);
}
}
| Update the usage of locknow in testdpc
Change-Id: I8dc17569d5d03a6ee7a30409a3778a1871717f11
Fix: 29379761
| app/src/main/java/com/afwsamples/testdpc/policy/PolicyManagementFragment.java | Update the usage of locknow in testdpc |
|
Java | apache-2.0 | 424fe389b06b04f0ecc6f67e2b697cb0ce9f462e | 0 | cgeo/cgeo,auricgoldfinger/cgeo,tobiasge/cgeo,cgeo/cgeo,rsudev/c-geo-opensource,matej116/cgeo,matej116/cgeo,tobiasge/cgeo,rsudev/c-geo-opensource,cgeo/cgeo,S-Bartfast/cgeo,auricgoldfinger/cgeo,auricgoldfinger/cgeo,matej116/cgeo,S-Bartfast/cgeo,tobiasge/cgeo,rsudev/c-geo-opensource,S-Bartfast/cgeo,cgeo/cgeo | package cgeo.geocaching.maps;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Units;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.MapViewImpl;
import cgeo.geocaching.utils.DisplayUtils;
import cgeo.geocaching.utils.Log;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import org.apache.commons.lang3.tuple.ImmutablePair;
public class ScaleDrawer {
private static final double SCALE_WIDTH_FACTOR = 1.0 / 2.5;
private Paint scale = null;
private Paint scaleShadow = null;
private BlurMaskFilter blur = null;
private float pixelDensity = 0;
public ScaleDrawer() {
pixelDensity = DisplayUtils.getDisplayDensity();
}
private static double keepSignificantDigit(final double distance) {
final double scale = Math.pow(10, Math.floor(Math.log10(distance)));
return scale * Math.floor(distance / scale);
}
public void drawScale(final Canvas canvas, final MapViewImpl mapView) {
final double span = mapView.getLongitudeSpan() / 1e6;
final GeoPointImpl center = mapView.getMapViewCenter();
if (center == null) {
Log.w("No center, cannot draw scale");
return;
}
final int bottom = mapView.getHeight() - 14; // pixels from bottom side of screen
final Geopoint leftCoords = new Geopoint(center.getLatitudeE6() / 1e6, center.getLongitudeE6() / 1e6 - span / 2);
final Geopoint rightCoords = new Geopoint(center.getLatitudeE6() / 1e6, center.getLongitudeE6() / 1e6 + span / 2);
final ImmutablePair<Double, String> scaled = Units.scaleDistance(leftCoords.distanceTo(rightCoords) * SCALE_WIDTH_FACTOR);
final double distanceRound = keepSignificantDigit(scaled.left);
final double pixels = Math.round((mapView.getWidth() * SCALE_WIDTH_FACTOR / scaled.left) * distanceRound);
if (blur == null) {
blur = new BlurMaskFilter(3, BlurMaskFilter.Blur.NORMAL);
}
if (scaleShadow == null) {
scaleShadow = new Paint();
scaleShadow.setAntiAlias(true);
scaleShadow.setStrokeWidth(4 * pixelDensity);
scaleShadow.setMaskFilter(blur);
scaleShadow.setTextSize(14 * pixelDensity);
scaleShadow.setTypeface(Typeface.DEFAULT_BOLD);
}
if (scale == null) {
scale = new Paint();
scale.setAntiAlias(true);
scale.setStrokeWidth(2 * pixelDensity);
scale.setTextSize(14 * pixelDensity);
scale.setTypeface(Typeface.DEFAULT_BOLD);
}
if (mapView.needsInvertedColors()) {
scaleShadow.setColor(0xFF000000);
scale.setColor(0xFFFFFFFF);
} else {
scaleShadow.setColor(0xFFFFFFFF);
scale.setColor(0xFF000000);
}
final String info = String.format(distanceRound >= 1 ? "%.0f" : "%.1f", distanceRound) + " " + scaled.right;
final float x = (float) (pixels - 10 * pixelDensity);
final float y = bottom - 10 * pixelDensity;
canvas.drawLine(10, bottom, 10, bottom - 8 * pixelDensity, scaleShadow);
canvas.drawLine((int) (pixels + 10), bottom, (int) (pixels + 10), bottom - 8 * pixelDensity, scaleShadow);
canvas.drawLine(8, bottom, (int) (pixels + 12), bottom, scaleShadow);
canvas.drawText(info, x, y, scaleShadow);
canvas.drawLine(11, bottom, 11, bottom - (6 * pixelDensity), scale);
canvas.drawLine((int) (pixels + 9), bottom, (int) (pixels + 9), bottom - 6 * pixelDensity, scale);
canvas.drawLine(10, bottom, (int) (pixels + 10), bottom, scale);
canvas.drawText(info, x, y, scale);
}
}
| main/src/cgeo/geocaching/maps/ScaleDrawer.java | package cgeo.geocaching.maps;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Units;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.MapViewImpl;
import cgeo.geocaching.utils.DisplayUtils;
import cgeo.geocaching.utils.Log;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import org.apache.commons.lang3.tuple.ImmutablePair;
public class ScaleDrawer {
private static final double SCALE_WIDTH_FACTOR = 1.0 / 2.5;
private Paint scale = null;
private Paint scaleShadow = null;
private BlurMaskFilter blur = null;
private float pixelDensity = 0;
public ScaleDrawer() {
pixelDensity = DisplayUtils.getDisplayDensity();
}
private static double keepSignificantDigit(final double distance) {
final double scale = Math.pow(10, Math.floor(Math.log10(distance)));
return scale * Math.floor(distance / scale);
}
public void drawScale(final Canvas canvas, final MapViewImpl mapView) {
final double span = mapView.getLongitudeSpan() / 1e6;
final GeoPointImpl center = mapView.getMapViewCenter();
if (center == null) {
Log.w("No center, cannot draw scale");
return;
}
final int bottom = mapView.getHeight() - 14; // pixels from bottom side of screen
final Geopoint leftCoords = new Geopoint(center.getLatitudeE6() / 1e6, center.getLongitudeE6() / 1e6 - span / 2);
final Geopoint rightCoords = new Geopoint(center.getLatitudeE6() / 1e6, center.getLongitudeE6() / 1e6 + span / 2);
final ImmutablePair<Double, String> scaled = Units.scaleDistance(leftCoords.distanceTo(rightCoords) * SCALE_WIDTH_FACTOR);
final double distanceRound = keepSignificantDigit(scaled.left);
final double pixels = Math.round((mapView.getWidth() * SCALE_WIDTH_FACTOR / scaled.left) * distanceRound);
if (blur == null) {
blur = new BlurMaskFilter(3, BlurMaskFilter.Blur.NORMAL);
}
if (scaleShadow == null) {
scaleShadow = new Paint();
scaleShadow.setAntiAlias(true);
scaleShadow.setStrokeWidth(4 * pixelDensity);
scaleShadow.setMaskFilter(blur);
scaleShadow.setTextSize(14 * pixelDensity);
scaleShadow.setTypeface(Typeface.DEFAULT_BOLD);
}
if (scale == null) {
scale = new Paint();
scale.setAntiAlias(true);
scale.setStrokeWidth(2 * pixelDensity);
scale.setTextSize(14 * pixelDensity);
scale.setTypeface(Typeface.DEFAULT_BOLD);
}
if (mapView.needsInvertedColors()) {
scaleShadow.setColor(0xFF000000);
scale.setColor(0xFFFFFFFF);
} else {
scaleShadow.setColor(0xFFFFFFFF);
scale.setColor(0xFF000000);
}
final String formatString = distanceRound >= 1 ? "%.0f" : "%.1f";
canvas.drawLine(10, bottom, 10, bottom - 8 * pixelDensity, scaleShadow);
canvas.drawLine((int) (pixels + 10), bottom, (int) (pixels + 10), bottom - 8 * pixelDensity, scaleShadow);
canvas.drawLine(8, bottom, (int) (pixels + 12), bottom, scaleShadow);
canvas.drawText(String.format(formatString, distanceRound) + " " + scaled.right, (float) (pixels - 10 * pixelDensity), bottom - 10 * pixelDensity, scaleShadow);
canvas.drawLine(11, bottom, 11, bottom - (6 * pixelDensity), scale);
canvas.drawLine((int) (pixels + 9), bottom, (int) (pixels + 9), bottom - 6 * pixelDensity, scale);
canvas.drawLine(10, bottom, (int) (pixels + 10), bottom, scale);
canvas.drawText(String.format(formatString, distanceRound) + " " + scaled.right, (float) (pixels - 10 * pixelDensity), bottom - 10 * pixelDensity, scale);
}
}
| extract duplicated calculations for scale drawer
| main/src/cgeo/geocaching/maps/ScaleDrawer.java | extract duplicated calculations for scale drawer |
|
Java | apache-2.0 | 1e3e7832e4b1b01fd89d9f82c97db9ad2e4875b0 | 0 | jimmycd/liquibase,jimmycd/liquibase,jimmycd/liquibase,mattbertolini/liquibase,jimmycd/liquibase,mattbertolini/liquibase,mattbertolini/liquibase,liquibase/liquibase,liquibase/liquibase,fossamagna/liquibase,fossamagna/liquibase,fossamagna/liquibase,liquibase/liquibase,mattbertolini/liquibase | package liquibase.hub.listener;
import liquibase.Scope;
import liquibase.change.Change;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.changelog.visitor.AbstractChangeExecListener;
import liquibase.changelog.visitor.ChangeExecListener;
import liquibase.changelog.visitor.ChangeLogSyncListener;
import liquibase.configuration.HubConfiguration;
import liquibase.configuration.LiquibaseConfiguration;
import liquibase.database.Database;
import liquibase.exception.LiquibaseException;
import liquibase.exception.PreconditionErrorException;
import liquibase.exception.PreconditionFailedException;
import liquibase.hub.HubService;
import liquibase.hub.HubServiceFactory;
import liquibase.hub.LiquibaseHubException;
import liquibase.hub.model.HubChangeLog;
import liquibase.hub.model.Operation;
import liquibase.hub.model.OperationChangeEvent;
import liquibase.logging.Logger;
import liquibase.precondition.core.PreconditionContainer;
import liquibase.serializer.ChangeLogSerializer;
import liquibase.serializer.ChangeLogSerializerFactory;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.statement.SqlStatement;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
public class HubChangeExecListener extends AbstractChangeExecListener
implements ChangeExecListener, ChangeLogSyncListener {
private static final Logger logger = Scope.getCurrentScope().getLog(HubChangeExecListener.class);
private final Operation operation;
private final Map<ChangeSet, Date> startDateMap = new HashMap<>();
private String rollbackScriptContents;
public HubChangeExecListener(Operation operation) {
this.operation = operation;
}
public void setRollbackScriptContents(String rollbackScriptContents) {
this.rollbackScriptContents = rollbackScriptContents;
}
@Override
public void willRun(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, ChangeSet.RunStatus runStatus) {
startDateMap.put(changeSet, new Date());
}
@Override
public void willRun(Change change, ChangeSet changeSet, DatabaseChangeLog changeLog, Database database) {
startDateMap.put(changeSet, new Date());
}
@Override
public void ran(ChangeSet changeSet,
DatabaseChangeLog databaseChangeLog,
Database database,
ChangeSet.ExecType execType) {
String message = "PASSED::" + changeSet.getId() + "::" + changeSet.getAuthor();
updateHub(changeSet, databaseChangeLog, database, "UPDATE", "PASS", message);
}
/**
* Called before a change is rolled back.
*
* @param changeSet changeSet that was rolled back
* @param databaseChangeLog parent change log
* @param database the database the rollback was executed on.
*/
@Override
public void willRollback(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) {
startDateMap.put(changeSet, new Date());
}
/**
*
* Called when there is a rollback failure
*
* @param changeSet changeSet that was rolled back
* @param databaseChangeLog parent change log
* @param database the database the rollback was executed on.
* @param e original exception
*
*/
@Override
public void rollbackFailed(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Exception e) {
updateHubForRollback(changeSet, databaseChangeLog, database, "FAIL", e.getMessage());
}
/**
*
* Called which a change set is successfully rolled back
*
* @param changeSet changeSet that was rolled back
* @param databaseChangeLog parent change log
* @param database the database the rollback was executed on.
*
*/
@Override
public void rolledBack(ChangeSet changeSet,
DatabaseChangeLog databaseChangeLog,
Database database) {
String message = "PASSED::" + changeSet.getId() + "::" + changeSet.getAuthor();
updateHubForRollback(changeSet, databaseChangeLog, database, "PASS", message);
}
@Override
public void preconditionFailed(PreconditionFailedException error, PreconditionContainer.FailOption onFail) {
}
@Override
public void preconditionErrored(PreconditionErrorException error, PreconditionContainer.ErrorOption onError) {
}
@Override
public void ran(Change change, ChangeSet changeSet, DatabaseChangeLog changeLog, Database database) {
}
@Override
public void runFailed(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Exception exception) {
updateHub(changeSet, databaseChangeLog, database, "UPDATE", "FAIL", exception.getMessage());
}
@Override
public void markedRan(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) {
startDateMap.put(changeSet, new Date());
String message = "PASSED::" + changeSet.getId() + "::" + changeSet.getAuthor();
updateHub(changeSet, databaseChangeLog, database, "SYNC", "PASS", message);
}
//
// Send an update message to Hub for this change set rollback
//
private void updateHubForRollback(ChangeSet changeSet,
DatabaseChangeLog databaseChangeLog,
Database database,
String operationStatusType,
String statusMessage) {
if (operation == null) {
boolean hubOn =
! (LiquibaseConfiguration.getInstance().getConfiguration(HubConfiguration.class).getLiquibaseHubMode().equalsIgnoreCase("off"));
if (hubOn) {
String message =
"Hub communication failure.\n" +
"The data for operation on changeset '" +
changeSet.getId() +
"' by author '" + changeSet.getAuthor() + "'\n" +
"was not successfully recorded in your Liquibase Hub project";
Scope.getCurrentScope().getUI().sendMessage(message);
logger.info(message);
}
return;
}
HubChangeLog hubChangeLog;
final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
try {
hubChangeLog = hubService.getChangeLog(UUID.fromString(databaseChangeLog.getChangeLogId()));
if (hubChangeLog == null) {
logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
return;
}
}
catch (LiquibaseHubException lhe) {
logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
return;
}
//
// POST /organizations/{id}/projects/{id}/operations/{id}/change-events
//
OperationChangeEvent operationChangeEvent = new OperationChangeEvent();
operationChangeEvent.setEventType("ROLLBACK");
operationChangeEvent.setStartDate(startDateMap.get(changeSet));
operationChangeEvent.setEndDate(new Date());
operationChangeEvent.setChangesetId(changeSet.getId());
operationChangeEvent.setChangesetFilename(changeSet.getFilePath());
operationChangeEvent.setChangesetAuthor(changeSet.getAuthor());
List<String> sqlList = new ArrayList<>();
try {
if (rollbackScriptContents != null) {
sqlList.add(rollbackScriptContents);
}
else if (changeSet.hasCustomRollbackChanges()) {
List<Change> changes = changeSet.getRollback().getChanges();
for (Change change : changes) {
SqlStatement[] statements = change.generateStatements(database);
for (SqlStatement statement : statements) {
for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, database)) {
sqlList.add(sql.toSql());
}
}
}
}
else {
List<Change> changes = changeSet.getChanges();
for (Change change : changes) {
SqlStatement[] statements = change.generateRollbackStatements(database);
for (SqlStatement statement : statements) {
for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, database)) {
sqlList.add(sql.toSql());
}
}
}
}
}
catch (LiquibaseException lbe) {
logger.warning(lbe.getMessage());
}
String[] sqlArray = new String[sqlList.size()];
sqlArray = sqlList.toArray(sqlArray);
operationChangeEvent.setGeneratedSql(sqlArray);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ChangeLogSerializer serializer =
ChangeLogSerializerFactory.getInstance().getSerializer(".json");
try {
serializer.write(Collections.singletonList(changeSet), baos);
operationChangeEvent.setChangesetBody(baos.toString("UTF-8"));
}
catch (IOException ioe) {
//
// Consume
//
}
operationChangeEvent.setOperationStatusType(operationStatusType);
operationChangeEvent.setStatusMessage(statusMessage);
operationChangeEvent.setLogs("LOGS");
operationChangeEvent.setLogsTimestamp(new Date());
operationChangeEvent.setProject(hubChangeLog.getProject());
operationChangeEvent.setOperation(operation);
try {
hubService.sendOperationChangeEvent(operationChangeEvent);
}
catch (LiquibaseException lbe) {
logger.warning(lbe.getMessage());
logger.warning("Unable to send Operation Change Event for operation '" + operation.getId().toString() +
" change set '" + changeSet.toString(false));
}
}
//
// Send an update message to Hub for this change set
//
private void updateHub(ChangeSet changeSet,
DatabaseChangeLog databaseChangeLog,
Database database,
String eventType,
String operationStatusType,
String statusMessage) {
//
// If not connected to Hub but we are supposed to be then show message
//
if (operation == null) {
boolean hubOn =
! (LiquibaseConfiguration.getInstance().getConfiguration(HubConfiguration.class).getLiquibaseHubMode().equalsIgnoreCase("off"));
if (hubOn) {
String message =
"Hub communication failure.\n" +
"The data for operation on changeset '" +
changeSet.getId() +
"' by author '" + changeSet.getAuthor() + "'\n" +
"was not successfully recorded in your Liquibase Hub project";
Scope.getCurrentScope().getUI().sendMessage(message);
logger.info(message);
}
return;
}
HubChangeLog hubChangeLog;
final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
try {
hubChangeLog = hubService.getChangeLog(UUID.fromString(databaseChangeLog.getChangeLogId()));
if (hubChangeLog == null) {
logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
return;
}
}
catch (LiquibaseHubException lhe) {
logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
return;
}
//
// POST /organizations/{id}/projects/{id}/operations/{id}/change-events
//
List<Change> changes = changeSet.getChanges();
List<String> sqlList = new ArrayList<>();
for (Change change : changes) {
Sql[] sqls = SqlGeneratorFactory.getInstance().generateSql(change, database);
for (Sql sql : sqls) {
sqlList.add(sql.toSql());
}
}
String[] sqlArray = new String[sqlList.size()];
sqlArray = sqlList.toArray(sqlArray);
OperationChangeEvent operationChangeEvent = new OperationChangeEvent();
operationChangeEvent.setEventType(eventType);
operationChangeEvent.setStartDate(startDateMap.get(changeSet));
operationChangeEvent.setEndDate(new Date());
operationChangeEvent.setChangesetId(changeSet.getId());
operationChangeEvent.setChangesetFilename(changeSet.getFilePath());
operationChangeEvent.setChangesetAuthor(changeSet.getAuthor());
operationChangeEvent.setOperationStatusType(operationStatusType);
operationChangeEvent.setStatusMessage(statusMessage);
operationChangeEvent.setGeneratedSql(sqlArray);
operationChangeEvent.setOperation(operation);
operationChangeEvent.setLogsTimestamp(new Date());
operationChangeEvent.setLogs("LOGS");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ChangeLogSerializer serializer = ChangeLogSerializerFactory.getInstance().getSerializer(".json");
try {
serializer.write(Collections.singletonList(changeSet), baos);
operationChangeEvent.setChangesetBody(baos.toString("UTF-8"));
}
catch (IOException ioe) {
//
// Consume
//
}
operationChangeEvent.setProject(hubChangeLog.getProject());
operationChangeEvent.setOperation(operation);
try {
hubService.sendOperationChangeEvent(operationChangeEvent);
}
catch (LiquibaseException lbe) {
logger.warning("Unable to send Operation Change Event for operation '" + operation.getId().toString() +
" change set '" + changeSet.toString(false));
}
}
}
| liquibase-core/src/main/java/liquibase/hub/listener/HubChangeExecListener.java | package liquibase.hub.listener;
import liquibase.Scope;
import liquibase.change.Change;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.changelog.visitor.AbstractChangeExecListener;
import liquibase.changelog.visitor.ChangeExecListener;
import liquibase.changelog.visitor.ChangeLogSyncListener;
import liquibase.configuration.HubConfiguration;
import liquibase.configuration.LiquibaseConfiguration;
import liquibase.database.Database;
import liquibase.exception.LiquibaseException;
import liquibase.exception.PreconditionErrorException;
import liquibase.exception.PreconditionFailedException;
import liquibase.hub.HubService;
import liquibase.hub.HubServiceFactory;
import liquibase.hub.LiquibaseHubException;
import liquibase.hub.model.HubChangeLog;
import liquibase.hub.model.Operation;
import liquibase.hub.model.OperationChangeEvent;
import liquibase.logging.Logger;
import liquibase.precondition.core.PreconditionContainer;
import liquibase.serializer.ChangeLogSerializer;
import liquibase.serializer.ChangeLogSerializerFactory;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.statement.SqlStatement;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
public class HubChangeExecListener extends AbstractChangeExecListener
implements ChangeExecListener, ChangeLogSyncListener {
private static final Logger logger = Scope.getCurrentScope().getLog(HubChangeExecListener.class);
private final Operation operation;
private final Map<ChangeSet, Date> startDateMap = new HashMap<>();
private String rollbackScriptContents;
public HubChangeExecListener(Operation operation) {
this.operation = operation;
}
public void setRollbackScriptContents(String rollbackScriptContents) {
this.rollbackScriptContents = rollbackScriptContents;
}
@Override
public void willRun(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, ChangeSet.RunStatus runStatus) {
startDateMap.put(changeSet, new Date());
}
@Override
public void willRun(Change change, ChangeSet changeSet, DatabaseChangeLog changeLog, Database database) {
startDateMap.put(changeSet, new Date());
}
@Override
public void ran(ChangeSet changeSet,
DatabaseChangeLog databaseChangeLog,
Database database,
ChangeSet.ExecType execType) {
String message = "PASSED::" + changeSet.getId() + "::" + changeSet.getAuthor();
updateHub(changeSet, databaseChangeLog, database, "UPDATE", "PASS", message);
}
/**
* Called before a change is rolled back.
*
* @param changeSet changeSet that was rolled back
* @param databaseChangeLog parent change log
* @param database the database the rollback was executed on.
*/
@Override
public void willRollback(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) {
startDateMap.put(changeSet, new Date());
}
/**
*
* Called when there is a rollback failure
*
* @param changeSet changeSet that was rolled back
* @param databaseChangeLog parent change log
* @param database the database the rollback was executed on.
* @param e original exception
*
*/
@Override
public void rollbackFailed(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Exception e) {
updateHubForRollback(changeSet, databaseChangeLog, database, "FAIL", e.getMessage());
}
/**
*
* Called which a change set is successfully rolled back
*
* @param changeSet changeSet that was rolled back
* @param databaseChangeLog parent change log
* @param database the database the rollback was executed on.
*
*/
@Override
public void rolledBack(ChangeSet changeSet,
DatabaseChangeLog databaseChangeLog,
Database database) {
String message = "PASSED::" + changeSet.getId() + "::" + changeSet.getAuthor();
updateHubForRollback(changeSet, databaseChangeLog, database, "PASS", message);
}
@Override
public void preconditionFailed(PreconditionFailedException error, PreconditionContainer.FailOption onFail) {
}
@Override
public void preconditionErrored(PreconditionErrorException error, PreconditionContainer.ErrorOption onError) {
}
@Override
public void ran(Change change, ChangeSet changeSet, DatabaseChangeLog changeLog, Database database) {
}
@Override
public void runFailed(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Exception exception) {
updateHub(changeSet, databaseChangeLog, database, "UPDATE", "FAIL", exception.getMessage());
}
@Override
public void markedRan(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) {
startDateMap.put(changeSet, new Date());
String message = "PASSED::" + changeSet.getId() + "::" + changeSet.getAuthor();
updateHub(changeSet, databaseChangeLog, database, "SYNC", "PASS", message);
}
//
// Send an update message to Hub for this change set rollback
//
private void updateHubForRollback(ChangeSet changeSet,
DatabaseChangeLog databaseChangeLog,
Database database,
String operationStatusType,
String statusMessage) {
if (operation == null) {
boolean hubOn =
! (LiquibaseConfiguration.getInstance().getConfiguration(HubConfiguration.class).getLiquibaseHubMode().equalsIgnoreCase("off"));
if (hubOn) {
String message =
"Hub communication failure.\n" +
"The data for operation on changeset '" +
changeSet.getId() +
"' by author '" + changeSet.getAuthor() + "'\n" +
"was not successfully recorded in your Liquibase Hub project";
Scope.getCurrentScope().getUI().sendMessage(message);
logger.info(message);
}
return;
}
HubChangeLog hubChangeLog;
final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
try {
hubChangeLog = hubService.getChangeLog(UUID.fromString(databaseChangeLog.getChangeLogId()));
if (hubChangeLog == null) {
logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
return;
}
}
catch (LiquibaseHubException lhe) {
logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
return;
}
//
// POST /organizations/{id}/projects/{id}/operations/{id}/change-events
//
OperationChangeEvent operationChangeEvent = new OperationChangeEvent();
operationChangeEvent.setEventType("ROLLBACK");
operationChangeEvent.setStartDate(startDateMap.get(changeSet));
operationChangeEvent.setEndDate(new Date());
operationChangeEvent.setChangesetId(changeSet.getId());
operationChangeEvent.setChangesetFilename(changeSet.getFilePath());
operationChangeEvent.setChangesetAuthor(changeSet.getAuthor());
List<String> sqlList = new ArrayList<>();
try {
if (rollbackScriptContents != null) {
sqlList.add(rollbackScriptContents);
}
else if (changeSet.hasCustomRollbackChanges()) {
List<Change> changes = changeSet.getRollback().getChanges();
for (Change change : changes) {
SqlStatement[] statements = change.generateStatements(database);
for (SqlStatement statement : statements) {
for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, database)) {
sqlList.add(sql.toSql());
}
}
}
}
else {
List<Change> changes = changeSet.getChanges();
for (Change change : changes) {
SqlStatement[] statements = change.generateRollbackStatements(database);
for (SqlStatement statement : statements) {
for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, database)) {
sqlList.add(sql.toSql());
}
}
}
}
}
catch (LiquibaseException lbe) {
logger.warning(lbe.getMessage());
}
String[] sqlArray = new String[sqlList.size()];
sqlArray = sqlList.toArray(sqlArray);
operationChangeEvent.setGeneratedSql(sqlArray);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ChangeLogSerializer serializer =
ChangeLogSerializerFactory.getInstance().getSerializer(".json");
try {
serializer.write(Collections.singletonList(changeSet), baos);
operationChangeEvent.setChangesetBody(baos.toString("UTF-8"));
}
catch (IOException ioe) {
//
// Consume
//
}
operationChangeEvent.setOperationStatusType(operationStatusType);
operationChangeEvent.setStatusMessage(statusMessage);
operationChangeEvent.setLogs("LOGS");
operationChangeEvent.setLogsTimestamp(new Date());
operationChangeEvent.setProject(hubChangeLog.getProject());
operationChangeEvent.setOperation(operation);
try {
hubService.sendOperationChangeEvent(operationChangeEvent);
}
catch (LiquibaseException lbe) {
logger.warning(lbe.getMessage());
logger.warning("Unable to send Operation Change Event for operation '" + operation.getId().toString() +
" change set '" + changeSet.toString(false));
}
}
//
// Send an update message to Hub for this change set
//
private void updateHub(ChangeSet changeSet,
DatabaseChangeLog databaseChangeLog,
Database database,
String eventType,
String operationStatusType,
String statusMessage) {
//
// If not connected to Hub but we are supposed to be then show message
//
if (operation == null) {
boolean hubOn =
! (LiquibaseConfiguration.getInstance().getConfiguration(HubConfiguration.class).getLiquibaseHubMode().equalsIgnoreCase("off"));
if (hubOn) {
String message =
"Hub communication failure.\n" +
"The data for operation on changeset '" +
changeSet.getId() +
"' by author '" + changeSet.getAuthor() + "'\n" +
"was not successfully recorded in your Liquibase Hub project";
Scope.getCurrentScope().getUI().sendMessage(message);
logger.info(message);
}
return;
}
HubChangeLog hubChangeLog;
final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
try {
hubChangeLog = hubService.getChangeLog(UUID.fromString(databaseChangeLog.getChangeLogId()));
if (hubChangeLog == null) {
logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
return;
}
}
catch (LiquibaseHubException lhe) {
logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
return;
}
//
// POST /organizations/{id}/projects/{id}/operations/{id}/change-events
//
List<Change> changes = changeSet.getChanges();
List<String> sqlList = new ArrayList<>();
for (Change change : changes) {
Sql[] sqls = SqlGeneratorFactory.getInstance().generateSql(change, database);
for (Sql sql : sqls) {
sqlList.add(sql.toSql());
}
}
String[] sqlArray = new String[sqlList.size()];
sqlArray = sqlList.toArray(sqlArray);
OperationChangeEvent operationChangeEvent = new OperationChangeEvent();
operationChangeEvent.setEventType(eventType);
operationChangeEvent.setStartDate(startDateMap.get(changeSet));
operationChangeEvent.setEndDate(new Date());
operationChangeEvent.setChangesetId(changeSet.getId());
operationChangeEvent.setChangesetFilename(changeSet.getFilePath());
operationChangeEvent.setChangesetAuthor(changeSet.getAuthor());
operationChangeEvent.setOperationStatusType(operationStatusType);
operationChangeEvent.setStatusMessage(statusMessage.length() <= 255 ? statusMessage : statusMessage.substring(0,255));
operationChangeEvent.setGeneratedSql(sqlArray);
operationChangeEvent.setOperation(operation);
operationChangeEvent.setLogsTimestamp(new Date());
operationChangeEvent.setLogs("LOGS");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ChangeLogSerializer serializer = ChangeLogSerializerFactory.getInstance().getSerializer(".json");
try {
serializer.write(Collections.singletonList(changeSet), baos);
operationChangeEvent.setChangesetBody(baos.toString("UTF-8"));
}
catch (IOException ioe) {
//
// Consume
//
}
operationChangeEvent.setProject(hubChangeLog.getProject());
operationChangeEvent.setOperation(operation);
try {
hubService.sendOperationChangeEvent(operationChangeEvent);
}
catch (LiquibaseException lbe) {
logger.warning("Unable to send Operation Change Event for operation '" + operation.getId().toString() +
" change set '" + changeSet.toString(false));
}
}
}
| Remove 255 character restriction on statusMessage
| liquibase-core/src/main/java/liquibase/hub/listener/HubChangeExecListener.java | Remove 255 character restriction on statusMessage |
|
Java | apache-2.0 | 5142c6fce56714529ca31511727b72565db74dd1 | 0 | michaelhochleitner/SimpleChat | package com.example.y95278.simplechat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "com.example.y95278.simplechat.MainActivity";
private MyWebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connectToServer(View view) {
String serverUrl = "http://127.0.0.1:8080/chat";
URI serverURI;
try {
serverURI = new URI(serverUrl);
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
this.mWebSocketClient = new MyWebSocketClient(serverURI);
mWebSocketClient.connect();
Log.i(TAG,"Connecting to "+serverUrl);
Log.i(TAG,mWebSocketClient.getReadyState().toString());
}
public void sendMessage(View view){
Log.i(TAG,"sendMessage called");
EditText inputTextView = findViewById(R.id.editText);
String inputText = inputTextView.getText().toString();
mWebSocketClient.send(inputText);
}
}
| app/src/main/java/com/example/y95278/simplechat/MainActivity.java | package com.example.y95278.simplechat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import java.net.URI;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "com.example.y95278.simplechat.MainActivity";
private MyWebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connectToServer(View view) {
String serverUrl = "http://127.0.0.1:8080/chat";
URI serverURI = URI.create(serverUrl);
this.mWebSocketClient = new MyWebSocketClient(serverURI);
mWebSocketClient.connect();
Log.i(TAG,"Connecting to "+serverUrl);
Log.i(TAG,mWebSocketClient.getReadyState().toString());
}
public void sendMessage(View view){
Log.i(TAG,"sendMessage called");
EditText inputTextView = (EditText) findViewById(R.id.editText);
String inputText = inputTextView.getText().toString();
mWebSocketClient.send(inputText);
}
}
| Added try catch around serverURI = new URI(serverUrl)
| app/src/main/java/com/example/y95278/simplechat/MainActivity.java | Added try catch around serverURI = new URI(serverUrl) |
|
Java | apache-2.0 | 79bab7e294b1582903b93dc0bce6421fb6b52e63 | 0 | btmura/rbb | /*
* Copyright (C) 2012 Brian Muramatsu
*
* 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.btmura.android.reddit.accounts;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;
import com.btmura.android.reddit.R;
import com.btmura.android.reddit.app.AddAccountFragment;
import com.btmura.android.reddit.app.LoginFragment;
import com.btmura.android.reddit.content.ThemePrefs;
public class AccountAuthenticatorActivity
extends SupportAccountAuthenticatorActivity
implements LoginFragment.OnLoginListener,
AddAccountFragment.OnAccountAddedListener {
private static final String TAG_ADD_ACCOUNT = "AddAccount";
public static final String EXTRA_USERNAME = "username";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(ThemePrefs.getTheme(this));
setContentView(R.layout.account_authenticator);
getActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
LoginFragment frag = LoginFragment.newInstance(newStateToken());
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.account_authenticator_container, frag);
ft.commit();
}
}
private static CharSequence newStateToken() {
return new StringBuilder("rbb_").append(System.currentTimeMillis());
}
@Override
public void onLogin(String oauthCallbackUrl) {
// TODO(btmura): compare state tokens
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
AddAccountFragment.newInstance(oauthCallbackUrl)
.show(ft, TAG_ADD_ACCOUNT);
}
@Override
public void onAccountAdded(Bundle result) {
setAccountAuthenticatorResult(result);
setResult(RESULT_OK);
finish();
}
@Override
public void onAccountCancelled() {
finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
return handleHome();
default:
return super.onOptionsItemSelected(item);
}
}
private boolean handleHome() {
finish();
return true;
}
}
| src/com/btmura/android/reddit/accounts/AccountAuthenticatorActivity.java | /*
* Copyright (C) 2012 Brian Muramatsu
*
* 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.btmura.android.reddit.accounts;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import com.btmura.android.reddit.R;
import com.btmura.android.reddit.app.AddAccountFragment;
import com.btmura.android.reddit.app.LoginFragment;
import com.btmura.android.reddit.content.ThemePrefs;
public class AccountAuthenticatorActivity
extends SupportAccountAuthenticatorActivity
implements LoginFragment.OnLoginListener,
AddAccountFragment.OnAccountAddedListener {
private static final String TAG_ADD_ACCOUNT = "AddAccount";
public static final String EXTRA_USERNAME = "username";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(ThemePrefs.getTheme(this));
setContentView(R.layout.account_authenticator);
if (savedInstanceState == null) {
LoginFragment frag = LoginFragment.newInstance(newStateToken());
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.account_authenticator_container, frag);
ft.commit();
}
}
private static CharSequence newStateToken() {
return new StringBuilder("rbb_").append(System.currentTimeMillis());
}
@Override
public void onLogin(String oauthCallbackUrl) {
// TODO(btmura): compare state tokens
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
AddAccountFragment.newInstance(oauthCallbackUrl)
.show(ft, TAG_ADD_ACCOUNT);
}
@Override
public void onAccountAdded(Bundle result) {
setAccountAuthenticatorResult(result);
setResult(RESULT_OK);
finish();
}
@Override
public void onAccountCancelled() {
finish();
}
}
| Enable home up for Login fragment
| src/com/btmura/android/reddit/accounts/AccountAuthenticatorActivity.java | Enable home up for Login fragment |
|
Java | apache-2.0 | a134f8b33edcebc2809e47ef2bdd19076d52ab6d | 0 | taverna-incubator/incubator-taverna-language,taverna-incubator/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language | package uk.org.taverna.scufl2.api.common;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import uk.org.taverna.scufl2.api.common.Visitor.VisitorWithPath;
import uk.org.taverna.scufl2.api.configurations.Configuration;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.core.BlockingControlLink;
import uk.org.taverna.scufl2.api.core.DataLink;
import uk.org.taverna.scufl2.api.core.Workflow;
import uk.org.taverna.scufl2.api.dispatchstack.DispatchStack;
import uk.org.taverna.scufl2.api.dispatchstack.DispatchStackLayer;
import uk.org.taverna.scufl2.api.iterationstrategy.IterationStrategyNode;
import uk.org.taverna.scufl2.api.iterationstrategy.IterationStrategyStack;
import uk.org.taverna.scufl2.api.port.InputPort;
import uk.org.taverna.scufl2.api.port.OutputPort;
import uk.org.taverna.scufl2.api.port.Port;
import uk.org.taverna.scufl2.api.port.ProcessorPort;
import uk.org.taverna.scufl2.api.profiles.ProcessorPortBinding;
import uk.org.taverna.scufl2.api.property.PropertyResource;
public class URITools {
private static final String MERGE_POSITION = "mergePosition";
private static final String TO = "to";
private static final String FROM = "from";
private static final String DATALINK = "datalink";
private static final URI DOT = URI.create(".");
public URI relativePath(URI base, URI uri) {
URI root = base.resolve("/");
if (!root.equals(uri.resolve("/"))) {
// Different protocol/host/auth
return uri;
}
base = base.normalize();
uri = uri.normalize();
if (base.resolve("#").equals(uri.resolve("#"))) {
// Same path, easy
return base.relativize(uri);
}
if (base.isAbsolute()) {
// Ignore hostname and protocol
base = root.relativize(base).resolve(".");
uri = root.relativize(uri);
}
// Pretend they start from /
base = root.resolve(base).resolve(".");
uri = root.resolve(uri);
URI candidate = base.relativize(uri);
URI relation = DOT;
while (candidate.getPath().startsWith("/")
&& !(base.getPath().isEmpty() || base.getPath().equals("/"))) {
base = base.resolve("../");
relation = relation.resolve("../");
candidate = base.relativize(uri);
}
// Add the ../.. again
URI resolved = relation.resolve(candidate);
return resolved;
}
public URI relativeUriForBean(WorkflowBean bean, WorkflowBean relativeToBean) {
URI rootUri = uriForBean(relativeToBean);
URI beanUri = uriForBean(bean);
return relativePath(rootUri, beanUri);
}
public WorkflowBean resolveUri(URI uri, WorkflowBundle wfBundle) {
// Check if it's a workflow URI
String rel = Workflow.WORKFLOW_ROOT.relativize(uri).toASCIIString();
if (rel.matches("[0-9a-f-]+/")) {
for (Workflow wf : wfBundle.getWorkflows()) {
if (wf.getWorkflowIdentifier().equals(uri)) {
return wf;
}
}
return null;
}
// Naive, super-inefficient reverse-lookup - we could have even returned
// early!
final Map<URI, WorkflowBean> uriToBean = new HashMap<URI, WorkflowBean>();
wfBundle.accept(new VisitorWithPath() {
@Override
public boolean visit() {
WorkflowBean node = getCurrentNode();
URI uri = uriForBean(node);
WorkflowBean existing = uriToBean.put(uri, node);
if (existing != null) {
String msg = "Multiple nodes with same URI {0}: {1} {2}";
throw new IllegalStateException(MessageFormat.format(msg,
uri, existing, node));
}
return !(node instanceof Configuration);
}
});
if (! uri.isAbsolute()) {
// Make absolute
uri = uriForBean(wfBundle).resolve(uri);
}
return uriToBean.get(uri);
}
public URI uriForBean(WorkflowBean bean) {
if (bean == null) {
throw new NullPointerException("Bean can't be null");
}
if (bean instanceof Root) {
Root root = (Root) bean;
if (root.getSameBaseAs() == null) {
if (root instanceof WorkflowBundle) {
root.setSameBaseAs(WorkflowBundle.generateIdentifier());
} else {
throw new IllegalArgumentException(
"sameBaseAs is null for bean " + bean);
}
}
return root.getSameBaseAs();
}
if (bean instanceof Child) {
Child child = (Child) bean;
WorkflowBean parent = child.getParent();
if (parent == null) {
throw new IllegalStateException("Bean does not have a parent: "
+ child);
}
URI parentUri = uriForBean(parent);
if (!parentUri.getPath().endsWith("/")) {
parentUri = parentUri.resolve(parentUri.getPath() + "/");
}
String relation;
if (child instanceof InputPort) {
relation = "in/";
} else if (child instanceof OutputPort) {
relation = "out/";
} else if (child instanceof IterationStrategyStack) {
relation = "iterationstrategy/";
} else {
// TODO: Get relation by container annotations
relation = child.getClass().getSimpleName() + "/";
// Stupid fallback
}
URI relationURI = parentUri.resolve(relation.toLowerCase());
if (parent instanceof List) {
int index = ((List) parent).indexOf(child);
return parentUri.resolve(index + "/");
}
if (bean instanceof Named) {
Named named = (Named) bean;
String name = validFilename(named.getName());
if (!(bean instanceof Port)) {
name = name + "/";
}
return relationURI.resolve(name);
} else if (bean instanceof DataLink) {
DataLink dataLink = (DataLink) bean;
Workflow wf = dataLink.getParent();
URI wfUri = uriForBean(wf);
URI receivesFrom = relativePath(wfUri,
uriForBean(dataLink.getReceivesFrom()));
URI sendsTo = relativePath(wfUri,
uriForBean(dataLink.getSendsTo()));
String dataLinkUri = MessageFormat.format(
"{0}?{1}={2}&{3}={4}", DATALINK, FROM, receivesFrom,
TO, sendsTo);
if (dataLink.getMergePosition() != null) {
dataLinkUri += MessageFormat.format("&{0}={1}",
MERGE_POSITION, dataLink.getMergePosition());
}
return wfUri.resolve(dataLinkUri);
} else if(bean instanceof BlockingControlLink) {
BlockingControlLink runAfterCondition = (BlockingControlLink) bean;
Workflow wf = runAfterCondition.getParent();
URI wfUri = uriForBean(wf);
URI start = relativePath(wfUri,
uriForBean(runAfterCondition.getBlock()));
URI after = relativePath(wfUri,
uriForBean(runAfterCondition.getUntilFinished()));
String conditionUri = MessageFormat.format("{0}?{1}={2}&{3}={4}",
"control", "block", start,
"untilFinished", after);
return wfUri.resolve(conditionUri);
} else if (bean instanceof DispatchStack) {
return relationURI;
} else if (bean instanceof DispatchStackLayer) {
DispatchStackLayer dispatchStackLayer = (DispatchStackLayer) bean;
} else if (bean instanceof IterationStrategyStack) {
return relationURI;
} else if (bean instanceof IterationStrategyNode) {
IterationStrategyNode iterationStrategyNode = (IterationStrategyNode) bean;
parent = iterationStrategyNode.getParent();
List<IterationStrategyNode> parentList = (List<IterationStrategyNode>) parent;
int index = parentList.indexOf(iterationStrategyNode);
return parentUri.resolve(index + "/");
} else if (bean instanceof ProcessorPortBinding) {
// Named after the processor port, extract in/blah part.
ProcessorPortBinding<?, ?> processorPortBinding = (ProcessorPortBinding<?, ?>) bean;
ProcessorPort procPort = processorPortBinding
.getBoundProcessorPort();
URI procPortUri = relativeUriForBean(procPort,
processorPortBinding.getParent().getBoundProcessor());
return parentUri.resolve(procPortUri);
} else {
throw new IllegalStateException(
"Can't create URIs for non-named child: " + bean);
}
}
if (bean instanceof PropertyResource) {
PropertyResource propertyResource = (PropertyResource) bean;
URI resourceURI = propertyResource.getResourceURI();
if (resourceURI != null) {
return resourceURI;
}
throw new IllegalStateException(
"PropertyResource does not have a resourceURI");
}
throw new IllegalArgumentException("Unsupported type "
+ bean.getClass() + " for bean " + bean);
}
public String validFilename(String name) {
// Make a relative URI
URI uri;
try {
uri = new URI(null, null, name, null, null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid name " + name);
}
String ascii = uri.toASCIIString();
// And escape / and \
String escaped = ascii.replace("/", "%2f");
// escaped = escaped.replace("\\", "%5c");
escaped = escaped.replace(":", "%3a");
escaped = escaped.replace("=", "%3d");
return escaped;
}
}
| scufl2-api/src/main/java/uk/org/taverna/scufl2/api/common/URITools.java | package uk.org.taverna.scufl2.api.common;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import uk.org.taverna.scufl2.api.common.Visitor.VisitorWithPath;
import uk.org.taverna.scufl2.api.configurations.Configuration;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.core.BlockingControlLink;
import uk.org.taverna.scufl2.api.core.DataLink;
import uk.org.taverna.scufl2.api.core.Workflow;
import uk.org.taverna.scufl2.api.dispatchstack.DispatchStack;
import uk.org.taverna.scufl2.api.dispatchstack.DispatchStackLayer;
import uk.org.taverna.scufl2.api.iterationstrategy.IterationStrategyNode;
import uk.org.taverna.scufl2.api.iterationstrategy.IterationStrategyStack;
import uk.org.taverna.scufl2.api.port.InputPort;
import uk.org.taverna.scufl2.api.port.OutputPort;
import uk.org.taverna.scufl2.api.port.Port;
import uk.org.taverna.scufl2.api.port.ProcessorPort;
import uk.org.taverna.scufl2.api.profiles.ProcessorPortBinding;
import uk.org.taverna.scufl2.api.property.PropertyResource;
public class URITools {
private static final String MERGE_POSITION = "mergePosition";
private static final String TO = "to";
private static final String FROM = "from";
private static final String DATALINK = "datalink";
private static final URI DOT = URI.create(".");
public URI relativePath(URI base, URI uri) {
URI root = base.resolve("/");
if (!root.equals(uri.resolve("/"))) {
// Different protocol/host/auth
return uri;
}
base = base.normalize();
uri = uri.normalize();
if (base.resolve("#").equals(uri.resolve("#"))) {
// Same path, easy
return base.relativize(uri);
}
if (base.isAbsolute()) {
// Ignore hostname and protocol
base = root.relativize(base).resolve(".");
uri = root.relativize(uri);
}
// Pretend they start from /
base = root.resolve(base).resolve(".");
uri = root.resolve(uri);
URI candidate = base.relativize(uri);
URI relation = DOT;
while (candidate.getPath().startsWith("/")
&& !(base.getPath().isEmpty() || base.getPath().equals("/"))) {
base = base.resolve("../");
relation = relation.resolve("../");
candidate = base.relativize(uri);
}
// Add the ../.. again
URI resolved = relation.resolve(candidate);
return resolved;
}
public URI relativeUriForBean(WorkflowBean bean, WorkflowBean relativeToBean) {
URI rootUri = uriForBean(relativeToBean);
URI beanUri = uriForBean(bean);
return relativePath(rootUri, beanUri);
}
public WorkflowBean resolveUri(URI uri, WorkflowBundle wfBundle) {
// Naive, super-inefficient reverse-lookup - we could have even returned
// early!
final Map<URI, WorkflowBean> uriToBean = new HashMap<URI, WorkflowBean>();
wfBundle.accept(new VisitorWithPath() {
@Override
public boolean visit() {
WorkflowBean node = getCurrentNode();
URI uri = uriForBean(node);
WorkflowBean existing = uriToBean.put(uri, node);
if (existing != null) {
String msg = "Multiple nodes with same URI {0}: {1} {2}";
throw new IllegalStateException(MessageFormat.format(msg,
uri, existing, node));
}
return !(node instanceof Configuration);
}
});
if (! uri.isAbsolute()) {
// Make absolute
uri = uriForBean(wfBundle).resolve(uri);
}
return uriToBean.get(uri);
}
public URI uriForBean(WorkflowBean bean) {
if (bean == null) {
throw new NullPointerException("Bean can't be null");
}
if (bean instanceof Root) {
Root root = (Root) bean;
if (root.getSameBaseAs() == null) {
if (root instanceof WorkflowBundle) {
root.setSameBaseAs(WorkflowBundle.generateIdentifier());
} else {
throw new IllegalArgumentException(
"sameBaseAs is null for bean " + bean);
}
}
return root.getSameBaseAs();
}
if (bean instanceof Child) {
Child child = (Child) bean;
WorkflowBean parent = child.getParent();
if (parent == null) {
throw new IllegalStateException("Bean does not have a parent: "
+ child);
}
URI parentUri = uriForBean(parent);
if (!parentUri.getPath().endsWith("/")) {
parentUri = parentUri.resolve(parentUri.getPath() + "/");
}
String relation;
if (child instanceof InputPort) {
relation = "in/";
} else if (child instanceof OutputPort) {
relation = "out/";
} else if (child instanceof IterationStrategyStack) {
relation = "iterationstrategy/";
} else {
// TODO: Get relation by container annotations
relation = child.getClass().getSimpleName() + "/";
// Stupid fallback
}
URI relationURI = parentUri.resolve(relation.toLowerCase());
if (parent instanceof List) {
int index = ((List) parent).indexOf(child);
return parentUri.resolve(index + "/");
}
if (bean instanceof Named) {
Named named = (Named) bean;
String name = validFilename(named.getName());
if (!(bean instanceof Port)) {
name = name + "/";
}
return relationURI.resolve(name);
} else if (bean instanceof DataLink) {
DataLink dataLink = (DataLink) bean;
Workflow wf = dataLink.getParent();
URI wfUri = uriForBean(wf);
URI receivesFrom = relativePath(wfUri,
uriForBean(dataLink.getReceivesFrom()));
URI sendsTo = relativePath(wfUri,
uriForBean(dataLink.getSendsTo()));
String dataLinkUri = MessageFormat.format(
"{0}?{1}={2}&{3}={4}", DATALINK, FROM, receivesFrom,
TO, sendsTo);
if (dataLink.getMergePosition() != null) {
dataLinkUri += MessageFormat.format("&{0}={1}",
MERGE_POSITION, dataLink.getMergePosition());
}
return wfUri.resolve(dataLinkUri);
} else if(bean instanceof BlockingControlLink) {
BlockingControlLink runAfterCondition = (BlockingControlLink) bean;
Workflow wf = runAfterCondition.getParent();
URI wfUri = uriForBean(wf);
URI start = relativePath(wfUri,
uriForBean(runAfterCondition.getBlock()));
URI after = relativePath(wfUri,
uriForBean(runAfterCondition.getUntilFinished()));
String conditionUri = MessageFormat.format("{0}?{1}={2}&{3}={4}",
"control", "block", start,
"untilFinished", after);
return wfUri.resolve(conditionUri);
} else if (bean instanceof DispatchStack) {
return relationURI;
} else if (bean instanceof DispatchStackLayer) {
DispatchStackLayer dispatchStackLayer = (DispatchStackLayer) bean;
} else if (bean instanceof IterationStrategyStack) {
return relationURI;
} else if (bean instanceof IterationStrategyNode) {
IterationStrategyNode iterationStrategyNode = (IterationStrategyNode) bean;
parent = iterationStrategyNode.getParent();
List<IterationStrategyNode> parentList = (List<IterationStrategyNode>) parent;
int index = parentList.indexOf(iterationStrategyNode);
return parentUri.resolve(index + "/");
} else if (bean instanceof ProcessorPortBinding) {
// Named after the processor port, extract in/blah part.
ProcessorPortBinding<?, ?> processorPortBinding = (ProcessorPortBinding<?, ?>) bean;
ProcessorPort procPort = processorPortBinding
.getBoundProcessorPort();
URI procPortUri = relativeUriForBean(procPort,
processorPortBinding.getParent().getBoundProcessor());
return parentUri.resolve(procPortUri);
} else {
throw new IllegalStateException(
"Can't create URIs for non-named child: " + bean);
}
}
if (bean instanceof PropertyResource) {
PropertyResource propertyResource = (PropertyResource) bean;
URI resourceURI = propertyResource.getResourceURI();
if (resourceURI != null) {
return resourceURI;
}
throw new IllegalStateException(
"PropertyResource does not have a resourceURI");
}
throw new IllegalArgumentException("Unsupported type "
+ bean.getClass() + " for bean " + bean);
}
public String validFilename(String name) {
// Make a relative URI
URI uri;
try {
uri = new URI(null, null, name, null, null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid name " + name);
}
String ascii = uri.toASCIIString();
// And escape / and \
String escaped = ascii.replace("/", "%2f");
// escaped = escaped.replace("\\", "%5c");
escaped = escaped.replace(":", "%3a");
escaped = escaped.replace("=", "%3d");
return escaped;
}
}
| Find workflow by workflow identifiers
git-svn-id: e0a7080a86b4679b823146ccb1bf7147a527563d@12526 bf327186-88b3-11dd-a302-d386e5130c1c
| scufl2-api/src/main/java/uk/org/taverna/scufl2/api/common/URITools.java | Find workflow by workflow identifiers |
|
Java | apache-2.0 | 36207cc88c720c60f9117022b6fe35bdff9bd71d | 0 | apache/wicket,mosoft521/wicket,mosoft521/wicket,apache/wicket,mosoft521/wicket,mosoft521/wicket,mosoft521/wicket,apache/wicket,apache/wicket,apache/wicket | /*
* 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.wicket.page;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.Cookie;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.feedback.FeedbackDelay;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.IWrappedHeaderItem;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.head.OnEventHeaderItem;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.head.PriorityHeaderItem;
import org.apache.wicket.markup.head.internal.HeaderResponse;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.markup.parser.filter.HtmlHeaderSectionHandler;
import org.apache.wicket.markup.renderStrategy.AbstractHeaderRenderStrategy;
import org.apache.wicket.markup.renderStrategy.IHeaderRenderStrategy;
import org.apache.wicket.markup.repeater.AbstractRepeater;
import org.apache.wicket.request.IRequestCycle;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.response.StringResponse;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Generics;
import org.apache.wicket.util.string.AppendingStringBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A partial update of a page that collects components and header contributions to be written to the
* client in a specific String-based format (XML, JSON, * ...).
* <p>
* The elements of such response are:
* <ul>
* <li>component - the markup of the updated component</li>
* <li>header-contribution - all HeaderItems which have been contributed in any{@link Component#renderHead(IHeaderResponse)},
* {@link Behavior#renderHead(Component, IHeaderResponse)} or JavaScript explicitly added via {@link #appendJavaScript(CharSequence)}
* or {@link #prependJavaScript(CharSequence)}</li>
* </ul>
*/
public abstract class PartialPageUpdate
{
private static final Logger LOG = LoggerFactory.getLogger(PartialPageUpdate.class);
/**
* A list of scripts (JavaScript) which should be executed on the client side before the
* components' replacement
*/
protected final List<CharSequence> prependJavaScripts = Generics.newArrayList();
/**
* A list of scripts (JavaScript) which should be executed on the client side after the
* components' replacement
*/
protected final List<CharSequence> appendJavaScripts = Generics.newArrayList();
/**
* A list of scripts (JavaScript) which should be executed on the client side after the
* components' replacement.
* Executed immediately after the replacement of the components, and before appendJavaScripts
*/
protected final List<CharSequence> domReadyJavaScripts = Generics.newArrayList();
/**
* The component instances that will be rendered/replaced.
*/
protected final Map<String, Component> markupIdToComponent = new LinkedHashMap<String, Component>();
/**
* A flag that indicates that components cannot be added anymore.
* See https://issues.apache.org/jira/browse/WICKET-3564
*
* @see #add(Component, String)
*/
protected transient boolean componentsFrozen;
/**
* Buffer of response body.
*/
protected final ResponseBuffer bodyBuffer;
/**
* Buffer of response header.
*/
protected final ResponseBuffer headerBuffer;
protected HtmlHeaderContainer header = null;
private Component originalHeaderContainer = null;
// whether a header contribution is being rendered
private boolean headerRendering = false;
private IHeaderResponse headerResponse;
/**
* The page which components are being updated.
*/
private final Page page;
/**
* Constructor.
*
* @param page
* the page which components are being updated.
*/
public PartialPageUpdate(final Page page)
{
this.page = page;
this.originalHeaderContainer = page.get(HtmlHeaderSectionHandler.HEADER_ID);
WebResponse response = (WebResponse) page.getResponse();
bodyBuffer = new ResponseBuffer(response);
headerBuffer = new ResponseBuffer(response);
}
/**
* Serializes this object to the response.
*
* @param response
* the response to write to
* @param encoding
* the encoding for the response
*/
public void writeTo(final Response response, final String encoding)
{
try {
writeHeader(response, encoding);
onBeforeRespond(response);
// queue up prepend javascripts. unlike other steps these are executed out of order so that
// components can contribute them from inside their onbeforerender methods.
writeEvaluations(response, prependJavaScripts);
// process added components
writeComponents(response, encoding);
onAfterRespond(response);
// execute the dom ready javascripts as first javascripts
// after component replacement
List<CharSequence> evaluationScripts = new ArrayList<>();
evaluationScripts.addAll(domReadyJavaScripts);
evaluationScripts.addAll(appendJavaScripts);
writeEvaluations(response, evaluationScripts);
writeFooter(response, encoding);
} finally {
if (header != null && originalHeaderContainer!= null) {
// restore a normal header
page.replace(originalHeaderContainer);
header = null;
}
}
}
/**
* Hook-method called before components are written.
*
* @param response
*/
protected void onBeforeRespond(Response response) {
}
/**
* Hook-method called after components are written.
*
* @param response
*/
protected void onAfterRespond(Response response) {
}
/**
* @param response
* the response to write to
* @param encoding
* the encoding for the response
*/
protected abstract void writeFooter(Response response, String encoding);
/**
*
* @param response
* the response to write to
* @param js
* the JavaScript to evaluate
*/
protected void writeEvaluations(final Response response, Collection<CharSequence> scripts)
{
if (scripts.size() > 0)
{
StringBuilder combinedScript = new StringBuilder(1024);
for (CharSequence script : scripts)
{
combinedScript.append("(function(){").append(script).append("})();");
}
StringResponse stringResponse = new StringResponse();
IHeaderResponse headerResponse = Application.get().decorateHeaderResponse(new HeaderResponse()
{
@Override
protected Response getRealResponse()
{
return stringResponse;
}
});
headerResponse.render(JavaScriptHeaderItem.forScript(combinedScript, null));
headerResponse.close();
writeHeaderContribution(response, stringResponse.getBuffer());
}
}
/**
* Processes components added to the target. This involves attaching components, rendering
* markup into a client side xml envelope, and detaching them
*
* @param response
* the response to write to
* @param encoding
* the encoding for the response
*/
private void writeComponents(Response response, String encoding)
{
componentsFrozen = true;
List<Component> toBeWritten = new ArrayList<>(markupIdToComponent.size());
// delay preparation of feedbacks after all other components
try (FeedbackDelay delay = new FeedbackDelay(RequestCycle.get())) {
for (Component component : markupIdToComponent.values())
{
if (!containsAncestorFor(component))
{
if (prepareComponent(component)) {
toBeWritten.add(component);
}
}
}
// .. now prepare all postponed feedbacks
delay.beforeRender();
}
// write components
for (Component component : toBeWritten)
{
writeComponent(response, component.getAjaxRegionMarkupId(), component, encoding);
}
if (header != null)
{
RequestCycle cycle = RequestCycle.get();
// some header responses buffer all calls to render*** until close is called.
// when they are closed, they do something (i.e. aggregate all JS resource urls to a
// single url), and then "flush" (by writing to the real response) before closing.
// to support this, we need to allow header contributions to be written in the close
// tag, which we do here:
headerRendering = true;
// save old response, set new
Response oldResponse = cycle.setResponse(headerBuffer);
headerBuffer.reset();
// now, close the response (which may render things)
header.getHeaderResponse().close();
// revert to old response
cycle.setResponse(oldResponse);
// write the XML tags and we're done
writeHeaderContribution(response, headerBuffer.getContents());
headerRendering = false;
}
}
/**
* Prepare a single component
*
* @param component
* the component to prepare
* @return wether the component was prepared
*/
protected boolean prepareComponent(Component component)
{
if (component.getRenderBodyOnly() == true)
{
throw new IllegalStateException(
"A partial update is not possible for a component that has renderBodyOnly enabled. Component: " +
component.toString());
}
component.setOutputMarkupId(true);
// Initialize temporary variables
final Page page = component.findParent(Page.class);
if (page == null)
{
// dont throw an exception but just ignore this component, somehow
// it got removed from the page.
LOG.warn("Component '{}' not rendered because it was already removed from page", component);
return false;
}
try
{
component.beforeRender();
}
catch (RuntimeException e)
{
bodyBuffer.reset();
throw e;
}
return true;
}
/**
* Writes a single component
*
* @param response
* the response to write to
* @param markupId
* the markup id to use for the component replacement
* @param component
* the component which markup will be used as replacement
* @param encoding
* the encoding for the response
*/
protected abstract void writeComponent(Response response, String markupId, Component component, String encoding);
/**
* Writes the head part of the response.
* For example XML preamble
*
* @param response
* the response to write to
* @param encoding
* the encoding for the response
*/
protected abstract void writeHeader(Response response, String encoding);
/**
* Writes header contribution (<link/> or <script/>) to the response.
*
* @param response
* the response to write to
*/
protected abstract void writeHeaderContribution(Response response, CharSequence contents);
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PartialPageUpdate that = (PartialPageUpdate) o;
if (!appendJavaScripts.equals(that.appendJavaScripts)) return false;
if (!domReadyJavaScripts.equals(that.domReadyJavaScripts)) return false;
return prependJavaScripts.equals(that.prependJavaScripts);
}
@Override
public int hashCode()
{
int result = prependJavaScripts.hashCode();
result = 31 * result + appendJavaScripts.hashCode();
result = 31 * result + domReadyJavaScripts.hashCode();
return result;
}
/**
* Adds script to the ones which are executed after the component replacement.
*
* @param javascript
* the javascript to execute
*/
public final void appendJavaScript(final CharSequence javascript)
{
Args.notNull(javascript, "javascript");
appendJavaScripts.add(javascript);
}
/**
* Adds script to the ones which are executed before the component replacement.
*
* @param javascript
* the javascript to execute
*/
public final void prependJavaScript(CharSequence javascript)
{
Args.notNull(javascript, "javascript");
prependJavaScripts.add(javascript);
}
/**
* Adds a component to be updated at the client side with its current markup
*
* @param component
* the component to update
* @param markupId
* the markup id to use to find the component in the page's markup
* @throws IllegalArgumentException
* thrown when a Page or an AbstractRepeater is added
* @throws IllegalStateException
* thrown when components no more can be added for replacement.
*/
public final void add(final Component component, final String markupId)
throws IllegalArgumentException, IllegalStateException
{
Args.notEmpty(markupId, "markupId");
Args.notNull(component, "component");
if (component instanceof Page)
{
if (component != page)
{
throw new IllegalArgumentException("Cannot add another page");
}
}
else
{
Page pageOfComponent = component.findParent(Page.class);
if (pageOfComponent == null)
{
// no longer on page - log the error but don't block the user of the application
// (which was the behavior in Wicket <= 7).
LOG.warn("Component '{}' not cannot be updated because it was already removed from page", component);
return;
}
else if (pageOfComponent != page)
{
// on another page
throw new IllegalArgumentException("Component " + component.toString() + " cannot be updated because it is on another page.");
}
if (component instanceof AbstractRepeater)
{
throw new IllegalArgumentException(
"Component " +
component.getClass().getName() +
" is a repeater and cannot be added to a partial page update directly. " +
"Instead add its parent or another markup container higher in the hierarchy.");
}
}
if (componentsFrozen)
{
throw new IllegalStateException("A partial update of the page is being rendered, component " + component.toString() + " can no longer be added");
}
component.setMarkupId(markupId);
markupIdToComponent.put(markupId, component);
}
/**
* @return a read-only collection of all components which have been added for replacement so far.
*/
public final Collection<? extends Component> getComponents()
{
return Collections.unmodifiableCollection(markupIdToComponent.values());
}
/**
* Detaches the page if at least one of its components was updated.
*
* @param requestCycle
* the current request cycle
*/
public void detach(IRequestCycle requestCycle)
{
Iterator<Component> iterator = markupIdToComponent.values().iterator();
while (iterator.hasNext())
{
final Component component = iterator.next();
final Page parentPage = component.findParent(Page.class);
if (parentPage != null)
{
parentPage.detach();
break;
}
}
}
/**
* Checks if the target contains an ancestor for the given component
*
* @param component
* the component which ancestors should be checked.
* @return <code>true</code> if target contains an ancestor for the given component
*/
protected boolean containsAncestorFor(Component component)
{
Component cursor = component.getParent();
while (cursor != null)
{
if (markupIdToComponent.containsValue(cursor))
{
return true;
}
cursor = cursor.getParent();
}
return false;
}
/**
* @return {@code true} if the page has been added for replacement
*/
public boolean containsPage()
{
return markupIdToComponent.values().contains(page);
}
/**
* Gets or creates an IHeaderResponse instance to use for the header contributions.
*
* @return IHeaderResponse instance to use for the header contributions.
*/
public IHeaderResponse getHeaderResponse()
{
if (headerResponse == null)
{
// we don't need to decorate the header response here because this is called from
// within PartialHtmlHeaderContainer, which decorates the response
headerResponse = new PartialHeaderResponse();
}
return headerResponse;
}
/**
* @param response
* the response to write to
* @param component
* to component which will contribute to the header
*/
protected void writeHeaderContribution(final Response response, final Component component)
{
headerRendering = true;
// create the htmlheadercontainer if needed
if (header == null)
{
header = new PartialHtmlHeaderContainer(this);
page.addOrReplace(header);
}
RequestCycle requestCycle = component.getRequestCycle();
// save old response, set new
Response oldResponse = requestCycle.setResponse(headerBuffer);
try {
headerBuffer.reset();
IHeaderRenderStrategy strategy = AbstractHeaderRenderStrategy.get();
strategy.renderHeader(header, null, component);
} finally {
// revert to old response
requestCycle.setResponse(oldResponse);
}
writeHeaderContribution(response, headerBuffer.getContents());
headerRendering = false;
}
/**
* Sets the Content-Type header to indicate the type of the response.
*
* @param response
* the current we response
* @param encoding
* the encoding to use
*/
public abstract void setContentType(WebResponse response, String encoding);
/**
* Header container component for partial page updates.
* <p>
* This container is temporarily injected into the page to provide the
* {@link IHeaderResponse} while components are rendered. It is never
* rendered itself.
*
* @author Matej Knopp
*/
private static class PartialHtmlHeaderContainer extends HtmlHeaderContainer
{
private static final long serialVersionUID = 1L;
/**
* Keep transiently, in case the containing page gets serialized before
* this container is removed again. This happens when DebugBar determines
* the page size by serializing/deserializing it.
*/
private transient PartialPageUpdate pageUpdate;
/**
* Constructor.
*
* @param update
* the partial page update
*/
public PartialHtmlHeaderContainer(PartialPageUpdate pageUpdate)
{
super(HtmlHeaderSectionHandler.HEADER_ID);
this.pageUpdate = pageUpdate;
}
/**
*
* @see org.apache.wicket.markup.html.internal.HtmlHeaderContainer#newHeaderResponse()
*/
@Override
protected IHeaderResponse newHeaderResponse()
{
if (pageUpdate == null) {
throw new IllegalStateException("disconnected from pageUpdate after serialization");
}
return pageUpdate.getHeaderResponse();
}
}
/**
* Header response for partial updates.
*
* @author Matej Knopp
*/
private class PartialHeaderResponse extends HeaderResponse
{
@Override
public void render(HeaderItem item)
{
while (item instanceof IWrappedHeaderItem)
{
item = ((IWrappedHeaderItem) item).getWrapped();
}
if (item instanceof OnLoadHeaderItem)
{
if (!wasItemRendered(item))
{
PartialPageUpdate.this.appendJavaScript(((OnLoadHeaderItem) item).getJavaScript());
markItemRendered(item);
}
}
else if (item instanceof OnEventHeaderItem)
{
if (!wasItemRendered(item))
{
PartialPageUpdate.this.appendJavaScript(((OnEventHeaderItem) item).getCompleteJavaScript());
markItemRendered(item);
}
}
else if (item instanceof OnDomReadyHeaderItem)
{
if (!wasItemRendered(item))
{
PartialPageUpdate.this.domReadyJavaScripts.add(((OnDomReadyHeaderItem)item).getJavaScript());
markItemRendered(item);
}
}
else if (headerRendering)
{
super.render(item);
}
else
{
LOG.debug("Only methods that can be called on IHeaderResponse outside renderHead() are #render(OnLoadHeaderItem) and #render(OnDomReadyHeaderItem)");
}
}
@Override
protected Response getRealResponse()
{
return RequestCycle.get().getResponse();
}
}
/**
* Wrapper of a response that buffers its contents.
*
* @author Igor Vaynberg (ivaynberg)
* @author Sven Meier (svenmeier)
*
* @see ResponseBuffer#getContents()
* @see ResponseBuffer#reset()
*/
protected static final class ResponseBuffer extends WebResponse
{
private final AppendingStringBuffer buffer = new AppendingStringBuffer(256);
private final WebResponse originalResponse;
/**
* Constructor.
*
* @param originalResponse
* the original request cycle response
*/
private ResponseBuffer(WebResponse originalResponse)
{
this.originalResponse = originalResponse;
}
/**
* @see org.apache.wicket.request.Response#encodeURL(CharSequence)
*/
@Override
public String encodeURL(CharSequence url)
{
return originalResponse.encodeURL(url);
}
/**
* @return contents of the response
*/
public CharSequence getContents()
{
return buffer;
}
/**
* @see org.apache.wicket.request.Response#write(CharSequence)
*/
@Override
public void write(CharSequence cs)
{
buffer.append(cs);
}
/**
* Resets the response to a clean state so it can be reused to save on garbage.
*/
@Override
public void reset()
{
buffer.clear();
}
@Override
public void write(byte[] array)
{
throw new UnsupportedOperationException("Cannot write binary data.");
}
@Override
public void write(byte[] array, int offset, int length)
{
throw new UnsupportedOperationException("Cannot write binary data.");
}
@Override
public Object getContainerResponse()
{
return originalResponse.getContainerResponse();
}
@Override
public void addCookie(Cookie cookie)
{
originalResponse.addCookie(cookie);
}
@Override
public void clearCookie(Cookie cookie)
{
originalResponse.clearCookie(cookie);
}
@Override
public void setHeader(String name, String value)
{
originalResponse.setHeader(name, value);
}
@Override
public void addHeader(String name, String value)
{
originalResponse.addHeader(name, value);
}
@Override
public void setDateHeader(String name, Instant date)
{
originalResponse.setDateHeader(name, date);
}
@Override
public void setContentLength(long length)
{
originalResponse.setContentLength(length);
}
@Override
public void setContentType(String mimeType)
{
originalResponse.setContentType(mimeType);
}
@Override
public void setStatus(int sc)
{
originalResponse.setStatus(sc);
}
@Override
public void sendError(int sc, String msg)
{
originalResponse.sendError(sc, msg);
}
@Override
public String encodeRedirectURL(CharSequence url)
{
return originalResponse.encodeRedirectURL(url);
}
@Override
public void sendRedirect(String url)
{
originalResponse.sendRedirect(url);
}
@Override
public boolean isRedirect()
{
return originalResponse.isRedirect();
}
@Override
public void flush()
{
originalResponse.flush();
}
}
} | wicket-core/src/main/java/org/apache/wicket/page/PartialPageUpdate.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.wicket.page;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.Cookie;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.feedback.FeedbackDelay;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.IWrappedHeaderItem;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.head.OnEventHeaderItem;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.head.PriorityHeaderItem;
import org.apache.wicket.markup.head.internal.HeaderResponse;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.markup.parser.filter.HtmlHeaderSectionHandler;
import org.apache.wicket.markup.renderStrategy.AbstractHeaderRenderStrategy;
import org.apache.wicket.markup.renderStrategy.IHeaderRenderStrategy;
import org.apache.wicket.markup.repeater.AbstractRepeater;
import org.apache.wicket.request.IRequestCycle;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.response.StringResponse;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Generics;
import org.apache.wicket.util.string.AppendingStringBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A partial update of a page that collects components and header contributions to be written to the
* client in a specific String-based format (XML, JSON, * ...).
* <p>
* The elements of such response are:
* <ul>
* <li>component - the markup of the updated component</li>
* <li>header-contribution - all HeaderItems which have been contributed in any{@link Component#renderHead(IHeaderResponse)},
* {@link Behavior#renderHead(Component, IHeaderResponse)} or JavaScript explicitly added via {@link #appendJavaScript(CharSequence)}
* or {@link #prependJavaScript(CharSequence)}</li>
* </ul>
*/
public abstract class PartialPageUpdate
{
private static final Logger LOG = LoggerFactory.getLogger(PartialPageUpdate.class);
/**
* A list of scripts (JavaScript) which should be executed on the client side before the
* components' replacement
*/
protected final List<CharSequence> prependJavaScripts = Generics.newArrayList();
/**
* A list of scripts (JavaScript) which should be executed on the client side after the
* components' replacement
*/
protected final List<CharSequence> appendJavaScripts = Generics.newArrayList();
/**
* A list of scripts (JavaScript) which should be executed on the client side after the
* components' replacement.
* Executed immediately after the replacement of the components, and before appendJavaScripts
*/
protected final List<CharSequence> domReadyJavaScripts = Generics.newArrayList();
/**
* The component instances that will be rendered/replaced.
*/
protected final Map<String, Component> markupIdToComponent = new LinkedHashMap<String, Component>();
/**
* A flag that indicates that components cannot be added anymore.
* See https://issues.apache.org/jira/browse/WICKET-3564
*
* @see #add(Component, String)
*/
protected transient boolean componentsFrozen;
/**
* Buffer of response body.
*/
protected final ResponseBuffer bodyBuffer;
/**
* Buffer of response header.
*/
protected final ResponseBuffer headerBuffer;
protected HtmlHeaderContainer header = null;
private Component originalHeaderContainer = null;
// whether a header contribution is being rendered
private boolean headerRendering = false;
private IHeaderResponse headerResponse;
/**
* The page which components are being updated.
*/
private final Page page;
/**
* Constructor.
*
* @param page
* the page which components are being updated.
*/
public PartialPageUpdate(final Page page)
{
this.page = page;
this.originalHeaderContainer = page.get(HtmlHeaderSectionHandler.HEADER_ID);
WebResponse response = (WebResponse) page.getResponse();
bodyBuffer = new ResponseBuffer(response);
headerBuffer = new ResponseBuffer(response);
}
/**
* Serializes this object to the response.
*
* @param response
* the response to write to
* @param encoding
* the encoding for the response
*/
public void writeTo(final Response response, final String encoding)
{
try {
writeHeader(response, encoding);
onBeforeRespond(response);
// queue up prepend javascripts. unlike other steps these are executed out of order so that
// components can contribute them from inside their onbeforerender methods.
writeEvaluations(response, prependJavaScripts);
// process added components
writeComponents(response, encoding);
onAfterRespond(response);
// execute the dom ready javascripts as first javascripts
// after component replacement
List<CharSequence> evaluationScripts = new ArrayList<>();
evaluationScripts.addAll(domReadyJavaScripts);
evaluationScripts.addAll(appendJavaScripts);
writeEvaluations(response, evaluationScripts);
writeFooter(response, encoding);
} finally {
if (header != null && originalHeaderContainer!= null) {
// restore a normal header
page.replace(originalHeaderContainer);
header = null;
}
}
}
/**
* Hook-method called before components are written.
*
* @param response
*/
protected void onBeforeRespond(Response response) {
}
/**
* Hook-method called after components are written.
*
* @param response
*/
protected void onAfterRespond(Response response) {
}
/**
* @param response
* the response to write to
* @param encoding
* the encoding for the response
*/
protected abstract void writeFooter(Response response, String encoding);
/**
*
* @param response
* the response to write to
* @param js
* the JavaScript to evaluate
*/
protected void writeEvaluations(final Response response, Collection<CharSequence> scripts)
{
if (scripts.size() > 0)
{
StringBuilder combinedScript = new StringBuilder(1024);
for (CharSequence script : scripts)
{
combinedScript.append("(function(){").append(script).append("})();");
}
StringResponse stringResponse = new StringResponse();
IHeaderResponse headerResponse = Application.get().decorateHeaderResponse(new HeaderResponse()
{
@Override
protected Response getRealResponse()
{
return stringResponse;
}
});
headerResponse.render(JavaScriptHeaderItem.forScript(combinedScript, null));
headerResponse.close();
writeHeaderContribution(response, stringResponse.getBuffer());
}
}
/**
* Processes components added to the target. This involves attaching components, rendering
* markup into a client side xml envelope, and detaching them
*
* @param response
* the response to write to
* @param encoding
* the encoding for the response
*/
private void writeComponents(Response response, String encoding)
{
componentsFrozen = true;
List<Component> toBeWritten = new ArrayList<>(markupIdToComponent.size());
// delay preparation of feedbacks after all other components
try (FeedbackDelay delay = new FeedbackDelay(RequestCycle.get())) {
for (Component component : markupIdToComponent.values())
{
if (!containsAncestorFor(component))
{
if (prepareComponent(component)) {
toBeWritten.add(component);
}
}
}
// .. now prepare all postponed feedbacks
delay.beforeRender();
}
// write components
for (Component component : toBeWritten)
{
writeComponent(response, component.getAjaxRegionMarkupId(), component, encoding);
}
if (header != null)
{
RequestCycle cycle = RequestCycle.get();
// some header responses buffer all calls to render*** until close is called.
// when they are closed, they do something (i.e. aggregate all JS resource urls to a
// single url), and then "flush" (by writing to the real response) before closing.
// to support this, we need to allow header contributions to be written in the close
// tag, which we do here:
headerRendering = true;
// save old response, set new
Response oldResponse = cycle.setResponse(headerBuffer);
headerBuffer.reset();
// now, close the response (which may render things)
header.getHeaderResponse().close();
// revert to old response
cycle.setResponse(oldResponse);
// write the XML tags and we're done
writeHeaderContribution(response, headerBuffer.getContents());
headerRendering = false;
}
}
/**
* Prepare a single component
*
* @param component
* the component to prepare
* @return wether the component was prepared
*/
protected boolean prepareComponent(Component component)
{
if (component.getRenderBodyOnly() == true)
{
throw new IllegalStateException(
"A partial update is not possible for a component that has renderBodyOnly enabled. Component: " +
component.toString());
}
component.setOutputMarkupId(true);
// Initialize temporary variables
final Page page = component.findParent(Page.class);
if (page == null)
{
// dont throw an exception but just ignore this component, somehow
// it got removed from the page.
LOG.warn("Component '{}' not rendered because it was already removed from page", component);
return false;
}
try
{
component.beforeRender();
}
catch (RuntimeException e)
{
bodyBuffer.reset();
throw e;
}
return true;
}
/**
* Writes a single component
*
* @param response
* the response to write to
* @param markupId
* the markup id to use for the component replacement
* @param component
* the component which markup will be used as replacement
* @param encoding
* the encoding for the response
*/
protected abstract void writeComponent(Response response, String markupId, Component component, String encoding);
/**
* Writes the head part of the response.
* For example XML preamble
*
* @param response
* the response to write to
* @param encoding
* the encoding for the response
*/
protected abstract void writeHeader(Response response, String encoding);
/**
* Writes header contribution (<link/> or <script/>) to the response.
*
* @param response
* the response to write to
*/
protected abstract void writeHeaderContribution(Response response, CharSequence contents);
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PartialPageUpdate that = (PartialPageUpdate) o;
if (!appendJavaScripts.equals(that.appendJavaScripts)) return false;
if (!domReadyJavaScripts.equals(that.domReadyJavaScripts)) return false;
return prependJavaScripts.equals(that.prependJavaScripts);
}
@Override
public int hashCode()
{
int result = prependJavaScripts.hashCode();
result = 31 * result + appendJavaScripts.hashCode();
result = 31 * result + domReadyJavaScripts.hashCode();
return result;
}
/**
* Adds script to the ones which are executed after the component replacement.
*
* @param javascript
* the javascript to execute
*/
public final void appendJavaScript(final CharSequence javascript)
{
Args.notNull(javascript, "javascript");
appendJavaScripts.add(javascript);
}
/**
* Adds script to the ones which are executed before the component replacement.
*
* @param javascript
* the javascript to execute
*/
public final void prependJavaScript(CharSequence javascript)
{
Args.notNull(javascript, "javascript");
prependJavaScripts.add(javascript);
}
/**
* Adds a component to be updated at the client side with its current markup
*
* @param component
* the component to update
* @param markupId
* the markup id to use to find the component in the page's markup
* @throws IllegalArgumentException
* thrown when a Page or an AbstractRepeater is added
* @throws IllegalStateException
* thrown when components no more can be added for replacement.
*/
public final void add(final Component component, final String markupId)
throws IllegalArgumentException, IllegalStateException
{
Args.notEmpty(markupId, "markupId");
Args.notNull(component, "component");
if (component instanceof Page)
{
if (component != page)
{
throw new IllegalArgumentException("Cannot add another page");
}
}
else
{
Page pageOfComponent = component.findParent(Page.class);
if (pageOfComponent == null)
{
// no longer on page - log the error but don't block the user of the application
// (which was the behavior in Wicket <= 7).
LOG.warn("Component '{}' not cannot be updated because it was already removed from page", component);
return;
}
else if (pageOfComponent != page)
{
// on another page
throw new IllegalArgumentException("Component " + component.toString() + " cannot be updated because it is on another page.");
}
if (component instanceof AbstractRepeater)
{
throw new IllegalArgumentException(
"Component " +
component.getClass().getName() +
" is a repeater and cannot be added to a partial page update directly. " +
"Instead add its parent or another markup container higher in the hierarchy.");
}
}
if (componentsFrozen)
{
throw new IllegalStateException("A partial update of the page is being rendered, component " + component.toString() + " can no longer be added");
}
component.setMarkupId(markupId);
markupIdToComponent.put(markupId, component);
}
/**
* @return a read-only collection of all components which have been added for replacement so far.
*/
public final Collection<? extends Component> getComponents()
{
return Collections.unmodifiableCollection(markupIdToComponent.values());
}
/**
* Detaches the page if at least one of its components was updated.
*
* @param requestCycle
* the current request cycle
*/
public void detach(IRequestCycle requestCycle)
{
Iterator<Component> iterator = markupIdToComponent.values().iterator();
while (iterator.hasNext())
{
final Component component = iterator.next();
final Page parentPage = component.findParent(Page.class);
if (parentPage != null)
{
parentPage.detach();
break;
}
}
}
/**
* Checks if the target contains an ancestor for the given component
*
* @param component
* the component which ancestors should be checked.
* @return <code>true</code> if target contains an ancestor for the given component
*/
protected boolean containsAncestorFor(Component component)
{
Component cursor = component.getParent();
while (cursor != null)
{
if (markupIdToComponent.containsValue(cursor))
{
return true;
}
cursor = cursor.getParent();
}
return false;
}
/**
* @return {@code true} if the page has been added for replacement
*/
public boolean containsPage()
{
return markupIdToComponent.values().contains(page);
}
/**
* Gets or creates an IHeaderResponse instance to use for the header contributions.
*
* @return IHeaderResponse instance to use for the header contributions.
*/
public IHeaderResponse getHeaderResponse()
{
if (headerResponse == null)
{
// we don't need to decorate the header response here because this is called from
// within PartialHtmlHeaderContainer, which decorates the response
headerResponse = new PartialHeaderResponse();
}
return headerResponse;
}
/**
* @param response
* the response to write to
* @param component
* to component which will contribute to the header
*/
protected void writeHeaderContribution(final Response response, final Component component)
{
headerRendering = true;
// create the htmlheadercontainer if needed
if (header == null)
{
header = new PartialHtmlHeaderContainer(this);
page.addOrReplace(header);
}
RequestCycle requestCycle = component.getRequestCycle();
// save old response, set new
Response oldResponse = requestCycle.setResponse(headerBuffer);
try {
headerBuffer.reset();
IHeaderRenderStrategy strategy = AbstractHeaderRenderStrategy.get();
strategy.renderHeader(header, null, component);
} finally {
// revert to old response
requestCycle.setResponse(oldResponse);
}
writeHeaderContribution(response, headerBuffer.getContents());
headerRendering = false;
}
/**
* Sets the Content-Type header to indicate the type of the response.
*
* @param response
* the current we response
* @param encoding
* the encoding to use
*/
public abstract void setContentType(WebResponse response, String encoding);
/**
* Header container component for partial page updates.
* <p>
* This container is temporarily injected into the page to provide the
* {@link IHeaderResponse} while components are rendered. It is never
* rendered itself.
*
* @author Matej Knopp
*/
private static class PartialHtmlHeaderContainer extends HtmlHeaderContainer
{
private static final long serialVersionUID = 1L;
/**
* Keep transiently, in case the containing page gets serialized before
* this container is removed again. This happens when DebugBar determines
* the page size by serializing/deserializing it.
*/
private transient PartialPageUpdate pageUpdate;
/**
* Constructor.
*
* @param update
* the partial page update
*/
public PartialHtmlHeaderContainer(PartialPageUpdate pageUpdate)
{
super(HtmlHeaderSectionHandler.HEADER_ID);
this.pageUpdate = pageUpdate;
}
/**
*
* @see org.apache.wicket.markup.html.internal.HtmlHeaderContainer#newHeaderResponse()
*/
@Override
protected IHeaderResponse newHeaderResponse()
{
if (pageUpdate == null) {
throw new IllegalStateException("disconnected from pageUpdate after serialization");
}
return pageUpdate.getHeaderResponse();
}
}
/**
* Header response for partial updates.
*
* @author Matej Knopp
*/
private class PartialHeaderResponse extends HeaderResponse
{
@Override
public void render(HeaderItem item)
{
PriorityHeaderItem priorityHeaderItem = null;
while (item instanceof IWrappedHeaderItem)
{
if (item instanceof PriorityHeaderItem)
{
priorityHeaderItem = (PriorityHeaderItem) item;
}
item = ((IWrappedHeaderItem) item).getWrapped();
}
if (item instanceof OnLoadHeaderItem)
{
if (!wasItemRendered(item))
{
PartialPageUpdate.this.appendJavaScript(((OnLoadHeaderItem) item).getJavaScript());
markItemRendered(item);
}
}
else if (item instanceof OnEventHeaderItem)
{
if (!wasItemRendered(item))
{
PartialPageUpdate.this.appendJavaScript(((OnEventHeaderItem) item).getCompleteJavaScript());
markItemRendered(item);
}
}
else if (item instanceof OnDomReadyHeaderItem)
{
if (!wasItemRendered(item))
{
if (priorityHeaderItem != null)
{
PartialPageUpdate.this.domReadyJavaScripts.add(0, ((OnDomReadyHeaderItem)item).getJavaScript());
}
else
{
PartialPageUpdate.this.domReadyJavaScripts.add(((OnDomReadyHeaderItem)item).getJavaScript());
}
markItemRendered(item);
}
}
else if (headerRendering)
{
super.render(item);
}
else
{
LOG.debug("Only methods that can be called on IHeaderResponse outside renderHead() are #render(OnLoadHeaderItem) and #render(OnDomReadyHeaderItem)");
}
}
@Override
protected Response getRealResponse()
{
return RequestCycle.get().getResponse();
}
}
/**
* Wrapper of a response that buffers its contents.
*
* @author Igor Vaynberg (ivaynberg)
* @author Sven Meier (svenmeier)
*
* @see ResponseBuffer#getContents()
* @see ResponseBuffer#reset()
*/
protected static final class ResponseBuffer extends WebResponse
{
private final AppendingStringBuffer buffer = new AppendingStringBuffer(256);
private final WebResponse originalResponse;
/**
* Constructor.
*
* @param originalResponse
* the original request cycle response
*/
private ResponseBuffer(WebResponse originalResponse)
{
this.originalResponse = originalResponse;
}
/**
* @see org.apache.wicket.request.Response#encodeURL(CharSequence)
*/
@Override
public String encodeURL(CharSequence url)
{
return originalResponse.encodeURL(url);
}
/**
* @return contents of the response
*/
public CharSequence getContents()
{
return buffer;
}
/**
* @see org.apache.wicket.request.Response#write(CharSequence)
*/
@Override
public void write(CharSequence cs)
{
buffer.append(cs);
}
/**
* Resets the response to a clean state so it can be reused to save on garbage.
*/
@Override
public void reset()
{
buffer.clear();
}
@Override
public void write(byte[] array)
{
throw new UnsupportedOperationException("Cannot write binary data.");
}
@Override
public void write(byte[] array, int offset, int length)
{
throw new UnsupportedOperationException("Cannot write binary data.");
}
@Override
public Object getContainerResponse()
{
return originalResponse.getContainerResponse();
}
@Override
public void addCookie(Cookie cookie)
{
originalResponse.addCookie(cookie);
}
@Override
public void clearCookie(Cookie cookie)
{
originalResponse.clearCookie(cookie);
}
@Override
public void setHeader(String name, String value)
{
originalResponse.setHeader(name, value);
}
@Override
public void addHeader(String name, String value)
{
originalResponse.addHeader(name, value);
}
@Override
public void setDateHeader(String name, Instant date)
{
originalResponse.setDateHeader(name, date);
}
@Override
public void setContentLength(long length)
{
originalResponse.setContentLength(length);
}
@Override
public void setContentType(String mimeType)
{
originalResponse.setContentType(mimeType);
}
@Override
public void setStatus(int sc)
{
originalResponse.setStatus(sc);
}
@Override
public void sendError(int sc, String msg)
{
originalResponse.sendError(sc, msg);
}
@Override
public String encodeRedirectURL(CharSequence url)
{
return originalResponse.encodeRedirectURL(url);
}
@Override
public void sendRedirect(String url)
{
originalResponse.sendRedirect(url);
}
@Override
public boolean isRedirect()
{
return originalResponse.isRedirect();
}
@Override
public void flush()
{
originalResponse.flush();
}
}
} | WICKET-6703 priorityHeaderItems are already sorted
in ResourceAggregator | wicket-core/src/main/java/org/apache/wicket/page/PartialPageUpdate.java | WICKET-6703 priorityHeaderItems are already sorted |
|
Java | apache-2.0 | db1facbbcd9369de879851371f8f495388f91d99 | 0 | johnwlockwood/appengine-mapreduce,johnwlockwood/appengine-mapreduce,johnwlockwood/appengine-mapreduce,OsoTech/appengine-mapreduce,OsoTech/appengine-mapreduce,johnwlockwood/appengine-mapreduce,OsoTech/appengine-mapreduce,OsoTech/appengine-mapreduce | // Copyright 2012 Google Inc. All Rights Reserved.
package com.google.appengine.tools.mapreduce.impl;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileStat;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.FinalizationException;
import com.google.appengine.api.files.GSFileOptions;
import com.google.appengine.api.files.LockException;
import com.google.appengine.api.files.RecordReadChannel;
import com.google.appengine.api.files.RecordWriteChannel;
import com.google.appengine.tools.development.testing.LocalFileServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.mapreduce.InputReader;
import com.google.appengine.tools.mapreduce.KeyValue;
import com.google.appengine.tools.mapreduce.MapReduceSpecification;
import com.google.appengine.tools.mapreduce.Mapper;
import com.google.appengine.tools.mapreduce.Marshaller;
import com.google.appengine.tools.mapreduce.Marshallers;
import com.google.appengine.tools.mapreduce.Output;
import com.google.appengine.tools.mapreduce.OutputWriter;
import com.google.appengine.tools.mapreduce.ReducerInput;
import com.google.appengine.tools.mapreduce.inputs.ConsecutiveLongInput;
import com.google.appengine.tools.mapreduce.outputs.NoOutput;
import com.google.appengine.tools.mapreduce.reducers.KeyProjectionReducer;
import junit.framework.TestCase;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
/**
*
*/
public class InMemoryShuffleJobTest extends TestCase {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(InMemoryShuffleJobTest.class.getName());
private static final FileService FILE_SERVICE = FileServiceFactory.getFileService();
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalFileServiceTestConfig());
private final Marshaller<Integer> intMarshaller = Marshallers.getIntegerMarshaller();
private final String mrJobId = "JobId";
private final int inputSize = 1000;
private final int valueRange = 100;
private final int numShards = 10;
private final Mapper<Long, Integer, Integer> mapper = new Mapper<Long, Integer, Integer>() {
private static final long serialVersionUID = -7327871496359562255L;
@Override
public void map(Long value) {
getContext().emit(mapToRand(value), value.intValue());
}
};
private ConsecutiveLongInput input;
private MapReduceSpecification<Long, Integer, Integer, Integer, Void> specification;
@Override
protected void setUp() throws Exception {
super.setUp();
input = new ConsecutiveLongInput(-inputSize, inputSize, numShards);
specification = MapReduceSpecification.<Long, Integer, Integer, Integer, Void>of("JobName",
input,
mapper,
intMarshaller,
intMarshaller,
KeyProjectionReducer.<Integer, Integer>create(),
NoOutput.<Integer, Void>create(numShards));
helper.setUp();
}
@Override
protected void tearDown() throws Exception {
helper.tearDown();
super.tearDown();
}
private static class ThrowingFileWriteChannel implements FileWriteChannel {
private final FileWriteChannel wrapped;
private final double throwProb;
private MockFileService mockFileService;
private ThrowingFileWriteChannel(
MockFileService mockFileService, FileWriteChannel wrapped, double throwProb) {
this.mockFileService = mockFileService;
this.wrapped = wrapped;
this.throwProb = throwProb;
}
@Override
public int write(ByteBuffer src) throws IOException {
throwMaybe();
mockFileService.writeCounter.incrementAndGet();
return wrapped.write(src);
}
private void throwMaybe() throws IOException {
if (mockFileService.r.nextDouble() < throwProb) {
mockFileService.throwCounter.incrementAndGet();
throw new IOException();
}
}
@Override
public boolean isOpen() {
return wrapped.isOpen();
}
@Override
public void close() throws IOException {
throwMaybe();
wrapped.close();
}
@Override
public void closeFinally() throws IllegalStateException, IOException {
throwMaybe();
wrapped.closeFinally();
}
@Override
public int write(ByteBuffer arg0, String arg1) throws IOException {
throwMaybe();
return wrapped.write(arg0, arg1);
}
}
private static class ThrowingFileReadChannel implements FileReadChannel {
private final FileReadChannel wrapped;
private final double throwProb;
private MockFileService mockFileService;
private ThrowingFileReadChannel(
MockFileService mockFileService, FileReadChannel toWrapp, double throwProb) {
this.mockFileService = mockFileService;
wrapped = toWrapp;
this.throwProb = throwProb;
}
@Override
public int read(ByteBuffer dst) throws IOException {
throwMaybe();
mockFileService.readCounter.incrementAndGet();
return wrapped.read(dst);
}
@Override
public boolean isOpen() {
return wrapped.isOpen();
}
@Override
public void close() throws IOException {
throwMaybe();
wrapped.close();
}
private void throwMaybe() throws IOException {
if (mockFileService.r.nextDouble() < throwProb) {
mockFileService.throwCounter.incrementAndGet();
throw new IOException();
}
}
@Override
public long position() throws IOException {
return wrapped.position();
}
@Override
public FileReadChannel position(long arg0) throws IOException {
throwMaybe();
return wrapped.position(arg0);
}
}
private static class ThrowingRecordWriteChannel implements RecordWriteChannel {
private final RecordWriteChannel wrapped;
private final double throwProb;
private MockFileService mockFileService;
private ThrowingRecordWriteChannel(
MockFileService mockFileService, RecordWriteChannel toWrapp, double throwProb) {
this.mockFileService = mockFileService;
wrapped = toWrapp;
this.throwProb = throwProb;
}
@Override
public int write(ByteBuffer src) throws IOException {
throwMaybe();
mockFileService.writeCounter.incrementAndGet();
return wrapped.write(src);
}
private void throwMaybe() throws IOException {
if (mockFileService.r.nextDouble() < throwProb) {
mockFileService.throwCounter.incrementAndGet();
throw new IOException();
}
}
@Override
public boolean isOpen() {
return wrapped.isOpen();
}
@Override
public void close() throws IOException {
throwMaybe();
wrapped.close();
}
@Override
public void closeFinally() throws IllegalStateException, IOException {
throwMaybe();
wrapped.closeFinally();
}
@Override
public int write(ByteBuffer arg0, String arg1) throws IOException {
throwMaybe();
mockFileService.writeCounter.incrementAndGet();
return wrapped.write(arg0, arg1);
}
}
private static class ThrowingRecordReadChannel implements RecordReadChannel {
private final RecordReadChannel wrapped;
private final double throwProb;
private MockFileService mockFileService;
private ThrowingRecordReadChannel(
MockFileService mockFileService, RecordReadChannel toWrapp, double throwProb) {
this.mockFileService = mockFileService;
wrapped = toWrapp;
this.throwProb = throwProb;
}
@Override
public long position() throws IOException {
return wrapped.position();
}
@Override
public void position(long arg0) throws IOException {
throwMaybe();
wrapped.position(arg0);
}
@Override
public ByteBuffer readRecord() throws IOException {
throwMaybe();
mockFileService.readCounter.incrementAndGet();
return wrapped.readRecord();
}
private void throwMaybe() throws IOException {
if (mockFileService.r.nextDouble() < throwProb) {
mockFileService.throwCounter.incrementAndGet();
throw new IOException();
}
}
}
private class MockFileService implements FileService {
private final AtomicInteger readCounter = new AtomicInteger(0);
private final AtomicInteger writeCounter = new AtomicInteger(0);
private final AtomicInteger throwCounter = new AtomicInteger(0);
private final Random r = new Random(17);
private final double throwOnRead;
private final double throwOnWrite;
public MockFileService(double throwOnRead, double throwOnWrite) {
this.throwOnRead = throwOnRead;
this.throwOnWrite = throwOnWrite;
}
@Override
public AppEngineFile createNewBlobFile(String arg0) throws IOException {
return FILE_SERVICE.createNewBlobFile(arg0);
}
@Override
public AppEngineFile createNewBlobFile(String arg0, String arg1) throws IOException {
return FILE_SERVICE.createNewBlobFile(arg0, arg1);
}
@Override
public AppEngineFile createNewGSFile(GSFileOptions arg0) throws IOException {
return FILE_SERVICE.createNewGSFile(arg0);
}
@Override
public AppEngineFile getBlobFile(BlobKey arg0) {
return FILE_SERVICE.getBlobFile(arg0);
}
@Override
public BlobKey getBlobKey(AppEngineFile arg0) {
return FILE_SERVICE.getBlobKey(arg0);
}
@Override
public String getDefaultGsBucketName() throws IOException {
return FILE_SERVICE.getDefaultGsBucketName();
}
@Override
public FileReadChannel openReadChannel(AppEngineFile arg0, boolean arg1)
throws FileNotFoundException, LockException, IOException {
return new ThrowingFileReadChannel(
this, FILE_SERVICE.openReadChannel(arg0, arg1), throwOnRead);
}
@Override
public RecordReadChannel openRecordReadChannel(AppEngineFile arg0, boolean arg1)
throws FileNotFoundException, LockException, IOException {
return new ThrowingRecordReadChannel(
this, FILE_SERVICE.openRecordReadChannel(arg0, arg1), throwOnRead);
}
@Override
public RecordWriteChannel openRecordWriteChannel(AppEngineFile arg0, boolean arg1)
throws FileNotFoundException, FinalizationException, LockException, IOException {
return new ThrowingRecordWriteChannel(
this, FILE_SERVICE.openRecordWriteChannel(arg0, arg1), throwOnWrite);
}
@Override
public FileWriteChannel openWriteChannel(AppEngineFile arg0, boolean arg1)
throws FileNotFoundException, FinalizationException, LockException, IOException {
return new ThrowingFileWriteChannel(
this, FILE_SERVICE.openWriteChannel(arg0, arg1), throwOnWrite);
}
@Override
public FileStat stat(AppEngineFile arg0) throws IOException {
return FILE_SERVICE.stat(arg0);
}
@Override
public void delete(AppEngineFile... arg0) throws IOException {
FILE_SERVICE.delete(arg0);
}
}
public int mapToRand(long value) {
Random rand = new Random(value);
return rand.nextInt(valueRange);
}
private void testShuffler(double throwOnRead, double throwOnWrite) throws IOException {
Output<KeyValue<Integer, Integer>, List<AppEngineFile>> output = new IntermediateOutput<
Integer, Integer>(mrJobId, numShards, specification.getIntermediateKeyMarshaller(),
specification.getIntermediateValueMarshaller());
List<? extends InputReader<Long>> readers = input.createReaders();
List<? extends OutputWriter<KeyValue<Integer, Integer>>> writers = output.createWriters();
assertEquals(numShards, readers.size());
assertEquals(numShards, writers.size());
map(mrJobId, numShards, readers, writers);
List<AppEngineFile> mapOutputs = output.finish(writers);
ArrayList<AppEngineFile> reduceInputFiles = createInputFiles();
MockFileService fileService = new MockFileService(throwOnRead, throwOnWrite);
InMemoryShuffleJob<Integer, Integer, Integer> shuffleJob =
new InMemoryShuffleJob<Integer, Integer, Integer>(
specification, fileService);
shuffleJob.run(mapOutputs, reduceInputFiles, new ShuffleResult<Integer, Integer, Integer>(
reduceInputFiles, Collections.<OutputWriter<Integer>>emptyList(),
Collections.<InputReader<KeyValue<Integer, ReducerInput<Integer>>>>emptyList()));
IntermediateInput<Integer, Integer> reduceInput =
new IntermediateInput<Integer, Integer>(reduceInputFiles, intMarshaller, intMarshaller);
int totalCount = assertShuffledCorrectly(reduceInput, mapper);
assertEquals(2 * inputSize, totalCount);
assertEquals(2 * inputSize + numShards, fileService.readCounter.get());
assertEquals(valueRange, fileService.writeCounter.get());
assertTrue(throwOnRead <= 0 || fileService.throwCounter.get() > 0);
assertTrue(throwOnWrite <= 0 || fileService.throwCounter.get() > 0);
}
private ArrayList<AppEngineFile> createInputFiles() throws IOException {
ArrayList<AppEngineFile> reduceInputFiles = new ArrayList<AppEngineFile>();
for (int i = 0; i < numShards; i++) {
reduceInputFiles.add(FILE_SERVICE.createNewBlobFile(
MapReduceConstants.REDUCE_INPUT_MIME_TYPE, mrJobId + ": reduce input, shard " + i));
}
return reduceInputFiles;
}
@Test
public void testShuffler() throws IOException {
testShuffler(0, 0);
}
@Test
public void testAllReadsFail() throws IOException {
try {
testShuffler(1, 0);
fail();
} catch (RuntimeException e) {
assertTrue(e.getMessage().startsWith("RetryHelper"));
assertEquals(IOException.class, e.getCause().getClass());
}
}
@Test
public void testReadFailOften() throws IOException {
testShuffler(.1, 0);
}
@Test
public void testReadFailSometimes() throws IOException {
testShuffler(.05, 0);
}
@Test
public void testReadFailRarely() throws IOException {
testShuffler(.025, 0);
}
@Test
public void testAllWritesFail() throws IOException {
try {
testShuffler(0, 1);
fail();
} catch (RuntimeException e) {
assertTrue(e.getMessage().startsWith("RetryHelper"));
assertEquals(IOException.class, e.getCause().getClass());
}
}
@Test
public void testWritesFailOften() throws IOException {
testShuffler(0, 0.5);
}
@Test
public void testWritesFailSometimes() throws IOException {
testShuffler(0, .2);
}
@Test
public void testWritesFailRarely() throws IOException {
testShuffler(0, .05);
}
private void map(String mrJobId, int numShards, List<? extends InputReader<Long>> readers,
List<? extends OutputWriter<KeyValue<Integer, Integer>>> writers) {
InProcessMapReduce<Long, Integer, Integer, Integer, Void> impl =
new InProcessMapReduce<Long, Integer, Integer, Integer, Void>(mrJobId, specification);
impl.map(readers, writers);
}
private int assertShuffledCorrectly(
IntermediateInput<Integer, Integer> reducerInput, Mapper<Long, Integer, Integer> mapper)
throws IOException {
int count = 0;
for (InputReader<KeyValue<Integer, ReducerInput<Integer>>> reader :
reducerInput.createReaders()) {
while (true) {
KeyValue<Integer, ReducerInput<Integer>> kv;
try {
kv = reader.next();
} catch (NoSuchElementException e) {
break;
}
ReducerInput<Integer> iter = kv.getValue();
assertTrue(iter.hasNext());
while (iter.hasNext()) {
Integer value = iter.next();
Integer key = mapToRand(value.longValue());
assertEquals(kv.getKey(), key);
count++;
}
}
}
return count;
}
}
| java/test/com/google/appengine/tools/mapreduce/impl/InMemoryShuffleJobTest.java | // Copyright 2012 Google Inc. All Rights Reserved.
package com.google.appengine.tools.mapreduce.impl;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileStat;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.FinalizationException;
import com.google.appengine.api.files.GSFileOptions;
import com.google.appengine.api.files.LockException;
import com.google.appengine.api.files.RecordReadChannel;
import com.google.appengine.api.files.RecordWriteChannel;
import com.google.appengine.tools.development.testing.LocalFileServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.mapreduce.InputReader;
import com.google.appengine.tools.mapreduce.KeyValue;
import com.google.appengine.tools.mapreduce.MapReduceSpecification;
import com.google.appengine.tools.mapreduce.Mapper;
import com.google.appengine.tools.mapreduce.Marshaller;
import com.google.appengine.tools.mapreduce.Marshallers;
import com.google.appengine.tools.mapreduce.Output;
import com.google.appengine.tools.mapreduce.OutputWriter;
import com.google.appengine.tools.mapreduce.ReducerInput;
import com.google.appengine.tools.mapreduce.inputs.ConsecutiveLongInput;
import com.google.appengine.tools.mapreduce.outputs.NoOutput;
import com.google.appengine.tools.mapreduce.reducers.KeyProjectionReducer;
import junit.framework.TestCase;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
/**
*
*/
public class InMemoryShuffleJobTest extends TestCase {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(InMemoryShuffleJobTest.class.getName());
private static final FileService FILE_SERVICE = FileServiceFactory.getFileService();
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalFileServiceTestConfig());
private final Marshaller<Integer> intMarshaller = Marshallers.getIntegerMarshaller();
private final String mrJobId = "JobId";
private final int inputSize = 1000;
private final int valueRange = 100;
private final int numShards = 10;
private final Mapper<Long, Integer, Integer> mapper = new Mapper<Long, Integer, Integer>() {
private static final long serialVersionUID = -7327871496359562255L;
@Override
public void map(Long value) {
getContext().emit(mapToRand(value), value.intValue());
}
};
private ConsecutiveLongInput input;
private MapReduceSpecification<Long, Integer, Integer, Integer, Void> specification;
@Override
protected void setUp() throws Exception {
super.setUp();
input = new ConsecutiveLongInput(-inputSize, inputSize, numShards);
specification = MapReduceSpecification.<Long, Integer, Integer, Integer, Void>of("JobName",
input,
mapper,
intMarshaller,
intMarshaller,
KeyProjectionReducer.<Integer, Integer>create(),
NoOutput.<Integer, Void>create(numShards));
helper.setUp();
}
@Override
protected void tearDown() throws Exception {
helper.tearDown();
super.tearDown();
}
private static class ThrowingFileWriteChannel implements FileWriteChannel {
private final FileWriteChannel wrapped;
private final double throwProb;
private MockFileService mockFileService;
private ThrowingFileWriteChannel(
MockFileService mockFileService, FileWriteChannel wrapped, double throwProb) {
this.mockFileService = mockFileService;
this.wrapped = wrapped;
this.throwProb = throwProb;
}
@Override
public int write(ByteBuffer src) throws IOException {
throwMaybe();
mockFileService.writeCounter.incrementAndGet();
return wrapped.write(src);
}
private void throwMaybe() throws IOException {
if (mockFileService.r.nextDouble() < throwProb) {
mockFileService.throwCounter.incrementAndGet();
throw new IOException();
}
}
@Override
public boolean isOpen() {
return wrapped.isOpen();
}
@Override
public void close() throws IOException {
throwMaybe();
wrapped.close();
}
@Override
public void closeFinally() throws IllegalStateException, IOException {
throwMaybe();
wrapped.closeFinally();
}
@Override
public int write(ByteBuffer arg0, String arg1) throws IOException {
throwMaybe();
return wrapped.write(arg0, arg1);
}
}
private static class ThrowingFileReadChannel implements FileReadChannel {
private final FileReadChannel wrapped;
private final double throwProb;
private MockFileService mockFileService;
private ThrowingFileReadChannel(
MockFileService mockFileService, FileReadChannel toWrapp, double throwProb) {
this.mockFileService = mockFileService;
wrapped = toWrapp;
this.throwProb = throwProb;
}
@Override
public int read(ByteBuffer dst) throws IOException {
throwMaybe();
mockFileService.readCounter.incrementAndGet();
return wrapped.read(dst);
}
@Override
public boolean isOpen() {
return wrapped.isOpen();
}
@Override
public void close() throws IOException {
throwMaybe();
wrapped.close();
}
private void throwMaybe() throws IOException {
if (mockFileService.r.nextDouble() < throwProb) {
mockFileService.throwCounter.incrementAndGet();
throw new IOException();
}
}
@Override
public long position() throws IOException {
return wrapped.position();
}
@Override
public FileReadChannel position(long arg0) throws IOException {
throwMaybe();
return wrapped.position(arg0);
}
}
private static class ThrowingRecordWriteChannel implements RecordWriteChannel {
private final RecordWriteChannel wrapped;
private final double throwProb;
private MockFileService mockFileService;
private ThrowingRecordWriteChannel(
MockFileService mockFileService, RecordWriteChannel toWrapp, double throwProb) {
this.mockFileService = mockFileService;
wrapped = toWrapp;
this.throwProb = throwProb;
}
@Override
public int write(ByteBuffer src) throws IOException {
throwMaybe();
mockFileService.writeCounter.incrementAndGet();
return wrapped.write(src);
}
private void throwMaybe() throws IOException {
if (mockFileService.r.nextDouble() < throwProb) {
mockFileService.throwCounter.incrementAndGet();
throw new IOException();
}
}
@Override
public boolean isOpen() {
return wrapped.isOpen();
}
@Override
public void close() throws IOException {
throwMaybe();
wrapped.close();
}
@Override
public void closeFinally() throws IllegalStateException, IOException {
throwMaybe();
wrapped.closeFinally();
}
@Override
public int write(ByteBuffer arg0, String arg1) throws IOException {
throwMaybe();
mockFileService.writeCounter.incrementAndGet();
return wrapped.write(arg0, arg1);
}
}
private static class ThrowingRecordReadChannel implements RecordReadChannel {
private final RecordReadChannel wrapped;
private final double throwProb;
private MockFileService mockFileService;
private ThrowingRecordReadChannel(
MockFileService mockFileService, RecordReadChannel toWrapp, double throwProb) {
this.mockFileService = mockFileService;
wrapped = toWrapp;
this.throwProb = throwProb;
}
@Override
public long position() throws IOException {
return wrapped.position();
}
@Override
public void position(long arg0) throws IOException {
throwMaybe();
wrapped.position(arg0);
}
@Override
public ByteBuffer readRecord() throws IOException {
throwMaybe();
mockFileService.readCounter.incrementAndGet();
return wrapped.readRecord();
}
private void throwMaybe() throws IOException {
if (mockFileService.r.nextDouble() < throwProb) {
mockFileService.throwCounter.incrementAndGet();
throw new IOException();
}
}
}
private class MockFileService implements FileService {
private final AtomicInteger readCounter = new AtomicInteger(0);
private final AtomicInteger writeCounter = new AtomicInteger(0);
private final AtomicInteger throwCounter = new AtomicInteger(0);
private final Random r = new Random(17);
private final double throwOnRead;
private final double throwOnWrite;
public MockFileService(double throwOnRead, double throwOnWrite) {
this.throwOnRead = throwOnRead;
this.throwOnWrite = throwOnWrite;
}
@Override
public AppEngineFile createNewBlobFile(String arg0) throws IOException {
return FILE_SERVICE.createNewBlobFile(arg0);
}
@Override
public AppEngineFile createNewBlobFile(String arg0, String arg1) throws IOException {
return FILE_SERVICE.createNewBlobFile(arg0, arg1);
}
@Override
public AppEngineFile createNewGSFile(GSFileOptions arg0) throws IOException {
return FILE_SERVICE.createNewGSFile(arg0);
}
@Override
public AppEngineFile getBlobFile(BlobKey arg0) {
return FILE_SERVICE.getBlobFile(arg0);
}
@Override
public BlobKey getBlobKey(AppEngineFile arg0) {
return FILE_SERVICE.getBlobKey(arg0);
}
@Override
public String getDefaultGsBucketName() throws IOException {
return FILE_SERVICE.getDefaultGsBucketName();
}
@Override
public FileReadChannel openReadChannel(AppEngineFile arg0, boolean arg1)
throws FileNotFoundException, LockException, IOException {
return new ThrowingFileReadChannel(
this, FILE_SERVICE.openReadChannel(arg0, arg1), throwOnRead);
}
@Override
public RecordReadChannel openRecordReadChannel(AppEngineFile arg0, boolean arg1)
throws FileNotFoundException, LockException, IOException {
return new ThrowingRecordReadChannel(
this, FILE_SERVICE.openRecordReadChannel(arg0, arg1), throwOnRead);
}
@Override
public RecordWriteChannel openRecordWriteChannel(AppEngineFile arg0, boolean arg1)
throws FileNotFoundException, FinalizationException, LockException, IOException {
return new ThrowingRecordWriteChannel(
this, FILE_SERVICE.openRecordWriteChannel(arg0, arg1), throwOnWrite);
}
@Override
public FileWriteChannel openWriteChannel(AppEngineFile arg0, boolean arg1)
throws FileNotFoundException, FinalizationException, LockException, IOException {
return new ThrowingFileWriteChannel(
this, FILE_SERVICE.openWriteChannel(arg0, arg1), throwOnWrite);
}
@Override
public FileStat stat(AppEngineFile arg0) throws IOException {
return FILE_SERVICE.stat(arg0);
}
}
public int mapToRand(long value) {
Random rand = new Random(value);
return rand.nextInt(valueRange);
}
private void testShuffler(double throwOnRead, double throwOnWrite) throws IOException {
Output<KeyValue<Integer, Integer>, List<AppEngineFile>> output = new IntermediateOutput<
Integer, Integer>(mrJobId, numShards, specification.getIntermediateKeyMarshaller(),
specification.getIntermediateValueMarshaller());
List<? extends InputReader<Long>> readers = input.createReaders();
List<? extends OutputWriter<KeyValue<Integer, Integer>>> writers = output.createWriters();
assertEquals(numShards, readers.size());
assertEquals(numShards, writers.size());
map(mrJobId, numShards, readers, writers);
List<AppEngineFile> mapOutputs = output.finish(writers);
ArrayList<AppEngineFile> reduceInputFiles = createInputFiles();
MockFileService fileService = new MockFileService(throwOnRead, throwOnWrite);
InMemoryShuffleJob<Integer, Integer, Integer> shuffleJob =
new InMemoryShuffleJob<Integer, Integer, Integer>(
specification, fileService);
shuffleJob.run(mapOutputs, reduceInputFiles, new ShuffleResult<Integer, Integer, Integer>(
reduceInputFiles, Collections.<OutputWriter<Integer>>emptyList(),
Collections.<InputReader<KeyValue<Integer, ReducerInput<Integer>>>>emptyList()));
IntermediateInput<Integer, Integer> reduceInput =
new IntermediateInput<Integer, Integer>(reduceInputFiles, intMarshaller, intMarshaller);
int totalCount = assertShuffledCorrectly(reduceInput, mapper);
assertEquals(2 * inputSize, totalCount);
assertEquals(2 * inputSize + numShards, fileService.readCounter.get());
assertEquals(valueRange, fileService.writeCounter.get());
assertTrue(throwOnRead <= 0 || fileService.throwCounter.get() > 0);
assertTrue(throwOnWrite <= 0 || fileService.throwCounter.get() > 0);
}
private ArrayList<AppEngineFile> createInputFiles() throws IOException {
ArrayList<AppEngineFile> reduceInputFiles = new ArrayList<AppEngineFile>();
for (int i = 0; i < numShards; i++) {
reduceInputFiles.add(FILE_SERVICE.createNewBlobFile(
MapReduceConstants.REDUCE_INPUT_MIME_TYPE, mrJobId + ": reduce input, shard " + i));
}
return reduceInputFiles;
}
@Test
public void testShuffler() throws IOException {
testShuffler(0, 0);
}
@Test
public void testAllReadsFail() throws IOException {
try {
testShuffler(1, 0);
fail();
} catch (RuntimeException e) {
assertTrue(e.getMessage().startsWith("RetryHelper"));
assertEquals(IOException.class, e.getCause().getClass());
}
}
@Test
public void testReadFailOften() throws IOException {
testShuffler(.1, 0);
}
@Test
public void testReadFailSometimes() throws IOException {
testShuffler(.05, 0);
}
@Test
public void testReadFailRarely() throws IOException {
testShuffler(.025, 0);
}
@Test
public void testAllWritesFail() throws IOException {
try {
testShuffler(0, 1);
fail();
} catch (RuntimeException e) {
assertTrue(e.getMessage().startsWith("RetryHelper"));
assertEquals(IOException.class, e.getCause().getClass());
}
}
@Test
public void testWritesFailOften() throws IOException {
testShuffler(0, 0.5);
}
@Test
public void testWritesFailSometimes() throws IOException {
testShuffler(0, .2);
}
@Test
public void testWritesFailRarely() throws IOException {
testShuffler(0, .05);
}
private void map(String mrJobId, int numShards, List<? extends InputReader<Long>> readers,
List<? extends OutputWriter<KeyValue<Integer, Integer>>> writers) {
InProcessMapReduce<Long, Integer, Integer, Integer, Void> impl =
new InProcessMapReduce<Long, Integer, Integer, Integer, Void>(mrJobId, specification);
impl.map(readers, writers);
}
private int assertShuffledCorrectly(
IntermediateInput<Integer, Integer> reducerInput, Mapper<Long, Integer, Integer> mapper)
throws IOException {
int count = 0;
for (InputReader<KeyValue<Integer, ReducerInput<Integer>>> reader :
reducerInput.createReaders()) {
while (true) {
KeyValue<Integer, ReducerInput<Integer>> kv;
try {
kv = reader.next();
} catch (NoSuchElementException e) {
break;
}
ReducerInput<Integer> iter = kv.getValue();
assertTrue(iter.hasNext());
while (iter.hasNext()) {
Integer value = iter.next();
Integer key = mapToRand(value.longValue());
assertEquals(kv.getKey(), key);
count++;
}
}
}
return count;
}
}
|
Fix compile error resulting from the add of Delete to the API in 1.7.1
Revision created by MOE tool push_codebase.
MOE_MIGRATION=5445
git-svn-id: 120402244b5714bfc5c7f1741d57d585f71ae04f@353 441dd3cb-e453-d85f-364a-b28e0c74875c
| java/test/com/google/appengine/tools/mapreduce/impl/InMemoryShuffleJobTest.java | ||
Java | apache-2.0 | ba9cb84a602d74a8a46cbee653b65b72c1721661 | 0 | afilimonov/jackrabbit-oak,mduerig/jackrabbit-oak,meggermo/jackrabbit-oak,chetanmeh/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,kwin/jackrabbit-oak,francescomari/jackrabbit-oak,ieb/jackrabbit-oak,tripodsan/jackrabbit-oak,code-distillery/jackrabbit-oak,kwin/jackrabbit-oak,leftouterjoin/jackrabbit-oak,catholicon/jackrabbit-oak,davidegiannella/jackrabbit-oak,rombert/jackrabbit-oak,leftouterjoin/jackrabbit-oak,alexparvulescu/jackrabbit-oak,davidegiannella/jackrabbit-oak,catholicon/jackrabbit-oak,catholicon/jackrabbit-oak,afilimonov/jackrabbit-oak,stillalex/jackrabbit-oak,mduerig/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,tripodsan/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,anchela/jackrabbit-oak,joansmith/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,kwin/jackrabbit-oak,alexkli/jackrabbit-oak,meggermo/jackrabbit-oak,mduerig/jackrabbit-oak,stillalex/jackrabbit-oak,rombert/jackrabbit-oak,alexkli/jackrabbit-oak,alexparvulescu/jackrabbit-oak,joansmith/jackrabbit-oak,kwin/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,ieb/jackrabbit-oak,bdelacretaz/jackrabbit-oak,ieb/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,bdelacretaz/jackrabbit-oak,tripodsan/jackrabbit-oak,alexparvulescu/jackrabbit-oak,rombert/jackrabbit-oak,francescomari/jackrabbit-oak,yesil/jackrabbit-oak,alexkli/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,joansmith/jackrabbit-oak,code-distillery/jackrabbit-oak,yesil/jackrabbit-oak,code-distillery/jackrabbit-oak,leftouterjoin/jackrabbit-oak,ieb/jackrabbit-oak,joansmith/jackrabbit-oak,rombert/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,meggermo/jackrabbit-oak,alexparvulescu/jackrabbit-oak,davidegiannella/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,bdelacretaz/jackrabbit-oak,mduerig/jackrabbit-oak,yesil/jackrabbit-oak,chetanmeh/jackrabbit-oak,afilimonov/jackrabbit-oak,mduerig/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,kwin/jackrabbit-oak,code-distillery/jackrabbit-oak,tripodsan/jackrabbit-oak,leftouterjoin/jackrabbit-oak,davidegiannella/jackrabbit-oak,code-distillery/jackrabbit-oak,bdelacretaz/jackrabbit-oak,anchela/jackrabbit-oak,meggermo/jackrabbit-oak,chetanmeh/jackrabbit-oak,anchela/jackrabbit-oak,chetanmeh/jackrabbit-oak,stillalex/jackrabbit-oak,alexkli/jackrabbit-oak,alexparvulescu/jackrabbit-oak,afilimonov/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,joansmith/jackrabbit-oak,francescomari/jackrabbit-oak,yesil/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexkli/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,chetanmeh/jackrabbit-oak,catholicon/jackrabbit-oak,stillalex/jackrabbit-oak,davidegiannella/jackrabbit-oak,stillalex/jackrabbit-oak,meggermo/jackrabbit-oak | /*
* 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.jackrabbit.mk.model.tree;
import org.apache.jackrabbit.mk.json.JsopBuilder;
import org.apache.jackrabbit.oak.commons.PathUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* JSOP Diff Builder
*/
public class DiffBuilder {
private final NodeState before;
private final NodeState after;
private final String path;
private final int depth;
private final String pathFilter;
private final NodeStore store;
public DiffBuilder(NodeState before, NodeState after, String path, int depth,
NodeStore store, String pathFilter) {
this.before = before;
this.after = after;
this.path = path;
this.depth = depth;
this.store = store;
this.pathFilter = (pathFilter == null || "".equals(pathFilter)) ? "/" : pathFilter;
}
public String build() throws Exception {
final JsopBuilder buff = new JsopBuilder();
// maps (key: the target node, value: the path to the target)
// for tracking added/removed nodes; this allows us
// to detect 'move' operations
// TODO performance problem: this class uses NodeState as a hash key,
// which is not recommended because the hashCode and equals methods
// of those classes are slow
final HashMap<NodeState, ArrayList<String>> addedNodes = new HashMap<NodeState, ArrayList<String>>();
final HashMap<NodeState, ArrayList<String>> removedNodes = new HashMap<NodeState, ArrayList<String>>();
if (!PathUtils.isAncestor(path, pathFilter)
&& !path.startsWith(pathFilter)) {
return "";
}
if (before == null) {
if (after != null) {
buff.tag('+').key(path).object();
toJson(buff, after, depth);
return buff.endObject().newline().toString();
} else {
// path doesn't exist in the specified revisions
return "";
}
} else if (after == null) {
buff.tag('-');
buff.value(path);
return buff.newline().toString();
}
TraversingNodeDiffHandler diffHandler = new TraversingNodeDiffHandler(store) {
int levels = depth < 0 ? Integer.MAX_VALUE : depth;
@Override
public void propertyAdded(PropertyState after) {
String p = PathUtils.concat(getCurrentPath(), after.getName());
if (p.startsWith(pathFilter)) {
buff.tag('^').
key(p).
encodedValue(after.getEncodedValue()).
newline();
}
}
@Override
public void propertyChanged(PropertyState before, PropertyState after) {
String p = PathUtils.concat(getCurrentPath(), after.getName());
if (p.startsWith(pathFilter)) {
buff.tag('^').
key(p).
encodedValue(after.getEncodedValue()).
newline();
}
}
@Override
public void propertyDeleted(PropertyState before) {
String p = PathUtils.concat(getCurrentPath(), before.getName());
if (p.startsWith(pathFilter)) {
// since property and node deletions can't be distinguished
// using the "- <path>" notation we're representing
// property deletions as "^ <path>:null"
buff.tag('^').
key(p).
value(null).
newline();
}
}
@Override
public void childNodeAdded(String name, NodeState after) {
String p = PathUtils.concat(getCurrentPath(), name);
if (p.startsWith(pathFilter)) {
ArrayList<String> removedPaths = removedNodes.get(after);
if (removedPaths != null) {
// move detected
String removedPath = removedPaths.remove(0);
if (removedPaths.isEmpty()) {
removedNodes.remove(after);
}
buff.tag('>').
// path/to/deleted/node
key(removedPath).
// path/to/added/node
value(p).
newline();
} else {
ArrayList<String> addedPaths = addedNodes.get(after);
if (addedPaths == null) {
addedPaths = new ArrayList<String>();
addedNodes.put(after, addedPaths);
}
addedPaths.add(p);
}
}
}
@Override
public void childNodeDeleted(String name, NodeState before) {
String p = PathUtils.concat(getCurrentPath(), name);
if (p.startsWith(pathFilter)) {
ArrayList<String> addedPaths = addedNodes.get(before);
if (addedPaths != null) {
// move detected
String addedPath = addedPaths.remove(0);
if (addedPaths.isEmpty()) {
addedNodes.remove(before);
}
buff.tag('>').
// path/to/deleted/node
key(p).
// path/to/added/node
value(addedPath).
newline();
} else {
ArrayList<String> removedPaths = removedNodes.get(before);
if (removedPaths == null) {
removedPaths = new ArrayList<String>();
removedNodes.put(before, removedPaths);
}
removedPaths.add(p);
}
}
}
@Override
public void childNodeChanged(String name, NodeState before, NodeState after) {
String p = PathUtils.concat(getCurrentPath(), name);
if (PathUtils.isAncestor(p, pathFilter)
|| p.startsWith(pathFilter)) {
--levels;
if (levels >= 0) {
// recurse
super.childNodeChanged(name, before, after);
} else {
buff.tag('^');
buff.key(p);
buff.object().endObject();
buff.newline();
}
++levels;
}
}
};
diffHandler.start(before, after, path);
// finally process remaining added nodes ...
for (Map.Entry<NodeState, ArrayList<String>> entry : addedNodes.entrySet()) {
for (String p : entry.getValue()) {
buff.tag('+').
key(p).object();
toJson(buff, entry.getKey(), depth);
buff.endObject().newline();
}
}
// ... and removed nodes
for (Map.Entry<NodeState, ArrayList<String>> entry : removedNodes.entrySet()) {
for (String p : entry.getValue()) {
buff.tag('-');
buff.value(p);
buff.newline();
}
}
return buff.toString();
}
private void toJson(JsopBuilder builder, NodeState node, int depth) {
for (PropertyState property : node.getProperties()) {
builder.key(property.getName()).encodedValue(property.getEncodedValue());
}
if (depth != 0) {
for (ChildNode entry : node.getChildNodeEntries(0, -1)) {
builder.key(entry.getName()).object();
toJson(builder, entry.getNode(), depth < 0 ? depth : depth - 1);
builder.endObject();
}
}
}
}
| oak-mk/src/main/java/org/apache/jackrabbit/mk/model/tree/DiffBuilder.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.jackrabbit.mk.model.tree;
import org.apache.jackrabbit.mk.json.JsopBuilder;
import org.apache.jackrabbit.mk.store.RevisionProvider;
import org.apache.jackrabbit.oak.commons.PathUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* JSOP Diff Builder
*/
public class DiffBuilder {
private final NodeState before;
private final NodeState after;
private final String path;
private final int depth;
private final String pathFilter;
private final RevisionProvider store;
public DiffBuilder(NodeState before, NodeState after, String path, int depth,
RevisionProvider store, String pathFilter) {
this.before = before;
this.after = after;
this.path = path;
this.depth = depth;
this.store = store;
this.pathFilter = (pathFilter == null || "".equals(pathFilter)) ? "/" : pathFilter;
}
public String build() throws Exception {
final JsopBuilder buff = new JsopBuilder();
// maps (key: the target node, value: the path to the target)
// for tracking added/removed nodes; this allows us
// to detect 'move' operations
// TODO performance problem: this class uses NodeState as a hash key,
// which is not recommended because the hashCode and equals methods
// of those classes are slow
final HashMap<NodeState, ArrayList<String>> addedNodes = new HashMap<NodeState, ArrayList<String>>();
final HashMap<NodeState, ArrayList<String>> removedNodes = new HashMap<NodeState, ArrayList<String>>();
if (!PathUtils.isAncestor(path, pathFilter)
&& !path.startsWith(pathFilter)) {
return "";
}
if (before == null) {
if (after != null) {
buff.tag('+').key(path).object();
toJson(buff, after, depth);
return buff.endObject().newline().toString();
} else {
// path doesn't exist in the specified revisions
return "";
}
} else if (after == null) {
buff.tag('-');
buff.value(path);
return buff.newline().toString();
}
TraversingNodeDiffHandler diffHandler = new TraversingNodeDiffHandler(store) {
int levels = depth < 0 ? Integer.MAX_VALUE : depth;
@Override
public void propertyAdded(PropertyState after) {
String p = PathUtils.concat(getCurrentPath(), after.getName());
if (p.startsWith(pathFilter)) {
buff.tag('^').
key(p).
encodedValue(after.getEncodedValue()).
newline();
}
}
@Override
public void propertyChanged(PropertyState before, PropertyState after) {
String p = PathUtils.concat(getCurrentPath(), after.getName());
if (p.startsWith(pathFilter)) {
buff.tag('^').
key(p).
encodedValue(after.getEncodedValue()).
newline();
}
}
@Override
public void propertyDeleted(PropertyState before) {
String p = PathUtils.concat(getCurrentPath(), before.getName());
if (p.startsWith(pathFilter)) {
// since property and node deletions can't be distinguished
// using the "- <path>" notation we're representing
// property deletions as "^ <path>:null"
buff.tag('^').
key(p).
value(null).
newline();
}
}
@Override
public void childNodeAdded(String name, NodeState after) {
String p = PathUtils.concat(getCurrentPath(), name);
if (p.startsWith(pathFilter)) {
ArrayList<String> removedPaths = removedNodes.get(after);
if (removedPaths != null) {
// move detected
String removedPath = removedPaths.remove(0);
if (removedPaths.isEmpty()) {
removedNodes.remove(after);
}
buff.tag('>').
// path/to/deleted/node
key(removedPath).
// path/to/added/node
value(p).
newline();
} else {
ArrayList<String> addedPaths = addedNodes.get(after);
if (addedPaths == null) {
addedPaths = new ArrayList<String>();
addedNodes.put(after, addedPaths);
}
addedPaths.add(p);
}
}
}
@Override
public void childNodeDeleted(String name, NodeState before) {
String p = PathUtils.concat(getCurrentPath(), name);
if (p.startsWith(pathFilter)) {
ArrayList<String> addedPaths = addedNodes.get(before);
if (addedPaths != null) {
// move detected
String addedPath = addedPaths.remove(0);
if (addedPaths.isEmpty()) {
addedNodes.remove(before);
}
buff.tag('>').
// path/to/deleted/node
key(p).
// path/to/added/node
value(addedPath).
newline();
} else {
ArrayList<String> removedPaths = removedNodes.get(before);
if (removedPaths == null) {
removedPaths = new ArrayList<String>();
removedNodes.put(before, removedPaths);
}
removedPaths.add(p);
}
}
}
@Override
public void childNodeChanged(String name, NodeState before, NodeState after) {
String p = PathUtils.concat(getCurrentPath(), name);
if (PathUtils.isAncestor(p, pathFilter)
|| p.startsWith(pathFilter)) {
--levels;
if (levels >= 0) {
// recurse
super.childNodeChanged(name, before, after);
} else {
buff.tag('^');
buff.key(p);
buff.object().endObject();
buff.newline();
}
++levels;
}
}
};
diffHandler.start(before, after, path);
// finally process remaining added nodes ...
for (Map.Entry<NodeState, ArrayList<String>> entry : addedNodes.entrySet()) {
for (String p : entry.getValue()) {
buff.tag('+').
key(p).object();
toJson(buff, entry.getKey(), depth);
buff.endObject().newline();
}
}
// ... and removed nodes
for (Map.Entry<NodeState, ArrayList<String>> entry : removedNodes.entrySet()) {
for (String p : entry.getValue()) {
buff.tag('-');
buff.value(p);
buff.newline();
}
}
return buff.toString();
}
private void toJson(JsopBuilder builder, NodeState node, int depth) {
for (PropertyState property : node.getProperties()) {
builder.key(property.getName()).encodedValue(property.getEncodedValue());
}
if (depth != 0) {
for (ChildNode entry : node.getChildNodeEntries(0, -1)) {
builder.key(entry.getName()).object();
toJson(builder, entry.getNode(), depth < 0 ? depth : depth - 1);
builder.endObject();
}
}
}
}
| OAK-979: MicroKernel.diff() returns incomplete JSON when moves are involved (H2)
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1519290 13f79535-47bb-0310-9956-ffa450edef68
| oak-mk/src/main/java/org/apache/jackrabbit/mk/model/tree/DiffBuilder.java | OAK-979: MicroKernel.diff() returns incomplete JSON when moves are involved (H2) |
|
Java | apache-2.0 | 8b4d4d277f17d0b399a7f9ddca37d7339883fda7 | 0 | wmixvideo/nfe,danieldhp/nfe,eldevanjr/nfe | package com.fincatto.documentofiscal.utils;
import com.fincatto.documentofiscal.DFConfig;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Signature;
import java.security.UnrecoverableEntryException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
public class DFAssinaturaDigital {
private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
private static final String[] ELEMENTOS_ASSINAVEIS = new String[]{"infEvento", "infCanc", "infNFe", "infInut", "infMDFe", "infCte"};
private final DFConfig config;
public DFAssinaturaDigital(final DFConfig config) {
this.config = config;
}
public boolean isValida(final InputStream xmlStream) throws Exception {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
final Document document = dbf.newDocumentBuilder().parse(xmlStream);
final NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nodeList.getLength() == 0) {
throw new IllegalStateException("Nao foi encontrada a assinatura do XML.");
}
final String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).getDeclaredConstructor().newInstance());
final DOMValidateContext validateContext = new DOMValidateContext(new DFKeySelector(), nodeList.item(0));
for (final String tag : DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS) {
final NodeList elements = document.getElementsByTagName(tag);
if (elements.getLength() > 0) {
validateContext.setIdAttributeNS((Element) elements.item(0), null, "Id");
}
}
return signatureFactory.unmarshalXMLSignature(validateContext).validate(validateContext);
}
public String assinarDocumento(final String conteudoXml) throws Exception {
return this.assinarDocumento(conteudoXml, DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS);
}
public String assinarDocumento(final String conteudoXml, final String... elementosAssinaveis) throws Exception {
try (StringReader reader = new StringReader(conteudoXml)) {
try (StringWriter writer = new StringWriter()) {
this.assinarDocumento(reader, writer, elementosAssinaveis);
return writer.toString();
}
}
}
public void assinarDocumento(Reader xmlReader, Writer xmlAssinado, final String... elementosAssinaveis) throws Exception {
final KeyStore.PrivateKeyEntry keyEntry = getPrivateKeyEntry();
//Adiciona System.out p/ verificação do certificado que assina o documento
try {
String dn = ((X509Certificate)keyEntry.getCertificate()).getSubjectX500Principal().getName();
LdapName ldapDN = null;
ldapDN = new LdapName(dn);
String commonName = ldapDN.getRdns().stream()
.filter(rdn -> StringUtils.equalsIgnoreCase(rdn.getType(), "CN")).map(val -> val.getValue() + "").findFirst()
.orElse("");
System.out.println("CERTIFICADO ASSINANDO(CNPJ):" + commonName );
} catch (InvalidNameException e) {
}
final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
final List<Transform> transforms = new ArrayList<>(2);
transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
transforms.add(signatureFactory.newTransform(DFAssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null));
final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate()));
final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(xmlReader));
for (final String elementoAssinavel : elementosAssinaveis) {
final NodeList elements = document.getElementsByTagName(elementoAssinavel);
for (int i = 0; i < elements.getLength(); i++) {
final Element element = (Element) elements.item(i);
final String id = element.getAttribute("Id");
element.setIdAttribute("Id", true);
final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null);
final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode()));
}
}
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(document), new StreamResult(xmlAssinado));
}
private KeyStore.PrivateKeyEntry getPrivateKeyEntry() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray());
if(StringUtils.isNotEmpty(config.getCertificadoAlias())){
final String certificateAlias = config.getCertificadoAlias() != null ? config.getCertificadoAlias()
: config.getCertificadoKeyStore().aliases().nextElement();
return (KeyStore.PrivateKeyEntry) config.getCertificadoKeyStore().getEntry(certificateAlias, passwordProtection);
}else{
KeyStore ks = config.getCertificadoKeyStore();
for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
String alias = e.nextElement();
if (ks.isKeyEntry(alias)) {
return (KeyStore.PrivateKeyEntry) ks.getEntry(alias, passwordProtection);
}
}
throw new RuntimeException("Não foi possível encontrar a chave privada do certificado");
}
}
public String assinarString(String _string) throws Exception {
byte[] buffer = _string.getBytes();
Signature signatureProvider = Signature.getInstance("SHA1withRSA");
signatureProvider.initSign(getPrivateKeyEntry().getPrivateKey());
signatureProvider.update(buffer, 0, buffer.length);
byte[] signature = signatureProvider.sign();
System.out.println(getPrivateKeyEntry().getPrivateKey().getFormat());
return Base64.getEncoder().encodeToString(signature);
}
static class DFKeySelector extends KeySelector {
@Override
public KeySelectorResult select(final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context) throws KeySelectorException {
for (final Object object : keyInfo.getContent()) {
final XMLStructure info = (XMLStructure) object;
if (info instanceof X509Data) {
final X509Data x509Data = (X509Data) info;
for (final Object certificado : x509Data.getContent()) {
if (certificado instanceof X509Certificate) {
final X509Certificate x509Certificate = (X509Certificate) certificado;
if (this.algEquals(method.getAlgorithm(), x509Certificate.getPublicKey().getAlgorithm())) {
return x509Certificate::getPublicKey;
}
}
}
}
}
throw new KeySelectorException("Nao foi localizada a chave do certificado.");
}
private boolean algEquals(final String algURI, final String algName) {
return ((algName.equalsIgnoreCase("DSA") && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) || (algName.equalsIgnoreCase("RSA") && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)));
}
}
} | src/main/java/com/fincatto/documentofiscal/utils/DFAssinaturaDigital.java | package com.fincatto.documentofiscal.utils;
import com.fincatto.documentofiscal.DFConfig;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Signature;
import java.security.UnrecoverableEntryException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
public class DFAssinaturaDigital {
private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
private static final String[] ELEMENTOS_ASSINAVEIS = new String[]{"infEvento", "infCanc", "infNFe", "infInut", "infMDFe", "infCte"};
private final DFConfig config;
public DFAssinaturaDigital(final DFConfig config) {
this.config = config;
}
public boolean isValida(final InputStream xmlStream) throws Exception {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
final Document document = dbf.newDocumentBuilder().parse(xmlStream);
final NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nodeList.getLength() == 0) {
throw new IllegalStateException("Nao foi encontrada a assinatura do XML.");
}
final String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).getDeclaredConstructor().newInstance());
final DOMValidateContext validateContext = new DOMValidateContext(new DFKeySelector(), nodeList.item(0));
for (final String tag : DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS) {
final NodeList elements = document.getElementsByTagName(tag);
if (elements.getLength() > 0) {
validateContext.setIdAttributeNS((Element) elements.item(0), null, "Id");
}
}
return signatureFactory.unmarshalXMLSignature(validateContext).validate(validateContext);
}
public String assinarDocumento(final String conteudoXml) throws Exception {
return this.assinarDocumento(conteudoXml, DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS);
}
public String assinarDocumento(final String conteudoXml, final String... elementosAssinaveis) throws Exception {
try (StringReader reader = new StringReader(conteudoXml)) {
try (StringWriter writer = new StringWriter()) {
this.assinarDocumento(reader, writer, elementosAssinaveis);
return writer.toString();
}
}
}
public void assinarDocumento(Reader xmlReader, Writer xmlAssinado, final String... elementosAssinaveis) throws Exception {
final KeyStore.PrivateKeyEntry keyEntry = getPrivateKeyEntry();
//Adiciona System.out p/ verificação do certificado que assina o documento
try {
String dn = ((X509Certificate)keyEntry.getCertificate()).getSubjectX500Principal().getName();
LdapName ldapDN = null;
ldapDN = new LdapName(dn);
String commonName = ldapDN.getRdns().stream()
.filter(rdn -> StringUtils.equalsIgnoreCase(rdn.getType(), "CN")).map(val -> val.getValue() + "").findFirst()
.orElse("");
System.out.println("CERTIFICADO ASSINANDO(CNPJ):" + commonName );
} catch (InvalidNameException e) {
}
final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
final List<Transform> transforms = new ArrayList<>(2);
transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
transforms.add(signatureFactory.newTransform(DFAssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null));
final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate()));
final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(xmlReader));
for (final String elementoAssinavel : elementosAssinaveis) {
final NodeList elements = document.getElementsByTagName(elementoAssinavel);
for (int i = 0; i < elements.getLength(); i++) {
final Element element = (Element) elements.item(i);
final String id = element.getAttribute("Id");
element.setIdAttribute("Id", true);
final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null);
final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode()));
}
}
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(document), new StreamResult(xmlAssinado));
}
private KeyStore.PrivateKeyEntry getPrivateKeyEntry() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
// final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray());
//
// KeyStore ks = config.getCertificadoKeyStore();
// for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
// String alias = e.nextElement();
// if (ks.isKeyEntry(alias)) {
// return (KeyStore.PrivateKeyEntry) ks.getEntry(alias, passwordProtection);
// }
// }
//
// throw new RuntimeException("Não foi possível encontrar a chave privada do certificado");
final String certificateAlias = config.getCertificadoAlias() != null ? config.getCertificadoAlias()
: config.getCertificadoKeyStore().aliases().nextElement();
final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray());
return (KeyStore.PrivateKeyEntry) config.getCertificadoKeyStore().getEntry(certificateAlias, passwordProtection);
}
public String assinarString(String _string) throws Exception {
byte[] buffer = _string.getBytes();
Signature signatureProvider = Signature.getInstance("SHA1withRSA");
signatureProvider.initSign(getPrivateKeyEntry().getPrivateKey());
signatureProvider.update(buffer, 0, buffer.length);
byte[] signature = signatureProvider.sign();
System.out.println(getPrivateKeyEntry().getPrivateKey().getFormat());
return Base64.getEncoder().encodeToString(signature);
}
static class DFKeySelector extends KeySelector {
@Override
public KeySelectorResult select(final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context) throws KeySelectorException {
for (final Object object : keyInfo.getContent()) {
final XMLStructure info = (XMLStructure) object;
if (info instanceof X509Data) {
final X509Data x509Data = (X509Data) info;
for (final Object certificado : x509Data.getContent()) {
if (certificado instanceof X509Certificate) {
final X509Certificate x509Certificate = (X509Certificate) certificado;
if (this.algEquals(method.getAlgorithm(), x509Certificate.getPublicKey().getAlgorithm())) {
return x509Certificate::getPublicKey;
}
}
}
}
}
throw new KeySelectorException("Nao foi localizada a chave do certificado.");
}
private boolean algEquals(final String algURI, final String algName) {
return ((algName.equalsIgnoreCase("DSA") && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) || (algName.equalsIgnoreCase("RSA") && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)));
}
}
} | Corrige código que desconsidera o ALIAS escolhido na configuração.
| src/main/java/com/fincatto/documentofiscal/utils/DFAssinaturaDigital.java | Corrige código que desconsidera o ALIAS escolhido na configuração. |
|
Java | apache-2.0 | b75b1b70a10128b21518ff68e532391686cade3f | 0 | telefonicaid/fiware-sdc,Fiware/cloud.SDC,telefonicaid/fiware-sdc,Fiware/cloud.SDC,Fiware/cloud.SDC,Fiware/cloud.SDC,telefonicaid/fiware-sdc,telefonicaid/fiware-sdc | /**
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br>
* This file is part of FI-WARE project.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License.
* </p>
* <p>
* You may obtain a copy of the License at:<br>
* <br>
* http://www.apache.org/licenses/LICENSE-2.0
* </p>
* <p>
* 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.
* </p>
* <p>
* See the License for the specific language governing permissions and limitations under the License.
* </p>
* <p>
* For those usages not covered by the Apache version 2.0 License please contact with [email protected]
* </p>
*/
/**
*
*/
package com.telefonica.euro_iaas.sdc.manager.impl;
import static java.text.MessageFormat.format;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.telefonica.euro_iaas.commons.dao.EntityNotFoundException;
import com.telefonica.euro_iaas.sdc.dao.ChefClientDao;
import com.telefonica.euro_iaas.sdc.dao.ChefNodeDao;
import com.telefonica.euro_iaas.sdc.dao.ProductInstanceDao;
import com.telefonica.euro_iaas.sdc.exception.CanNotCallChefException;
import com.telefonica.euro_iaas.sdc.exception.ChefClientExecutionException;
import com.telefonica.euro_iaas.sdc.exception.NodeExecutionException;
import com.telefonica.euro_iaas.sdc.exception.OpenStackException;
import com.telefonica.euro_iaas.sdc.installator.impl.InstallatorChefImpl;
import com.telefonica.euro_iaas.sdc.installator.impl.InstallatorPuppetImpl;
import com.telefonica.euro_iaas.sdc.keystoneutils.OpenStackRegion;
import com.telefonica.euro_iaas.sdc.manager.NodeManager;
import com.telefonica.euro_iaas.sdc.model.ProductInstance;
import com.telefonica.euro_iaas.sdc.model.dto.ChefClient;
import com.telefonica.euro_iaas.sdc.model.dto.ChefNode;
import com.telefonica.euro_iaas.sdc.util.HttpsClient;
/**
* @author alberts
*/
public class NodeManagerImpl implements NodeManager {
private ProductInstanceDao productInstanceDao;
private ChefClientDao chefClientDao;
private ChefNodeDao chefNodeDao;
private HttpClient client;
private HttpsClient httpsClient;
private OpenStackRegion openStackRegion;
private static Logger log = LoggerFactory.getLogger(NodeManagerImpl.class);
private static Logger puppetLog = LoggerFactory.getLogger(InstallatorPuppetImpl.class);
private static Logger chefLog = LoggerFactory.getLogger(InstallatorChefImpl.class);
/*
* (non-Javadoc)
*
* @see
* com.telefonica.euro_iaas.sdc.manager.ChefClientManager#chefNodeDelete
* (java.lang.String, java.lang.String)
*/
public void nodeDelete(String vdc, String nodeName, String token) throws NodeExecutionException {
log.info("deleting node");
boolean error = false;
try {
puppetDelete(vdc, nodeName, token);
} catch (Exception e) {
error = true;
}
try {
chefClientDelete(vdc, nodeName, token);
} catch (Exception e2) {
error = true;
}
List<ProductInstance> productInstances = null;
String hostname = nodeName.split("\\.")[0];
try {
productInstances = productInstanceDao.findByHostname(nodeName);
for (int i = 0; i < productInstances.size(); i++) {
productInstanceDao.remove(productInstances.get(i));
}
} catch (EntityNotFoundException enfe) {
String errorMsg = "The hostname " + hostname + " does not have products installed " + enfe.getMessage();
log.warn(errorMsg);
}
if (error) {
throw new NodeExecutionException ("Error to delete the node");
}
}
private void puppetDelete(String vdc, String nodeName, String token) throws NodeExecutionException {
puppetLog.info("deleting node " + nodeName + " from puppet master");
String deleteUrl = null;
try {
deleteUrl = openStackRegion.getPuppetWrapperEndPoint(token) + "v2/node/" + nodeName;
} catch (OpenStackException e2) {
puppetLog.warn(e2.getMessage());
}
if (deleteUrl != null) {
Map<String, String> headers = new HashMap<String, String>();
headers.put(HttpsClient.HEADER_AUTH, token);
headers.put(HttpsClient.HEADER_TENNANT, vdc);
try {
int statusCode;
statusCode = httpsClient.doHttps(HttpMethod.DELETE, deleteUrl, "", headers);
if (statusCode == 200 || statusCode == 404) { // 404 means node
// didn't exist in
// puppet
log.info("Node deleted");
} else {
String msg = format("[puppet delete node] response code was: {0}", statusCode);
puppetLog.info(msg);
throw new NodeExecutionException(msg);
}
puppetLog.info("Node succesfully deleted from pupper master");
} catch (IOException e) {
puppetLog.info(e.getMessage());
throw new NodeExecutionException(e);
} catch (IllegalStateException e1) {
puppetLog.info(e1.getMessage());
throw new NodeExecutionException(e1);
} catch (KeyManagementException | NoSuchAlgorithmException e2) {
puppetLog.info(e2.getMessage());
throw new NodeExecutionException(e2);
}
}
}
private void chefClientDelete(String vdc, String chefClientName, String token) throws ChefClientExecutionException {
chefLog.info("deleting node " + chefClientName + " from chef server");
ChefNode node;
List<ProductInstance> productInstances = null;
String hostname = null;
try {
// Eliminacion del nodo
node = chefNodeDao.loadNode(chefClientName, token);
chefNodeDao.deleteNode(node, token);
chefLog.info("Node " + chefClientName + " deleted from Chef Server");
chefClientDao.deleteChefClient(chefClientName, token);
} catch (CanNotCallChefException e) {
String errorMsg = "Error deleting the Node" + chefClientName + " in Chef server. Description: "
+ e.getMessage();
chefLog.warn(errorMsg);
} catch (Exception e2) {
String errorMsg = "The ChefClient " + chefClientName + " was not found in the system " + e2.getMessage();
chefLog.info(errorMsg);
throw new ChefClientExecutionException(errorMsg, e2);
}
}
/*
* (non-Javadoc)
*
* @see
* com.telefonica.euro_iaas.sdc.manager.ChefClientManager#chefClientfindAll
* ()
*/
public ChefClient chefClientfindByHostname(String hostname, String token) throws EntityNotFoundException,
ChefClientExecutionException {
ChefClient chefClient;
try {
chefClient = chefClientDao.chefClientfindByHostname(hostname, token);
} catch (EntityNotFoundException e) {
throw e;
} catch (Exception e) {
String message = " An error ocurred invoing the Chef server to load " + "ChefClient whose hostname is "
+ hostname;
log.info(message);
throw new ChefClientExecutionException(message, e);
}
return chefClient;
}
/*
* (non-Javadoc)
*
* @see
* com.telefonica.euro_iaas.sdc.manager.ChefClientManager#chefClientload
* (java.lang.String, java.lang.String)
*/
public ChefClient chefClientload(String chefClientName, String token) throws ChefClientExecutionException,
EntityNotFoundException {
ChefClient chefClient = new ChefClient();
try {
chefClient = chefClientDao.getChefClient(chefClientName, token);
} catch (EntityNotFoundException e) {
String men = "The node is not in the chef-server: " + chefClientName + " : " + e.getMessage();
log.warn (men);
throw new EntityNotFoundException(ChefClient.class, men, chefClientName);
} catch (Exception e) {
String message = " An error ocurred invoing the Chef server to load ChefClient named " + chefClientName;
log.info(message);
throw new ChefClientExecutionException(message, e);
}
return chefClient;
}
/**
* @param chefClientDao
* the chefClientDao to set
*/
public void setChefClientDao(ChefClientDao chefClientDao) {
this.chefClientDao = chefClientDao;
}
/**
* @param chefNodeDao
* the chefNodeDao to set
*/
public void setChefNodeDao(ChefNodeDao chefNodeDao) {
this.chefNodeDao = chefNodeDao;
}
/**
* @param productInstanceDao
* the productInstanceDao to set
*/
public void setProductInstanceDao(ProductInstanceDao productInstanceDao) {
this.productInstanceDao = productInstanceDao;
}
/**
* @param client
* the client to set
*/
public void setClient(HttpClient client) {
this.client = client;
}
public void setOpenStackRegion(OpenStackRegion openStackRegion) {
this.openStackRegion = openStackRegion;
}
public void setHttpsClient(HttpsClient httpsClient) {
this.httpsClient = httpsClient;
}
}
| core/src/main/java/com/telefonica/euro_iaas/sdc/manager/impl/NodeManagerImpl.java | /**
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br>
* This file is part of FI-WARE project.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License.
* </p>
* <p>
* You may obtain a copy of the License at:<br>
* <br>
* http://www.apache.org/licenses/LICENSE-2.0
* </p>
* <p>
* 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.
* </p>
* <p>
* See the License for the specific language governing permissions and limitations under the License.
* </p>
* <p>
* For those usages not covered by the Apache version 2.0 License please contact with [email protected]
* </p>
*/
/**
*
*/
package com.telefonica.euro_iaas.sdc.manager.impl;
import static java.text.MessageFormat.format;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.telefonica.euro_iaas.commons.dao.EntityNotFoundException;
import com.telefonica.euro_iaas.sdc.dao.ChefClientDao;
import com.telefonica.euro_iaas.sdc.dao.ChefNodeDao;
import com.telefonica.euro_iaas.sdc.dao.ProductInstanceDao;
import com.telefonica.euro_iaas.sdc.exception.CanNotCallChefException;
import com.telefonica.euro_iaas.sdc.exception.ChefClientExecutionException;
import com.telefonica.euro_iaas.sdc.exception.NodeExecutionException;
import com.telefonica.euro_iaas.sdc.exception.OpenStackException;
import com.telefonica.euro_iaas.sdc.installator.impl.InstallatorChefImpl;
import com.telefonica.euro_iaas.sdc.installator.impl.InstallatorPuppetImpl;
import com.telefonica.euro_iaas.sdc.keystoneutils.OpenStackRegion;
import com.telefonica.euro_iaas.sdc.manager.NodeManager;
import com.telefonica.euro_iaas.sdc.model.ProductInstance;
import com.telefonica.euro_iaas.sdc.model.dto.ChefClient;
import com.telefonica.euro_iaas.sdc.model.dto.ChefNode;
import com.telefonica.euro_iaas.sdc.util.HttpsClient;
/**
* @author alberts
*/
public class NodeManagerImpl implements NodeManager {
private ProductInstanceDao productInstanceDao;
private ChefClientDao chefClientDao;
private ChefNodeDao chefNodeDao;
private HttpClient client;
private HttpsClient httpsClient;
private OpenStackRegion openStackRegion;
private static Logger log = LoggerFactory.getLogger(NodeManagerImpl.class);
private static Logger puppetLog = LoggerFactory.getLogger(InstallatorPuppetImpl.class);
private static Logger chefLog = LoggerFactory.getLogger(InstallatorChefImpl.class);
/*
* (non-Javadoc)
*
* @see
* com.telefonica.euro_iaas.sdc.manager.ChefClientManager#chefNodeDelete
* (java.lang.String, java.lang.String)
*/
public void nodeDelete(String vdc, String nodeName, String token) throws NodeExecutionException {
log.info("deleting node");
try {
puppetDelete(vdc, nodeName, token);
chefClientDelete(vdc, nodeName, token);
} catch (Exception e) {
try {
chefClientDelete(vdc, nodeName, token);
} catch (Exception e2) {
throw new NodeExecutionException(e2);
}
}
List<ProductInstance> productInstances = null;
// eliminacion de los productos instalados en la maquina virtual
String hostname = nodeName.split("\\.")[0];
try {
productInstances = productInstanceDao.findByHostname(nodeName);
for (int i = 0; i < productInstances.size(); i++) {
productInstanceDao.remove(productInstances.get(i));
}
} catch (EntityNotFoundException enfe) {
String errorMsg = "The hostname " + hostname + " does not have products installed " + enfe.getMessage();
log.warn(errorMsg);
}
}
private void puppetDelete(String vdc, String nodeName, String token) throws NodeExecutionException {
puppetLog.info("deleting node " + nodeName + " from puppet master");
String deleteUrl = null;
try {
deleteUrl = openStackRegion.getPuppetWrapperEndPoint(token) + "v2/node/" + nodeName;
} catch (OpenStackException e2) {
puppetLog.warn(e2.getMessage());
}
if (deleteUrl != null) {
Map<String, String> headers = new HashMap<String, String>();
headers.put(HttpsClient.HEADER_AUTH, token);
headers.put(HttpsClient.HEADER_TENNANT, vdc);
try {
int statusCode;
statusCode = httpsClient.doHttps(HttpMethod.DELETE, deleteUrl, "", headers);
if (statusCode == 200 || statusCode == 404) { // 404 means node
// didn't exist in
// puppet
log.info("Node deleted");
} else {
String msg = format("[puppet delete node] response code was: {0}", statusCode);
puppetLog.info(msg);
throw new NodeExecutionException(msg);
}
puppetLog.info("Node succesfully deleted from pupper master");
} catch (IOException e) {
puppetLog.info(e.getMessage());
throw new NodeExecutionException(e);
} catch (IllegalStateException e1) {
puppetLog.info(e1.getMessage());
throw new NodeExecutionException(e1);
} catch (KeyManagementException | NoSuchAlgorithmException e2) {
puppetLog.info(e2.getMessage());
throw new NodeExecutionException(e2);
}
}
}
private void chefClientDelete(String vdc, String chefClientName, String token) throws ChefClientExecutionException {
chefLog.info("deleting node " + chefClientName + " from chef server");
ChefNode node;
List<ProductInstance> productInstances = null;
String hostname = null;
try {
// Eliminacion del nodo
node = chefNodeDao.loadNode(chefClientName, token);
chefNodeDao.deleteNode(node, token);
chefLog.info("Node " + chefClientName + " deleted from Chef Server");
chefClientDao.deleteChefClient(chefClientName, token);
} catch (CanNotCallChefException e) {
String errorMsg = "Error deleting the Node" + chefClientName + " in Chef server. Description: "
+ e.getMessage();
chefLog.warn(errorMsg);
} catch (Exception e2) {
String errorMsg = "The ChefClient " + chefClientName + " was not found in the system " + e2.getMessage();
chefLog.info(errorMsg);
throw new ChefClientExecutionException(errorMsg, e2);
}
}
/*
* (non-Javadoc)
*
* @see
* com.telefonica.euro_iaas.sdc.manager.ChefClientManager#chefClientfindAll
* ()
*/
public ChefClient chefClientfindByHostname(String hostname, String token) throws EntityNotFoundException,
ChefClientExecutionException {
ChefClient chefClient;
try {
chefClient = chefClientDao.chefClientfindByHostname(hostname, token);
} catch (EntityNotFoundException e) {
throw e;
} catch (Exception e) {
String message = " An error ocurred invoing the Chef server to load " + "ChefClient whose hostname is "
+ hostname;
log.info(message);
throw new ChefClientExecutionException(message, e);
}
return chefClient;
}
/*
* (non-Javadoc)
*
* @see
* com.telefonica.euro_iaas.sdc.manager.ChefClientManager#chefClientload
* (java.lang.String, java.lang.String)
*/
public ChefClient chefClientload(String chefClientName, String token) throws ChefClientExecutionException,
EntityNotFoundException {
ChefClient chefClient = new ChefClient();
try {
chefClient = chefClientDao.getChefClient(chefClientName, token);
} catch (EntityNotFoundException e) {
String men = "The node is not in the chef-server: " + chefClientName + " : " + e.getMessage();
log.warn (men);
throw new EntityNotFoundException(ChefClient.class, men, chefClientName);
} catch (Exception e) {
String message = " An error ocurred invoing the Chef server to load ChefClient named " + chefClientName;
log.info(message);
throw new ChefClientExecutionException(message, e);
}
return chefClient;
}
/**
* @param chefClientDao
* the chefClientDao to set
*/
public void setChefClientDao(ChefClientDao chefClientDao) {
this.chefClientDao = chefClientDao;
}
/**
* @param chefNodeDao
* the chefNodeDao to set
*/
public void setChefNodeDao(ChefNodeDao chefNodeDao) {
this.chefNodeDao = chefNodeDao;
}
/**
* @param productInstanceDao
* the productInstanceDao to set
*/
public void setProductInstanceDao(ProductInstanceDao productInstanceDao) {
this.productInstanceDao = productInstanceDao;
}
/**
* @param client
* the client to set
*/
public void setClient(HttpClient client) {
this.client = client;
}
public void setOpenStackRegion(OpenStackRegion openStackRegion) {
this.openStackRegion = openStackRegion;
}
public void setHttpsClient(HttpsClient httpsClient) {
this.httpsClient = httpsClient;
}
}
| check if there is an error to delete the node in puppet and chef
| core/src/main/java/com/telefonica/euro_iaas/sdc/manager/impl/NodeManagerImpl.java | check if there is an error to delete the node in puppet and chef |
|
Java | apache-2.0 | eaeb0d1189c61f6b7860ca711501a4e94fb2e27a | 0 | cristiani/encuestame,cristiani/encuestame,cristiani/encuestame,cristiani/encuestame,cristiani/encuestame | /*
************************************************************************************
* Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
* encuestame Development Team.
* Licensed under the Apache Software License version 2.0
* 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.encuestame.test.config;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.encuestame.persistence.dao.CommentsOperations;
import org.encuestame.persistence.dao.IAccountDao;
import org.encuestame.persistence.dao.IClientDao;
import org.encuestame.persistence.dao.IDashboardDao;
import org.encuestame.persistence.dao.IEmail;
import org.encuestame.persistence.dao.IFrontEndDao;
import org.encuestame.persistence.dao.IGeoPoint;
import org.encuestame.persistence.dao.IGeoPointTypeDao;
import org.encuestame.persistence.dao.IGroupDao;
import org.encuestame.persistence.dao.IHashTagDao;
import org.encuestame.persistence.dao.INotification;
import org.encuestame.persistence.dao.IPermissionDao;
import org.encuestame.persistence.dao.IPoll;
import org.encuestame.persistence.dao.IProjectDao;
import org.encuestame.persistence.dao.IQuestionDao;
import org.encuestame.persistence.dao.ISurvey;
import org.encuestame.persistence.dao.ISurveyFormatDao;
import org.encuestame.persistence.dao.ITweetPoll;
import org.encuestame.persistence.dao.imp.ClientDao;
import org.encuestame.persistence.dao.imp.DashboardDao;
import org.encuestame.persistence.dao.imp.EmailDao;
import org.encuestame.persistence.dao.imp.FrontEndDao;
import org.encuestame.persistence.dao.imp.HashTagDao;
import org.encuestame.persistence.dao.imp.PollDao;
import org.encuestame.persistence.dao.imp.TweetPollDao;
import org.encuestame.persistence.domain.AbstractSurvey.CustomFinalMessage;
import org.encuestame.persistence.domain.AccessRate;
import org.encuestame.persistence.domain.Attachment;
import org.encuestame.persistence.domain.Client;
import org.encuestame.persistence.domain.Comment;
import org.encuestame.persistence.domain.Email;
import org.encuestame.persistence.domain.EmailList;
import org.encuestame.persistence.domain.GeoPoint;
import org.encuestame.persistence.domain.GeoPointFolder;
import org.encuestame.persistence.domain.GeoPointFolderType;
import org.encuestame.persistence.domain.GeoPointType;
import org.encuestame.persistence.domain.HashTag;
import org.encuestame.persistence.domain.HashTagRanking;
import org.encuestame.persistence.domain.Hit;
import org.encuestame.persistence.domain.Project;
import org.encuestame.persistence.domain.Project.Priority;
import org.encuestame.persistence.domain.dashboard.Dashboard;
import org.encuestame.persistence.domain.dashboard.Gadget;
import org.encuestame.persistence.domain.dashboard.GadgetProperties;
import org.encuestame.persistence.domain.notifications.Notification;
import org.encuestame.persistence.domain.question.Question;
import org.encuestame.persistence.domain.question.QuestionAnswer;
import org.encuestame.persistence.domain.question.QuestionAnswer.AnswerType;
import org.encuestame.persistence.domain.question.QuestionColettion;
import org.encuestame.persistence.domain.question.QuestionPreferences;
import org.encuestame.persistence.domain.security.Account;
import org.encuestame.persistence.domain.security.Group;
import org.encuestame.persistence.domain.security.Permission;
import org.encuestame.persistence.domain.security.SocialAccount;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.persistence.domain.security.Group.Type;
import org.encuestame.persistence.domain.survey.Poll;
import org.encuestame.persistence.domain.survey.PollFolder;
import org.encuestame.persistence.domain.survey.PollResult;
import org.encuestame.persistence.domain.survey.Survey;
import org.encuestame.persistence.domain.survey.SurveyFolder;
import org.encuestame.persistence.domain.survey.SurveyFormat;
import org.encuestame.persistence.domain.survey.SurveyGroup;
import org.encuestame.persistence.domain.survey.SurveyPagination;
import org.encuestame.persistence.domain.survey.SurveyResult;
import org.encuestame.persistence.domain.survey.SurveySection;
import org.encuestame.persistence.domain.tweetpoll.TweetPoll;
import org.encuestame.persistence.domain.tweetpoll.TweetPollFolder;
import org.encuestame.persistence.domain.tweetpoll.TweetPollResult;
import org.encuestame.persistence.domain.tweetpoll.TweetPollSavedPublishedStatus;
import org.encuestame.persistence.domain.tweetpoll.TweetPollSwitch;
import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
import org.encuestame.utils.PictureUtils;
import org.encuestame.utils.enums.CommentOptions;
import org.encuestame.utils.enums.EnMePermission;
import org.encuestame.utils.enums.GadgetType;
import org.encuestame.utils.enums.HitCategory;
import org.encuestame.utils.enums.LayoutEnum;
import org.encuestame.utils.enums.NotificationEnum;
import org.encuestame.utils.enums.Status;
import org.encuestame.utils.social.SocialProvider;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
/**
* Base Class to Test Cases.
* @author Picado, Juan juanATencuestame.org
* @since October 15, 2009
*/
public abstract class AbstractBase extends AbstractConfigurationBase{
/**
* Hibernate Template.
*/
@Autowired
private HibernateTemplate hibernateTemplate;
/** SurveyFormat Dao.**/
@Autowired
private ISurveyFormatDao surveyformatDaoImp;
/** User Security Dao.**/
@Autowired
private IAccountDao accountDao;
/**Group Security Dao.**/
@Autowired
private IGroupDao groupDaoImp;
/** Security Permissions Dao.**/
@Autowired
private IPermissionDao permissionDaoImp;
/** Catalog Location Dao.**/
@Autowired
private IGeoPoint geoPointDao;
/** Project Dao Imp.**/
@Autowired
private IProjectDao projectDaoImp;
/** Survey Dao Imp.**/
@Autowired
private ISurvey surveyDaoImp;
/** Question Dao Imp.**/
@Autowired
private IQuestionDao questionDaoImp;
/** Catalog Location Type Dao.**/
@Autowired
private IGeoPointTypeDao geoPointTypeDao;
/** {@link ClientDao}. **/
@Autowired
private IClientDao clientDao;
/** {@link TweetPollDao}. **/
@Autowired
private ITweetPoll iTweetPoll;
/** {@link PollDao}. **/
@Autowired
private IPoll pollDao;
/** {@link EmailDao}. **/
@Autowired
private IEmail emailDao;
/** {@link Notification}. **/
@Autowired
private INotification notificationDao;
/** {@link CommentsOperations} **/
@Autowired
private CommentsOperations commentsOperations;
/** Activate Notifications.**/
private Boolean activateNotifications = false;
/** Url Poll. **/
public final String URLPOLL = "http://www.encuestame.org";
/** {@link HashTagDao} **/
@Autowired
private IHashTagDao hashTagDao;
/** {@link FrontEndDao} **/
@Autowired
private IFrontEndDao frontEndDao;
/** {@link DashboardDao} **/
@Autowired
private IDashboardDao dashboardDao;
/**
* Get Property.
* @param property
* @return
*/
public String getProperty(final String property){
Resource resource = new ClassPathResource("properties-test/test-config.properties");
Properties props = null;
try {
props = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
//log.debug("Property ["+property+"] value ["+props.getProperty(property)+"]");
return props.getProperty(property);
}
/**
* Getter.
* @return the surveyFormatDaoImp
*/
public ISurveyFormatDao getSurveyFormatDaoImp() {
return surveyformatDaoImp;
}
/**
* @param surveyformatDaoImp {@link ISurveyFormatDao}
*/
public void setSurveyFormatDaoImp(final ISurveyFormatDao surveyformatDaoImp) {
this.surveyformatDaoImp = surveyformatDaoImp;
}
/**
* Force to push HIBERNATE domains saved to HIBERNATE SEARCH indexes.
* This is useful to test full text session search on test cases.
*/
public void flushIndexes(){
final FullTextSession fullTextSession = Search.getFullTextSession(getHibernateTemplate()
.getSessionFactory().getCurrentSession());
fullTextSession.flushToIndexes();
}
/**
* @return the userDao
*/
public IAccountDao getAccountDao() {
return accountDao;
}
/**
* @param userDao the userDao to set
*/
public void setAccountDao(final IAccountDao userDao) {
this.accountDao = userDao;
}
/**
* @return {@link IGroupDao}
*/
public IGroupDao getGroup(){
return groupDaoImp;
}
/**
* @param GroupDaoImp {@link IGroupDao}
*/
public void setgroupDao(final IGroupDao GroupDaoImp){
this.groupDaoImp = groupDaoImp;
}
/**
* @return the permissionDaoImp
*/
public IPermissionDao getPermissionDaoImp() {
return permissionDaoImp;
}
/**
* @param permissionDaoImp the permissionDaoImp to set
*/
public void setPermissionDaoImp(final IPermissionDao permissionDaoImp) {
this.permissionDaoImp = permissionDaoImp;
}
/**
* @return the groupDaoImp
*/
public IGroupDao getGroupDaoImp() {
return groupDaoImp;
}
/**
* @param secGroupDaoImp the secGroupDaoImp to set
*/
public void setGroupDaoImp(final IGroupDao groupDaoImp) {
this.groupDaoImp = groupDaoImp;
}
/**
* @return the projectDaoImp
*/
public IProjectDao getProjectDaoImp() {
return projectDaoImp;
}
/**
* @param projectDaoImp the projectDaoImp to set
*/
public void setProjectDaoImp(final IProjectDao projectDaoImp) {
this.projectDaoImp = projectDaoImp;
}
/**
* @return the surveyDaoImp
*/
public ISurvey getSurveyDaoImp() {
return surveyDaoImp;
}
/**
* @param surveyDaoImp the surveyDaoImp to set
*/
public void setSurveyDaoImp(final ISurvey surveyDaoImp) {
this.surveyDaoImp = surveyDaoImp;
}
/**
* @return the questionDaoImp
*/
public IQuestionDao getQuestionDaoImp() {
return questionDaoImp;
}
/**
* @param questionDaoImp the questionDaoImp to set
*/
public void setQuestionDaoImp(final IQuestionDao questionDaoImp) {
this.questionDaoImp = questionDaoImp;
}
/**
* @return the surveyformatDaoImp
*/
public ISurveyFormatDao getSurveyformatDaoImp() {
return surveyformatDaoImp;
}
/**
* @param surveyformatDaoImp the surveyformatDaoImp to set
*/
public void setSurveyformatDaoImp(ISurveyFormatDao surveyformatDaoImp) {
this.surveyformatDaoImp = surveyformatDaoImp;
}
/**
* @return the geoPointTypeDao
*/
public IGeoPointTypeDao getGeoPointTypeDao() {
return geoPointTypeDao;
}
/**
* @param geoPointTypeDao the geoPointTypeDao to set
*/
public void setGeoPointTypeDao(IGeoPointTypeDao geoPointTypeDao) {
this.geoPointTypeDao = geoPointTypeDao;
}
/**
* @return geoPointDao
*/
public IGeoPoint getGeoPointDao() {
return geoPointDao;
}
/**
* @param geoPointDao geoPointDao
*/
public void setGeoPointDao(final IGeoPoint geoPointDao) {
this.geoPointDao = geoPointDao;
}
/**
* @return {@link GeoPoint}
*/
public IGeoPoint getGeoPoint() {
return geoPointDao;
}
/**
* @param geoPoint {@link GeoPoint}
*/
public void setGeoPoint(final IGeoPoint geoPoint) {
this.geoPointDao = geoPoint;
}
/**
* @return {@link Poll}
*/
public IPoll getPollDao() {
return pollDao;
}
/**
* @param poll the iPoll to set
*/
public void setPollDao(final IPoll poll) {
this.pollDao = poll;
}
/**
* @return the catEmailDao
*/
public IEmail getCatEmailDao() {
return emailDao;
}
/**
* @param catEmailDao the catEmailDao to set
*/
public void setCatEmailDao(IEmail catEmailDao) {
this.emailDao = catEmailDao;
}
/**
* Helper to create poll
* @return poll
*/
public Poll createPoll(final Date createdAt,
final Question question,
final UserAccount userAccount,
final Boolean pollCompleted,
final Boolean pollPublish
){
final String pollHash = RandomStringUtils.randomAlphabetic(18);
final Poll poll = new Poll();
poll.setCreatedAt(createdAt);
poll.setQuestion(question);
poll.setPollHash(pollHash); //should be unique
poll.setEditorOwner(userAccount);
poll.setOwner(userAccount.getAccount());
poll.setPollCompleted(pollCompleted);
poll.setPublish(pollPublish);
poll.setShowComments(CommentOptions.APPROVE);
getPollDao().saveOrUpdate(poll);
return poll;
}
/**
* Helper create default poll.
* @param question
* @param userAccount
* @return
*/
public Poll createDefaultPoll(final Question question,
final UserAccount userAccount) {
return this.createPoll(new Date(), question, userAccount, Boolean.TRUE,
Boolean.TRUE);
}
/**
* Helper to create poll
* @param createdDate
* @param question
* @param hash
* @param currentUser
* @param pollCompleted
* @return
*/
public Poll createPoll(
final Date createdDate,
final Question question,
final String hash,
final UserAccount userAccount,
final Boolean pollCompleted,
final Boolean published){
final Poll poll = new Poll();
poll.setCreatedAt(createdDate);
poll.setCloseAfterDate(true);
poll.setAdditionalInfo("additional");
poll.setClosedDate(new Date());
poll.setClosedQuota(100);
poll.setCustomFinalMessage(CustomFinalMessage.FINALMESSAGE);
poll.setCustomMessage(true);
poll.setDislikeVote(300L);
poll.setLikeVote(560L);
poll.setEndDate(new Date());
poll.setFavorites(true);
poll.setNumbervotes(600L);
poll.setQuestion(question);
poll.setPollHash(hash);
poll.setEditorOwner(userAccount);
poll.setOwner(userAccount.getAccount());
poll.setPollCompleted(pollCompleted);
poll.setPublish(published);
poll.setShowComments(CommentOptions.APPROVE);
getPollDao().saveOrUpdate(poll);
return poll;
}
/**
* Helper to create Poll Result.
* @param questionAnswer {@link QuestionAnswer}
* @param poll {@link Poll}
* @return state
*/
public PollResult createPollResults(final QuestionAnswer questionAnswer, final Poll poll){
final PollResult pollRes = new PollResult();
pollRes.setAnswer(questionAnswer);
pollRes.setIpaddress("127.0.0."+RandomStringUtils.random(10));
pollRes.setPoll(poll);
pollRes.setVotationDate(new Date());
getPollDao().saveOrUpdate(pollRes);
return pollRes;
}
/**
* Create project.
* @param name Project's name
* @param descProject Project Description
* @param infoProject Informations's Project
* @param user user
* @return {@link Project}
*/
public Project createProject(
final String name,
final String descProject,
final String infoProject,
final Account user) {
final Project project = new Project();
final Calendar start = Calendar.getInstance();
final Calendar end = Calendar.getInstance();
end.add(Calendar.MONTH, 4);
project.setProjectDateFinish(end.getTime());
project.setProjectDateStart(start.getTime());
project.setProjectInfo(infoProject);
project.setProjectName(RandomStringUtils.randomAscii(4)+"_name");
project.setLead(createUserAccount("tes-"+RandomStringUtils.randomAscii(4), createAccount()));
project.setProjectDescription(descProject);
project.setProjectStatus(Status.ACTIVE);
project.setPriority(Priority.MEDIUM);
project.setHideProject(Boolean.FALSE);
project.setPublished(Boolean.TRUE);
project.setUsers(user);
getProjectDaoImp().saveOrUpdate(project);
return project;
}
/**
* Create Attachment.
* @param filename
* @param uploadDate
* @param project
* @return Attachment data.
*/
public Attachment createAttachment(
final String filename,
final Date uploadDate,
final Project project
){
final Attachment attachmentInfo = new Attachment();
attachmentInfo.setFilename(filename);
attachmentInfo.setUploadDate(uploadDate);
attachmentInfo.setProjectAttachment(project);
getProjectDaoImp().saveOrUpdate(attachmentInfo);
return attachmentInfo;
}
/**
* Create {@link Client}.
* @param name name
* @param project {@link Project}
* @return {@link Client}
*/
public Client createClient(final String name, final Project project){
final Client client = new Client();
client.setClientName(name);
client.setProject(project);
client.setClientEmail("");
client.setClientDescription("");
client.setClientFax("");
client.setClientTelephone("");
client.setClientTwitter("");
client.setClientUrl("");
getClientDao().saveOrUpdate(client);
return client;
}
/**
* Helper to create Secondary User.
* @param name user name
* @param secUser {@link Account}
* @return state
*/
public UserAccount createUserAccount(
final String name,
final Account account){
return createUserAccount(name, name.replace(" ", "")+"."+RandomStringUtils.randomNumeric(6)+"@users.com", account);
}
public UserAccount createSecondaryUserGroup(
final String name,
final Account secUser,
final Group group){
return createSecondaryUserGroup(name, name.replace(" ", "")+"."+RandomStringUtils.randomNumeric(6)+"@users.com", secUser, group);
}
public GadgetProperties createGadgetProperties(final String name, final String value,
final Gadget gadget,
final UserAccount user){
final GadgetProperties properties = new GadgetProperties();
properties.setGadgetPropName(name);
properties.setGadgetPropValue(value);
properties.setUserAccount(user);
properties.setGadget(gadget);
getDashboardDao().saveOrUpdate(properties);
return properties;
}
/**
* Create gadget default.
* @return
*/
public Gadget createGadgetDefault(final Dashboard board){
return this.createGadget("default", board);
}
/**
* Create gadget.
* @param name
* @param type
* @return
*/
public Gadget createGadget(final String name, final Dashboard board){
final Gadget gadget = new Gadget();
gadget.setGadgetName(name);
gadget.setGadgetType(GadgetType.getGadgetType("stream"));
gadget.setGadgetColumn(2);
gadget.setGadgetColor("default");
gadget.setGadgetPosition(0);
gadget.setDashboard(board);
getDashboardDao().saveOrUpdate(gadget);
return gadget;
}
/**
* Create dashboard.
* @param boardName
* @param favorite
* @param userAcc
* @return
*/
public Dashboard createDashboard(final String boardName, final Boolean favorite, final UserAccount userAcc){
final Dashboard board = new Dashboard();
board.setPageBoardName(boardName);
board.setDescription("");
board.setFavorite(favorite);
board.setFavoriteCounter(1);
board.setPageLayout(LayoutEnum.AAA_COLUMNS);
board.setBoardSequence(1);
board.setUserBoard(userAcc);
getDashboardDao().saveOrUpdate(board);
return board;
}
/**
* Create dashboard default.
* @param userAcc
* @return
*/
public Dashboard createDashboardDefault(final UserAccount userAcc){
return this.createDashboard("Board default", Boolean.TRUE, userAcc);
}
/**
* Create Secondary User.
* @param name
* @param email
* @param secUser
* @return
*/
public UserAccount createUserAccount(
final String name,
final String email,
final Account secUser) {
final UserAccount user= new UserAccount();
user.setCompleteName(name);
user.setUsername(name);
user.setPassword("12345");
user.setUserEmail(email.trim());
user.setEnjoyDate(new Date());
user.setInviteCode("xxxxxxx");
user.setAccount(secUser);
user.setUserStatus(true);
getAccountDao().saveOrUpdate(user);
return user;
}
/**
* Create Secondary User.
* @param name
* @param email
* @param secUser
* @return
*/
public UserAccount createSecondaryUserGroup(
final String name,
final String email,
final Account secUser,
final Group group){
final UserAccount user= new UserAccount();
user.setCompleteName(name);
user.setUsername(name);
user.setPassword("12345");
user.setUserEmail(email);
user.setEnjoyDate(new Date());
user.setInviteCode("xxxxxxx");
user.setAccount(secUser);
user.setUserStatus(true);
user.setGroup(group);
getAccountDao().saveOrUpdate(user);
return user;
}
/**
* Create account.
* @return {@link Account}
*/
public Account createAccount(){
Account user = new Account();
user.setEnabled(Boolean.TRUE);
user.setCreatedAccount(new Date());
getAccountDao().saveOrUpdate(user);
return user;
}
/**
* Create account with customized enabled.
* @param enabled cuztomized enabled.
* @return {@link Account}.
*/
public Account createAccount(final Boolean enabled){
final Account account = this.createAccount();
account.setEnabled(enabled);
getAccountDao().saveOrUpdate(account);
return account;
}
/**
* Create user account.
* @param status
* @param name
* @param account
* @return
*/
public UserAccount createUserAccount(final Boolean status, final Date createdAt , final String name, final Account account){
final UserAccount userAcc = this.createUserAccount(name, account);
userAcc.setEnjoyDate(createdAt);
userAcc.setUserStatus(status);
getAccountDao().saveOrUpdate(userAcc);
return userAcc;
}
/**
* Create User.
* @param twitterAccount account
* @param twitterPassword password
* @return {@link Account}
*/
public Account createUser(final String twitterAccount, final String twitterPassword){
Account user = new Account();
getAccountDao().saveOrUpdate(user);
return user;
}
/**
* Helper to create LocationType.
* @param locationTypeName locationTypeName
* @return locationType
*/
public GeoPointType createGeoPointType(final String locationTypeName){
final GeoPointType catLocatType = new GeoPointType();
catLocatType.setLocationTypeDescription(locationTypeName);
catLocatType.setLocationTypeLevel(1);
catLocatType.setUsers(createAccount());
getGeoPointTypeDao().saveOrUpdate(catLocatType);
return catLocatType;
}
/**
* Helper to create GeoPoint.
* @param locDescription locDescription
* @param locTypeName locTypeName
* @param Level Level
* @return location {@link GeoPointFolder}.
*/
public GeoPoint createGeoPoint(
final String locDescription,
final String locTypeName,
final Integer Level,
final Account secUsers,
final GeoPointFolder geoPointFolder){
final GeoPoint location = new GeoPoint();
location.setLocationStatus(Status.ACTIVE);
location.setLocationDescription(locDescription);
location.setLocationLatitude(2F);
location.setAccount(secUsers);
location.setGeoPointFolder(geoPointFolder);
location.setLocationLongitude(3F);
location.setTidtype(createGeoPointType(locTypeName));
getGeoPointDao().saveOrUpdate(location);
return location;
}
/**
* Create Default Location.
* @param locDescription description.
* @param locTypeName type
* @param Level level
* @param secUsers {@link Account}.
* @return
*/
public GeoPoint createGeoPoint(
final String locDescription,
final String locTypeName,
final Integer Level,
final Account secUsers){
return this.createGeoPoint(locDescription, locTypeName, Level, secUsers, null);
}
/**
* Helper to create Group.
* @param groupname user name
* @return state
*/
public Group createGroups(final String groupname){
return createGroups(groupname, this.createAccount());
}
public Group createGroups(final String groupname, final Account secUser){
final Group group = new Group();
group.setAccount(secUser);
group.setGroupName(groupname);
group.setIdState(1L);
group.setGroupType(Type.SECURITY);
group.setGroupDescriptionInfo("First Group");
getGroup().saveOrUpdate(group);
return group;
}
/**
* Helper to create Permission.
* @param permissionName name
* @return Permission
*/
public Permission createPermission(final String permissionName){
final Permission permission = new Permission();
permission.setPermissionDescription(permissionName);
permission.setPermission(EnMePermission.getPermissionString(permissionName));
getPermissionDaoImp().saveOrUpdate(permission);
return permission;
}
/**
* Helper to add permission to user.
* @param user user
* @param permission permission
*/
public void addPermissionToUser(final Account user, final Permission permission){
// final SecUserPermission userPerId = new SecUserPermission();
// final SecUserPermissionId id = new SecUserPermissionId();
/// id.setIdPermission(permission.getIdPermission());
// id.setUid(user.getUid());
// userPerId.setId(id);
//userPerId.setState(true);
// getSecUserDao().saveOrUpdate(userPerId);
}
/**
* Helper to add user to group.
* @param user user
* @param group group
*/
public void addGroupUser(
final UserAccount user,
final Group group)
{
/* final SecGroupUserId id = new SecGroupUserId();
id.setGroupId(group.getGroupId());
id.setUid(user.getUid());
final SecGroupUser secGroupUser = new SecGroupUser();
secGroupUser.setSecGroupUserId(id);
secGroupUser.setSecUsers(user);
secGroupUser.setSecGroups(group);*/
// getSecUserDao().assingGroupToUser(secGroupUser);
}
/**
* Helper permission to group.
* @param permission permission
* @param group group
*/
public void addPermissionToGroup(
final Permission permission,
final Group group)
{
// final SecGroupPermissionId groupPermissionId = new SecGroupPermissionId();
//// groupPermissionId.setGroupId(group.getGroupId());
// groupPermissionId.setIdPermission(permission.getIdPermission());
// final SecGroupPermission groupPermission = new SecGroupPermission();
// groupPermission.setId(groupPermissionId);
// groupPermission.setSecGroups(group);
// groupPermission.setSecPermission(permission);
// getSecGroup().saveOrUpdate(groupPermission);
}
/**
* Create question.
* @param question question
* @param pattern pattern
* @return {@link Question}
*/
public Question createQuestion(
final String question,
final String pattern){
final Question questions = new Question();
questions.setQidKey("1");
questions.setQuestion(question);
questions.setSlugQuestion(question.replace(" ", "-"));
questions.setSharedQuestion(Boolean.TRUE);
questions.setAccountQuestion(this.createAccount());
getQuestionDaoImp().saveOrUpdate(questions);
return questions;
}
public Question addQuestionSection(
final String question,
final SurveySection section,
final Account account){
final Question questions = new Question();
questions.setQidKey("1");
questions.setQuestion(question);
questions.setSlugQuestion(question.replace(" ", "-"));
questions.setSharedQuestion(Boolean.TRUE);
questions.setAccountQuestion(account);
questions.setSection(section);
getQuestionDaoImp().saveOrUpdate(questions);
return questions;
}
/**
* Create Default Question.
* @param questionName
* @return
*/
public Question createDefaultQuestion(final String questionName){
return this.createQuestion(questionName, "radio");
}
/**
* Create Question.
* @param questionName
* @param user
* @return
*/
public Question createQuestion(final String questionName, final Account user){
final Question question = this.createQuestion(questionName, "pattern");
question.setAccountQuestion(user);
getQuestionDaoImp().saveOrUpdate(question);
return question;
}
/**
* Create {@link Question}.
* @param questionName
* @param user
* @param createDate
* @param hits
* @return
*/
public Question createQuestion(
final String questionName,
final Account user,
final Date createDate,
final Long hits){
final Question question = this.createQuestion(questionName, "pattern");
question.setAccountQuestion(user);
question.setCreateDate(createDate);
question.setHits(hits);
getQuestionDaoImp().saveOrUpdate(question);
return question;
}
/**
* Create question.
* @param question question
* @param patron patron
* @param user user
* @return {@link Question}
*/
public Question createQuestion(final String question, final String patron, final Account user){
final Question questions = this.createQuestion(question, user);
questions.setQidKey("1");
questions.setHits(2L);
questions.setCreateDate(new Date());
getQuestionDaoImp().saveOrUpdate(questions);
return questions;
}
/**
* Create Question Answer.
* @param answer answer
* @param question question
* @param hash hash
* @return {@link QuestionAnswer}
*/
public QuestionAnswer createQuestionAnswer(final String answer, final Question question, final String hash){
final QuestionAnswer questionsAnswers = new QuestionAnswer();
questionsAnswers.setAnswer(answer);
questionsAnswers.setQuestions(question);
questionsAnswers.setUniqueAnserHash(hash);
questionsAnswers.setColor(PictureUtils.getRandomHexColor());
questionsAnswers.setAnswerType(AnswerType.DEFAULT);
getQuestionDaoImp().saveOrUpdate(questionsAnswers);
//log.info("Q "+questionsAnswers.getQuestionAnswerId());
return questionsAnswers;
}
/**
* Save survey responses.
* @param answer
* @param question
* @param survey
* @return
*/
public SurveyResult createSurveyResult(final QuestionAnswer answer,
final Question question, final Survey survey) {
final SurveyResult result = new SurveyResult();
result.setAnswer(answer);
result.setQuestion(question);
result.setSurvey(survey);
getSurveyDaoImp().saveOrUpdate(result);
return result;
}
/**
*Helper to Create Survey Group.
* @param surveyGroupName surveyGroupName
* @return {@link SurveyGroup}
*
**/
public SurveyGroup createSurveyGroup(String surveyGroupName){
final SurveyGroup surveyGroup = new SurveyGroup();
surveyGroup.setDateCreate(new Date());
surveyGroup.setGroupName(surveyGroupName);
getSurveyDaoImp().saveOrUpdate(surveyGroup);
return surveyGroup;
}
/**
*Helper to Create Question Collection.
* @param desCollection Collection Description
* @return {@link QuestionColettion}
*
**/
public QuestionColettion createQuestionCollect(String desCollection){
final QuestionColettion qCollection = new QuestionColettion();
qCollection.setCreationDate(new Date());
qCollection.setDesColeccion(desCollection);
qCollection.setSecUsers(createAccount());
getQuestionDaoImp().saveOrUpdate(qCollection);
return qCollection;
}
/**
* Helper to Create Surveys Format.
* @return {@link SurveyFormat}
* */
public SurveyFormat createSurveyFormat(
final String formatName,
final Date createdDate
){
final SurveyFormat sformat = new SurveyFormat();
sformat.setDateCreated(createdDate);
sformat.setSurveyFormatName(formatName);
sformat.getSurveyGroups().add(createSurveyGroup("editors"));
getSurveyformatDaoImp().saveOrUpdate(sformat);
return sformat;
}
/**
* Create Default Survey Format
* @return
*/
public SurveyFormat createDefaultSurveyFormat(){
return this.createSurveyFormat("New", new Date());
}
//TODO: Create Helpers for Publicated and Non Publicated TweetPoll
/**
* Create TWeetPoll.
* @param tweetId tweetId
* @param closeNotification tweetId
* @param resultNotification resultNotification
* @param allowLiveResults allowLiveResults
* @param publishTweetPoll publishTweetPoll
* @param scheduleTweetPoll publishTweetPoll
* @param scheduleDate scheduleDate
* @param publicationDateTweet publicationDateTweet
* @param completed completed
* @param tweetOwner tweetOwner
* @param question question
* @return tweetPoll.
*/
public TweetPoll createTweetPoll(
Long tweetId,
Boolean closeNotification,
Boolean resultNotification,
Boolean allowLiveResults,
Boolean publishTweetPoll,
Boolean scheduleTweetPoll,
Date scheduleDate,
Date publicationDateTweet,
Boolean completed,
Account tweetOwner,
Question question,
final UserAccount userAccount){
final TweetPoll tweetPoll = new TweetPoll();
tweetPoll.setCloseNotification(closeNotification);
tweetPoll.setResultNotification(resultNotification);
tweetPoll.setAllowLiveResults(allowLiveResults);
tweetPoll.setCompleted(completed);
tweetPoll.setPublishTweetPoll(publishTweetPoll);
tweetPoll.setQuestion(question);
tweetPoll.setScheduleDate(scheduleDate);
tweetPoll.setScheduleTweetPoll(scheduleTweetPoll);
tweetPoll.setCreateDate(publicationDateTweet);
tweetPoll.setFavourites(Boolean.TRUE);
tweetPoll.setTweetOwner(tweetOwner);
tweetPoll.setEditorOwner(userAccount);
getTweetPoll().saveOrUpdate(tweetPoll);
return tweetPoll;
}
/**
* Create Published {@link TweetPoll}.
* @param tweetOwner tweet owner
* @param question question
* @return {@link TweetPoll}
*/
public TweetPoll createPublishedTweetPoll(final Account tweetOwner, final Question question){
return createTweetPoll(12345L, false, false, false, true, true, new Date(), new Date(), false, tweetOwner, question, null);
}
/**
* Create published {@link TweetPoll}.
* @param tweetOwner
* @param question
* @param dateTweet
* @return
*/
public TweetPoll createPublishedTweetPoll(final Account tweetOwner, final Question question, final Date dateTweet){
return createTweetPoll(12345L, false, false, false, true, true, new Date(), dateTweet, false, tweetOwner, question, null);
}
/**
* Create published {@link TweetPoll}.
* @param question
* @param user
* @return
*/
public TweetPoll createPublishedTweetPoll(final Question question, final UserAccount user) {
return createTweetPoll(12345L, false, false, false, true, true, new Date(), new Date(), false, user.getAccount(), question, user);
}
public TweetPoll createPublishedTweetPoll(final Long id, final Question question, final UserAccount user) {
return createTweetPoll(id, false, false, false, true, true, new Date(), new Date(), false, user.getAccount(), question, user);
}
/**
* Create Not Published {@link TweetPoll}.
* @param tweetOwner tweet owner
* @param question question
* @return {@link TweetPoll}
*/
public TweetPoll createNotPublishedTweetPoll(final Account tweetOwner, final Question question){
return createTweetPoll(null, false, false, false, false, false, new Date(), null, false, tweetOwner, question, null);
}
/**
* Create {@link TweetPollSwitch}.
* @param questionsAnswers {@link QuestionAnswer}.
* @param tweetPollDomain {@link TweetPoll}.
* @return {@link TweetPollSwitch}.
*/
public TweetPollSwitch createTweetPollSwitch(final QuestionAnswer questionsAnswers, final TweetPoll tweetPollDomain){
final TweetPollSwitch tPollSwitch = new TweetPollSwitch();
tPollSwitch.setAnswers(questionsAnswers);
tPollSwitch.setTweetPoll(tweetPollDomain);
tPollSwitch.setCodeTweet(questionsAnswers.getUniqueAnserHash());
getTweetPoll().saveOrUpdate(tPollSwitch);
return tPollSwitch;
}
/**
* Create TweetPoll Result
* @param tweetPollSwitch {@link TweetPollResult}
* @param Ip ip address
* @return {@link TweetPollResult}.
*/
public TweetPollResult createTweetPollResult(final TweetPollSwitch tweetPollSwitch, final String Ip){
final TweetPollResult tweetPollResult = new TweetPollResult();
tweetPollResult.setIpVote(Ip);
tweetPollResult.setTweetPollSwitch(tweetPollSwitch);
tweetPollResult.setTweetResponseDate(new Date());
getTweetPoll().saveOrUpdate(tweetPollResult);
return tweetPollResult;
}
/**
* Create tweetpoll result data with polling date.
* @param tweetPollSwitch
* @param Ip
* @param pollingDate
* @return
*/
public TweetPollResult createTweetPollResultWithPollingDate(final TweetPollSwitch tweetPollSwitch, final String Ip, final Date pollingDate){
final TweetPollResult tpResults = this.createTweetPollResult(tweetPollSwitch, Ip);
tpResults.setTweetResponseDate(pollingDate);
getTweetPoll().saveOrUpdate(tpResults);
return tpResults;
}
/**
* Create Fast TweetPoll Votes.
* @return tweet poll
*/
public TweetPoll createFastTweetPollVotes(){
final UserAccount secondary = createUserAccount("jhon-"+RandomStringUtils.randomAscii(4), createAccount());
final Question question = createQuestion("who I am?", "");
final QuestionAnswer questionsAnswers1 = createQuestionAnswer("yes", question, "12345");
final QuestionAnswer questionsAnswers2 = createQuestionAnswer("no", question, "12346");
final TweetPoll tweetPoll = createPublishedTweetPoll(secondary.getAccount(), question);
final TweetPollSwitch pollSwitch1 = createTweetPollSwitch(questionsAnswers1, tweetPoll);
final TweetPollSwitch pollSwitch2 = createTweetPollSwitch(questionsAnswers2, tweetPoll);
createTweetPollResult(pollSwitch1, "192.168.0.1");
createTweetPollResult(pollSwitch1, "192.168.0.2");
createTweetPollResult(pollSwitch2, "192.168.0.3");
createTweetPollResult(pollSwitch2, "192.168.0.4");
//log.info("tw "+tweetPoll);
return tweetPoll;
}
/**
* Create {@link GeoPointFolder}.
* @param type {@link GeoPointFolderType}.
* @param locationFolderId folder Id
* @param secUsers {@link Account}.
* @param folderName name
* @param locationFolder
* @return {@link GeoPointFolder}.
*/
public GeoPointFolder createGeoPointFolder(
final GeoPointFolderType type,
final Account secUsers,
final String folderName,
final GeoPointFolder locationFolder){
final UserAccount userAcc = createUserAccount("Juan", secUsers);
final GeoPointFolder geoPointFolder = new GeoPointFolder();
geoPointFolder.setFolderType(type);
geoPointFolder.setFolderName(folderName);
geoPointFolder.setUsers(secUsers);
geoPointFolder.setSubLocationFolder(locationFolder);
geoPointFolder.setCreatedAt(Calendar.getInstance().getTime());
geoPointFolder.setCreatedBy(userAcc);
getGeoPointDao().saveOrUpdate(geoPointFolder);
return geoPointFolder;
}
/**
* Helper Create Survey Section.
* @param catState
* @param descSection
* @return
*/
public SurveySection createSurveySection(
final String descSection){
final SurveySection surveySection = new SurveySection();
surveySection.setDescSection(descSection);
/* surveySection.getQuestionSection().add(createDefaultQuestion("Why is your favourite movie"));
surveySection.getQuestionSection().add(createDefaultQuestion("Where do you live"));
surveySection.getQuestionSection().add(createDefaultQuestion("What do you do at home"));*/
getSurveyDaoImp().saveOrUpdate(surveySection);
return surveySection;
}
public SurveySection createDefaultSection(final String name, final Survey survey){
final SurveySection surveySection = new SurveySection();
surveySection.setDescSection(name);
surveySection.setSurvey(survey);
getSurveyDaoImp().saveOrUpdate(surveySection);
return surveySection;
}
/**
* Create Defaul Survey Pagination.
* @param surveySection
* @return
*/
public SurveyPagination createDefaultSurveyPagination(final SurveySection surveySection){
return this.createSurveyPagination(1, surveySection,this.createDefaultSurvey(this.createAccount()));
}
/**
* Create Survey Pagination.
* @param pageNumber
* @param surveySection
* @return
*/
public SurveyPagination createSurveyPagination(
final Integer pageNumber,
final SurveySection surveySection,
final Survey survey){
final SurveyPagination surveyPag = new SurveyPagination();
surveyPag.setPageNumber(pageNumber);
surveyPag.setSurveySection(surveySection);
surveyPag.setSurvey(survey);
return surveyPag;
}
/**
* Create Default Survey.
* @param secUsers
* @return
*/
public Survey createDefaultSurvey(final Account secUsers ){
return this.createSurvey("", new Date(), new Date(), secUsers,
new Date(), createDefaultSurveyFormat(), "FirstSurvey", new Date());
}
/**
*
* @param secUsers
* @param createdAt
* @return
*/
public Survey createDefaultSurvey(final Account secUsers, final String surveyName, final Date createdAt){
return this.createSurvey("", new Date(), new Date(), secUsers,
new Date(), createDefaultSurveyFormat(), surveyName, createdAt);
}
/**
* Create {@link Survey}
* @param complete
* @param dateInterview
* @param endDate
* @param secUsers
* @param startDate
* @param surveyFormat
* @return
*/
public Survey createSurvey(
final String complete,
final Date dateInterview,
final Date endDate,
final Account secUsers,
final Date startDate,
final SurveyFormat surveyFormat,
final String name,
final Date createdAt
){
final Survey survey = new Survey();
survey.setName(name);
survey.setComplete(complete);
survey.setDateInterview(dateInterview);
survey.setEndDate(endDate);
survey.setOwner(secUsers);
survey.setStartDate(startDate);
survey.setTicket(3);
survey.setCreatedAt(createdAt);
getSurveyDaoImp().saveOrUpdate(survey);
return survey;
}
/**
* Create Default List Email.
* @param user
* @param list
* @return
*/
public EmailList createDefaultListEmail(final Account user,final String list){
return this.createListEmails(user, list, new Date());
}
/**
* Create Default List Email.
* @return
*/
public EmailList createDefaultListEmail(){
return this.createListEmails(createAccount(), "default", new Date());
}
/**
* Create Default Email List.
* @param list list Name
* @return
*/
public EmailList createDefaultListEmail(final String list){
return this.createListEmails(createAccount(), list, new Date());
}
/**
*Create Default Email List.
* @param user
* @return
*/
public EmailList createDefaultListEmail(final Account user){
return this.createListEmails(user, "default", new Date());
}
/**
* Create Email List.
* @return
*/
public EmailList createListEmails(
final Account users,
final String listName,
final Date createDate){
final EmailList catListEmails = new EmailList();
catListEmails.setCreatedAt(createDate);
catListEmails.setListName(listName);
catListEmails.setUsuarioEmail(users);
getCatEmailDao().saveOrUpdate(catListEmails);
return catListEmails;
}
/**
* Create Default Emails.
* @param email
* @return
*/
public Email createDefaultEmails(final String email){
return this.createEmails(email, createDefaultListEmail());
}
/**
* Create Default Emails.
* @param email
* @param listEmail
* @return
*/
public Email createDefaultEmails(final String email, final EmailList listEmail){
return this.createEmails(email, listEmail);
}
/**
* Create Emails.
* @param email
* @param list
* @return
*/
public Email createEmails(
final String email,
final EmailList list){
final Email emails = new Email();
emails.setEmail(email);
emails.setIdListEmail(list);
getCatEmailDao().saveOrUpdate(emails);
return emails;
}
/**
* Create {@link SocialAccount}.
* @param consumerKey
* @param consumerSecret
* @param secretToken
* @param userAccount
* @param socialProfileUsername
* @return
*/
public SocialAccount createSocialAccount(
final String token,
final String secretToken,
final UserAccount userAccount,
final String socialProfileUsername,
final Boolean verified,
final SocialProvider provider) {
final SocialAccount socialAccount = new SocialAccount();
socialAccount.setAccessToken(token);
socialAccount.setSecretToken(secretToken);
socialAccount.setAccount(userAccount.getAccount());
socialAccount.setUserOwner(userAccount);
long randomNum = 100 + (int)(Math.random()* 4000);
socialAccount.setSocialProfileId(String.valueOf(randomNum)+RandomStringUtils.randomAlphanumeric(10));
socialAccount.setVerfied(verified);
socialAccount.setUserOwner(userAccount);
socialAccount.setAccounType(provider);
socialAccount.setSocialAccountName(socialProfileUsername+RandomStringUtils.randomAlphanumeric(10));
socialAccount.setUpgradedCredentials(new Date());
socialAccount.setAddedAccount(new Date());
socialAccount.setEmail("email"+String.valueOf(randomNum));
socialAccount.setProfileUrl("url"+String.valueOf(randomNum));
socialAccount.setRealName("real name"+String.valueOf(randomNum));
socialAccount.setApplicationKey(RandomUtils.nextLong(new Random(50)));
socialAccount.setRefreshToken("refresh_token_"+RandomStringUtils.randomAlphanumeric(10));
socialAccount.setType(org.encuestame.utils.social.TypeAuth.OAUTH1);
getAccountDao().saveOrUpdate(socialAccount);
return socialAccount;
}
/**
* Create Default Setted User.
* @param account {@link Account}.
* @return {@link SocialAccount}.
*/
public SocialAccount createDefaultSettedSocialAccount(final UserAccount account){
return this.createSocialAccount(
getProperty("twitter.test.token"),
getProperty("twitter.test.tokenSecret"),
account,
getProperty("twitter.test.account"), Boolean.TRUE, SocialProvider.TWITTER);
}
/**
* Create {@link SocialAccount} with {@link SocialProvider}.
* @param account {@link Account}
* @param provider {@link SocialProvider}
* @return {@link SocialAccount}.
*/
public SocialAccount createSocialProviderAccount(final UserAccount account, final SocialProvider provider){
return this.createSocialAccount(
getProperty("twitter.test.token"),
getProperty("twitter.test.tokenSecret"),
account,
getProperty("twitter.test.account"), Boolean.TRUE, provider);
}
/**
* Create Default Setted Verified Twitter Account.
* @param account
* @return
*/
public SocialAccount createDefaultSettedVerifiedSocialAccount(final UserAccount account){
return this.createSocialAccount(
getProperty("twitter.test.token"),
getProperty("twitter.test.tokenSecret"),
account,
getProperty("twitter.test.account"),
Boolean.TRUE, SocialProvider.TWITTER);
}
/**
*
* @param folderName
* @param users
* @return
*/
public SurveyFolder createSurveyFolders(final String folderName, final UserAccount users){
final SurveyFolder surveyFolders = new SurveyFolder();
surveyFolders.setCreatedAt(new Date());
surveyFolders.setFolderName(folderName);
surveyFolders.setUsers(users.getAccount());
surveyFolders.setStatus(Status.ACTIVE);
surveyFolders.setCreatedBy(users);
getSurveyDaoImp().saveOrUpdate(surveyFolders);
return surveyFolders;
}
/**
* Create {@link PollFolder}.
* @param folderName folder name
* @param users {@link Account}
* @return {@link PollFolder}.
*/
public PollFolder createPollFolder(final String folderName, final UserAccount users){
final PollFolder folder = new PollFolder();
folder.setCreatedAt(new Date());
folder.setFolderName(folderName);
folder.setUsers(users.getAccount());
folder.setStatus(Status.ACTIVE);
folder.setCreatedBy(users);
getPollDao().saveOrUpdate(folder);
return folder;
}
/**
* Create TweetPoll Folder.
* @param folderName
* @param users
* @return
*/
public TweetPollFolder createTweetPollFolder(final String folderName, final UserAccount users){
final TweetPollFolder folder = new TweetPollFolder();
folder.setCreatedAt(new Date());
folder.setFolderName(folderName);
folder.setStatus(Status.ACTIVE);
folder.setCreatedBy(users);
folder.setUsers(users.getAccount());
getTweetPoll().saveOrUpdate(folder);
return folder;
}
/**
* Add TweetPoll to Folder.
* @param folderId
* @param username
* @param tweetPollId
* @return
* @throws EnMeNoResultsFoundException
*/
public TweetPoll addTweetPollToFolder(final Long folderId, final Long userId, final Long tweetPollId) throws EnMeNoResultsFoundException{
final TweetPollFolder tpfolder = getTweetPoll().getTweetPollFolderById(folderId);
final TweetPoll tpoll = getTweetPoll().getTweetPollByIdandUserId(tweetPollId, userId);
tpoll.setTweetPollFolder(tpfolder);
getTweetPoll().saveOrUpdate(tpoll);
return tpoll;
}
/**
* Add Survey To Folder.
* @param folderId
* @param userId
* @param surveyId
* @return
* @throws EnMeNoResultsFoundException
*/
public Survey addSurveyToFolder(final Long folderId, final Long userId, final Long surveyId) throws EnMeNoResultsFoundException{
final SurveyFolder sfolder = getSurveyDaoImp().getSurveyFolderById(folderId);
final Survey survey = getSurveyDaoImp().getSurveyByIdandUserId(surveyId, userId);
survey.setSurveysfolder(sfolder);
getSurveyDaoImp().saveOrUpdate(survey);
return survey;
}
/**
* Add Poll to Folder.
* @param folderId
* @param userId
* @param pollId
* @return
* @throws EnMeNoResultsFoundException
*/
public Poll addPollToFolder(final Long folderId, final UserAccount userAccount, final Long pollId) throws EnMeNoResultsFoundException{
final PollFolder pfolder = getPollDao().getPollFolderById(folderId);
final Poll poll = getPollDao().getPollById(pollId, userAccount);
poll.setPollFolder(pfolder);
getPollDao().saveOrUpdate(poll);
return poll;
}
/**
* @return the activateNotifications
*/
public Boolean getActivateNotifications() {
return activateNotifications;
}
/**
* @param activateNotifications uthe activateNotifications to set
*/
public void setActivateNotifications(Boolean activateNotifications) {
this.activateNotifications = activateNotifications;
}
/**
* @return the clientDao
*/
public IClientDao getClientDao() {
return clientDao;
}
/**
* @param clientDao the clientDao to set
*/
public void setClientDao(final IClientDao clientDao) {
this.clientDao = clientDao;
}
/**
* @return the iTweetPoll
*/
public ITweetPoll getTweetPoll() {
return iTweetPoll;
}
/**
* @param iTweetPoll the iTweetPoll to set
*/
public void setTweetPoll(final ITweetPoll iTweetPoll) {
this.iTweetPoll = iTweetPoll;
}
/**
* @return the hibernateTemplate
*/
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
/**
* @param hibernateTemplate the hibernateTemplate to set
*/
public void setHibernateTemplate(final HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
/**
* Create Notification.
* @param message message
* @param secUser {@link Account}.
* @param description {@link NotificationEnum}.
*/
public Notification createNotification(
final String message,
final Account secUser,
final NotificationEnum description,
final Boolean readed){
final Notification notification = new Notification();
notification.setAdditionalDescription(message);
notification.setCreated(Calendar.getInstance().getTime());
notification.setDescription(description);
notification.setReaded(readed);
notification.setAccount(secUser);
notification.setUrlReference("http://google.es");
notification.setGroup(true);
getNotification().saveOrUpdate(notification);
return notification;
}
/**
* Create Hash Tag.
* @param hashTagName
* @return
*/
public HashTag createHashTag(final String hashTagName){
final HashTag hashTag = new HashTag();
hashTag.setHashTag(hashTagName.toLowerCase());
hashTag.setHits(0L);
hashTag.setUpdatedDate(new Date());
hashTag.setSize(0L);
getHashTagDao().saveOrUpdate(hashTag);
return hashTag;
}
/**
* Create hashtag with hits.
* @param hashTagName name
* @param hits total hits.
* @return {@link HashTag}
*/
public HashTag createHashTag(final String hashTagName, final Long hits){
final HashTag hastag = this.createHashTag(hashTagName);
hastag.setHits(hits);
getHashTagDao().saveOrUpdate(hastag);
return hastag;
}
/**
*
* @param hashTagName
* @param hits
* @return
*/
public HashTag createHashTag(final String hashTagName, final Long hits, final Long size){
final HashTag hastag = this.createHashTag(hashTagName);
hastag.setHits(hits);
hastag.setSize(size);
hastag.setUpdatedDate(new Date());
getHashTagDao().saveOrUpdate(hastag);
return hastag;
}
/**
* Helper.
* Create hashTag ranking.
* @param tag
* @param rankingDate
* @param average
* @return
*/
public HashTagRanking createHashTagRank(final HashTag tag, final Date rankingDate, final Double average){
final HashTagRanking tagRank = new HashTagRanking();
tagRank.setHashTag(tag);
tagRank.setAverage(average);
tagRank.setRankingDate(rankingDate);
getHashTagDao().saveOrUpdate(tagRank);
return tagRank;
}
/**
* @return the notification
*/
public INotification getNotification() {
return notificationDao;
}
/**
* @param notification the notification to set
*/
public void setNotification(final INotification notification) {
this.notificationDao = notification;
}
/**
* @return the hashTagDao
*/
public IHashTagDao getHashTagDao() {
return hashTagDao;
}
/**
* @param hashTagDao the hashTagDao to set
*/
public void setHashTagDao(IHashTagDao hashTagDao) {
this.hashTagDao = hashTagDao;
}
/**
* @return the frontEndDao
*/
public IFrontEndDao getFrontEndDao() {
return frontEndDao;
}
/**
* @param frontEndDao the frontEndDao to set
*/
public void setFrontEndDao(IFrontEndDao frontEndDao) {
this.frontEndDao = frontEndDao;
}
/**
* Create fake questions.
* @param user {@link Account};
*/
public void createFakesQuestions(final Account user){
createQuestion("Do you want soccer?", user);
createQuestion("Do you like apple's?", user);
createQuestion("Do you buy iPods?", user);
createQuestion("Do you like sky iPods Touch?", user);
createQuestion("Ipad VS Ipad2?", user);
createQuestion("How Often Do You Tweet? Survey Says Not That Often", user);
createQuestion("Is survey usseful on Twitter?", user);
createQuestion("Should be happy?", user);
createQuestion("Are you home alone?", user);
}
/**
* Create a list of fakes {@link TweetPoll}.
* @param userAccount
*/
public void createFakesTweetPoll(final UserAccount userAccount){
final Question question = createQuestion("Real Madrid or Barcelona?", userAccount.getAccount());
final Question question1 = createQuestion("Real Madrid or Barcelona?", userAccount.getAccount());
final Question question2 = createQuestion("Real Madrid or Barcelona?", userAccount.getAccount());
final Question question3 = createQuestion("Real Madrid or Barcelona?", userAccount.getAccount());
createTweetPollPublicated(Boolean.TRUE, Boolean.TRUE, new Date(), userAccount, question);
createTweetPollPublicated(Boolean.TRUE, Boolean.TRUE, new Date(), userAccount, question1);
createTweetPollPublicated(Boolean.TRUE, Boolean.TRUE, new Date(), userAccount, question2);
createTweetPollPublicated(Boolean.TRUE, Boolean.TRUE, new Date(), userAccount, question3);
}
/**
* Create {@link TweetPoll} published.
* @param publishTweetPoll
* @param completed
* @param scheduleDate
* @param tweetOwner
* @param question
* @return
*/
public TweetPoll createTweetPollPublicated(
final Boolean publishTweetPoll,
final Boolean completed,
final Date scheduleDate,
final UserAccount tweetOwner,
final Question question){
final TweetPoll tweetPoll = new TweetPoll();
tweetPoll.setPublishTweetPoll(publishTweetPoll);
tweetPoll.setCompleted(completed);
tweetPoll.setScheduleDate(scheduleDate);
tweetPoll.setCreateDate(new Date());
tweetPoll.setFavourites(false);
tweetPoll.setQuestion(question);
tweetPoll.setTweetOwner(tweetOwner.getAccount());
tweetPoll.setEditorOwner(tweetOwner);
getTweetPoll().saveOrUpdate(tweetPoll);
return tweetPoll;
}
/**
* Create TweetPoll social links.
* @param tweetPoll
* @param tweetId
* @param socialAccount
* @param tweetText
* @return
*/
public TweetPollSavedPublishedStatus createTweetPollSavedPublishedStatus(
final TweetPoll tweetPoll, final String tweetId,
final SocialAccount socialAccount, final String tweetText) {
return this.createSocialLinkSavedPublishedStatus(tweetPoll, null, null,
tweetId, socialAccount, tweetText);
}
/**
* Create social network link.
* @param tweetPoll
* @param poll
* @param survey
* @param tweetId
* @param socialAccount
* @param tweetText
* @return
*/
public TweetPollSavedPublishedStatus createSocialLinkSavedPublishedStatus(
final TweetPoll tweetPoll, final Poll poll, final Survey survey, final String tweetId,
final SocialAccount socialAccount, final String tweetText) {
final TweetPollSavedPublishedStatus publishedStatus = new TweetPollSavedPublishedStatus();
publishedStatus.setTweetPoll(tweetPoll);
publishedStatus.setStatus(org.encuestame.utils.enums.Status.SUCCESS);
publishedStatus.setTweetContent(tweetText);
publishedStatus.setSocialAccount(socialAccount);
publishedStatus.setTweetId(RandomStringUtils.randomAlphabetic(18));
publishedStatus.setPublicationDateTweet(new Date());
publishedStatus.setPoll(poll);
publishedStatus.setSurvey(survey);
getTweetPoll().saveOrUpdate(publishedStatus);
return publishedStatus;
}
/**
* Create Poll social links.
* @param poll
* @param tweetId
* @param socialAccount
* @param tweetText
* @return
*/
public TweetPollSavedPublishedStatus createPollSavedPublishedStatus(
final Poll poll, final String tweetId,
final SocialAccount socialAccount, final String tweetText) {
return this.createSocialLinkSavedPublishedStatus(null, poll, null, tweetId, socialAccount, tweetText);
}
/**
* Create hit new.
* @param tweetPoll
* @param poll
* @param survey
* @param ipAddress
* @return
*/
public Hit createHit(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag hashTag,
final String ipAddress){
final Hit hit = new Hit();
hit.setHitDate(Calendar.getInstance().getTime());
hit.setIpAddress(ipAddress);
hit.setPoll(poll);
hit.setSurvey(survey);
hit.setTweetPoll(tweetPoll);
hit.setHashTag(hashTag);
hit.setHitCategory(HitCategory.VISIT);
getFrontEndDao().saveOrUpdate(hit);
return hit;
}
/**
* Create TweetPoll hit.
* @param tweetPoll
* @param ipAddress
* @return
*/
public Hit createTweetPollHit(final TweetPoll tweetPoll, final String ipAddress){
return this.createHit(tweetPoll, null, null, null, ipAddress);
}
/**
* Create Poll hit.
* @param poll
* @param ipAddress
* @return
*/
public Hit createPollHit(final Poll poll, final String ipAddress){
return this.createHit(null, poll, null, null, ipAddress);
}
/**
* Create survey hit.
* @param survey
* @param ipAddress
* @return
*/
public Hit createSurveyHit(final Survey survey, final String ipAddress){
return this.createHit(null, null, survey, null, ipAddress);
}
/**
* Create HashTag hit.
* @param survey
* @param ipAddress
* @return
*/
public Hit createHashTagHit(final HashTag tag, final String ipAddress){
return this.createHit(null, null, null, tag, ipAddress);
}
/**
* @return the dashboardDao
*/
public IDashboardDao getDashboardDao() {
return dashboardDao;
}
/**
* @param dashboardDao the dashboardDao to set
*/
public void setDashboardDao(final IDashboardDao dashboardDao) {
this.dashboardDao = dashboardDao;
}
/**
* @return the commentsOperationsDao
*/
public CommentsOperations getCommentsOperations() {
return commentsOperations;
}
/**
* @param commentsOperationsDao the commentsOperationsDao to set
*/
public void setCommentsOperations(final CommentsOperations commentsOperations) {
this.commentsOperations = commentsOperations;
}
/**
* Create comment.
* @param comm
* @param likeVote
* @param tpoll
* @param survey
* @param poll
* @return
*/
public Comment createComment(
final String comm,
final Long likeVote,
final TweetPoll tpoll,
final Survey survey,
final Poll poll,
final UserAccount user,
final Long dislikeVote,
final Date createdAt){
final Comment comment = new Comment();
comment.setComment(comm);
comment.setCreatedAt(createdAt);
comment.setLikeVote(likeVote);
comment.setDislikeVote(dislikeVote);
comment.setPoll(poll);
comment.setParentId(null);
comment.setSurvey(survey);
comment.setTweetPoll(tpoll);
comment.setUser(user);
getCommentsOperations().saveOrUpdate(comment);
return comment;
}
/**
* Create default tweetPoll comment.
* @param tpoll
* @return
*/
public Comment createDefaultTweetPollComment(
final String comment,
final TweetPoll tpoll,
final UserAccount userAcc){
return this.createComment(comment, 0L, tpoll, null, null, userAcc, 0L , new Date());
}
/**
*
* @param comment
* @param tpoll
* @param userAcc
* @param likeVote
* @param dislikeVote
* @return
*/
public Comment createDefaultTweetPollCommentVoted(
final String comment,
final TweetPoll tpoll,
final UserAccount userAcc,
final Long likeVote,
final Long dislikeVote,
final Date createdAt){
return this.createComment(comment, likeVote, tpoll, null, null, userAcc, dislikeVote, createdAt);
}
/**
* Create default poll comment.
* @param poll
* @return
*/
public Comment createDefaultPollComment(
final String comment,
final Poll poll,
final UserAccount userAcc){
return this.createComment(comment, 0L, null, null, poll, userAcc, 0L , new Date());
}
/**
* Create default survey comment.
* @param survey
* @return
*/
public Comment createDefaultSurveyComment(
final String comment,
final Survey survey,
final UserAccount userAcc){
return this.createComment(comment, 0L, null, survey, null, userAcc, 0L, new Date());
}
/**
* Create access rate item.
* @param rate
* @param tpoll
* @param survey
* @param poll
* @param user
* @param ipAddress
* @return
*/
public AccessRate createAccessRateItem(final Boolean rate, final TweetPoll tpoll, final Survey survey, final Poll poll,
final UserAccount user, final String ipAddress){
final AccessRate vote = new AccessRate();
vote.setRate(rate);
vote.setTweetPoll(tpoll);
vote.setPoll(poll);
vote.setSurvey(survey);
vote.setUser(user);
vote.setIpAddress(ipAddress);
vote.setUpdatedDate(Calendar.getInstance().getTime());
getTweetPoll().saveOrUpdate(vote);
return vote;
}
/**
* Create tweetpoll access rate.
* @param rate
* @param tweetPoll
* @param ipAddress
* @return
*/
public AccessRate createTweetPollRate(final Boolean rate, final TweetPoll tweetPoll, final String ipAddress){
return this.createAccessRateItem(rate, tweetPoll, null, null, null, ipAddress);
}
/**
* Create poll access rate.
* @param rate
* @param tweetPoll
* @param ipAddress
* @return
*/
public AccessRate createPollRate(final Boolean rate, final Poll poll, final String ipAddress){
return this.createAccessRateItem(rate, null, null, poll, null, ipAddress);
}
/**
* Create survey rate.
* @param rate
* @param survey
* @param ipAddress
* @return
*/
public AccessRate createSurveyRate(final Boolean rate, final Survey survey, final String ipAddress){
return this.createAccessRateItem(rate, null, survey, null, null, ipAddress);
}
/**
* Create question preference
* @param preference
* @param value preference value
* @param question
* @return
*/
public QuestionPreferences createQuestionPreference(
final String preference, final String value, final Question question) {
final QuestionPreferences questionPreference = new QuestionPreferences();
questionPreference.setPreference(preference);
questionPreference.setQuestion(question);
questionPreference.setValue(value);
getQuestionDaoImp().saveOrUpdate(questionPreference);
return questionPreference;
}
}
| encuestame-persistence/src/test/java/org/encuestame/test/config/AbstractBase.java | /*
************************************************************************************
* Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
* encuestame Development Team.
* Licensed under the Apache Software License version 2.0
* 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.encuestame.test.config;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.encuestame.persistence.dao.CommentsOperations;
import org.encuestame.persistence.dao.IAccountDao;
import org.encuestame.persistence.dao.IClientDao;
import org.encuestame.persistence.dao.IDashboardDao;
import org.encuestame.persistence.dao.IEmail;
import org.encuestame.persistence.dao.IFrontEndDao;
import org.encuestame.persistence.dao.IGeoPoint;
import org.encuestame.persistence.dao.IGeoPointTypeDao;
import org.encuestame.persistence.dao.IGroupDao;
import org.encuestame.persistence.dao.IHashTagDao;
import org.encuestame.persistence.dao.INotification;
import org.encuestame.persistence.dao.IPermissionDao;
import org.encuestame.persistence.dao.IPoll;
import org.encuestame.persistence.dao.IProjectDao;
import org.encuestame.persistence.dao.IQuestionDao;
import org.encuestame.persistence.dao.ISurvey;
import org.encuestame.persistence.dao.ISurveyFormatDao;
import org.encuestame.persistence.dao.ITweetPoll;
import org.encuestame.persistence.dao.imp.ClientDao;
import org.encuestame.persistence.dao.imp.DashboardDao;
import org.encuestame.persistence.dao.imp.EmailDao;
import org.encuestame.persistence.dao.imp.FrontEndDao;
import org.encuestame.persistence.dao.imp.HashTagDao;
import org.encuestame.persistence.dao.imp.PollDao;
import org.encuestame.persistence.dao.imp.TweetPollDao;
import org.encuestame.persistence.domain.AbstractSurvey.CustomFinalMessage;
import org.encuestame.persistence.domain.AccessRate;
import org.encuestame.persistence.domain.Attachment;
import org.encuestame.persistence.domain.Client;
import org.encuestame.persistence.domain.Comment;
import org.encuestame.persistence.domain.Email;
import org.encuestame.persistence.domain.EmailList;
import org.encuestame.persistence.domain.GeoPoint;
import org.encuestame.persistence.domain.GeoPointFolder;
import org.encuestame.persistence.domain.GeoPointFolderType;
import org.encuestame.persistence.domain.GeoPointType;
import org.encuestame.persistence.domain.HashTag;
import org.encuestame.persistence.domain.HashTagRanking;
import org.encuestame.persistence.domain.Hit;
import org.encuestame.persistence.domain.Project;
import org.encuestame.persistence.domain.Project.Priority;
import org.encuestame.persistence.domain.dashboard.Dashboard;
import org.encuestame.persistence.domain.dashboard.Gadget;
import org.encuestame.persistence.domain.dashboard.GadgetProperties;
import org.encuestame.persistence.domain.notifications.Notification;
import org.encuestame.persistence.domain.question.Question;
import org.encuestame.persistence.domain.question.QuestionAnswer;
import org.encuestame.persistence.domain.question.QuestionAnswer.AnswerType;
import org.encuestame.persistence.domain.question.QuestionColettion;
import org.encuestame.persistence.domain.security.Account;
import org.encuestame.persistence.domain.security.Group;
import org.encuestame.persistence.domain.security.Permission;
import org.encuestame.persistence.domain.security.SocialAccount;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.persistence.domain.security.Group.Type;
import org.encuestame.persistence.domain.survey.Poll;
import org.encuestame.persistence.domain.survey.PollFolder;
import org.encuestame.persistence.domain.survey.PollResult;
import org.encuestame.persistence.domain.survey.Survey;
import org.encuestame.persistence.domain.survey.SurveyFolder;
import org.encuestame.persistence.domain.survey.SurveyFormat;
import org.encuestame.persistence.domain.survey.SurveyGroup;
import org.encuestame.persistence.domain.survey.SurveyPagination;
import org.encuestame.persistence.domain.survey.SurveyResult;
import org.encuestame.persistence.domain.survey.SurveySection;
import org.encuestame.persistence.domain.tweetpoll.TweetPoll;
import org.encuestame.persistence.domain.tweetpoll.TweetPollFolder;
import org.encuestame.persistence.domain.tweetpoll.TweetPollResult;
import org.encuestame.persistence.domain.tweetpoll.TweetPollSavedPublishedStatus;
import org.encuestame.persistence.domain.tweetpoll.TweetPollSwitch;
import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
import org.encuestame.utils.PictureUtils;
import org.encuestame.utils.enums.CommentOptions;
import org.encuestame.utils.enums.EnMePermission;
import org.encuestame.utils.enums.GadgetType;
import org.encuestame.utils.enums.HitCategory;
import org.encuestame.utils.enums.LayoutEnum;
import org.encuestame.utils.enums.NotificationEnum;
import org.encuestame.utils.enums.Status;
import org.encuestame.utils.social.SocialProvider;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
/**
* Base Class to Test Cases.
* @author Picado, Juan juanATencuestame.org
* @since October 15, 2009
*/
public abstract class AbstractBase extends AbstractConfigurationBase{
/**
* Hibernate Template.
*/
@Autowired
private HibernateTemplate hibernateTemplate;
/** SurveyFormat Dao.**/
@Autowired
private ISurveyFormatDao surveyformatDaoImp;
/** User Security Dao.**/
@Autowired
private IAccountDao accountDao;
/**Group Security Dao.**/
@Autowired
private IGroupDao groupDaoImp;
/** Security Permissions Dao.**/
@Autowired
private IPermissionDao permissionDaoImp;
/** Catalog Location Dao.**/
@Autowired
private IGeoPoint geoPointDao;
/** Project Dao Imp.**/
@Autowired
private IProjectDao projectDaoImp;
/** Survey Dao Imp.**/
@Autowired
private ISurvey surveyDaoImp;
/** Question Dao Imp.**/
@Autowired
private IQuestionDao questionDaoImp;
/** Catalog Location Type Dao.**/
@Autowired
private IGeoPointTypeDao geoPointTypeDao;
/** {@link ClientDao}. **/
@Autowired
private IClientDao clientDao;
/** {@link TweetPollDao}. **/
@Autowired
private ITweetPoll iTweetPoll;
/** {@link PollDao}. **/
@Autowired
private IPoll pollDao;
/** {@link EmailDao}. **/
@Autowired
private IEmail emailDao;
/** {@link Notification}. **/
@Autowired
private INotification notificationDao;
/** {@link CommentsOperations} **/
@Autowired
private CommentsOperations commentsOperations;
/** Activate Notifications.**/
private Boolean activateNotifications = false;
/** Url Poll. **/
public final String URLPOLL = "http://www.encuestame.org";
/** {@link HashTagDao} **/
@Autowired
private IHashTagDao hashTagDao;
/** {@link FrontEndDao} **/
@Autowired
private IFrontEndDao frontEndDao;
/** {@link DashboardDao} **/
@Autowired
private IDashboardDao dashboardDao;
/**
* Get Property.
* @param property
* @return
*/
public String getProperty(final String property){
Resource resource = new ClassPathResource("properties-test/test-config.properties");
Properties props = null;
try {
props = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
//log.debug("Property ["+property+"] value ["+props.getProperty(property)+"]");
return props.getProperty(property);
}
/**
* Getter.
* @return the surveyFormatDaoImp
*/
public ISurveyFormatDao getSurveyFormatDaoImp() {
return surveyformatDaoImp;
}
/**
* @param surveyformatDaoImp {@link ISurveyFormatDao}
*/
public void setSurveyFormatDaoImp(final ISurveyFormatDao surveyformatDaoImp) {
this.surveyformatDaoImp = surveyformatDaoImp;
}
/**
* Force to push HIBERNATE domains saved to HIBERNATE SEARCH indexes.
* This is useful to test full text session search on test cases.
*/
public void flushIndexes(){
final FullTextSession fullTextSession = Search.getFullTextSession(getHibernateTemplate()
.getSessionFactory().getCurrentSession());
fullTextSession.flushToIndexes();
}
/**
* @return the userDao
*/
public IAccountDao getAccountDao() {
return accountDao;
}
/**
* @param userDao the userDao to set
*/
public void setAccountDao(final IAccountDao userDao) {
this.accountDao = userDao;
}
/**
* @return {@link IGroupDao}
*/
public IGroupDao getGroup(){
return groupDaoImp;
}
/**
* @param GroupDaoImp {@link IGroupDao}
*/
public void setgroupDao(final IGroupDao GroupDaoImp){
this.groupDaoImp = groupDaoImp;
}
/**
* @return the permissionDaoImp
*/
public IPermissionDao getPermissionDaoImp() {
return permissionDaoImp;
}
/**
* @param permissionDaoImp the permissionDaoImp to set
*/
public void setPermissionDaoImp(final IPermissionDao permissionDaoImp) {
this.permissionDaoImp = permissionDaoImp;
}
/**
* @return the groupDaoImp
*/
public IGroupDao getGroupDaoImp() {
return groupDaoImp;
}
/**
* @param secGroupDaoImp the secGroupDaoImp to set
*/
public void setGroupDaoImp(final IGroupDao groupDaoImp) {
this.groupDaoImp = groupDaoImp;
}
/**
* @return the projectDaoImp
*/
public IProjectDao getProjectDaoImp() {
return projectDaoImp;
}
/**
* @param projectDaoImp the projectDaoImp to set
*/
public void setProjectDaoImp(final IProjectDao projectDaoImp) {
this.projectDaoImp = projectDaoImp;
}
/**
* @return the surveyDaoImp
*/
public ISurvey getSurveyDaoImp() {
return surveyDaoImp;
}
/**
* @param surveyDaoImp the surveyDaoImp to set
*/
public void setSurveyDaoImp(final ISurvey surveyDaoImp) {
this.surveyDaoImp = surveyDaoImp;
}
/**
* @return the questionDaoImp
*/
public IQuestionDao getQuestionDaoImp() {
return questionDaoImp;
}
/**
* @param questionDaoImp the questionDaoImp to set
*/
public void setQuestionDaoImp(final IQuestionDao questionDaoImp) {
this.questionDaoImp = questionDaoImp;
}
/**
* @return the surveyformatDaoImp
*/
public ISurveyFormatDao getSurveyformatDaoImp() {
return surveyformatDaoImp;
}
/**
* @param surveyformatDaoImp the surveyformatDaoImp to set
*/
public void setSurveyformatDaoImp(ISurveyFormatDao surveyformatDaoImp) {
this.surveyformatDaoImp = surveyformatDaoImp;
}
/**
* @return the geoPointTypeDao
*/
public IGeoPointTypeDao getGeoPointTypeDao() {
return geoPointTypeDao;
}
/**
* @param geoPointTypeDao the geoPointTypeDao to set
*/
public void setGeoPointTypeDao(IGeoPointTypeDao geoPointTypeDao) {
this.geoPointTypeDao = geoPointTypeDao;
}
/**
* @return geoPointDao
*/
public IGeoPoint getGeoPointDao() {
return geoPointDao;
}
/**
* @param geoPointDao geoPointDao
*/
public void setGeoPointDao(final IGeoPoint geoPointDao) {
this.geoPointDao = geoPointDao;
}
/**
* @return {@link GeoPoint}
*/
public IGeoPoint getGeoPoint() {
return geoPointDao;
}
/**
* @param geoPoint {@link GeoPoint}
*/
public void setGeoPoint(final IGeoPoint geoPoint) {
this.geoPointDao = geoPoint;
}
/**
* @return {@link Poll}
*/
public IPoll getPollDao() {
return pollDao;
}
/**
* @param poll the iPoll to set
*/
public void setPollDao(final IPoll poll) {
this.pollDao = poll;
}
/**
* @return the catEmailDao
*/
public IEmail getCatEmailDao() {
return emailDao;
}
/**
* @param catEmailDao the catEmailDao to set
*/
public void setCatEmailDao(IEmail catEmailDao) {
this.emailDao = catEmailDao;
}
/**
* Helper to create poll
* @return poll
*/
public Poll createPoll(final Date createdAt,
final Question question,
final UserAccount userAccount,
final Boolean pollCompleted,
final Boolean pollPublish
){
final String pollHash = RandomStringUtils.randomAlphabetic(18);
final Poll poll = new Poll();
poll.setCreatedAt(createdAt);
poll.setQuestion(question);
poll.setPollHash(pollHash); //should be unique
poll.setEditorOwner(userAccount);
poll.setOwner(userAccount.getAccount());
poll.setPollCompleted(pollCompleted);
poll.setPublish(pollPublish);
poll.setShowComments(CommentOptions.APPROVE);
getPollDao().saveOrUpdate(poll);
return poll;
}
/**
* Helper create default poll.
* @param question
* @param userAccount
* @return
*/
public Poll createDefaultPoll(final Question question,
final UserAccount userAccount) {
return this.createPoll(new Date(), question, userAccount, Boolean.TRUE,
Boolean.TRUE);
}
/**
* Helper to create poll
* @param createdDate
* @param question
* @param hash
* @param currentUser
* @param pollCompleted
* @return
*/
public Poll createPoll(
final Date createdDate,
final Question question,
final String hash,
final UserAccount userAccount,
final Boolean pollCompleted,
final Boolean published){
final Poll poll = new Poll();
poll.setCreatedAt(createdDate);
poll.setCloseAfterDate(true);
poll.setAdditionalInfo("additional");
poll.setClosedDate(new Date());
poll.setClosedQuota(100);
poll.setCustomFinalMessage(CustomFinalMessage.FINALMESSAGE);
poll.setCustomMessage(true);
poll.setDislikeVote(300L);
poll.setLikeVote(560L);
poll.setEndDate(new Date());
poll.setFavorites(true);
poll.setNumbervotes(600L);
poll.setQuestion(question);
poll.setPollHash(hash);
poll.setEditorOwner(userAccount);
poll.setOwner(userAccount.getAccount());
poll.setPollCompleted(pollCompleted);
poll.setPublish(published);
poll.setShowComments(CommentOptions.APPROVE);
getPollDao().saveOrUpdate(poll);
return poll;
}
/**
* Helper to create Poll Result.
* @param questionAnswer {@link QuestionAnswer}
* @param poll {@link Poll}
* @return state
*/
public PollResult createPollResults(final QuestionAnswer questionAnswer, final Poll poll){
final PollResult pollRes = new PollResult();
pollRes.setAnswer(questionAnswer);
pollRes.setIpaddress("127.0.0."+RandomStringUtils.random(10));
pollRes.setPoll(poll);
pollRes.setVotationDate(new Date());
getPollDao().saveOrUpdate(pollRes);
return pollRes;
}
/**
* Create project.
* @param name Project's name
* @param descProject Project Description
* @param infoProject Informations's Project
* @param user user
* @return {@link Project}
*/
public Project createProject(
final String name,
final String descProject,
final String infoProject,
final Account user) {
final Project project = new Project();
final Calendar start = Calendar.getInstance();
final Calendar end = Calendar.getInstance();
end.add(Calendar.MONTH, 4);
project.setProjectDateFinish(end.getTime());
project.setProjectDateStart(start.getTime());
project.setProjectInfo(infoProject);
project.setProjectName(RandomStringUtils.randomAscii(4)+"_name");
project.setLead(createUserAccount("tes-"+RandomStringUtils.randomAscii(4), createAccount()));
project.setProjectDescription(descProject);
project.setProjectStatus(Status.ACTIVE);
project.setPriority(Priority.MEDIUM);
project.setHideProject(Boolean.FALSE);
project.setPublished(Boolean.TRUE);
project.setUsers(user);
getProjectDaoImp().saveOrUpdate(project);
return project;
}
/**
* Create Attachment.
* @param filename
* @param uploadDate
* @param project
* @return Attachment data.
*/
public Attachment createAttachment(
final String filename,
final Date uploadDate,
final Project project
){
final Attachment attachmentInfo = new Attachment();
attachmentInfo.setFilename(filename);
attachmentInfo.setUploadDate(uploadDate);
attachmentInfo.setProjectAttachment(project);
getProjectDaoImp().saveOrUpdate(attachmentInfo);
return attachmentInfo;
}
/**
* Create {@link Client}.
* @param name name
* @param project {@link Project}
* @return {@link Client}
*/
public Client createClient(final String name, final Project project){
final Client client = new Client();
client.setClientName(name);
client.setProject(project);
client.setClientEmail("");
client.setClientDescription("");
client.setClientFax("");
client.setClientTelephone("");
client.setClientTwitter("");
client.setClientUrl("");
getClientDao().saveOrUpdate(client);
return client;
}
/**
* Helper to create Secondary User.
* @param name user name
* @param secUser {@link Account}
* @return state
*/
public UserAccount createUserAccount(
final String name,
final Account account){
return createUserAccount(name, name.replace(" ", "")+"."+RandomStringUtils.randomNumeric(6)+"@users.com", account);
}
public UserAccount createSecondaryUserGroup(
final String name,
final Account secUser,
final Group group){
return createSecondaryUserGroup(name, name.replace(" ", "")+"."+RandomStringUtils.randomNumeric(6)+"@users.com", secUser, group);
}
public GadgetProperties createGadgetProperties(final String name, final String value,
final Gadget gadget,
final UserAccount user){
final GadgetProperties properties = new GadgetProperties();
properties.setGadgetPropName(name);
properties.setGadgetPropValue(value);
properties.setUserAccount(user);
properties.setGadget(gadget);
getDashboardDao().saveOrUpdate(properties);
return properties;
}
/**
* Create gadget default.
* @return
*/
public Gadget createGadgetDefault(final Dashboard board){
return this.createGadget("default", board);
}
/**
* Create gadget.
* @param name
* @param type
* @return
*/
public Gadget createGadget(final String name, final Dashboard board){
final Gadget gadget = new Gadget();
gadget.setGadgetName(name);
gadget.setGadgetType(GadgetType.getGadgetType("stream"));
gadget.setGadgetColumn(2);
gadget.setGadgetColor("default");
gadget.setGadgetPosition(0);
gadget.setDashboard(board);
getDashboardDao().saveOrUpdate(gadget);
return gadget;
}
/**
* Create dashboard.
* @param boardName
* @param favorite
* @param userAcc
* @return
*/
public Dashboard createDashboard(final String boardName, final Boolean favorite, final UserAccount userAcc){
final Dashboard board = new Dashboard();
board.setPageBoardName(boardName);
board.setDescription("");
board.setFavorite(favorite);
board.setFavoriteCounter(1);
board.setPageLayout(LayoutEnum.AAA_COLUMNS);
board.setBoardSequence(1);
board.setUserBoard(userAcc);
getDashboardDao().saveOrUpdate(board);
return board;
}
/**
* Create dashboard default.
* @param userAcc
* @return
*/
public Dashboard createDashboardDefault(final UserAccount userAcc){
return this.createDashboard("Board default", Boolean.TRUE, userAcc);
}
/**
* Create Secondary User.
* @param name
* @param email
* @param secUser
* @return
*/
public UserAccount createUserAccount(
final String name,
final String email,
final Account secUser) {
final UserAccount user= new UserAccount();
user.setCompleteName(name);
user.setUsername(name);
user.setPassword("12345");
user.setUserEmail(email.trim());
user.setEnjoyDate(new Date());
user.setInviteCode("xxxxxxx");
user.setAccount(secUser);
user.setUserStatus(true);
getAccountDao().saveOrUpdate(user);
return user;
}
/**
* Create Secondary User.
* @param name
* @param email
* @param secUser
* @return
*/
public UserAccount createSecondaryUserGroup(
final String name,
final String email,
final Account secUser,
final Group group){
final UserAccount user= new UserAccount();
user.setCompleteName(name);
user.setUsername(name);
user.setPassword("12345");
user.setUserEmail(email);
user.setEnjoyDate(new Date());
user.setInviteCode("xxxxxxx");
user.setAccount(secUser);
user.setUserStatus(true);
user.setGroup(group);
getAccountDao().saveOrUpdate(user);
return user;
}
/**
* Create account.
* @return {@link Account}
*/
public Account createAccount(){
Account user = new Account();
user.setEnabled(Boolean.TRUE);
user.setCreatedAccount(new Date());
getAccountDao().saveOrUpdate(user);
return user;
}
/**
* Create account with customized enabled.
* @param enabled cuztomized enabled.
* @return {@link Account}.
*/
public Account createAccount(final Boolean enabled){
final Account account = this.createAccount();
account.setEnabled(enabled);
getAccountDao().saveOrUpdate(account);
return account;
}
/**
* Create user account.
* @param status
* @param name
* @param account
* @return
*/
public UserAccount createUserAccount(final Boolean status, final Date createdAt , final String name, final Account account){
final UserAccount userAcc = this.createUserAccount(name, account);
userAcc.setEnjoyDate(createdAt);
userAcc.setUserStatus(status);
getAccountDao().saveOrUpdate(userAcc);
return userAcc;
}
/**
* Create User.
* @param twitterAccount account
* @param twitterPassword password
* @return {@link Account}
*/
public Account createUser(final String twitterAccount, final String twitterPassword){
Account user = new Account();
getAccountDao().saveOrUpdate(user);
return user;
}
/**
* Helper to create LocationType.
* @param locationTypeName locationTypeName
* @return locationType
*/
public GeoPointType createGeoPointType(final String locationTypeName){
final GeoPointType catLocatType = new GeoPointType();
catLocatType.setLocationTypeDescription(locationTypeName);
catLocatType.setLocationTypeLevel(1);
catLocatType.setUsers(createAccount());
getGeoPointTypeDao().saveOrUpdate(catLocatType);
return catLocatType;
}
/**
* Helper to create GeoPoint.
* @param locDescription locDescription
* @param locTypeName locTypeName
* @param Level Level
* @return location {@link GeoPointFolder}.
*/
public GeoPoint createGeoPoint(
final String locDescription,
final String locTypeName,
final Integer Level,
final Account secUsers,
final GeoPointFolder geoPointFolder){
final GeoPoint location = new GeoPoint();
location.setLocationStatus(Status.ACTIVE);
location.setLocationDescription(locDescription);
location.setLocationLatitude(2F);
location.setAccount(secUsers);
location.setGeoPointFolder(geoPointFolder);
location.setLocationLongitude(3F);
location.setTidtype(createGeoPointType(locTypeName));
getGeoPointDao().saveOrUpdate(location);
return location;
}
/**
* Create Default Location.
* @param locDescription description.
* @param locTypeName type
* @param Level level
* @param secUsers {@link Account}.
* @return
*/
public GeoPoint createGeoPoint(
final String locDescription,
final String locTypeName,
final Integer Level,
final Account secUsers){
return this.createGeoPoint(locDescription, locTypeName, Level, secUsers, null);
}
/**
* Helper to create Group.
* @param groupname user name
* @return state
*/
public Group createGroups(final String groupname){
return createGroups(groupname, this.createAccount());
}
public Group createGroups(final String groupname, final Account secUser){
final Group group = new Group();
group.setAccount(secUser);
group.setGroupName(groupname);
group.setIdState(1L);
group.setGroupType(Type.SECURITY);
group.setGroupDescriptionInfo("First Group");
getGroup().saveOrUpdate(group);
return group;
}
/**
* Helper to create Permission.
* @param permissionName name
* @return Permission
*/
public Permission createPermission(final String permissionName){
final Permission permission = new Permission();
permission.setPermissionDescription(permissionName);
permission.setPermission(EnMePermission.getPermissionString(permissionName));
getPermissionDaoImp().saveOrUpdate(permission);
return permission;
}
/**
* Helper to add permission to user.
* @param user user
* @param permission permission
*/
public void addPermissionToUser(final Account user, final Permission permission){
// final SecUserPermission userPerId = new SecUserPermission();
// final SecUserPermissionId id = new SecUserPermissionId();
/// id.setIdPermission(permission.getIdPermission());
// id.setUid(user.getUid());
// userPerId.setId(id);
//userPerId.setState(true);
// getSecUserDao().saveOrUpdate(userPerId);
}
/**
* Helper to add user to group.
* @param user user
* @param group group
*/
public void addGroupUser(
final UserAccount user,
final Group group)
{
/* final SecGroupUserId id = new SecGroupUserId();
id.setGroupId(group.getGroupId());
id.setUid(user.getUid());
final SecGroupUser secGroupUser = new SecGroupUser();
secGroupUser.setSecGroupUserId(id);
secGroupUser.setSecUsers(user);
secGroupUser.setSecGroups(group);*/
// getSecUserDao().assingGroupToUser(secGroupUser);
}
/**
* Helper permission to group.
* @param permission permission
* @param group group
*/
public void addPermissionToGroup(
final Permission permission,
final Group group)
{
// final SecGroupPermissionId groupPermissionId = new SecGroupPermissionId();
//// groupPermissionId.setGroupId(group.getGroupId());
// groupPermissionId.setIdPermission(permission.getIdPermission());
// final SecGroupPermission groupPermission = new SecGroupPermission();
// groupPermission.setId(groupPermissionId);
// groupPermission.setSecGroups(group);
// groupPermission.setSecPermission(permission);
// getSecGroup().saveOrUpdate(groupPermission);
}
/**
* Create question.
* @param question question
* @param pattern pattern
* @return {@link Question}
*/
public Question createQuestion(
final String question,
final String pattern){
final Question questions = new Question();
questions.setQidKey("1");
questions.setQuestion(question);
questions.setSlugQuestion(question.replace(" ", "-"));
questions.setSharedQuestion(Boolean.TRUE);
questions.setAccountQuestion(this.createAccount());
getQuestionDaoImp().saveOrUpdate(questions);
return questions;
}
public Question addQuestionSection(
final String question,
final SurveySection section,
final Account account){
final Question questions = new Question();
questions.setQidKey("1");
questions.setQuestion(question);
questions.setSlugQuestion(question.replace(" ", "-"));
questions.setSharedQuestion(Boolean.TRUE);
questions.setAccountQuestion(account);
questions.setSection(section);
getQuestionDaoImp().saveOrUpdate(questions);
return questions;
}
/**
* Create Default Question.
* @param questionName
* @return
*/
public Question createDefaultQuestion(final String questionName){
return this.createQuestion(questionName, "radio");
}
/**
* Create Question.
* @param questionName
* @param user
* @return
*/
public Question createQuestion(final String questionName, final Account user){
final Question question = this.createQuestion(questionName, "pattern");
question.setAccountQuestion(user);
getQuestionDaoImp().saveOrUpdate(question);
return question;
}
/**
* Create {@link Question}.
* @param questionName
* @param user
* @param createDate
* @param hits
* @return
*/
public Question createQuestion(
final String questionName,
final Account user,
final Date createDate,
final Long hits){
final Question question = this.createQuestion(questionName, "pattern");
question.setAccountQuestion(user);
question.setCreateDate(createDate);
question.setHits(hits);
getQuestionDaoImp().saveOrUpdate(question);
return question;
}
/**
* Create question.
* @param question question
* @param patron patron
* @param user user
* @return {@link Question}
*/
public Question createQuestion(final String question, final String patron, final Account user){
final Question questions = this.createQuestion(question, user);
questions.setQidKey("1");
questions.setHits(2L);
questions.setCreateDate(new Date());
getQuestionDaoImp().saveOrUpdate(questions);
return questions;
}
/**
* Create Question Answer.
* @param answer answer
* @param question question
* @param hash hash
* @return {@link QuestionAnswer}
*/
public QuestionAnswer createQuestionAnswer(final String answer, final Question question, final String hash){
final QuestionAnswer questionsAnswers = new QuestionAnswer();
questionsAnswers.setAnswer(answer);
questionsAnswers.setQuestions(question);
questionsAnswers.setUniqueAnserHash(hash);
questionsAnswers.setColor(PictureUtils.getRandomHexColor());
questionsAnswers.setAnswerType(AnswerType.DEFAULT);
getQuestionDaoImp().saveOrUpdate(questionsAnswers);
//log.info("Q "+questionsAnswers.getQuestionAnswerId());
return questionsAnswers;
}
/**
* Save survey responses.
* @param answer
* @param question
* @param survey
* @return
*/
public SurveyResult createSurveyResult(final QuestionAnswer answer,
final Question question, final Survey survey) {
final SurveyResult result = new SurveyResult();
result.setAnswer(answer);
result.setQuestion(question);
result.setSurvey(survey);
getSurveyDaoImp().saveOrUpdate(result);
return result;
}
/**
*Helper to Create Survey Group.
* @param surveyGroupName surveyGroupName
* @return {@link SurveyGroup}
*
**/
public SurveyGroup createSurveyGroup(String surveyGroupName){
final SurveyGroup surveyGroup = new SurveyGroup();
surveyGroup.setDateCreate(new Date());
surveyGroup.setGroupName(surveyGroupName);
getSurveyDaoImp().saveOrUpdate(surveyGroup);
return surveyGroup;
}
/**
*Helper to Create Question Collection.
* @param desCollection Collection Description
* @return {@link QuestionColettion}
*
**/
public QuestionColettion createQuestionCollect(String desCollection){
final QuestionColettion qCollection = new QuestionColettion();
qCollection.setCreationDate(new Date());
qCollection.setDesColeccion(desCollection);
qCollection.setSecUsers(createAccount());
getQuestionDaoImp().saveOrUpdate(qCollection);
return qCollection;
}
/**
* Helper to Create Surveys Format.
* @return {@link SurveyFormat}
* */
public SurveyFormat createSurveyFormat(
final String formatName,
final Date createdDate
){
final SurveyFormat sformat = new SurveyFormat();
sformat.setDateCreated(createdDate);
sformat.setSurveyFormatName(formatName);
sformat.getSurveyGroups().add(createSurveyGroup("editors"));
getSurveyformatDaoImp().saveOrUpdate(sformat);
return sformat;
}
/**
* Create Default Survey Format
* @return
*/
public SurveyFormat createDefaultSurveyFormat(){
return this.createSurveyFormat("New", new Date());
}
//TODO: Create Helpers for Publicated and Non Publicated TweetPoll
/**
* Create TWeetPoll.
* @param tweetId tweetId
* @param closeNotification tweetId
* @param resultNotification resultNotification
* @param allowLiveResults allowLiveResults
* @param publishTweetPoll publishTweetPoll
* @param scheduleTweetPoll publishTweetPoll
* @param scheduleDate scheduleDate
* @param publicationDateTweet publicationDateTweet
* @param completed completed
* @param tweetOwner tweetOwner
* @param question question
* @return tweetPoll.
*/
public TweetPoll createTweetPoll(
Long tweetId,
Boolean closeNotification,
Boolean resultNotification,
Boolean allowLiveResults,
Boolean publishTweetPoll,
Boolean scheduleTweetPoll,
Date scheduleDate,
Date publicationDateTweet,
Boolean completed,
Account tweetOwner,
Question question,
final UserAccount userAccount){
final TweetPoll tweetPoll = new TweetPoll();
tweetPoll.setCloseNotification(closeNotification);
tweetPoll.setResultNotification(resultNotification);
tweetPoll.setAllowLiveResults(allowLiveResults);
tweetPoll.setCompleted(completed);
tweetPoll.setPublishTweetPoll(publishTweetPoll);
tweetPoll.setQuestion(question);
tweetPoll.setScheduleDate(scheduleDate);
tweetPoll.setScheduleTweetPoll(scheduleTweetPoll);
tweetPoll.setCreateDate(publicationDateTweet);
tweetPoll.setFavourites(Boolean.TRUE);
tweetPoll.setTweetOwner(tweetOwner);
tweetPoll.setEditorOwner(userAccount);
getTweetPoll().saveOrUpdate(tweetPoll);
return tweetPoll;
}
/**
* Create Published {@link TweetPoll}.
* @param tweetOwner tweet owner
* @param question question
* @return {@link TweetPoll}
*/
public TweetPoll createPublishedTweetPoll(final Account tweetOwner, final Question question){
return createTweetPoll(12345L, false, false, false, true, true, new Date(), new Date(), false, tweetOwner, question, null);
}
/**
* Create published {@link TweetPoll}.
* @param tweetOwner
* @param question
* @param dateTweet
* @return
*/
public TweetPoll createPublishedTweetPoll(final Account tweetOwner, final Question question, final Date dateTweet){
return createTweetPoll(12345L, false, false, false, true, true, new Date(), dateTweet, false, tweetOwner, question, null);
}
/**
* Create published {@link TweetPoll}.
* @param question
* @param user
* @return
*/
public TweetPoll createPublishedTweetPoll(final Question question, final UserAccount user) {
return createTweetPoll(12345L, false, false, false, true, true, new Date(), new Date(), false, user.getAccount(), question, user);
}
public TweetPoll createPublishedTweetPoll(final Long id, final Question question, final UserAccount user) {
return createTweetPoll(id, false, false, false, true, true, new Date(), new Date(), false, user.getAccount(), question, user);
}
/**
* Create Not Published {@link TweetPoll}.
* @param tweetOwner tweet owner
* @param question question
* @return {@link TweetPoll}
*/
public TweetPoll createNotPublishedTweetPoll(final Account tweetOwner, final Question question){
return createTweetPoll(null, false, false, false, false, false, new Date(), null, false, tweetOwner, question, null);
}
/**
* Create {@link TweetPollSwitch}.
* @param questionsAnswers {@link QuestionAnswer}.
* @param tweetPollDomain {@link TweetPoll}.
* @return {@link TweetPollSwitch}.
*/
public TweetPollSwitch createTweetPollSwitch(final QuestionAnswer questionsAnswers, final TweetPoll tweetPollDomain){
final TweetPollSwitch tPollSwitch = new TweetPollSwitch();
tPollSwitch.setAnswers(questionsAnswers);
tPollSwitch.setTweetPoll(tweetPollDomain);
tPollSwitch.setCodeTweet(questionsAnswers.getUniqueAnserHash());
getTweetPoll().saveOrUpdate(tPollSwitch);
return tPollSwitch;
}
/**
* Create TweetPoll Result
* @param tweetPollSwitch {@link TweetPollResult}
* @param Ip ip address
* @return {@link TweetPollResult}.
*/
public TweetPollResult createTweetPollResult(final TweetPollSwitch tweetPollSwitch, final String Ip){
final TweetPollResult tweetPollResult = new TweetPollResult();
tweetPollResult.setIpVote(Ip);
tweetPollResult.setTweetPollSwitch(tweetPollSwitch);
tweetPollResult.setTweetResponseDate(new Date());
getTweetPoll().saveOrUpdate(tweetPollResult);
return tweetPollResult;
}
/**
* Create tweetpoll result data with polling date.
* @param tweetPollSwitch
* @param Ip
* @param pollingDate
* @return
*/
public TweetPollResult createTweetPollResultWithPollingDate(final TweetPollSwitch tweetPollSwitch, final String Ip, final Date pollingDate){
final TweetPollResult tpResults = this.createTweetPollResult(tweetPollSwitch, Ip);
tpResults.setTweetResponseDate(pollingDate);
getTweetPoll().saveOrUpdate(tpResults);
return tpResults;
}
/**
* Create Fast TweetPoll Votes.
* @return tweet poll
*/
public TweetPoll createFastTweetPollVotes(){
final UserAccount secondary = createUserAccount("jhon-"+RandomStringUtils.randomAscii(4), createAccount());
final Question question = createQuestion("who I am?", "");
final QuestionAnswer questionsAnswers1 = createQuestionAnswer("yes", question, "12345");
final QuestionAnswer questionsAnswers2 = createQuestionAnswer("no", question, "12346");
final TweetPoll tweetPoll = createPublishedTweetPoll(secondary.getAccount(), question);
final TweetPollSwitch pollSwitch1 = createTweetPollSwitch(questionsAnswers1, tweetPoll);
final TweetPollSwitch pollSwitch2 = createTweetPollSwitch(questionsAnswers2, tweetPoll);
createTweetPollResult(pollSwitch1, "192.168.0.1");
createTweetPollResult(pollSwitch1, "192.168.0.2");
createTweetPollResult(pollSwitch2, "192.168.0.3");
createTweetPollResult(pollSwitch2, "192.168.0.4");
//log.info("tw "+tweetPoll);
return tweetPoll;
}
/**
* Create {@link GeoPointFolder}.
* @param type {@link GeoPointFolderType}.
* @param locationFolderId folder Id
* @param secUsers {@link Account}.
* @param folderName name
* @param locationFolder
* @return {@link GeoPointFolder}.
*/
public GeoPointFolder createGeoPointFolder(
final GeoPointFolderType type,
final Account secUsers,
final String folderName,
final GeoPointFolder locationFolder){
final UserAccount userAcc = createUserAccount("Juan", secUsers);
final GeoPointFolder geoPointFolder = new GeoPointFolder();
geoPointFolder.setFolderType(type);
geoPointFolder.setFolderName(folderName);
geoPointFolder.setUsers(secUsers);
geoPointFolder.setSubLocationFolder(locationFolder);
geoPointFolder.setCreatedAt(Calendar.getInstance().getTime());
geoPointFolder.setCreatedBy(userAcc);
getGeoPointDao().saveOrUpdate(geoPointFolder);
return geoPointFolder;
}
/**
* Helper Create Survey Section.
* @param catState
* @param descSection
* @return
*/
public SurveySection createSurveySection(
final String descSection){
final SurveySection surveySection = new SurveySection();
surveySection.setDescSection(descSection);
/* surveySection.getQuestionSection().add(createDefaultQuestion("Why is your favourite movie"));
surveySection.getQuestionSection().add(createDefaultQuestion("Where do you live"));
surveySection.getQuestionSection().add(createDefaultQuestion("What do you do at home"));*/
getSurveyDaoImp().saveOrUpdate(surveySection);
return surveySection;
}
public SurveySection createDefaultSection(final String name, final Survey survey){
final SurveySection surveySection = new SurveySection();
surveySection.setDescSection(name);
surveySection.setSurvey(survey);
getSurveyDaoImp().saveOrUpdate(surveySection);
return surveySection;
}
/**
* Create Defaul Survey Pagination.
* @param surveySection
* @return
*/
public SurveyPagination createDefaultSurveyPagination(final SurveySection surveySection){
return this.createSurveyPagination(1, surveySection,this.createDefaultSurvey(this.createAccount()));
}
/**
* Create Survey Pagination.
* @param pageNumber
* @param surveySection
* @return
*/
public SurveyPagination createSurveyPagination(
final Integer pageNumber,
final SurveySection surveySection,
final Survey survey){
final SurveyPagination surveyPag = new SurveyPagination();
surveyPag.setPageNumber(pageNumber);
surveyPag.setSurveySection(surveySection);
surveyPag.setSurvey(survey);
return surveyPag;
}
/**
* Create Default Survey.
* @param secUsers
* @return
*/
public Survey createDefaultSurvey(final Account secUsers ){
return this.createSurvey("", new Date(), new Date(), secUsers,
new Date(), createDefaultSurveyFormat(), "FirstSurvey", new Date());
}
/**
*
* @param secUsers
* @param createdAt
* @return
*/
public Survey createDefaultSurvey(final Account secUsers, final String surveyName, final Date createdAt){
return this.createSurvey("", new Date(), new Date(), secUsers,
new Date(), createDefaultSurveyFormat(), surveyName, createdAt);
}
/**
* Create {@link Survey}
* @param complete
* @param dateInterview
* @param endDate
* @param secUsers
* @param startDate
* @param surveyFormat
* @return
*/
public Survey createSurvey(
final String complete,
final Date dateInterview,
final Date endDate,
final Account secUsers,
final Date startDate,
final SurveyFormat surveyFormat,
final String name,
final Date createdAt
){
final Survey survey = new Survey();
survey.setName(name);
survey.setComplete(complete);
survey.setDateInterview(dateInterview);
survey.setEndDate(endDate);
survey.setOwner(secUsers);
survey.setStartDate(startDate);
survey.setTicket(3);
survey.setCreatedAt(createdAt);
getSurveyDaoImp().saveOrUpdate(survey);
return survey;
}
/**
* Create Default List Email.
* @param user
* @param list
* @return
*/
public EmailList createDefaultListEmail(final Account user,final String list){
return this.createListEmails(user, list, new Date());
}
/**
* Create Default List Email.
* @return
*/
public EmailList createDefaultListEmail(){
return this.createListEmails(createAccount(), "default", new Date());
}
/**
* Create Default Email List.
* @param list list Name
* @return
*/
public EmailList createDefaultListEmail(final String list){
return this.createListEmails(createAccount(), list, new Date());
}
/**
*Create Default Email List.
* @param user
* @return
*/
public EmailList createDefaultListEmail(final Account user){
return this.createListEmails(user, "default", new Date());
}
/**
* Create Email List.
* @return
*/
public EmailList createListEmails(
final Account users,
final String listName,
final Date createDate){
final EmailList catListEmails = new EmailList();
catListEmails.setCreatedAt(createDate);
catListEmails.setListName(listName);
catListEmails.setUsuarioEmail(users);
getCatEmailDao().saveOrUpdate(catListEmails);
return catListEmails;
}
/**
* Create Default Emails.
* @param email
* @return
*/
public Email createDefaultEmails(final String email){
return this.createEmails(email, createDefaultListEmail());
}
/**
* Create Default Emails.
* @param email
* @param listEmail
* @return
*/
public Email createDefaultEmails(final String email, final EmailList listEmail){
return this.createEmails(email, listEmail);
}
/**
* Create Emails.
* @param email
* @param list
* @return
*/
public Email createEmails(
final String email,
final EmailList list){
final Email emails = new Email();
emails.setEmail(email);
emails.setIdListEmail(list);
getCatEmailDao().saveOrUpdate(emails);
return emails;
}
/**
* Create {@link SocialAccount}.
* @param consumerKey
* @param consumerSecret
* @param secretToken
* @param userAccount
* @param socialProfileUsername
* @return
*/
public SocialAccount createSocialAccount(
final String token,
final String secretToken,
final UserAccount userAccount,
final String socialProfileUsername,
final Boolean verified,
final SocialProvider provider) {
final SocialAccount socialAccount = new SocialAccount();
socialAccount.setAccessToken(token);
socialAccount.setSecretToken(secretToken);
socialAccount.setAccount(userAccount.getAccount());
socialAccount.setUserOwner(userAccount);
long randomNum = 100 + (int)(Math.random()* 4000);
socialAccount.setSocialProfileId(String.valueOf(randomNum)+RandomStringUtils.randomAlphanumeric(10));
socialAccount.setVerfied(verified);
socialAccount.setUserOwner(userAccount);
socialAccount.setAccounType(provider);
socialAccount.setSocialAccountName(socialProfileUsername+RandomStringUtils.randomAlphanumeric(10));
socialAccount.setUpgradedCredentials(new Date());
socialAccount.setAddedAccount(new Date());
socialAccount.setEmail("email"+String.valueOf(randomNum));
socialAccount.setProfileUrl("url"+String.valueOf(randomNum));
socialAccount.setRealName("real name"+String.valueOf(randomNum));
socialAccount.setApplicationKey(RandomUtils.nextLong(new Random(50)));
socialAccount.setRefreshToken("refresh_token_"+RandomStringUtils.randomAlphanumeric(10));
socialAccount.setType(org.encuestame.utils.social.TypeAuth.OAUTH1);
getAccountDao().saveOrUpdate(socialAccount);
return socialAccount;
}
/**
* Create Default Setted User.
* @param account {@link Account}.
* @return {@link SocialAccount}.
*/
public SocialAccount createDefaultSettedSocialAccount(final UserAccount account){
return this.createSocialAccount(
getProperty("twitter.test.token"),
getProperty("twitter.test.tokenSecret"),
account,
getProperty("twitter.test.account"), Boolean.TRUE, SocialProvider.TWITTER);
}
/**
* Create {@link SocialAccount} with {@link SocialProvider}.
* @param account {@link Account}
* @param provider {@link SocialProvider}
* @return {@link SocialAccount}.
*/
public SocialAccount createSocialProviderAccount(final UserAccount account, final SocialProvider provider){
return this.createSocialAccount(
getProperty("twitter.test.token"),
getProperty("twitter.test.tokenSecret"),
account,
getProperty("twitter.test.account"), Boolean.TRUE, provider);
}
/**
* Create Default Setted Verified Twitter Account.
* @param account
* @return
*/
public SocialAccount createDefaultSettedVerifiedSocialAccount(final UserAccount account){
return this.createSocialAccount(
getProperty("twitter.test.token"),
getProperty("twitter.test.tokenSecret"),
account,
getProperty("twitter.test.account"),
Boolean.TRUE, SocialProvider.TWITTER);
}
/**
*
* @param folderName
* @param users
* @return
*/
public SurveyFolder createSurveyFolders(final String folderName, final UserAccount users){
final SurveyFolder surveyFolders = new SurveyFolder();
surveyFolders.setCreatedAt(new Date());
surveyFolders.setFolderName(folderName);
surveyFolders.setUsers(users.getAccount());
surveyFolders.setStatus(Status.ACTIVE);
surveyFolders.setCreatedBy(users);
getSurveyDaoImp().saveOrUpdate(surveyFolders);
return surveyFolders;
}
/**
* Create {@link PollFolder}.
* @param folderName folder name
* @param users {@link Account}
* @return {@link PollFolder}.
*/
public PollFolder createPollFolder(final String folderName, final UserAccount users){
final PollFolder folder = new PollFolder();
folder.setCreatedAt(new Date());
folder.setFolderName(folderName);
folder.setUsers(users.getAccount());
folder.setStatus(Status.ACTIVE);
folder.setCreatedBy(users);
getPollDao().saveOrUpdate(folder);
return folder;
}
/**
* Create TweetPoll Folder.
* @param folderName
* @param users
* @return
*/
public TweetPollFolder createTweetPollFolder(final String folderName, final UserAccount users){
final TweetPollFolder folder = new TweetPollFolder();
folder.setCreatedAt(new Date());
folder.setFolderName(folderName);
folder.setStatus(Status.ACTIVE);
folder.setCreatedBy(users);
folder.setUsers(users.getAccount());
getTweetPoll().saveOrUpdate(folder);
return folder;
}
/**
* Add TweetPoll to Folder.
* @param folderId
* @param username
* @param tweetPollId
* @return
* @throws EnMeNoResultsFoundException
*/
public TweetPoll addTweetPollToFolder(final Long folderId, final Long userId, final Long tweetPollId) throws EnMeNoResultsFoundException{
final TweetPollFolder tpfolder = getTweetPoll().getTweetPollFolderById(folderId);
final TweetPoll tpoll = getTweetPoll().getTweetPollByIdandUserId(tweetPollId, userId);
tpoll.setTweetPollFolder(tpfolder);
getTweetPoll().saveOrUpdate(tpoll);
return tpoll;
}
/**
* Add Survey To Folder.
* @param folderId
* @param userId
* @param surveyId
* @return
* @throws EnMeNoResultsFoundException
*/
public Survey addSurveyToFolder(final Long folderId, final Long userId, final Long surveyId) throws EnMeNoResultsFoundException{
final SurveyFolder sfolder = getSurveyDaoImp().getSurveyFolderById(folderId);
final Survey survey = getSurveyDaoImp().getSurveyByIdandUserId(surveyId, userId);
survey.setSurveysfolder(sfolder);
getSurveyDaoImp().saveOrUpdate(survey);
return survey;
}
/**
* Add Poll to Folder.
* @param folderId
* @param userId
* @param pollId
* @return
* @throws EnMeNoResultsFoundException
*/
public Poll addPollToFolder(final Long folderId, final UserAccount userAccount, final Long pollId) throws EnMeNoResultsFoundException{
final PollFolder pfolder = getPollDao().getPollFolderById(folderId);
final Poll poll = getPollDao().getPollById(pollId, userAccount);
poll.setPollFolder(pfolder);
getPollDao().saveOrUpdate(poll);
return poll;
}
/**
* @return the activateNotifications
*/
public Boolean getActivateNotifications() {
return activateNotifications;
}
/**
* @param activateNotifications uthe activateNotifications to set
*/
public void setActivateNotifications(Boolean activateNotifications) {
this.activateNotifications = activateNotifications;
}
/**
* @return the clientDao
*/
public IClientDao getClientDao() {
return clientDao;
}
/**
* @param clientDao the clientDao to set
*/
public void setClientDao(final IClientDao clientDao) {
this.clientDao = clientDao;
}
/**
* @return the iTweetPoll
*/
public ITweetPoll getTweetPoll() {
return iTweetPoll;
}
/**
* @param iTweetPoll the iTweetPoll to set
*/
public void setTweetPoll(final ITweetPoll iTweetPoll) {
this.iTweetPoll = iTweetPoll;
}
/**
* @return the hibernateTemplate
*/
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
/**
* @param hibernateTemplate the hibernateTemplate to set
*/
public void setHibernateTemplate(final HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
/**
* Create Notification.
* @param message message
* @param secUser {@link Account}.
* @param description {@link NotificationEnum}.
*/
public Notification createNotification(
final String message,
final Account secUser,
final NotificationEnum description,
final Boolean readed){
final Notification notification = new Notification();
notification.setAdditionalDescription(message);
notification.setCreated(Calendar.getInstance().getTime());
notification.setDescription(description);
notification.setReaded(readed);
notification.setAccount(secUser);
notification.setUrlReference("http://google.es");
notification.setGroup(true);
getNotification().saveOrUpdate(notification);
return notification;
}
/**
* Create Hash Tag.
* @param hashTagName
* @return
*/
public HashTag createHashTag(final String hashTagName){
final HashTag hashTag = new HashTag();
hashTag.setHashTag(hashTagName.toLowerCase());
hashTag.setHits(0L);
hashTag.setUpdatedDate(new Date());
hashTag.setSize(0L);
getHashTagDao().saveOrUpdate(hashTag);
return hashTag;
}
/**
* Create hashtag with hits.
* @param hashTagName name
* @param hits total hits.
* @return {@link HashTag}
*/
public HashTag createHashTag(final String hashTagName, final Long hits){
final HashTag hastag = this.createHashTag(hashTagName);
hastag.setHits(hits);
getHashTagDao().saveOrUpdate(hastag);
return hastag;
}
/**
*
* @param hashTagName
* @param hits
* @return
*/
public HashTag createHashTag(final String hashTagName, final Long hits, final Long size){
final HashTag hastag = this.createHashTag(hashTagName);
hastag.setHits(hits);
hastag.setSize(size);
hastag.setUpdatedDate(new Date());
getHashTagDao().saveOrUpdate(hastag);
return hastag;
}
/**
* Helper.
* Create hashTag ranking.
* @param tag
* @param rankingDate
* @param average
* @return
*/
public HashTagRanking createHashTagRank(final HashTag tag, final Date rankingDate, final Double average){
final HashTagRanking tagRank = new HashTagRanking();
tagRank.setHashTag(tag);
tagRank.setAverage(average);
tagRank.setRankingDate(rankingDate);
getHashTagDao().saveOrUpdate(tagRank);
return tagRank;
}
/**
* @return the notification
*/
public INotification getNotification() {
return notificationDao;
}
/**
* @param notification the notification to set
*/
public void setNotification(final INotification notification) {
this.notificationDao = notification;
}
/**
* @return the hashTagDao
*/
public IHashTagDao getHashTagDao() {
return hashTagDao;
}
/**
* @param hashTagDao the hashTagDao to set
*/
public void setHashTagDao(IHashTagDao hashTagDao) {
this.hashTagDao = hashTagDao;
}
/**
* @return the frontEndDao
*/
public IFrontEndDao getFrontEndDao() {
return frontEndDao;
}
/**
* @param frontEndDao the frontEndDao to set
*/
public void setFrontEndDao(IFrontEndDao frontEndDao) {
this.frontEndDao = frontEndDao;
}
/**
* Create fake questions.
* @param user {@link Account};
*/
public void createFakesQuestions(final Account user){
createQuestion("Do you want soccer?", user);
createQuestion("Do you like apple's?", user);
createQuestion("Do you buy iPods?", user);
createQuestion("Do you like sky iPods Touch?", user);
createQuestion("Ipad VS Ipad2?", user);
createQuestion("How Often Do You Tweet? Survey Says Not That Often", user);
createQuestion("Is survey usseful on Twitter?", user);
createQuestion("Should be happy?", user);
createQuestion("Are you home alone?", user);
}
/**
* Create a list of fakes {@link TweetPoll}.
* @param userAccount
*/
public void createFakesTweetPoll(final UserAccount userAccount){
final Question question = createQuestion("Real Madrid or Barcelona?", userAccount.getAccount());
final Question question1 = createQuestion("Real Madrid or Barcelona?", userAccount.getAccount());
final Question question2 = createQuestion("Real Madrid or Barcelona?", userAccount.getAccount());
final Question question3 = createQuestion("Real Madrid or Barcelona?", userAccount.getAccount());
createTweetPollPublicated(Boolean.TRUE, Boolean.TRUE, new Date(), userAccount, question);
createTweetPollPublicated(Boolean.TRUE, Boolean.TRUE, new Date(), userAccount, question1);
createTweetPollPublicated(Boolean.TRUE, Boolean.TRUE, new Date(), userAccount, question2);
createTweetPollPublicated(Boolean.TRUE, Boolean.TRUE, new Date(), userAccount, question3);
}
/**
* Create {@link TweetPoll} published.
* @param publishTweetPoll
* @param completed
* @param scheduleDate
* @param tweetOwner
* @param question
* @return
*/
public TweetPoll createTweetPollPublicated(
final Boolean publishTweetPoll,
final Boolean completed,
final Date scheduleDate,
final UserAccount tweetOwner,
final Question question){
final TweetPoll tweetPoll = new TweetPoll();
tweetPoll.setPublishTweetPoll(publishTweetPoll);
tweetPoll.setCompleted(completed);
tweetPoll.setScheduleDate(scheduleDate);
tweetPoll.setCreateDate(new Date());
tweetPoll.setFavourites(false);
tweetPoll.setQuestion(question);
tweetPoll.setTweetOwner(tweetOwner.getAccount());
tweetPoll.setEditorOwner(tweetOwner);
getTweetPoll().saveOrUpdate(tweetPoll);
return tweetPoll;
}
/**
* Create TweetPoll social links.
* @param tweetPoll
* @param tweetId
* @param socialAccount
* @param tweetText
* @return
*/
public TweetPollSavedPublishedStatus createTweetPollSavedPublishedStatus(
final TweetPoll tweetPoll, final String tweetId,
final SocialAccount socialAccount, final String tweetText) {
return this.createSocialLinkSavedPublishedStatus(tweetPoll, null, null,
tweetId, socialAccount, tweetText);
}
/**
* Create social network link.
* @param tweetPoll
* @param poll
* @param survey
* @param tweetId
* @param socialAccount
* @param tweetText
* @return
*/
public TweetPollSavedPublishedStatus createSocialLinkSavedPublishedStatus(
final TweetPoll tweetPoll, final Poll poll, final Survey survey, final String tweetId,
final SocialAccount socialAccount, final String tweetText) {
final TweetPollSavedPublishedStatus publishedStatus = new TweetPollSavedPublishedStatus();
publishedStatus.setTweetPoll(tweetPoll);
publishedStatus.setStatus(org.encuestame.utils.enums.Status.SUCCESS);
publishedStatus.setTweetContent(tweetText);
publishedStatus.setSocialAccount(socialAccount);
publishedStatus.setTweetId(RandomStringUtils.randomAlphabetic(18));
publishedStatus.setPublicationDateTweet(new Date());
publishedStatus.setPoll(poll);
publishedStatus.setSurvey(survey);
getTweetPoll().saveOrUpdate(publishedStatus);
return publishedStatus;
}
/**
* Create Poll social links.
* @param poll
* @param tweetId
* @param socialAccount
* @param tweetText
* @return
*/
public TweetPollSavedPublishedStatus createPollSavedPublishedStatus(
final Poll poll, final String tweetId,
final SocialAccount socialAccount, final String tweetText) {
return this.createSocialLinkSavedPublishedStatus(null, poll, null, tweetId, socialAccount, tweetText);
}
/**
* Create hit new.
* @param tweetPoll
* @param poll
* @param survey
* @param ipAddress
* @return
*/
public Hit createHit(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag hashTag,
final String ipAddress){
final Hit hit = new Hit();
hit.setHitDate(Calendar.getInstance().getTime());
hit.setIpAddress(ipAddress);
hit.setPoll(poll);
hit.setSurvey(survey);
hit.setTweetPoll(tweetPoll);
hit.setHashTag(hashTag);
hit.setHitCategory(HitCategory.VISIT);
getFrontEndDao().saveOrUpdate(hit);
return hit;
}
/**
* Create TweetPoll hit.
* @param tweetPoll
* @param ipAddress
* @return
*/
public Hit createTweetPollHit(final TweetPoll tweetPoll, final String ipAddress){
return this.createHit(tweetPoll, null, null, null, ipAddress);
}
/**
* Create Poll hit.
* @param poll
* @param ipAddress
* @return
*/
public Hit createPollHit(final Poll poll, final String ipAddress){
return this.createHit(null, poll, null, null, ipAddress);
}
/**
* Create survey hit.
* @param survey
* @param ipAddress
* @return
*/
public Hit createSurveyHit(final Survey survey, final String ipAddress){
return this.createHit(null, null, survey, null, ipAddress);
}
/**
* Create HashTag hit.
* @param survey
* @param ipAddress
* @return
*/
public Hit createHashTagHit(final HashTag tag, final String ipAddress){
return this.createHit(null, null, null, tag, ipAddress);
}
/**
* @return the dashboardDao
*/
public IDashboardDao getDashboardDao() {
return dashboardDao;
}
/**
* @param dashboardDao the dashboardDao to set
*/
public void setDashboardDao(final IDashboardDao dashboardDao) {
this.dashboardDao = dashboardDao;
}
/**
* @return the commentsOperationsDao
*/
public CommentsOperations getCommentsOperations() {
return commentsOperations;
}
/**
* @param commentsOperationsDao the commentsOperationsDao to set
*/
public void setCommentsOperations(final CommentsOperations commentsOperations) {
this.commentsOperations = commentsOperations;
}
/**
* Create comment.
* @param comm
* @param likeVote
* @param tpoll
* @param survey
* @param poll
* @return
*/
public Comment createComment(
final String comm,
final Long likeVote,
final TweetPoll tpoll,
final Survey survey,
final Poll poll,
final UserAccount user,
final Long dislikeVote,
final Date createdAt){
final Comment comment = new Comment();
comment.setComment(comm);
comment.setCreatedAt(createdAt);
comment.setLikeVote(likeVote);
comment.setDislikeVote(dislikeVote);
comment.setPoll(poll);
comment.setParentId(null);
comment.setSurvey(survey);
comment.setTweetPoll(tpoll);
comment.setUser(user);
getCommentsOperations().saveOrUpdate(comment);
return comment;
}
/**
* Create default tweetPoll comment.
* @param tpoll
* @return
*/
public Comment createDefaultTweetPollComment(
final String comment,
final TweetPoll tpoll,
final UserAccount userAcc){
return this.createComment(comment, 0L, tpoll, null, null, userAcc, 0L , new Date());
}
/**
*
* @param comment
* @param tpoll
* @param userAcc
* @param likeVote
* @param dislikeVote
* @return
*/
public Comment createDefaultTweetPollCommentVoted(
final String comment,
final TweetPoll tpoll,
final UserAccount userAcc,
final Long likeVote,
final Long dislikeVote,
final Date createdAt){
return this.createComment(comment, likeVote, tpoll, null, null, userAcc, dislikeVote, createdAt);
}
/**
* Create default poll comment.
* @param poll
* @return
*/
public Comment createDefaultPollComment(
final String comment,
final Poll poll,
final UserAccount userAcc){
return this.createComment(comment, 0L, null, null, poll, userAcc, 0L , new Date());
}
/**
* Create default survey comment.
* @param survey
* @return
*/
public Comment createDefaultSurveyComment(
final String comment,
final Survey survey,
final UserAccount userAcc){
return this.createComment(comment, 0L, null, survey, null, userAcc, 0L, new Date());
}
/**
* Create access rate item.
* @param rate
* @param tpoll
* @param survey
* @param poll
* @param user
* @param ipAddress
* @return
*/
public AccessRate createAccessRateItem(final Boolean rate, final TweetPoll tpoll, final Survey survey, final Poll poll,
final UserAccount user, final String ipAddress){
final AccessRate vote = new AccessRate();
vote.setRate(rate);
vote.setTweetPoll(tpoll);
vote.setPoll(poll);
vote.setSurvey(survey);
vote.setUser(user);
vote.setIpAddress(ipAddress);
vote.setUpdatedDate(Calendar.getInstance().getTime());
getTweetPoll().saveOrUpdate(vote);
return vote;
}
/**
* Create tweetpoll access rate.
* @param rate
* @param tweetPoll
* @param ipAddress
* @return
*/
public AccessRate createTweetPollRate(final Boolean rate, final TweetPoll tweetPoll, final String ipAddress){
return this.createAccessRateItem(rate, tweetPoll, null, null, null, ipAddress);
}
/**
* Create poll access rate.
* @param rate
* @param tweetPoll
* @param ipAddress
* @return
*/
public AccessRate createPollRate(final Boolean rate, final Poll poll, final String ipAddress){
return this.createAccessRateItem(rate, null, null, poll, null, ipAddress);
}
/**
* Create survey rate.
* @param rate
* @param survey
* @param ipAddress
* @return
*/
public AccessRate createSurveyRate(final Boolean rate, final Survey survey, final String ipAddress){
return this.createAccessRateItem(rate, null, survey, null, null, ipAddress);
}
}
| Helpers methods for question preferences. ENCUESTAME-496
| encuestame-persistence/src/test/java/org/encuestame/test/config/AbstractBase.java | Helpers methods for question preferences. ENCUESTAME-496 |
|
Java | apache-2.0 | f630373186f754c4d44b8bd27d86b2f5f4ceda55 | 0 | obidea/semantika | /*
* Copyright (c) 2013-2014 Josef Hardi <[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 com.obidea.semantika.mapping.parser;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import com.obidea.semantika.database.IDatabaseMetadata;
import com.obidea.semantika.expression.base.ITerm;
import com.obidea.semantika.mapping.IMetaModel;
import com.obidea.semantika.mapping.base.IMapping;
import com.obidea.semantika.mapping.base.sql.SqlQuery;
import com.obidea.semantika.ontology.IOntology;
public abstract class AbstractMappingHandler
{
private String mBaseIri;
private IOntology mOntology;
private IDatabaseMetadata mDatabaseMetadata;
private SqlQuery mSqlQuery;
private URI mSubjectUri;
private URI mPredicateUri;
private ITerm mSubjectMapValue;
private ITerm mPredicateMapValue;
private ITerm mObjectMapValue;
private List<IMapping> mMappings = new ArrayList<IMapping>();
public AbstractMappingHandler(IMetaModel metaModel)
{
mOntology = metaModel.getOntology();
mDatabaseMetadata = metaModel.getDatabaseMetadata();
}
public void setBaseIri(String baseIri)
{
mBaseIri = baseIri;
}
public String getBaseIri()
{
return mBaseIri;
}
public IOntology getOntology()
{
return mOntology;
}
public IDatabaseMetadata getDatabaseMetadata()
{
return mDatabaseMetadata;
}
protected void addMapping(IMapping mapping)
{
mMappings.add(mapping);
}
public List<IMapping> getMappings()
{
return mMappings;
}
protected void setSqlQuery(SqlQuery sqlQuery)
{
mSqlQuery = sqlQuery;
}
public SqlQuery getSqlQuery()
{
return mSqlQuery;
}
protected void setSubjectUri(URI classUri)
{
mSubjectUri = classUri;
}
public URI getSubjectUri()
{
return mSubjectUri;
}
protected void setPredicateUri(URI propertyUri)
{
mPredicateUri = propertyUri;
}
public URI getPredicateUri()
{
return mPredicateUri;
}
protected void setSubjectMapValue(ITerm subjectTerm)
{
mSubjectMapValue = subjectTerm;
}
public ITerm getSubjectMapValue()
{
return mSubjectMapValue;
}
protected void setPredicateMapValue(ITerm predicateTerm)
{
mPredicateMapValue = predicateTerm;
}
public ITerm getPredicateMapValue()
{
return mPredicateMapValue;
}
protected void setObjectMapValue(ITerm objectTerm)
{
mObjectMapValue = objectTerm;
}
public ITerm getObjectMapValue()
{
return mObjectMapValue;
}
}
| src/com/obidea/semantika/mapping/parser/AbstractMappingHandler.java | /*
* Copyright (c) 2013-2014 Josef Hardi <[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 com.obidea.semantika.mapping.parser;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import com.obidea.semantika.database.IDatabaseMetadata;
import com.obidea.semantika.expression.base.ITerm;
import com.obidea.semantika.mapping.IMetaModel;
import com.obidea.semantika.mapping.base.IMapping;
import com.obidea.semantika.mapping.base.sql.SqlQuery;
import com.obidea.semantika.ontology.IOntology;
public abstract class AbstractMappingHandler
{
private String mBaseIri;
private IOntology mOntology;
private IDatabaseMetadata mDatabaseMetadata;
private SqlQuery mSqlQuery;
private URI mSubjectUri;
private URI mPredicateUri;
private ITerm mSubjectMapValue;
private ITerm mPredicateMapValue;
private ITerm mObjectMapValue;
private List<IMapping> mMappings = new ArrayList<IMapping>();
public AbstractMappingHandler(IMetaModel metaModel)
{
mOntology = metaModel.getOntology();
mDatabaseMetadata = metaModel.getDatabaseMetadata();
}
public IOntology getOntology()
{
return mOntology;
}
public IDatabaseMetadata getDatabaseMetadata()
{
return mDatabaseMetadata;
}
public void addMapping(IMapping mapping)
{
mMappings.add(mapping);
}
public List<IMapping> getMappings()
{
return mMappings;
}
public void setBaseIri(String baseIri)
{
mBaseIri = baseIri;
}
public String getBaseIri()
{
return mBaseIri;
}
public void setSqlQuery(SqlQuery sqlQuery)
{
mSqlQuery = sqlQuery;
}
public SqlQuery getSqlQuery()
{
return mSqlQuery;
}
public void setSubjectUri(URI classUri)
{
mSubjectUri = classUri;
}
public URI getSubjectUri()
{
return mSubjectUri;
}
public void setPredicateUri(URI propertyUri)
{
mPredicateUri = propertyUri;
}
public URI getPredicateUri()
{
return mPredicateUri;
}
public void setSubjectMapValue(ITerm subjectTerm)
{
mSubjectMapValue = subjectTerm;
}
public ITerm getSubjectMapValue()
{
return mSubjectMapValue;
}
public void setPredicateMapValue(ITerm predicateTerm)
{
mPredicateMapValue = predicateTerm;
}
public ITerm getPredicateMapValue()
{
return mPredicateMapValue;
}
public void setObjectMapValue(ITerm objectTerm)
{
mObjectMapValue = objectTerm;
}
public ITerm getObjectMapValue()
{
return mObjectMapValue;
}
}
| Code logic tidy. | src/com/obidea/semantika/mapping/parser/AbstractMappingHandler.java | Code logic tidy. |
|
Java | apache-2.0 | 13d8eecc76615c98838c3e25276b69c1abca2190 | 0 | rrutt/Alternator,mboudreau/Alternator,jentfoo/Alternator,rrutt/Alternator,mboudreau/Alternator,jentfoo/Alternator | package com.michelboudreau.alternator;
import java.io.File;
public class AlternatorDBServer {
/**
* Allow the database to be persisted to disk when the server shuts down.
*/
private static final boolean sandboxStatusSaveToDisk = false;
/**
* Discard the database contents when the server shuts down.
*/
private static final boolean sandboxStatusDiscardData = true;
private static final int defaultPort = 9090;
public static void main(final String[] args) throws Exception {
File persistenceFile = null;
int port = defaultPort;
if (args.length >= 1) {
String persistencePath = args[0];
persistenceFile = new File(persistencePath);
}
AlternatorDB db = new AlternatorDB(port, persistenceFile, sandboxStatusSaveToDisk);
db.start();
if (persistenceFile != null) {
System.out.println(
String.format("+++++ AlternatorDB loaded data from file: %s", persistenceFile.getCanonicalPath()));
}
System.out.println(
String.format("+++++ AlternatorDB has started and is listening on port %d.", port));
if (persistenceFile != null) {
System.out.println(
String.format("Press the Enter key to exit gracefully and save data to file: %s", persistenceFile.getCanonicalPath()));
}
System.out.print("Use Control-C to force exit (without saving data changes): ");
String input = System.console().readLine();
System.out.println("----- AlternatorDB is shutting down...");
db.stop();
if (persistenceFile != null) {
System.out.println(
String.format("----- Data was saved to file: %s", persistenceFile.getCanonicalPath()));
}
}
}
| src/main/java/com/michelboudreau/alternator/AlternatorDBServer.java | package com.michelboudreau.alternator;
public class AlternatorDBServer
{
public static void main(final String[] args) throws Exception
{
int port = 9090;
// TODO: Parse args for alternate port.
AlternatorDB db = new AlternatorDB(port);
db.start();
System.out.println(
String.format("AlternatorDB has started and is listening on port %d.", port));
}
}
| Support a persistence file in executable JAR console operation.
| src/main/java/com/michelboudreau/alternator/AlternatorDBServer.java | Support a persistence file in executable JAR console operation. |
|
Java | apache-2.0 | 46be6a08e9d1b4b989f74f800b71a1221321ab6e | 0 | aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7.internal.widget;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v7.appcompat.R;
import android.support.v7.internal.view.ViewPropertyAnimatorCompatSet;
import android.support.v7.widget.ActionMenuPresenter;
import android.support.v7.widget.ActionMenuView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
abstract class AbsActionBarView extends ViewGroup {
private static final Interpolator sAlphaInterpolator = new DecelerateInterpolator();
private static final int FADE_DURATION = 200;
protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener();
/** Context against which to inflate popup menus. */
protected final Context mPopupContext;
protected ActionMenuView mMenuView;
protected ActionMenuPresenter mActionMenuPresenter;
protected ViewGroup mSplitView;
protected boolean mSplitActionBar;
protected boolean mSplitWhenNarrow;
protected int mContentHeight;
protected ViewPropertyAnimatorCompat mVisibilityAnim;
private boolean mEatingTouch;
private boolean mEatingHover;
AbsActionBarView(Context context) {
this(context, null);
}
AbsActionBarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
AbsActionBarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final TypedValue tv = new TypedValue();
if (context.getTheme().resolveAttribute(R.attr.actionBarPopupTheme, tv, true)
&& tv.resourceId != 0) {
mPopupContext = new ContextThemeWrapper(context, tv.resourceId);
} else {
mPopupContext = context;
}
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= 8) {
super.onConfigurationChanged(newConfig);
}
// Action bar can change size on configuration changes.
// Reread the desired height from the theme-specified style.
TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.ActionBar,
R.attr.actionBarStyle, 0);
setContentHeight(a.getLayoutDimension(R.styleable.ActionBar_height, 0));
a.recycle();
if (mActionMenuPresenter != null) {
mActionMenuPresenter.onConfigurationChanged(newConfig);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// ActionBarViews always eat touch events, but should still respect the touch event dispatch
// contract. If the normal View implementation doesn't want the events, we'll just silently
// eat the rest of the gesture without reporting the events to the default implementation
// since that's what it expects.
final int action = MotionEventCompat.getActionMasked(ev);
if (action == MotionEvent.ACTION_DOWN) {
mEatingTouch = false;
}
if (!mEatingTouch) {
final boolean handled = super.onTouchEvent(ev);
if (action == MotionEvent.ACTION_DOWN && !handled) {
mEatingTouch = true;
}
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
mEatingTouch = false;
}
return true;
}
@Override
public boolean onHoverEvent(MotionEvent ev) {
// Same deal as onTouchEvent() above. Eat all hover events, but still
// respect the touch event dispatch contract.
final int action = MotionEventCompat.getActionMasked(ev);
if (action == MotionEventCompat.ACTION_HOVER_ENTER) {
mEatingHover = false;
}
if (!mEatingHover) {
final boolean handled = super.onHoverEvent(ev);
if (action == MotionEventCompat.ACTION_HOVER_ENTER && !handled) {
mEatingHover = true;
}
}
if (action == MotionEventCompat.ACTION_HOVER_EXIT
|| action == MotionEvent.ACTION_CANCEL) {
mEatingHover = false;
}
return true;
}
/**
* Sets whether the bar should be split right now, no questions asked.
* @param split true if the bar should split
*/
public void setSplitToolbar(boolean split) {
mSplitActionBar = split;
}
/**
* Sets whether the bar should split if we enter a narrow screen configuration.
* @param splitWhenNarrow true if the bar should check to split after a config change
*/
public void setSplitWhenNarrow(boolean splitWhenNarrow) {
mSplitWhenNarrow = splitWhenNarrow;
}
public void setContentHeight(int height) {
mContentHeight = height;
requestLayout();
}
public int getContentHeight() {
return mContentHeight;
}
public void setSplitView(ViewGroup splitView) {
mSplitView = splitView;
}
/**
* @return Current visibility or if animating, the visibility being animated to.
*/
public int getAnimatedVisibility() {
if (mVisibilityAnim != null) {
return mVisAnimListener.mFinalVisibility;
}
return getVisibility();
}
public void animateToVisibility(int visibility) {
if (mVisibilityAnim != null) {
mVisibilityAnim.cancel();
}
if (visibility == VISIBLE) {
if (getVisibility() != VISIBLE) {
ViewCompat.setAlpha(this, 0f);
if (mSplitView != null && mMenuView != null) {
ViewCompat.setAlpha(mMenuView, 0f);
}
}
ViewPropertyAnimatorCompat anim = ViewCompat.animate(this).alpha(1f);
anim.setDuration(FADE_DURATION);
anim.setInterpolator(sAlphaInterpolator);
if (mSplitView != null && mMenuView != null) {
ViewPropertyAnimatorCompatSet set = new ViewPropertyAnimatorCompatSet();
ViewPropertyAnimatorCompat splitAnim = ViewCompat.animate(mMenuView).alpha(1f);
splitAnim.setDuration(FADE_DURATION);
set.setListener(mVisAnimListener.withFinalVisibility(anim, visibility));
set.play(anim).play(splitAnim);
set.start();
} else {
anim.setListener(mVisAnimListener.withFinalVisibility(anim, visibility));
anim.start();
}
} else {
ViewPropertyAnimatorCompat anim = ViewCompat.animate(this).alpha(0f);
anim.setDuration(FADE_DURATION);
anim.setInterpolator(sAlphaInterpolator);
if (mSplitView != null && mMenuView != null) {
ViewPropertyAnimatorCompatSet set = new ViewPropertyAnimatorCompatSet();
ViewPropertyAnimatorCompat splitAnim = ViewCompat.animate(mMenuView).alpha(0f);
splitAnim.setDuration(FADE_DURATION);
set.setListener(mVisAnimListener.withFinalVisibility(anim, visibility));
set.play(anim).play(splitAnim);
set.start();
} else {
anim.setListener(mVisAnimListener.withFinalVisibility(anim, visibility));
anim.start();
}
}
}
public boolean showOverflowMenu() {
if (mActionMenuPresenter != null) {
return mActionMenuPresenter.showOverflowMenu();
}
return false;
}
public void postShowOverflowMenu() {
post(new Runnable() {
public void run() {
showOverflowMenu();
}
});
}
public boolean hideOverflowMenu() {
if (mActionMenuPresenter != null) {
return mActionMenuPresenter.hideOverflowMenu();
}
return false;
}
public boolean isOverflowMenuShowing() {
if (mActionMenuPresenter != null) {
return mActionMenuPresenter.isOverflowMenuShowing();
}
return false;
}
public boolean isOverflowMenuShowPending() {
if (mActionMenuPresenter != null) {
return mActionMenuPresenter.isOverflowMenuShowPending();
}
return false;
}
public boolean isOverflowReserved() {
return mActionMenuPresenter != null && mActionMenuPresenter.isOverflowReserved();
}
public boolean canShowOverflowMenu() {
return isOverflowReserved() && getVisibility() == VISIBLE;
}
public void dismissPopupMenus() {
if (mActionMenuPresenter != null) {
mActionMenuPresenter.dismissPopupMenus();
}
}
protected int measureChildView(View child, int availableWidth, int childSpecHeight,
int spacing) {
child.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST),
childSpecHeight);
availableWidth -= child.getMeasuredWidth();
availableWidth -= spacing;
return Math.max(0, availableWidth);
}
static protected int next(int x, int val, boolean isRtl) {
return isRtl ? x - val : x + val;
}
protected int positionChild(View child, int x, int y, int contentHeight, boolean reverse) {
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
int childTop = y + (contentHeight - childHeight) / 2;
if (reverse) {
child.layout(x - childWidth, childTop, x, childTop + childHeight);
} else {
child.layout(x, childTop, x + childWidth, childTop + childHeight);
}
return (reverse ? -childWidth : childWidth);
}
protected class VisibilityAnimListener implements ViewPropertyAnimatorListener {
private boolean mCanceled = false;
int mFinalVisibility;
public VisibilityAnimListener withFinalVisibility(ViewPropertyAnimatorCompat animation,
int visibility) {
mVisibilityAnim = animation;
mFinalVisibility = visibility;
return this;
}
@Override
public void onAnimationStart(View view) {
setVisibility(VISIBLE);
mCanceled = false;
}
@Override
public void onAnimationEnd(View view) {
if (mCanceled) return;
mVisibilityAnim = null;
setVisibility(mFinalVisibility);
if (mSplitView != null && mMenuView != null) {
mMenuView.setVisibility(mFinalVisibility);
}
}
@Override
public void onAnimationCancel(View view) {
mCanceled = true;
}
}
}
| v7/appcompat/src/android/support/v7/internal/widget/AbsActionBarView.java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7.internal.widget;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v7.appcompat.R;
import android.support.v7.internal.view.ViewPropertyAnimatorCompatSet;
import android.support.v7.widget.ActionMenuPresenter;
import android.support.v7.widget.ActionMenuView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
abstract class AbsActionBarView extends ViewGroup {
private static final Interpolator sAlphaInterpolator = new DecelerateInterpolator();
private static final int FADE_DURATION = 200;
protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener();
/** Context against which to inflate popup menus. */
protected final Context mPopupContext;
protected ActionMenuView mMenuView;
protected ActionMenuPresenter mActionMenuPresenter;
protected ViewGroup mSplitView;
protected boolean mSplitActionBar;
protected boolean mSplitWhenNarrow;
protected int mContentHeight;
protected ViewPropertyAnimatorCompat mVisibilityAnim;
AbsActionBarView(Context context) {
this(context, null);
}
AbsActionBarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
AbsActionBarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final TypedValue tv = new TypedValue();
if (context.getTheme().resolveAttribute(R.attr.actionBarPopupTheme, tv, true)
&& tv.resourceId != 0) {
mPopupContext = new ContextThemeWrapper(context, tv.resourceId);
} else {
mPopupContext = context;
}
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= 8) {
super.onConfigurationChanged(newConfig);
}
// Action bar can change size on configuration changes.
// Reread the desired height from the theme-specified style.
TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.ActionBar,
R.attr.actionBarStyle, 0);
setContentHeight(a.getLayoutDimension(R.styleable.ActionBar_height, 0));
a.recycle();
if (mActionMenuPresenter != null) {
mActionMenuPresenter.onConfigurationChanged(newConfig);
}
}
/**
* Sets whether the bar should be split right now, no questions asked.
* @param split true if the bar should split
*/
public void setSplitToolbar(boolean split) {
mSplitActionBar = split;
}
/**
* Sets whether the bar should split if we enter a narrow screen configuration.
* @param splitWhenNarrow true if the bar should check to split after a config change
*/
public void setSplitWhenNarrow(boolean splitWhenNarrow) {
mSplitWhenNarrow = splitWhenNarrow;
}
public void setContentHeight(int height) {
mContentHeight = height;
requestLayout();
}
public int getContentHeight() {
return mContentHeight;
}
public void setSplitView(ViewGroup splitView) {
mSplitView = splitView;
}
/**
* @return Current visibility or if animating, the visibility being animated to.
*/
public int getAnimatedVisibility() {
if (mVisibilityAnim != null) {
return mVisAnimListener.mFinalVisibility;
}
return getVisibility();
}
public void animateToVisibility(int visibility) {
if (mVisibilityAnim != null) {
mVisibilityAnim.cancel();
}
if (visibility == VISIBLE) {
if (getVisibility() != VISIBLE) {
ViewCompat.setAlpha(this, 0f);
if (mSplitView != null && mMenuView != null) {
ViewCompat.setAlpha(mMenuView, 0f);
}
}
ViewPropertyAnimatorCompat anim = ViewCompat.animate(this).alpha(1f);
anim.setDuration(FADE_DURATION);
anim.setInterpolator(sAlphaInterpolator);
if (mSplitView != null && mMenuView != null) {
ViewPropertyAnimatorCompatSet set = new ViewPropertyAnimatorCompatSet();
ViewPropertyAnimatorCompat splitAnim = ViewCompat.animate(mMenuView).alpha(1f);
splitAnim.setDuration(FADE_DURATION);
set.setListener(mVisAnimListener.withFinalVisibility(anim, visibility));
set.play(anim).play(splitAnim);
set.start();
} else {
anim.setListener(mVisAnimListener.withFinalVisibility(anim, visibility));
anim.start();
}
} else {
ViewPropertyAnimatorCompat anim = ViewCompat.animate(this).alpha(0f);
anim.setDuration(FADE_DURATION);
anim.setInterpolator(sAlphaInterpolator);
if (mSplitView != null && mMenuView != null) {
ViewPropertyAnimatorCompatSet set = new ViewPropertyAnimatorCompatSet();
ViewPropertyAnimatorCompat splitAnim = ViewCompat.animate(mMenuView).alpha(0f);
splitAnim.setDuration(FADE_DURATION);
set.setListener(mVisAnimListener.withFinalVisibility(anim, visibility));
set.play(anim).play(splitAnim);
set.start();
} else {
anim.setListener(mVisAnimListener.withFinalVisibility(anim, visibility));
anim.start();
}
}
}
public boolean showOverflowMenu() {
if (mActionMenuPresenter != null) {
return mActionMenuPresenter.showOverflowMenu();
}
return false;
}
public void postShowOverflowMenu() {
post(new Runnable() {
public void run() {
showOverflowMenu();
}
});
}
public boolean hideOverflowMenu() {
if (mActionMenuPresenter != null) {
return mActionMenuPresenter.hideOverflowMenu();
}
return false;
}
public boolean isOverflowMenuShowing() {
if (mActionMenuPresenter != null) {
return mActionMenuPresenter.isOverflowMenuShowing();
}
return false;
}
public boolean isOverflowMenuShowPending() {
if (mActionMenuPresenter != null) {
return mActionMenuPresenter.isOverflowMenuShowPending();
}
return false;
}
public boolean isOverflowReserved() {
return mActionMenuPresenter != null && mActionMenuPresenter.isOverflowReserved();
}
public boolean canShowOverflowMenu() {
return isOverflowReserved() && getVisibility() == VISIBLE;
}
public void dismissPopupMenus() {
if (mActionMenuPresenter != null) {
mActionMenuPresenter.dismissPopupMenus();
}
}
protected int measureChildView(View child, int availableWidth, int childSpecHeight,
int spacing) {
child.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST),
childSpecHeight);
availableWidth -= child.getMeasuredWidth();
availableWidth -= spacing;
return Math.max(0, availableWidth);
}
static protected int next(int x, int val, boolean isRtl) {
return isRtl ? x - val : x + val;
}
protected int positionChild(View child, int x, int y, int contentHeight, boolean reverse) {
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
int childTop = y + (contentHeight - childHeight) / 2;
if (reverse) {
child.layout(x - childWidth, childTop, x, childTop + childHeight);
} else {
child.layout(x, childTop, x + childWidth, childTop + childHeight);
}
return (reverse ? -childWidth : childWidth);
}
protected class VisibilityAnimListener implements ViewPropertyAnimatorListener {
private boolean mCanceled = false;
int mFinalVisibility;
public VisibilityAnimListener withFinalVisibility(ViewPropertyAnimatorCompat animation,
int visibility) {
mVisibilityAnim = animation;
mFinalVisibility = visibility;
return this;
}
@Override
public void onAnimationStart(View view) {
setVisibility(VISIBLE);
mCanceled = false;
}
@Override
public void onAnimationEnd(View view) {
if (mCanceled) return;
mVisibilityAnim = null;
setVisibility(mFinalVisibility);
if (mSplitView != null && mMenuView != null) {
mMenuView.setVisibility(mFinalVisibility);
}
}
@Override
public void onAnimationCancel(View view) {
mCanceled = true;
}
}
}
| Make AbsActionBarView eat touch/hover events
This code is taken straight out of Toolbar.
BUG: 22709057
Change-Id: I9a3e4c58e8fa8d15d7cef9f05adbb416006aedc0
| v7/appcompat/src/android/support/v7/internal/widget/AbsActionBarView.java | Make AbsActionBarView eat touch/hover events |
|
Java | bsd-3-clause | cab5608bf12b2a1d7612b0ee188455740f655a34 | 0 | NCIP/c3pr,NCIP/c3pr,NCIP/c3pr | package edu.duke.cabig.c3pr.dao;
import java.util.Arrays;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import edu.duke.cabig.c3pr.domain.Arm;
import edu.duke.cabig.c3pr.domain.Epoch;
import edu.duke.cabig.c3pr.domain.Identifier;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudyParticipantAssignment;
import edu.duke.cabig.c3pr.domain.StudySite;
import edu.emory.mathcs.backport.java.util.Collections;
import edu.nwu.bioinformatics.commons.CollectionUtils;
/**
* Hibernate implementation of StudyDao
* @author Priyatam
*/
public class StudyDao extends AbstractBaseDao<Study> {
private static final List<String> SUBSTRING_MATCH_PROPERTIES
= Arrays.asList("shortTitleText");
private static final List<String> EXACT_MATCH_PROPERTIES
= Collections.emptyList();
@Override
public Class<Study> domainClass() {
return Study.class;
}
/**
* This is a hack to load all collection objects in memory. Useful
* for editing a Study when you know you will be needing all collections
* To avoid Lazy loading Exception by Hibernate, a call to .size() is done
* for each collection
* @param id
* @return
*/
public Study getStudyDesignById(int id) {
Study study = (Study) getHibernateTemplate().get(domainClass(), id);
study.getIdentifiers().size();
study.getStudySites().size();
for (StudySite studySite : study.getStudySites()) {
studySite.getStudyInvestigators().size();
studySite.getStudyPersonnels().size();
}
study.getExcCriterias().size();
study.getIncCriterias().size();
study.getStudyDiseases().size();
List<Epoch> epochs = study.getEpochs();
epochs.size();
for (Epoch epoch : epochs) {
epoch.getArms().size();
}
return study;
}
@SuppressWarnings("unchecked")
public Study getByIdentifier(Identifier identifier) {
Criteria criteria = getSession().createCriteria(domainClass());
criteria = criteria.createCriteria("identifiers");
if(identifier.getType() != null) {
criteria.add(Restrictions.eq("type", identifier.getType()));
}
if(identifier.getSource() != null) {
criteria.add(Restrictions.eq("source", identifier.getSource()));
}
if(identifier.getValue() != null) {
criteria.add(Restrictions.eq("value", identifier.getValue()));
}
return (Study) CollectionUtils.firstElement(criteria.list());
}
public void merge(Study study) {
getHibernateTemplate().merge(study);
}
public List<Study> getBySubnames(String[] subnames) {
return findBySubname(subnames,
SUBSTRING_MATCH_PROPERTIES, EXACT_MATCH_PROPERTIES);
}
/*
* Searches based on an example object. Typical usage from your service class: -
* If you want to search based on diseaseCode, monitorCode,
* <li><code>Study study = new Study();</li></code>
* <li>code>study.setDiseaseCode("diseaseCode");</li></code>
* <li>code>study.setDMonitorCode("monitorCode");</li></code>
* <li>code>studyDao.searchByExample(study)</li></code>
* @return list of matching study objects based on your sample study object
*/
public List<Study> searchByExample(Study study, boolean isWildCard) {
Example example = Example.create(study).excludeZeroes().ignoreCase();
Criteria studyCriteria = getSession().createCriteria(Study.class);
if (isWildCard)
{
example.excludeProperty("doNotUse").enableLike(MatchMode.ANYWHERE);
studyCriteria.add(example);
if (study.getIdentifiers().size() > 0) {
studyCriteria.createCriteria("identifiers")
.add(Restrictions.like("value", study.getIdentifiers().get(0)
.getValue()+ "%"));
}
return studyCriteria.list();
}
return studyCriteria.add(example).list();
}
/**
* Default Search without a Wildchar
* @param study
* @return Search Results
*/
public List<Study> searchByExample(Study study) {
return searchByExample(study, false);
}
/**
* Returns all study objects
* @return list of study objects
*/
public List<Study> getAll(){
return getHibernateTemplate().find("from Study");
}
/**
* Get all Arms associated with all of this study's epochs
* @param studyId the study id
* @return list of Arm objects given a study id
*/
public List<Arm> getArmsForStudy(Integer studyId) {
return getHibernateTemplate().find("select a from Study s join s.epochs e join e.arms a " +
"where s.id = ?", studyId);
}
/**
* Get all Assignments associated with the given study
* @param studyId the study id
* @return list of StudyParticipantAssignments
*/
public List<StudyParticipantAssignment> getStudyParticipantAssignmentsForStudy(Integer studyId) {
return getHibernateTemplate().find("select a from Study s join s.studySites ss " +
"join ss.studyParticipantAssignments a where s.id = ?", studyId);
}
}
| codebase/projects/core/src/edu/duke/cabig/c3pr/dao/StudyDao.java | package edu.duke.cabig.c3pr.dao;
import java.util.Arrays;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import edu.duke.cabig.c3pr.domain.Arm;
import edu.duke.cabig.c3pr.domain.Epoch;
import edu.duke.cabig.c3pr.domain.Identifier;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudyParticipantAssignment;
import edu.duke.cabig.c3pr.domain.StudySite;
import edu.emory.mathcs.backport.java.util.Collections;
import edu.nwu.bioinformatics.commons.CollectionUtils;
/**
* Hibernate implementation of StudyDao
* @author Priyatam
*/
public class StudyDao extends AbstractBaseDao<Study> {
private static final List<String> SUBSTRING_MATCH_PROPERTIES
= Arrays.asList("shortTitleText");
private static final List<String> EXACT_MATCH_PROPERTIES
= Collections.emptyList();
@Override
public Class<Study> domainClass() {
return Study.class;
}
/**
* This is a hack to load all collection objects in memory. Useful
* for editing a Study when you know you will be needing all collections
* To avoid Lazy loading Exception by Hibernate, a call to .size() is done
* for each collection
* @param id
* @return
*/
public Study getStudyDesignById(int id) {
Study study = (Study) getHibernateTemplate().get(domainClass(), id);
study.getIdentifiers().size();
study.getStudySites().size();
for (StudySite studySite : study.getStudySites()) {
studySite.getStudyInvestigators().size();
studySite.getStudyPersonnels().size();
}
study.getExcCriterias().size();
study.getIncCriterias().size();
List<Epoch> epochs = study.getEpochs();
epochs.size();
for (Epoch epoch : epochs) {
epoch.getArms().size();
}
return study;
}
@SuppressWarnings("unchecked")
public Study getByIdentifier(Identifier identifier) {
Criteria criteria = getSession().createCriteria(domainClass());
criteria = criteria.createCriteria("identifiers");
if(identifier.getType() != null) {
criteria.add(Restrictions.eq("type", identifier.getType()));
}
if(identifier.getSource() != null) {
criteria.add(Restrictions.eq("source", identifier.getSource()));
}
if(identifier.getValue() != null) {
criteria.add(Restrictions.eq("value", identifier.getValue()));
}
return (Study) CollectionUtils.firstElement(criteria.list());
}
public void merge(Study study) {
getHibernateTemplate().merge(study);
}
public List<Study> getBySubnames(String[] subnames) {
return findBySubname(subnames,
SUBSTRING_MATCH_PROPERTIES, EXACT_MATCH_PROPERTIES);
}
/*
* Searches based on an example object. Typical usage from your service class: -
* If you want to search based on diseaseCode, monitorCode,
* <li><code>Study study = new Study();</li></code>
* <li>code>study.setDiseaseCode("diseaseCode");</li></code>
* <li>code>study.setDMonitorCode("monitorCode");</li></code>
* <li>code>studyDao.searchByExample(study)</li></code>
* @return list of matching study objects based on your sample study object
*/
public List<Study> searchByExample(Study study, boolean isWildCard) {
Example example = Example.create(study).excludeZeroes().ignoreCase();
Criteria studyCriteria = getSession().createCriteria(Study.class);
if (isWildCard)
{
example.excludeProperty("doNotUse").enableLike(MatchMode.ANYWHERE);
studyCriteria.add(example);
if (study.getIdentifiers().size() > 0) {
studyCriteria.createCriteria("identifiers")
.add(Restrictions.like("value", study.getIdentifiers().get(0)
.getValue()+ "%"));
}
return studyCriteria.list();
}
return studyCriteria.add(example).list();
}
/**
* Default Search without a Wildchar
* @param study
* @return Search Results
*/
public List<Study> searchByExample(Study study) {
return searchByExample(study, false);
}
/**
* Returns all study objects
* @return list of study objects
*/
public List<Study> getAll(){
return getHibernateTemplate().find("from Study");
}
/**
* Get all Arms associated with all of this study's epochs
* @param studyId the study id
* @return list of Arm objects given a study id
*/
public List<Arm> getArmsForStudy(Integer studyId) {
return getHibernateTemplate().find("select a from Study s join s.epochs e join e.arms a " +
"where s.id = ?", studyId);
}
/**
* Get all Assignments associated with the given study
* @param studyId the study id
* @return list of StudyParticipantAssignments
*/
public List<StudyParticipantAssignment> getStudyParticipantAssignmentsForStudy(Integer studyId) {
return getHibernateTemplate().find("select a from Study s join s.studySites ss " +
"join ss.studyParticipantAssignments a where s.id = ?", studyId);
}
}
| non-lazy loading of diseases for study
| codebase/projects/core/src/edu/duke/cabig/c3pr/dao/StudyDao.java | non-lazy loading of diseases for study |
|
Java | bsd-3-clause | 271b003df208a05871f6f2a99addc091e2538db8 | 0 | nish5887/blueprints,qiangswa/blueprints,joeyfreund/blueprints,germanviscuso/blueprints,dmargo/blueprints-seas,jwest-apigee/blueprints,orientechnologies/blueprints,wmudge/blueprints,echinopsii/net.echinopsii.3rdparty.blueprints,datablend/blueprints,tinkerpop/blueprints,maiklos-mirrors/tinkerpop_blueprints,iskytek/blueprints | package com.tinkerpop.blueprints.pgm.impls.neo4j;
import com.tinkerpop.blueprints.pgm.Edge;
import com.tinkerpop.blueprints.pgm.Graph;
import com.tinkerpop.blueprints.pgm.Index;
import com.tinkerpop.blueprints.pgm.Vertex;
import com.tinkerpop.blueprints.pgm.impls.neo4j.util.Neo4jGraphEdgeSequence;
import com.tinkerpop.blueprints.pgm.impls.neo4j.util.Neo4jVertexSequence;
import org.neo4j.graphdb.*;
//import org.neo4j.index.Isolation;
import org.neo4j.index.IndexService;
import org.neo4j.index.lucene.LuceneIndexService;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import java.io.File;
import java.util.Map;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class Neo4jGraph implements Graph {
private GraphDatabaseService neo4j;
private String directory;
private Neo4jIndex index;
private Transaction tx;
private boolean automaticTransactions = true;
private IndexService indexService;
public Neo4jGraph(final String directory) {
this(directory, null);
}
public GraphDatabaseService getGraphDatabaseService() {
return this.neo4j;
}
public IndexService getIndexService() {
return indexService;
}
public Neo4jGraph(final String directory, Map<String, String> configuration) {
this.directory = directory;
if (null != configuration)
this.neo4j = new EmbeddedGraphDatabase(this.directory, configuration);
else
this.neo4j = new EmbeddedGraphDatabase(this.directory);
indexService = new LuceneIndexService(neo4j);
//indexService.setIsolation(Isolation.SAME_TX);
this.index = new Neo4jIndex(indexService, this);
if (this.automaticTransactions) {
this.tx = neo4j.beginTx();
}
}
public Index getIndex() {
return this.index;
}
public Vertex addVertex(final Object id) {
Vertex vertex = new Neo4jVertex(neo4j.createNode(), this);
this.stopStartTransaction();
return vertex;
}
public Vertex getVertex(final Object id) {
if (null == id)
return null;
try {
Long longId = Double.valueOf(id.toString()).longValue();
Node node = this.neo4j.getNodeById(longId);
return new Neo4jVertex(node, this);
} catch (NotFoundException e) {
return null;
} catch (NumberFormatException e) {
throw new RuntimeException("Neo vertex ids must be convertible to a long value");
}
}
public Iterable<Vertex> getVertices() {
return new Neo4jVertexSequence(this.neo4j.getAllNodes(), this);
}
public Iterable<Edge> getEdges() {
return new Neo4jGraphEdgeSequence(this.neo4j.getAllNodes(), this);
}
public void removeVertex(final Vertex vertex) {
Long id = (Long) vertex.getId();
Node node = neo4j.getNodeById(id);
if (null != node) {
for (String key : vertex.getPropertyKeys()) {
this.index.remove(key, vertex.getProperty(key), vertex);
}
for (Edge edge : vertex.getInEdges()) {
this.removeEdge(edge);
}
for (Edge edge : vertex.getOutEdges()) {
this.removeEdge(edge);
}
node.delete();
this.stopStartTransaction();
}
}
public Edge addEdge(final Object id, final Vertex outVertex, final Vertex inVertex, final String label) {
Node outNode = (Node) ((Neo4jVertex) outVertex).getRawElement();
Node inNode = (Node) ((Neo4jVertex) inVertex).getRawElement();
Relationship relationship = outNode.createRelationshipTo(inNode, DynamicRelationshipType.withName(label));
this.stopStartTransaction();
return new Neo4jEdge(relationship, this);
}
public void removeEdge(Edge edge) {
((Relationship) ((Neo4jEdge) edge).getRawElement()).delete();
this.stopStartTransaction();
}
protected void stopStartTransaction() {
if (this.automaticTransactions) {
if (null != tx) {
this.tx.success();
this.tx.finish();
this.tx = neo4j.beginTx();
} else {
throw new RuntimeException("There is no active transaction to stop");
}
}
}
public void startTransaction() {
if (this.automaticTransactions)
throw new RuntimeException("Turn off automatic transactions to use manual transaction handling");
this.tx = neo4j.beginTx();
}
public void stopTransaction(boolean success) {
if (this.automaticTransactions)
throw new RuntimeException("Turn off automatic transactions to use manual transaction handling");
if (success) {
this.tx.success();
} else {
this.tx.failure();
}
this.tx.finish();
}
public void setAutoTransactions(boolean automatic) {
this.automaticTransactions = automatic;
if (null != this.tx) {
this.tx.success();
this.tx.finish();
}
}
public void shutdown() {
if (this.automaticTransactions) {
try {
this.tx.success();
this.tx.finish();
} catch (TransactionFailureException e) {
}
}
this.neo4j.shutdown();
this.index.shutdown();
}
public void clear() {
this.shutdown();
deleteGraphDirectory(new File(this.directory));
this.neo4j = new EmbeddedGraphDatabase(this.directory);
LuceneIndexService indexService = new LuceneIndexService(neo4j);
//indexService.setIsolation(Isolation.SAME_TX);
this.index = new Neo4jIndex(indexService, this);
this.tx = neo4j.beginTx();
this.removeVertex(this.getVertex(0));
this.stopStartTransaction();
}
private static void deleteGraphDirectory(final File directory) {
if (directory.exists()) {
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
deleteGraphDirectory(file);
}
file.delete();
}
}
}
public String toString() {
return "neo4jgraph[" + this.directory + "]";
}
}
| src/main/java/com/tinkerpop/blueprints/pgm/impls/neo4j/Neo4jGraph.java | package com.tinkerpop.blueprints.pgm.impls.neo4j;
import com.tinkerpop.blueprints.pgm.Edge;
import com.tinkerpop.blueprints.pgm.Graph;
import com.tinkerpop.blueprints.pgm.Index;
import com.tinkerpop.blueprints.pgm.Vertex;
import com.tinkerpop.blueprints.pgm.impls.neo4j.util.Neo4jGraphEdgeSequence;
import com.tinkerpop.blueprints.pgm.impls.neo4j.util.Neo4jVertexSequence;
import org.neo4j.graphdb.*;
//import org.neo4j.index.Isolation;
import org.neo4j.index.lucene.LuceneIndexService;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import java.io.File;
import java.util.Map;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class Neo4jGraph implements Graph {
private GraphDatabaseService neo;
private String directory;
private Neo4jIndex index;
private Transaction tx;
private boolean automaticTransactions = true;
public Neo4jGraph(final String directory) {
this(directory, null);
}
public GraphDatabaseService getGraphDatabaseService() {
return this.neo;
}
public Neo4jGraph(final String directory, Map<String, String> configuration) {
this.directory = directory;
if (null != configuration)
this.neo = new EmbeddedGraphDatabase(this.directory, configuration);
else
this.neo = new EmbeddedGraphDatabase(this.directory);
LuceneIndexService indexService = new LuceneIndexService(neo);
//indexService.setIsolation(Isolation.SAME_TX);
this.index = new Neo4jIndex(indexService, this);
if (this.automaticTransactions) {
this.tx = neo.beginTx();
}
}
public Index getIndex() {
return this.index;
}
public Vertex addVertex(final Object id) {
Vertex vertex = new Neo4jVertex(neo.createNode(), this);
this.stopStartTransaction();
return vertex;
}
public Vertex getVertex(final Object id) {
if (null == id)
return null;
try {
Long longId = Double.valueOf(id.toString()).longValue();
Node node = this.neo.getNodeById(longId);
return new Neo4jVertex(node, this);
} catch (NotFoundException e) {
return null;
} catch (NumberFormatException e) {
throw new RuntimeException("Neo vertex ids must be convertible to a long value");
}
}
public Iterable<Vertex> getVertices() {
return new Neo4jVertexSequence(this.neo.getAllNodes(), this);
}
public Iterable<Edge> getEdges() {
return new Neo4jGraphEdgeSequence(this.neo.getAllNodes(), this);
}
public void removeVertex(final Vertex vertex) {
Long id = (Long) vertex.getId();
Node node = neo.getNodeById(id);
if (null != node) {
for (String key : vertex.getPropertyKeys()) {
this.index.remove(key, vertex.getProperty(key), vertex);
}
for (Edge edge : vertex.getInEdges()) {
this.removeEdge(edge);
}
for (Edge edge : vertex.getOutEdges()) {
this.removeEdge(edge);
}
node.delete();
this.stopStartTransaction();
}
}
public Edge addEdge(final Object id, final Vertex outVertex, final Vertex inVertex, final String label) {
Node outNode = (Node) ((Neo4jVertex) outVertex).getRawElement();
Node inNode = (Node) ((Neo4jVertex) inVertex).getRawElement();
Relationship relationship = outNode.createRelationshipTo(inNode, DynamicRelationshipType.withName(label));
this.stopStartTransaction();
return new Neo4jEdge(relationship, this);
}
public void removeEdge(Edge edge) {
((Relationship) ((Neo4jEdge) edge).getRawElement()).delete();
this.stopStartTransaction();
}
protected void stopStartTransaction() {
if (this.automaticTransactions) {
if (null != tx) {
this.tx.success();
this.tx.finish();
this.tx = neo.beginTx();
} else {
throw new RuntimeException("There is no active transaction to stop");
}
}
}
public void startTransaction() {
if (this.automaticTransactions)
throw new RuntimeException("Turn off automatic transactions to use manual transaction handling");
this.tx = neo.beginTx();
}
public void stopTransaction(boolean success) {
if (this.automaticTransactions)
throw new RuntimeException("Turn off automatic transactions to use manual transaction handling");
if (success) {
this.tx.success();
} else {
this.tx.failure();
}
this.tx.finish();
}
public void setAutoTransactions(boolean automatic) {
this.automaticTransactions = automatic;
if (null != this.tx) {
this.tx.success();
this.tx.finish();
}
}
public void shutdown() {
if (this.automaticTransactions) {
try {
this.tx.success();
this.tx.finish();
} catch (TransactionFailureException e) {
}
}
this.neo.shutdown();
this.index.shutdown();
}
public void clear() {
this.shutdown();
deleteGraphDirectory(new File(this.directory));
this.neo = new EmbeddedGraphDatabase(this.directory);
LuceneIndexService indexService = new LuceneIndexService(neo);
//indexService.setIsolation(Isolation.SAME_TX);
this.index = new Neo4jIndex(indexService, this);
this.tx = neo.beginTx();
this.removeVertex(this.getVertex(0));
this.stopStartTransaction();
}
private static void deleteGraphDirectory(final File directory) {
if (directory.exists()) {
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
deleteGraphDirectory(file);
}
file.delete();
}
}
}
public String toString() {
return "neo4jgraph[" + this.directory + "]";
}
}
| adding getIndexService and refactored neo->neo4j
| src/main/java/com/tinkerpop/blueprints/pgm/impls/neo4j/Neo4jGraph.java | adding getIndexService and refactored neo->neo4j |
|
Java | bsd-3-clause | 00de91425c483f84df37ff2535ef16b3d64e4ad5 | 0 | msowka/openxc-android,openxc/openxc-android,prateeknitish391/demo,dhootha/openxc-android,dhootha/openxc-android,petemaclellan/openxc-android,prateeknitish391/demo,msowka/openxc-android,mray19027/openxc-android,mray19027/openxc-android,ChernyshovYuriy/openxc-android,openxc/openxc-android,ChernyshovYuriy/openxc-android,petemaclellan/openxc-android,prateeknitish391/demo | package com.openxc.measurements;
import junit.framework.TestCase;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class BrakePedalStatusTest extends TestCase {
BrakePedalStatus measurement;
@Override
public void setUp() {
measurement = new BrakePedalStatus(new Boolean(false));
}
public void testGet() {
assertThat(measurement.getValue().booleanValue(), equalTo(false));
}
public void testHasNoRange() {
assertFalse(measurement.hasRange());
}
public void testGenericName() {
assertEquals(measurement.getGenericName(), measurement.ID);
}
}
| openxc-it/src/test/java/com/openxc/measurements/BrakePedalStatusTest.java | package com.openxc.measurements;
import junit.framework.TestCase;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class BrakePedalStatusTest extends TestCase {
BrakePedalStatus measurement;
@Override
public void setUp() {
measurement = new BrakePedalStatus(new Boolean(false));
}
public void testGet() {
assertThat(measurement.getValue().booleanValue(), equalTo(false));
}
public void testHasNoRange() {
assertFalse(measurement.hasRange());
}
}
| Test that genericName method is overridden.
| openxc-it/src/test/java/com/openxc/measurements/BrakePedalStatusTest.java | Test that genericName method is overridden. |
|
Java | bsd-3-clause | f3da95e05d6bc0e2667bd32a31baabed5e9d5975 | 0 | muloem/xins,muloem/xins,muloem/xins | /*
* $Id$
*/
package org.xins.common.service.http;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.util.Iterator;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpRecoverableException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.TimeOutException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.collections.PropertyReaderUtils;
import org.xins.common.net.URLEncoding;
import org.xins.common.service.CallException;
import org.xins.common.service.CallRequest;
import org.xins.common.service.CallResult;
import org.xins.common.service.ConnectionRefusedCallException;
import org.xins.common.service.ConnectionTimeOutCallException;
import org.xins.common.service.Descriptor;
import org.xins.common.service.GenericCallException;
import org.xins.common.service.IOCallException;
import org.xins.common.service.ServiceCaller;
import org.xins.common.service.SocketTimeOutCallException;
import org.xins.common.service.TargetDescriptor;
import org.xins.common.service.TotalTimeOutCallException;
import org.xins.common.service.UnexpectedExceptionCallException;
import org.xins.common.text.FastStringBuffer;
/**
* HTTP service caller. This class can be used to perform a call to an HTTP
* server and fail-over to other HTTP servers if the first one fails.
*
* <p>The following example code snippet constructs an
* <code>HTTPServiceCaller</code> instance:
*
* <blockquote><code>{@link Descriptor Descriptor} descriptor = {@link org.xins.common.service.DescriptorBuilder DescriptorBuilder}.{@link org.xins.common.service.DescriptorBuilder#build(PropertyReader,String) build}(properties, PROPERTY_NAME);
* <br />HTTPServiceCaller caller = new {@link #HTTPServiceCaller(Descriptor,HTTPServiceCaller.Method) HTTPServiceCaller}(descriptor, HTTPServiceCaller.{@link #GET GET});</code></blockquote>
*
* <p>A call can be executed as follows, using this <code>HTTPServiceCaller</code>:
*
* <blockquote><code>{@link org.xins.common.collections.PropertyReader PropertyReader} params = new {@link org.xins.common.collections.BasicPropertyReader BasicPropertyReader}();
* <br />params.set("street", "Broadband Avenue");
* <br />params.set("houseNumber", "12");
* <br />{@link HTTPServiceCaller.Result HTTPServiceCaller.Result} result = caller.{@link #call(PropertyReader) call}(params);</code></blockquote>
*
* <p>TODO: Fix the example code for XINS 0.207.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.115
*/
public final class HTTPServiceCaller extends ServiceCaller {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
// TODO: Decide whether Method should be an inner class in this class or not
// TODO: Decide whether these constants Method should be in this class or elsewhere
/**
* Constant representing the HTTP GET method.
*/
public static final Method GET = new Method("GET");
/**
* Constant representing the HTTP POST method.
*/
public static final Method POST = new Method("POST");
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Creates an appropriate <code>HttpMethod</code> object for the specified
* URL.
*
* @param url
* the URL for which to create an {@link HttpMethod} object, should not
* be <code>null</code>.
*
* @param request
* the HTTP call request, should not be <code>null</code>.
* be sent.
*
* @return
* the constructed {@link HttpMethod} object, never <code>null</code>.
*
* @throws NullPointerException
* if <code>request == null</code>.
*/
private static HttpMethod createMethod(String url,
HTTPCallRequest request) {
Method method = request.getMethod();
PropertyReader parameters = request.getParameters();
// HTTP POST request
if (method == POST) {
PostMethod postMethod = new PostMethod(url);
// Loop through the parameters
Iterator keys = parameters.getNames();
while (keys.hasNext()) {
// Get the parameter key
String key = (String) keys.next();
// Get the value
Object value = parameters.get(key);
// Add this parameter key/value combination
if (key != null && value != null) {
postMethod.addParameter(key, value.toString());
}
}
return postMethod;
// HTTP GET request
} else if (method == GET) {
GetMethod getMethod = new GetMethod(url);
// Loop through the parameters
FastStringBuffer query = new FastStringBuffer(255);
Iterator keys = parameters.getNames();
while (keys.hasNext()) {
// Get the parameter key
String key = (String) keys.next();
// Get the value
Object value = parameters.get(key);
// Add this parameter key/value combination
if (key != null && value != null) {
if (query.getLength() > 0) {
query.append(",");
}
query.append(URLEncoding.encode(key));
query.append("=");
query.append(URLEncoding.encode(value.toString()));
}
}
if (query.getLength() > 0) {
getMethod.setQueryString(query.toString());
}
return getMethod;
// Unrecognized HTTP method (only GET and POST are supported)
} else {
throw new Error("Unrecognized method \"" + method + "\".");
}
}
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>HTTPServiceCaller</code> object.
*
* @param descriptor
* the descriptor of the service, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>descriptor == null</code>.
*
* @since XINS 0.207
*/
public HTTPServiceCaller(Descriptor descriptor)
throws IllegalArgumentException {
super(descriptor);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected Object doCallImpl(TargetDescriptor target,
CallRequest request)
throws Throwable {
// Delegate to method with more specialized interface
return call(target, (HTTPCallRequest) request);
}
/**
* Performs the specified request towards the HTTP service. If the call
* succeeds with one of the targets, then a {@link Result} object is
* returned, that combines the HTTP status code and the data returned.
* Otherwise, if none of the targets could successfully be called, a
* {@link CallException} is thrown.
*
* @param request
* the call request, not <code>null</code>.
*
* @return
* the result of the call, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>request == null</code>.
*
* @throws GenericCallException
* if the (first) call attempt failed due to a generic reason.
*/
public Result call(HTTPCallRequest request)
throws GenericCallException, HTTPCallException {
CallResult callResult;
try {
callResult = doCall(request);
// Allow GenericCallException, HTTPCallException and Error to proceed,
// but block other kinds of exceptions and throw an Error instead.
} catch (GenericCallException exception) {
throw exception;
} catch (HTTPCallException exception) {
throw exception;
} catch (Exception exception) {
throw new Error(getClass().getName() + ".doCall(" + request.getClass().getName() + ") threw " + exception.getClass().getName() + '.');
}
return (Result) callResult.getResult();
}
/**
* Executes the specified HTTP call request on the specified target. If the
* call fails in any way, then a {@link CallException} is thrown.
*
* @param target
* the service target on which to execute the request, cannot be
* <code>null</code>.
*
* @param request
* the call request to execute, cannot be <code>null</code>.
*
* @return
* the call result, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>target == null || request == null</code>.
*
* @throws GenericCallException
* if the call to the specified target failed due to a generic reason.
*
* @throws HTTPCallException
* if the call to the specified target failed due to an HTTP-specific
* error.
*
* @since XINS 0.207
*/
public Result call(TargetDescriptor target,
HTTPCallRequest request)
throws IllegalArgumentException,
GenericCallException,
HTTPCallException {
// TODO: Review log message 3304. Perhaps remove it.
// NOTE: Preconditions are checked by the CallExecutor constructor
// Prepare a thread for execution of the call
CallExecutor executor = new CallExecutor(target, request);
// TODO: Log that we are about to make an HTTP call
// Perform the HTTP call
boolean succeeded = false;
long start = System.currentTimeMillis();
long duration;
try {
controlTimeOut(executor, target);
succeeded = true;
// Total time-out exceeded
} catch (TimeOutException exception) {
duration = System.currentTimeMillis() - start;
// TODO: Log the total time-out (2015 ?)
throw new TotalTimeOutCallException(request, target, duration);
} finally {
// Determine the call duration
duration = System.currentTimeMillis() - start;
}
// Check for exceptions
Throwable exception = executor.getException();
if (exception != null) {
// Connection refusal
if (exception instanceof ConnectException) {
// TODO: Log connection refusal (2012 ?)
throw new ConnectionRefusedCallException(request, target, duration);
// Connection time-out
} else if (exception instanceof HttpConnection.ConnectionTimeoutException) {
// TODO: Log connection time-out (2013 ?)
throw new ConnectionTimeOutCallException(request, target, duration);
// Socket time-out
} else if (exception instanceof HttpRecoverableException) {
// XXX: This is an ugly way to detect a socket time-out, but there
// does not seem to be a better way in HttpClient 2.0. This
// will, however, be fixed in HttpClient 3.0. See:
// http://issues.apache.org/bugzilla/show_bug.cgi?id=19868
String exMessage = exception.getMessage();
if (exMessage != null && exMessage.startsWith("java.net.SocketTimeoutException")) {
// TODO: Log socket time-out (2014 ?)
throw new SocketTimeOutCallException(request, target, duration);
// Unspecific I/O error
} else {
// TODO: Log unspecific I/O error (2017 ?)
throw new IOCallException(request, target, duration, (IOException) exception);
}
// Unspecific I/O error
} else if (exception instanceof IOException) {
// TODO: Log unspecific I/O error (2017 ?)
throw new IOCallException(request, target, duration, (IOException) exception);
// Unrecognized kind of exception caught
} else {
// TODO: Log unrecognized exception error (2018 ?)
throw new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
}
// TODO: Log (2016 ?)
// Grab the result from the HTTP call
Result result = executor.getResult();
// Check the status code, if necessary
HTTPStatusCodeVerifier verifier = request.getStatusCodeVerifier();
if (verifier != null) {
int code = result.getStatusCode();
if (! verifier.isAcceptable(code)) {
// TODO: Pass down body as well. Perhaps just pass down complete
// Result object and add getter for the body to the
// StatusCodeHTTPCallException class.
throw new StatusCodeHTTPCallException(request, target, duration, code);
}
}
return result;
}
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* Result returned from an HTTP request.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.115
*/
public static final class Result extends Object {
//----------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------
/**
* Constructs a new <code>Result</code> object.
*
* @param code
* the HTTP return code, must be >= 0.
*
* @param data
* the retrieved data, not <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>code < 0 || data == null</code>.
*/
public Result(int code, byte[] data)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("data", data);
if (code < 0) {
throw new IllegalArgumentException("code (" + code + ") < 0");
}
// Just store the arguments in fields
_code = code;
_data = data;
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* The HTTP return code.
*/
private final int _code;
/**
* The data returned.
*/
private final byte[] _data;
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Returns the HTTP status code.
*
* @return
* the HTTP status code.
*
* @since XINS 0.207
*/
public int getStatusCode() {
return _code;
}
/**
* Returns the result data as a byte array. Note that this is not a copy
* or clone of the internal data structure, but it is a link to the
* actual data structure itself.
*
* @return
* a byte array of the result data, not <code>null</code>.
*/
public byte[] getData() {
return _data;
}
/**
* Returns the returned data as a <code>String</code>. The encoding
* <code>US-ASCII</code> is assumed.
*
* @return
* the result data as a text string, not <code>null</code>.
*/
public String getString() {
final String ENCODING = "US-ASCII";
try {
return getString(ENCODING);
} catch (UnsupportedEncodingException exception) {
throw new Error("Encoding \"" + ENCODING + "\" is unsupported.");
}
}
/**
* Returns the returned data as a <code>String</code> in the specified
* encoding.
*
* @param encoding
* the encoding to use in the conversion from bytes to a text string,
* not <code>null</code>.
*
* @return
* the result data as a text string, not <code>null</code>.
*
* @throws UnsupportedEncodingException
* if the specified encoding is not supported.
*/
public String getString(String encoding)
throws UnsupportedEncodingException {
byte[] bytes = getData();
return new String(bytes, encoding);
}
/**
* Returns the returned data as an <code>InputStream</code>. The input
* stream is based directly on the underlying byte array.
*
* @return
* an {@link InputStream} that returns the returned data, never
* <code>null</code>.
*
* @since XINS 0.194
*/
public InputStream getStream() {
return new ByteArrayInputStream(_data);
}
}
/**
* HTTP method. Possible values for variable of this class:
*
* <ul>
* <li>{@link #GET}
* <li>{@link #POST}
* </ul>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.115
*/
public static final class Method extends Object {
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new <code>Method</code> object with the specified name.
*
* @param name
* the name of the method, for example <code>"GET"</code> or
* <code>"POST"</code>; should not be <code>null</code>.
*/
Method(String name) {
_name = name;
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* The name of this method. For example <code>"GET"</code> or
* <code>"POST"</code>. This field should never be <code>null</code>.
*/
private final String _name;
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Returns a textual representation of this object. The implementation
* of this method returns the name of this HTTP method, like
* <code>"GET"</code> or <code>"POST"</code>.
*
* @return
* the name of this method, e.g. <code>"GET"</code> or
* <code>"POST"</code>; never <code>null</code>.
*/
public String toString() {
return _name;
}
}
/**
* Executor of calls to an API.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.207
*/
private static final class CallExecutor extends Thread {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The number of constructed call executors.
*/
private static int CALL_EXECUTOR_COUNT;
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new <code>CallExecutor</code> for the specified call to
* a XINS API.
*
* @param target
* the service target on which to execute the request, cannot be
* <code>null</code>.
*
* @param request
* the call request to execute, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>target == null || request == null</code>.
*/
private CallExecutor(TargetDescriptor target,
HTTPCallRequest request)
throws IllegalArgumentException {
// Create textual representation of this object
_asString = "HTTP call executor #" + (++CALL_EXECUTOR_COUNT);
// Check preconditions
MandatoryArgumentChecker.check("target", target, "request", request);
// Store target and request for later use in the run() method
_target = target;
_request = request;
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* Textual representation of this object. Never <code>null</code>.
*/
private final String _asString;
/**
* The service target on which to execute the request. Never
* <code>null</code>.
*/
private final TargetDescriptor _target;
/**
* The call request to execute. Never <code>null</code>.
*/
private final HTTPCallRequest _request;
/**
* The exception caught while executing the call. If there was no
* exception, then this field is <code>null</code>.
*/
private Throwable _exception;
/**
* The result from the call. The value of this field is
* <code>null</code> if the call was unsuccessful or if it was not
* executed yet..
*/
private Result _result;
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Runs this thread. It will call the XINS API. If that call was
* successful, then the status code is stored in this object. Otherwise
* there is an exception. In that case the exception is stored in this
* object.
*/
public void run() {
// TODO: Check if this request was already executed, since this is a
// stateful object. If not, mark it as executing within a
// synchronized section, so it may no 2 threads may execute
// this request at the same time.
// NOTE: Performance could be improved by using local variables for
// _target and _request
// Get the input parameters
PropertyReader params = _request.getParameters();
// TODO: Uncomment or remove the following line:
// LogdocSerializable serParams = PropertyReaderUtils.serialize(params, "-");
// Construct new HttpClient object
HttpClient client = new HttpClient();
// Determine URL and time-outs
String url = _target.getURL();
int totalTimeOut = _target.getTotalTimeOut();
int connectionTimeOut = _target.getConnectionTimeOut();
int socketTimeOut = _target.getSocketTimeOut();
// Configure connection time-out and socket time-out
client.setConnectionTimeout(connectionTimeOut);
client.setTimeout (socketTimeOut);
// Construct the method object
HttpMethod method = createMethod(url, _request);
// Log that we are about to make the HTTP call
// TODO: Uncomment or remove the following line:
// Log.log_2011(url, functionName, serParams, totalTimeOut, connectionTimeOut, socketTimeOut);
// Perform the HTTP call
try {
int statusCode = client.executeMethod(method);
byte[] body = method.getResponseBody();
// Store the result immediately
_result = new Result(statusCode, body);
// If an exception is thrown, store it for processing at later stage
} catch (Throwable exception) {
_exception = exception;
}
// Release the HTTP connection immediately
try {
method.releaseConnection();
} catch (Throwable exception) {
// TODO: Log
}
// TODO: Mark this CallExecutor object as executed, so it may not be
// run again
}
/**
* Gets the exception if any generated when calling the method.
*
* @return
* the invocation exception or <code>null</code> if the call
* performed successfully.
*/
public Throwable getException() {
return _exception;
}
/**
* Returns the result if the call was successful. If the call was
* unsuccessful, then <code>null</code> is returned.
*
* @return
* the result from the call, or <code>null</code> if it was
* unsuccessful.
*/
public Result getResult() {
return _result;
}
}
}
| src/java-common/org/xins/common/service/http/HTTPServiceCaller.java | /*
* $Id$
*/
package org.xins.common.service.http;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.util.Iterator;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpRecoverableException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.TimeOutException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.collections.PropertyReaderUtils;
import org.xins.common.net.URLEncoding;
import org.xins.common.service.CallException;
import org.xins.common.service.CallRequest;
import org.xins.common.service.CallResult;
import org.xins.common.service.ConnectionRefusedCallException;
import org.xins.common.service.ConnectionTimeOutCallException;
import org.xins.common.service.Descriptor;
import org.xins.common.service.GenericCallException;
import org.xins.common.service.IOCallException;
import org.xins.common.service.ServiceCaller;
import org.xins.common.service.SocketTimeOutCallException;
import org.xins.common.service.TargetDescriptor;
import org.xins.common.service.TotalTimeOutCallException;
import org.xins.common.service.UnexpectedExceptionCallException;
import org.xins.common.text.FastStringBuffer;
/**
* HTTP service caller. This class can be used to perform a call to an HTTP
* server and fail-over to other HTTP servers if the first one fails.
*
* <p>The following example code snippet constructs an
* <code>HTTPServiceCaller</code> instance:
*
* <blockquote><code>{@link Descriptor Descriptor} descriptor = {@link org.xins.common.service.DescriptorBuilder DescriptorBuilder}.{@link org.xins.common.service.DescriptorBuilder#build(PropertyReader,String) build}(properties, PROPERTY_NAME);
* <br />HTTPServiceCaller caller = new {@link #HTTPServiceCaller(Descriptor,HTTPServiceCaller.Method) HTTPServiceCaller}(descriptor, HTTPServiceCaller.{@link #GET GET});</code></blockquote>
*
* <p>A call can be executed as follows, using this <code>HTTPServiceCaller</code>:
*
* <blockquote><code>{@link org.xins.common.collections.PropertyReader PropertyReader} params = new {@link org.xins.common.collections.BasicPropertyReader BasicPropertyReader}();
* <br />params.set("street", "Broadband Avenue");
* <br />params.set("houseNumber", "12");
* <br />{@link HTTPServiceCaller.Result HTTPServiceCaller.Result} result = caller.{@link #call(PropertyReader) call}(params);</code></blockquote>
*
* <p>TODO: Fix the example code for XINS 0.207.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.115
*/
public final class HTTPServiceCaller extends ServiceCaller {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Constant representing the HTTP GET method.
*/
public static final Method GET = new Method("GET");
/**
* Constant representing the HTTP POST method.
*/
public static final Method POST = new Method("POST");
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Creates an appropriate <code>HttpMethod</code> object for the specified
* URL.
*
* @param url
* the URL for which to create an {@link HttpMethod} object, should not
* be <code>null</code>.
*
* @param request
* the HTTP call request, should not be <code>null</code>.
* be sent.
*
* @return
* the constructed {@link HttpMethod} object, never <code>null</code>.
*
* @throws NullPointerException
* if <code>request == null</code>.
*/
private static HttpMethod createMethod(String url,
HTTPCallRequest request) {
Method method = request.getMethod();
PropertyReader parameters = request.getParameters();
// HTTP POST request
if (method == POST) {
PostMethod postMethod = new PostMethod(url);
// Loop through the parameters
Iterator keys = parameters.getNames();
while (keys.hasNext()) {
// Get the parameter key
String key = (String) keys.next();
// Get the value
Object value = parameters.get(key);
// Add this parameter key/value combination
if (key != null && value != null) {
postMethod.addParameter(key, value.toString());
}
}
return postMethod;
// HTTP GET request
} else if (method == GET) {
GetMethod getMethod = new GetMethod(url);
// Loop through the parameters
FastStringBuffer query = new FastStringBuffer(255);
Iterator keys = parameters.getNames();
while (keys.hasNext()) {
// Get the parameter key
String key = (String) keys.next();
// Get the value
Object value = parameters.get(key);
// Add this parameter key/value combination
if (key != null && value != null) {
if (query.getLength() > 0) {
query.append(",");
}
query.append(URLEncoding.encode(key));
query.append("=");
query.append(URLEncoding.encode(value.toString()));
}
}
if (query.getLength() > 0) {
getMethod.setQueryString(query.toString());
}
return getMethod;
// Unrecognized HTTP method (only GET and POST are supported)
} else {
throw new Error("Unrecognized method \"" + method + "\".");
}
}
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>HTTPServiceCaller</code> object.
*
* @param descriptor
* the descriptor of the service, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>descriptor == null</code>.
*
* @since XINS 0.207
*/
public HTTPServiceCaller(Descriptor descriptor)
throws IllegalArgumentException {
super(descriptor);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected Object doCallImpl(TargetDescriptor target,
CallRequest request)
throws Throwable {
// Delegate to method with more specialized interface
return call(target, (HTTPCallRequest) request);
}
/**
* Performs the specified request towards the HTTP service. If the call
* succeeds with one of the targets, then a {@link Result} object is
* returned, that combines the HTTP status code and the data returned.
* Otherwise, if none of the targets could successfully be called, a
* {@link CallException} is thrown.
*
* @param request
* the call request, not <code>null</code>.
*
* @return
* the result of the call, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>request == null</code>.
*
* @throws GenericCallException
* if the (first) call attempt failed due to a generic reason.
*/
public Result call(HTTPCallRequest request)
throws GenericCallException, HTTPCallException {
CallResult callResult;
try {
callResult = doCall(request);
// Allow GenericCallException, HTTPCallException and Error to proceed,
// but block other kinds of exceptions and throw an Error instead.
} catch (GenericCallException exception) {
throw exception;
} catch (HTTPCallException exception) {
throw exception;
} catch (Exception exception) {
throw new Error(getClass().getName() + ".doCall(" + request.getClass().getName() + ") threw " + exception.getClass().getName() + '.');
}
return (Result) callResult.getResult();
}
/**
* Executes the specified HTTP call request on the specified target. If the
* call fails in any way, then a {@link CallException} is thrown.
*
* @param target
* the service target on which to execute the request, cannot be
* <code>null</code>.
*
* @param request
* the call request to execute, cannot be <code>null</code>.
*
* @return
* the call result, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>target == null || request == null</code>.
*
* @throws GenericCallException
* if the call to the specified target failed due to a generic reason.
*
* @throws HTTPCallException
* if the call to the specified target failed due to an HTTP-specific
* error.
*
* @since XINS 0.207
*/
public Result call(TargetDescriptor target,
HTTPCallRequest request)
throws IllegalArgumentException,
GenericCallException,
HTTPCallException {
// TODO: Review log message 3304. Perhaps remove it.
// NOTE: Preconditions are checked by the CallExecutor constructor
// Prepare a thread for execution of the call
CallExecutor executor = new CallExecutor(target, request);
// TODO: Log that we are about to make an HTTP call
// Perform the HTTP call
boolean succeeded = false;
long start = System.currentTimeMillis();
long duration;
try {
controlTimeOut(executor, target);
succeeded = true;
// Total time-out exceeded
} catch (TimeOutException exception) {
duration = System.currentTimeMillis() - start;
// TODO: Log the total time-out (2015 ?)
throw new TotalTimeOutCallException(request, target, duration);
} finally {
// Determine the call duration
duration = System.currentTimeMillis() - start;
}
// Check for exceptions
Throwable exception = executor.getException();
if (exception != null) {
// Connection refusal
if (exception instanceof ConnectException) {
// TODO: Log connection refusal (2012 ?)
throw new ConnectionRefusedCallException(request, target, duration);
// Connection time-out
} else if (exception instanceof HttpConnection.ConnectionTimeoutException) {
// TODO: Log connection time-out (2013 ?)
throw new ConnectionTimeOutCallException(request, target, duration);
// Socket time-out
} else if (exception instanceof HttpRecoverableException) {
// XXX: This is an ugly way to detect a socket time-out, but there
// does not seem to be a better way in HttpClient 2.0. This
// will, however, be fixed in HttpClient 3.0. See:
// http://issues.apache.org/bugzilla/show_bug.cgi?id=19868
String exMessage = exception.getMessage();
if (exMessage != null && exMessage.startsWith("java.net.SocketTimeoutException")) {
// TODO: Log socket time-out (2014 ?)
throw new SocketTimeOutCallException(request, target, duration);
// Unspecific I/O error
} else {
// TODO: Log unspecific I/O error (2017 ?)
throw new IOCallException(request, target, duration, (IOException) exception);
}
// Unspecific I/O error
} else if (exception instanceof IOException) {
// TODO: Log unspecific I/O error (2017 ?)
throw new IOCallException(request, target, duration, (IOException) exception);
// Unrecognized kind of exception caught
} else {
// TODO: Log unrecognized exception error (2018 ?)
throw new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
}
// TODO: Log (2016 ?)
// TODO: Check HTTP status code
return executor.getResult();
}
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* Result returned from an HTTP request.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.115
*/
public static final class Result extends Object {
//----------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------
/**
* Constructs a new <code>Result</code> object.
*
* @param code
* the HTTP return code, must be >= 0.
*
* @param data
* the retrieved data, not <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>code < 0 || data == null</code>.
*/
public Result(int code, byte[] data)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("data", data);
if (code < 0) {
throw new IllegalArgumentException("code (" + code + ") < 0");
}
// Just store the arguments in fields
_code = code;
_data = data;
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* The HTTP return code.
*/
private final int _code;
/**
* The data returned.
*/
private final byte[] _data;
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Returns the HTTP status code.
*
* @return
* the HTTP status code.
*
* @since XINS 0.207
*/
public int getStatusCode() {
return _code;
}
/**
* Returns the result data as a byte array. Note that this is not a copy
* or clone of the internal data structure, but it is a link to the
* actual data structure itself.
*
* @return
* a byte array of the result data, not <code>null</code>.
*/
public byte[] getData() {
return _data;
}
/**
* Returns the returned data as a <code>String</code>. The encoding
* <code>US-ASCII</code> is assumed.
*
* @return
* the result data as a text string, not <code>null</code>.
*/
public String getString() {
final String ENCODING = "US-ASCII";
try {
return getString(ENCODING);
} catch (UnsupportedEncodingException exception) {
throw new Error("Encoding \"" + ENCODING + "\" is unsupported.");
}
}
/**
* Returns the returned data as a <code>String</code> in the specified
* encoding.
*
* @param encoding
* the encoding to use in the conversion from bytes to a text string,
* not <code>null</code>.
*
* @return
* the result data as a text string, not <code>null</code>.
*
* @throws UnsupportedEncodingException
* if the specified encoding is not supported.
*/
public String getString(String encoding)
throws UnsupportedEncodingException {
byte[] bytes = getData();
return new String(bytes, encoding);
}
/**
* Returns the returned data as an <code>InputStream</code>. The input
* stream is based directly on the underlying byte array.
*
* @return
* an {@link InputStream} that returns the returned data, never
* <code>null</code>.
*
* @since XINS 0.194
*/
public InputStream getStream() {
return new ByteArrayInputStream(_data);
}
}
/**
* HTTP method. Possible values for variable of this class:
*
* <ul>
* <li>{@link #GET}
* <li>{@link #POST}
* </ul>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.115
*/
public static final class Method extends Object {
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new <code>Method</code> object with the specified name.
*
* @param name
* the name of the method, for example <code>"GET"</code> or
* <code>"POST"</code>; should not be <code>null</code>.
*/
Method(String name) {
_name = name;
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* The name of this method. For example <code>"GET"</code> or
* <code>"POST"</code>. This field should never be <code>null</code>.
*/
private final String _name;
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Returns a textual representation of this object. The implementation
* of this method returns the name of this HTTP method, like
* <code>"GET"</code> or <code>"POST"</code>.
*
* @return
* the name of this method, e.g. <code>"GET"</code> or
* <code>"POST"</code>; never <code>null</code>.
*/
public String toString() {
return _name;
}
}
/**
* Executor of calls to an API.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.207
*/
private static final class CallExecutor extends Thread {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The number of constructed call executors.
*/
private static int CALL_EXECUTOR_COUNT;
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new <code>CallExecutor</code> for the specified call to
* a XINS API.
*
* @param target
* the service target on which to execute the request, cannot be
* <code>null</code>.
*
* @param request
* the call request to execute, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>target == null || request == null</code>.
*/
private CallExecutor(TargetDescriptor target,
HTTPCallRequest request)
throws IllegalArgumentException {
// Create textual representation of this object
_asString = "HTTP call executor #" + (++CALL_EXECUTOR_COUNT);
// Check preconditions
MandatoryArgumentChecker.check("target", target, "request", request);
// Store target and request for later use in the run() method
_target = target;
_request = request;
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* Textual representation of this object. Never <code>null</code>.
*/
private final String _asString;
/**
* The service target on which to execute the request. Never
* <code>null</code>.
*/
private final TargetDescriptor _target;
/**
* The call request to execute. Never <code>null</code>.
*/
private final HTTPCallRequest _request;
/**
* The exception caught while executing the call. If there was no
* exception, then this field is <code>null</code>.
*/
private Throwable _exception;
/**
* The result from the call. The value of this field is
* <code>null</code> if the call was unsuccessful or if it was not
* executed yet..
*/
private Result _result;
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Runs this thread. It will call the XINS API. If that call was
* successful, then the status code is stored in this object. Otherwise
* there is an exception. In that case the exception is stored in this
* object.
*/
public void run() {
// TODO: Check if this request was already executed, since this is a
// stateful object.
// NOTE: Performance could be improved by using local variables for
// _target and _request
// Get the input parameters
PropertyReader params = _request.getParameters();
// TODO: Uncomment or remove the following line:
// LogdocSerializable serParams = PropertyReaderUtils.serialize(params, "-");
// Construct new HttpClient object
HttpClient client = new HttpClient();
// Determine URL and time-outs
String url = _target.getURL();
int totalTimeOut = _target.getTotalTimeOut();
int connectionTimeOut = _target.getConnectionTimeOut();
int socketTimeOut = _target.getSocketTimeOut();
// Configure connection time-out and socket time-out
client.setConnectionTimeout(connectionTimeOut);
client.setTimeout (socketTimeOut);
// Construct the method object
HttpMethod method = createMethod(url, _request);
// Log that we are about to make the HTTP call
// TODO: Uncomment or remove the following line:
// Log.log_2011(url, functionName, serParams, totalTimeOut, connectionTimeOut, socketTimeOut);
// Perform the HTTP call
try {
int statusCode = client.executeMethod(method);
byte[] body = method.getResponseBody();
// Store the result immediately
_result = new Result(statusCode, body);
// If an exception is thrown, store it for processing at later stage
} catch (Throwable exception) {
_exception = exception;
}
// Release the HTTP connection immediately
try {
method.releaseConnection();
} catch (Throwable exception) {
// TODO: Log
}
// TODO: Mark this CallExecutor object as executed, so it may not be
// run again
}
/**
* Gets the exception if any generated when calling the method.
*
* @return
* the invocation exception or <code>null</code> if the call
* performed successfully.
*/
public Throwable getException() {
return _exception;
}
/**
* Returns the result if the call was successful. If the call was
* unsuccessful, then <code>null</code> is returned.
*
* @return
* the result from the call, or <code>null</code> if it was
* unsuccessful.
*/
public Result getResult() {
return _result;
}
}
}
| Now validating status code.
| src/java-common/org/xins/common/service/http/HTTPServiceCaller.java | Now validating status code. |
|
Java | mit | 5f6cbe1a6127748395f04c33e4f60f4b91cf6db5 | 0 | viromedia/viro,viromedia/viro,viromedia/viro,viromedia/viro | /*
* Copyright © 2016 Viro Media. All rights reserved.
*/
package com.viromedia.bridge.utility;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.datasource.DataSubscriber;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.DefaultExecutorSupplier;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.image.CloseableBitmap;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.react.bridge.ReadableMap;
import com.viro.core.Texture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
/**
* This class downloads images and returns them as @{link Bitmap} objects
* by leveraging the Facebook Fresco image downloading/caching library.
*/
public class ImageDownloader {
private static final String TAG = ViroLog.getTag(ImageDownloader.class);
private static final String URI_KEY = "uri";
private final Context mContext;
private final ConcurrentHashMap<CountDownLatch, Bitmap> mImageMap;
private final DefaultExecutorSupplier mExecutorSupplier;
private Bitmap.Config mConfig = Bitmap.Config.ARGB_8888;
public ImageDownloader(Context context) {
mContext = context;
mImageMap = new ConcurrentHashMap<>();
mExecutorSupplier = new DefaultExecutorSupplier(1);
}
/**
* This method fetches an image synchronously.
*
* @param map a ReadableMap with a "uri" key, ideally the same one we get from the JS layer
* @return the bitmap containing the image data
*/
public Bitmap getImageSync(ReadableMap map) {
if (!map.hasKey(URI_KEY)) {
throw new IllegalArgumentException("Unable to find \"uri\" key in given source map.");
}
return getImageSync(Helper.parseUri(map.getString(URI_KEY), mContext));
}
/**
* This method fetches an image synchronously.
*
* @param uri a URI representing the location of the image to fetch.
* @return the bitmap containing the image data.
*/
public Bitmap getImageSync(Uri uri) {
CountDownLatch latch = new CountDownLatch(1);
getImage(uri, latch, null);
try {
latch.await();
} catch (InterruptedException e) {
throw new IllegalStateException("Fetching bitmap was interrupted!");
}
Bitmap toReturn = mImageMap.get(latch);
mImageMap.remove(latch);
if (toReturn != null) {
return toReturn;
} else {
ViroLog.warn(TAG, "Could not download image at: " + uri.toString());
return null;
}
}
/**
* This method fetches an image asynchrously
*
* @param map a ReadableMap with a "uri" key, ideally the same one we get from the JS layer
* @param listener object that will be called once the image is fetched.
*/
public void getImageAsync(ReadableMap map, ImageDownloadListener listener) {
if (listener == null) {
ViroLog.warn(TAG, "The given ImageDownloadListener is null. Doing nothing.");
return;
}
if (!map.hasKey(URI_KEY)) {
throw new IllegalArgumentException("Unable to find \"uri\" key in given source map.");
}
getImage(Helper.parseUri(map.getString(URI_KEY), mContext), null, listener);
}
private void getImage(Uri uri, final CountDownLatch latch, final ImageDownloadListener listener) {
ImagePipeline imagePipeline = Fresco.getImagePipeline();
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri).build();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(request, mContext);
DataSubscriber<CloseableReference<CloseableImage>> dataSubscriber =
new BaseDataSubscriber<CloseableReference<CloseableImage>>() {
@Override
protected void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
if (!dataSource.isFinished()) {
return;
}
// If the listener isn't still valid, then return before we fetch the result
// and the memory-intensive bitmap.
if (listener != null && !listener.isValid()) {
return;
}
// If we need to keep track and close any CloseableReferences, but NOT the
// data contained within.
CloseableReference<CloseableImage> result = dataSource.getResult();
CloseableImage image = result.get();
if (image instanceof CloseableBitmap) {
Bitmap bitmap = ((CloseableBitmap) image).getUnderlyingBitmap();
if (listener != null) {
listener.completed(bitmap.copy(mConfig, true));
} else {
Bitmap temp = bitmap.copy(mConfig, true);
if (temp != null) {
mImageMap.put(latch, temp);
}
}
}
result.close();
dataSource.close();
if (latch != null) {
latch.countDown();
}
}
@Override
protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
if (latch != null) {
latch.countDown();
}
Throwable t = dataSource.getFailureCause();
if (listener != null) {
listener.failed(t.getMessage());
}
}
};
dataSource.subscribe(dataSubscriber, mExecutorSupplier.forBackgroundTasks());
}
public void setTextureFormat(Texture.Format format) {
if (format == Texture.Format.RGB565) {
mConfig = Bitmap.Config.RGB_565;
}
else {
mConfig = Bitmap.Config.ARGB_8888;
}
}
}
| android/viro_bridge/src/main/java/com/viromedia/bridge/utility/ImageDownloader.java | /*
* Copyright © 2016 Viro Media. All rights reserved.
*/
package com.viromedia.bridge.utility;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.datasource.DataSubscriber;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.DefaultExecutorSupplier;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.image.CloseableBitmap;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.react.bridge.ReadableMap;
import com.viro.core.Texture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
/**
* This class downloads images and returns them as @{link Bitmap} objects
* by leveraging the Facebook Fresco image downloading/caching library.
*/
public class ImageDownloader {
private static final String TAG = ViroLog.getTag(ImageDownloader.class);
private static final String URI_KEY = "uri";
private final Context mContext;
private final ConcurrentHashMap<CountDownLatch, Bitmap> mImageMap;
private final DefaultExecutorSupplier mExecutorSupplier;
private Bitmap.Config mConfig = Bitmap.Config.ARGB_8888;
public ImageDownloader(Context context) {
mContext = context;
mImageMap = new ConcurrentHashMap<>();
mExecutorSupplier = new DefaultExecutorSupplier(1);
}
/**
* This method fetches an image synchronously.
*
* @param map a ReadableMap with a "uri" key, ideally the same one we get from the JS layer
* @return the bitmap containing the image data
*/
public Bitmap getImageSync(ReadableMap map) {
if (!map.hasKey(URI_KEY)) {
throw new IllegalArgumentException("Unable to find \"uri\" key in given source map.");
}
return getImageSync(Helper.parseUri(map.getString(URI_KEY), mContext));
}
/**
* This method fetches an image synchronously.
*
* @param uri a URI representing the location of the image to fetch.
* @return the bitmap containing the image data.
*/
public Bitmap getImageSync(Uri uri) {
CountDownLatch latch = new CountDownLatch(1);
getImage(uri, latch, null);
try {
latch.await();
} catch (InterruptedException e) {
throw new IllegalStateException("Fetching bitmap was interrupted!");
}
Bitmap toReturn = mImageMap.get(latch);
mImageMap.remove(latch);
if (toReturn != null) {
return toReturn;
} else {
ViroLog.warn(TAG, "Could not download image at: " + uri.toString());
return null;
}
}
/**
* This method fetches an image asynchrously
*
* @param map a ReadableMap with a "uri" key, ideally the same one we get from the JS layer
* @param listener object that will be called once the image is fetched.
*/
public void getImageAsync(ReadableMap map, ImageDownloadListener listener) {
if (listener == null) {
ViroLog.warn(TAG, "The given ImageDownloadListener is null. Doing nothing.");
return;
}
if (!map.hasKey(URI_KEY)) {
throw new IllegalArgumentException("Unable to find \"uri\" key in given source map.");
}
getImage(Helper.parseUri(map.getString(URI_KEY), mContext), null, listener);
}
private void getImage(Uri uri, final CountDownLatch latch, final ImageDownloadListener listener) {
ImagePipeline imagePipeline = Fresco.getImagePipeline();
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri).build();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(request, mContext);
DataSubscriber<CloseableReference<CloseableImage>> dataSubscriber =
new BaseDataSubscriber<CloseableReference<CloseableImage>>() {
@Override
protected void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
if (!dataSource.isFinished()) {
return;
}
// If the listener isn't still valid, then return before we fetch the result
// and the memory-intensive bitmap.
if (listener != null && !listener.isValid()) {
return;
}
// If we need to keep track and close any CloseableReferences, but NOT the
// data contained within.
CloseableReference<CloseableImage> result = dataSource.getResult();
CloseableImage image = result.get();
if (image instanceof CloseableBitmap) {
Bitmap bitmap = ((CloseableBitmap) image).getUnderlyingBitmap();
if (listener != null) {
listener.completed(bitmap.copy(mConfig, true));
} else {
mImageMap.put(latch, bitmap.copy(mConfig, true));
}
}
result.close();
dataSource.close();
if (latch != null) {
latch.countDown();
}
}
@Override
protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
if (latch != null) {
latch.countDown();
}
Throwable t = dataSource.getFailureCause();
if (listener != null) {
listener.failed(t.getMessage());
}
}
};
dataSource.subscribe(dataSubscriber, mExecutorSupplier.forBackgroundTasks());
}
public void setTextureFormat(Texture.Format format) {
if (format == Texture.Format.RGB565) {
mConfig = Bitmap.Config.RGB_565;
}
else {
mConfig = Bitmap.Config.ARGB_8888;
}
}
}
| VIRO-2918 Fix NPE in ImageDownloader
- somehow the Bitmap.copy() failed and returned null, do nothing in that case
Former-commit-id: 62d4753944c49f1299108b9a3b583b48ae2604fa | android/viro_bridge/src/main/java/com/viromedia/bridge/utility/ImageDownloader.java | VIRO-2918 Fix NPE in ImageDownloader |
|
Java | mit | 3ff5953d487502603e04117ac0de3eeb2579fca2 | 0 | AlfiyaZi/LeapMotionP5,AlfiyaZi/LeapMotionP5,AlfiyaZi/LeapMotionP5 | /**
* ##library.name##
* ##library.sentence##
* ##library.url##
*
* Copyright 2013 James Britt / Neurogami
*
* The MIT License (MIT)
*
* 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.
*
*
* @author ##author##
* @modified ##date##
* @version ##library.prettyVersion## (##library.version##)
*/
package com.neurogami.leaphacking;
import com.leapmotion.leap.*;
import processing.core.*;
public class LeapMotionP5 {
// owner is a reference to the parent sketch
PApplet owner;
public Controller defaultController;
public HandList globalHands;
public DefaultListener defaultListener;
public final static String VERSION = "##library.prettyVersion##";
/**
* a Constructor, usually called in the setup() method in your sketch to
* initialize and start the library.
*
* It isn't essential to have this library, as you can just import the library
* and then create Leap Motion class instances on your own.
*
* @example LeapMotionP5
* @param ownerP
*/
public LeapMotionP5(PApplet ownerP) {
owner = ownerP;
defaultListener = new DefaultListener();
defaultListener.owner = ownerP;
defaultController = createController(defaultListener);
}
public LeapMotionP5(PApplet ownerP, boolean useCallbackListener ) {
owner = ownerP;
defaultListener = new DefaultListener();
defaultListener.owner = ownerP;
defaultListener.useFrameCallback = useCallbackListener;
defaultController = createController(defaultListener);
}
public Controller createController(Object listener) {
return( new Controller( (Listener) listener) );
}
public HandList hands() {
return defaultListener.hands();
}
/**
* return the version of the library.
*
* @return String
*/
public static String version() {
return VERSION;
}
}
| src/com/neurogami/leaphacking/LeapMotionP5.java | /**
* ##library.name##
* ##library.sentence##
* ##library.url##
*
* Copyright 2013 James Britt / Neurogami
*
* The MIT License (MIT)
*
* 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.
*
*
* @author ##author##
* @modified ##date##
* @version ##library.prettyVersion## (##library.version##)
*/
package com.neurogami.leaphacking;
import com.leapmotion.leap.*;
import processing.core.*;
public class LeapMotionP5 {
// owner is a reference to the parent sketch
PApplet owner;
public Controller defaultController;
public HandList globalHands;
public DefaultListener defaultListener;
public final static String VERSION = "##library.prettyVersion##";
/**
* a Constructor, usually called in the setup() method in your sketch to
* initialize and start the library.
*
* It isn't essential to have this library, as you can just import the library
* and then create Leap Motion class instances on your own.
*
* @example LeapMotionP5
* @param ownerP
*/
public LeapMotionP5(PApplet ownerP) {
owner = ownerP;
defaultListener = new DefaultListener();
defaultController = createController(defaultListener);
}
public Controller createController(Object listener) {
return( new Controller( (Listener) listener) );
}
public HandList hands() {
return defaultListener.hands();
}
/**
* return the version of the library.
*
* @return String
*/
public static String version() {
return VERSION;
}
}
| Still twerking around with alternative ways to reference Leap objects
| src/com/neurogami/leaphacking/LeapMotionP5.java | Still twerking around with alternative ways to reference Leap objects |
|
Java | mit | def61e9d607e4e2c62329857628f01c1ad2ddd83 | 0 | ceyhuno/react-native-navigation,3sidedcube/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,thanhzusu/react-native-navigation,ceyhuno/react-native-navigation,chicojasl/react-native-navigation,Jpoliachik/react-native-navigation,Jpoliachik/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,thanhzusu/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,3sidedcube/react-native-navigation,chicojasl/react-native-navigation,ceyhuno/react-native-navigation,thanhzusu/react-native-navigation,thanhzusu/react-native-navigation,guyca/react-native-navigation,thanhzusu/react-native-navigation,guyca/react-native-navigation,wix/react-native-navigation,Jpoliachik/react-native-navigation,thanhzusu/react-native-navigation,3sidedcube/react-native-navigation,3sidedcube/react-native-navigation,Jpoliachik/react-native-navigation,Jpoliachik/react-native-navigation,chicojasl/react-native-navigation,Jpoliachik/react-native-navigation,wix/react-native-navigation,ceyhuno/react-native-navigation,wix/react-native-navigation,guyca/react-native-navigation,guyca/react-native-navigation,ceyhuno/react-native-navigation,ceyhuno/react-native-navigation | package com.reactnativenavigation.react;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Collections;
import java.util.List;
public class NavigationPackage implements ReactPackage {
private ReactNativeHost reactNativeHost;
@SuppressWarnings("WeakerAccess")
public NavigationPackage(final ReactNativeHost reactNativeHost) {
this.reactNativeHost = reactNativeHost;
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Collections.singletonList(new NavigationModule(reactContext, reactNativeHost.getReactInstanceManager()));
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
| lib/android/app/src/main/java/com/reactnativenavigation/react/NavigationPackage.java | package com.reactnativenavigation.react;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NavigationPackage implements ReactPackage {
private ReactNativeHost reactNativeHost;
public NavigationPackage(final ReactNativeHost reactNativeHost) {
this.reactNativeHost = reactNativeHost;
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new NavigationModule(reactContext, reactNativeHost.getReactInstanceManager())
);
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
| Drop RN 0.46 support
| lib/android/app/src/main/java/com/reactnativenavigation/react/NavigationPackage.java | Drop RN 0.46 support |
|
Java | mit | 227337d4899ce93520404edf2fb79f66be8cde45 | 0 | kazyx/wirespider | /*
* WireSpider
*
* Copyright (c) 2015 kazyx
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*/
package net.kazyx.wirespider;
import net.kazyx.wirespider.extension.ExtensionRequest;
import net.kazyx.wirespider.extension.compression.CompressionStrategy;
import net.kazyx.wirespider.extension.compression.DeflateRequest;
import net.kazyx.wirespider.extension.compression.PerMessageDeflate;
import net.kazyx.wirespider.util.Base64;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
public class ExtensionDeflateTest {
public static class CompressorTest {
private PerMessageDeflate mCompression;
@Before
public void setup() {
mCompression = new PerMessageDeflate(null);
}
@Test
public void compressDecompress() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append("TestMessage");
}
byte[] source = sb.toString().getBytes("UTF-8");
ByteBuffer compressed = mCompression.compress(ByteBuffer.wrap(source));
System.out.println("Compressed: " + source.length + " to " + compressed.remaining());
ByteBuffer decompressed = mCompression.decompress(compressed);
System.out.println("Decompressed: " + decompressed.capacity());
assertThat(Arrays.equals(source, decompressed.array()), is(true));
}
@Test
public void compressDecompress2() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append("TestMessage");
}
byte[] source = sb.toString().getBytes("UTF-8");
ByteBuffer compressed = mCompression.compress(ByteBuffer.wrap(source));
System.out.println("Compressed: " + source.length + " to " + compressed.remaining());
ByteBuffer decompressed = mCompression.decompress(compressed);
System.out.println("Decompressed: " + decompressed.capacity());
assertThat(Arrays.equals(source, decompressed.array()), is(true));
compressed = mCompression.compress(ByteBuffer.wrap(source));
System.out.println("Compressed: " + source.length + " to " + compressed.remaining());
decompressed = mCompression.decompress(compressed);
System.out.println("Decompressed: " + decompressed.capacity());
assertThat(Arrays.equals(source, decompressed.array()), is(true));
}
}
public static class BuilderTest {
@Test(expected = UnsupportedOperationException.class)
public void maxClientWindowBits() {
new DeflateRequest.Builder().setMaxClientWindowBits(10);
}
@Test(expected = IllegalArgumentException.class)
public void maxServerWindowBitsLow() {
new DeflateRequest.Builder().setMaxServerWindowBits(7);
}
@Test(expected = IllegalArgumentException.class)
public void maxServerWindowBitsHigh() {
new DeflateRequest.Builder().setMaxServerWindowBits(16);
}
@Test
public void maxServerWindowBitsInRange() {
new DeflateRequest.Builder()
.setMaxServerWindowBits(8)
.setMaxServerWindowBits(9)
.setMaxServerWindowBits(10)
.setMaxServerWindowBits(11)
.setMaxServerWindowBits(12)
.setMaxServerWindowBits(13)
.setMaxServerWindowBits(14)
.setMaxServerWindowBits(15);
}
}
public static class IntegrationDeflateTest {
private static TestWebSocketServer server = new TestWebSocketServer(10000);
@BeforeClass
public static void setupClass() throws Exception {
Base64.setEncoder(new Base64Encoder());
server.registerExtension(TestWebSocketServer.Extension.DEFLATE);
server.boot();
}
@AfterClass
public static void teardownClass() throws Exception {
server.shutdown();
}
@Test
public void fixedTextCompressionWindow15() throws ExecutionException, InterruptedException, TimeoutException, IOException {
fixedTextCompressionByWindowSize(15, 4096);
}
@Test
public void fixedTextCompressionWindow8() throws ExecutionException, InterruptedException, TimeoutException, IOException {
fixedTextCompressionByWindowSize(8, 4096);
}
@Test
public void smallText() throws InterruptedException, ExecutionException, TimeoutException, IOException {
fixedTextCompressionByWindowSize(15, 1);
}
private void fixedTextCompressionByWindowSize(int windowSize, int msgSize) throws IOException, InterruptedException, ExecutionException, TimeoutException {
final CustomLatch latch = new CustomLatch(1);
final String data = TestUtil.fixedLengthFixedString(msgSize);
DeflateRequest extReq = new DeflateRequest.Builder()
.setMaxServerWindowBits(windowSize)
.setStrategy(new CompressionStrategy() {
@Override
public int minSizeInBytes() {
return 100;
}
})
.build();
SessionRequest seed = new SessionRequest.Builder(URI.create("ws://127.0.0.1:10000"), new SilentEventHandler() {
@Override
public void onClosed(int code, String reason) {
latch.unlockByFailure();
}
@Override
public void onTextMessage(String message) {
if (data.equals(message)) {
latch.countDown();
} else {
System.out.println("Text message not matched");
latch.unlockByFailure();
}
}
}).setExtensions(Collections.<ExtensionRequest>singletonList(extReq))
.setMaxResponsePayloadSizeInBytes(msgSize * 5)
.build();
WebSocketFactory factory = new WebSocketFactory();
WebSocket ws = null;
try {
Future<WebSocket> future = factory.openAsync(seed);
ws = future.get(1000, TimeUnit.MILLISECONDS);
assertThat(ws.extensions().size(), is(1));
assertThat(ws.extensions().get(0), instanceOf(PerMessageDeflate.class));
ws.sendTextMessageAsync(data);
assertThat(latch.await(10000, TimeUnit.MILLISECONDS), is(true));
assertThat(latch.isUnlockedByFailure(), is(false));
} finally {
if (ws != null) {
ws.closeNow();
}
factory.destroy();
}
}
@Test
public void randomTextCompressionWindow15() throws ExecutionException, InterruptedException, TimeoutException, IOException {
randomTextCompressionByWindowSize(15);
}
@Test
public void randomTextCompressionWindow8() throws ExecutionException, InterruptedException, TimeoutException, IOException {
randomTextCompressionByWindowSize(8);
}
private void randomTextCompressionByWindowSize(int size) throws IOException, InterruptedException, ExecutionException, TimeoutException {
final int MESSAGE_SIZE = 4096;
final CustomLatch latch = new CustomLatch(1);
final String data = TestUtil.fixedLengthRandomString(MESSAGE_SIZE);
DeflateRequest extReq = new DeflateRequest.Builder()
.setMaxServerWindowBits(size)
.build();
SessionRequest seed = new SessionRequest.Builder(URI.create("ws://127.0.0.1:10000"), new SilentEventHandler() {
@Override
public void onClosed(int code, String reason) {
latch.unlockByFailure();
}
@Override
public void onTextMessage(String message) {
if (data.equals(message)) {
latch.countDown();
} else {
System.out.println("Text message not matched");
latch.unlockByFailure();
}
}
}).setExtensions(Collections.<ExtensionRequest>singletonList(extReq))
.setMaxResponsePayloadSizeInBytes(MESSAGE_SIZE * 5)
.build();
WebSocketFactory factory = new WebSocketFactory();
WebSocket ws = null;
try {
Future<WebSocket> future = factory.openAsync(seed);
ws = future.get(1000, TimeUnit.MILLISECONDS);
assertThat(ws.extensions().size(), is(1));
assertThat(ws.extensions().get(0), instanceOf(PerMessageDeflate.class));
ws.sendTextMessageAsync(data);
assertThat(latch.await(10000, TimeUnit.MILLISECONDS), is(true));
assertThat(latch.isUnlockedByFailure(), is(false));
} finally {
if (ws != null) {
ws.closeNow();
}
factory.destroy();
}
}
@Test
public void fixedBinaryCompressionWindow8() throws InterruptedException, ExecutionException, TimeoutException, IOException {
fixedBinaryCompressionByWindowSize(8, 4096);
}
@Test
public void fixedBinaryCompressionWindow15() throws InterruptedException, ExecutionException, TimeoutException, IOException {
fixedBinaryCompressionByWindowSize(15, 4096);
}
@Test
public void smallBinary() throws InterruptedException, ExecutionException, TimeoutException, IOException {
fixedBinaryCompressionByWindowSize(15, 1);
}
private void fixedBinaryCompressionByWindowSize(int serverWindowSize, final int msgSize) throws ExecutionException, InterruptedException, TimeoutException, IOException {
final CustomLatch latch = new CustomLatch(1);
final byte[] data = TestUtil.fixedLengthFixedByteArray(msgSize);
final byte[] copy = Arrays.copyOf(data, data.length);
DeflateRequest extReq = new DeflateRequest.Builder()
.setMaxServerWindowBits(serverWindowSize)
.setStrategy(new CompressionStrategy() {
@Override
public int minSizeInBytes() {
return 100;
}
})
.build();
SessionRequest seed = new SessionRequest.Builder(URI.create("ws://127.0.0.1:10000"), new SilentEventHandler() {
@Override
public void onClosed(int code, String reason) {
latch.unlockByFailure();
}
@Override
public void onBinaryMessage(byte[] message) {
if (Arrays.equals(copy, message)) {
latch.countDown();
} else {
System.out.println("Text message not matched");
latch.unlockByFailure();
}
}
}).setExtensions(Collections.<ExtensionRequest>singletonList(extReq))
.setMaxResponsePayloadSizeInBytes(msgSize * 5)
.build();
WebSocketFactory factory = new WebSocketFactory();
WebSocket ws = null;
try {
Future<WebSocket> future = factory.openAsync(seed);
ws = future.get(1000, TimeUnit.MILLISECONDS);
assertThat(ws.handshake().extensions().size(), is(1));
assertThat(ws.handshake().extensions().get(0), instanceOf(PerMessageDeflate.class));
ws.sendBinaryMessageAsync(data);
assertThat(latch.await(10000, TimeUnit.MILLISECONDS), is(true));
assertThat(latch.isUnlockedByFailure(), is(false));
} finally {
if (ws != null) {
ws.closeNow();
}
factory.destroy();
}
}
@Test
public void randomBinaryCompressionWindow8() throws InterruptedException, ExecutionException, TimeoutException, IOException {
randomBinaryCompressionByWindowSize(8);
}
@Test
public void randomBinaryCompressionWindow15() throws InterruptedException, ExecutionException, TimeoutException, IOException {
randomBinaryCompressionByWindowSize(15);
}
private void randomBinaryCompressionByWindowSize(int size) throws ExecutionException, InterruptedException, TimeoutException, IOException {
final int MESSAGE_SIZE = 4096;
final CustomLatch latch = new CustomLatch(1);
final byte[] data = TestUtil.fixedLengthRandomByteArray(MESSAGE_SIZE);
final byte[] copy = Arrays.copyOf(data, data.length);
DeflateRequest extReq = new DeflateRequest.Builder()
.setMaxServerWindowBits(size)
.build();
SessionRequest seed = new SessionRequest.Builder(URI.create("ws://127.0.0.1:10000"), new SilentEventHandler() {
@Override
public void onClosed(int code, String reason) {
latch.unlockByFailure();
}
@Override
public void onBinaryMessage(byte[] message) {
if (Arrays.equals(copy, message)) {
latch.countDown();
} else {
System.out.println("Text message not matched");
latch.unlockByFailure();
}
}
}).setExtensions(Collections.<ExtensionRequest>singletonList(extReq))
.setMaxResponsePayloadSizeInBytes(MESSAGE_SIZE * 5)
.build();
WebSocketFactory factory = new WebSocketFactory();
WebSocket ws = null;
try {
Future<WebSocket> future = factory.openAsync(seed);
ws = future.get(1000, TimeUnit.MILLISECONDS);
assertThat(ws.handshake().extensions().size(), is(1));
assertThat(ws.handshake().extensions().get(0), instanceOf(PerMessageDeflate.class));
ws.sendBinaryMessageAsync(data);
assertThat(latch.await(10000, TimeUnit.MILLISECONDS), is(true));
assertThat(latch.isUnlockedByFailure(), is(false));
} finally {
if (ws != null) {
ws.closeNow();
}
factory.destroy();
}
}
}
public static class CompressionStrategyTest {
private static final int SIZE_BASE = 200;
private PerMessageDeflate mCompression;
@Before
public void setup() {
mCompression = new PerMessageDeflate(new CompressionStrategy() {
@Override
public int minSizeInBytes() {
return SIZE_BASE;
}
});
}
@Test(expected = IOException.class)
public void dataSizeSmallerThanCompressionMinRange() throws IOException {
final byte[] original = TestUtil.fixedLengthFixedByteArray(SIZE_BASE - 1);
mCompression.compress(ByteBuffer.wrap(original)).array();
}
@Test
public void dataSizeEqualsCompressionMinRange() throws IOException {
final byte[] original = TestUtil.fixedLengthFixedByteArray(SIZE_BASE);
final byte[] copy = Arrays.copyOf(original, original.length);
byte[] compressed = mCompression.compress(ByteBuffer.wrap(original)).array();
assertThat(Arrays.equals(copy, compressed), is(false));
}
@Test
public void dataSizeLargerThanCompressionMinRange() throws IOException {
final byte[] original = TestUtil.fixedLengthFixedByteArray(SIZE_BASE + 1);
final byte[] copy = Arrays.copyOf(original, original.length);
byte[] compressed = mCompression.compress(ByteBuffer.wrap(original)).array();
assertThat(Arrays.equals(copy, compressed), is(false));
}
@Test(expected = IOException.class)
public void requestBuilder() throws IOException {
CompressionStrategy strategy = new CompressionStrategy() {
@Override
public int minSizeInBytes() {
return 2;
}
};
DeflateRequest req = new DeflateRequest.Builder()
.setStrategy(strategy)
.build();
PerMessageDeflate deflate = ((PerMessageDeflate) req.extension());
byte[] one = {(byte) 0x11};
assertThat(Arrays.equals(deflate.compress(ByteBuffer.wrap(one)).array(), one), is(true));
}
}
}
| wirespider/permessage-deflate/src/test/java/net/kazyx/wirespider/ExtensionDeflateTest.java | /*
* WireSpider
*
* Copyright (c) 2015 kazyx
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*/
package net.kazyx.wirespider;
import net.kazyx.wirespider.extension.ExtensionRequest;
import net.kazyx.wirespider.extension.compression.CompressionStrategy;
import net.kazyx.wirespider.extension.compression.DeflateRequest;
import net.kazyx.wirespider.extension.compression.PerMessageDeflate;
import net.kazyx.wirespider.util.Base64;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
public class ExtensionDeflateTest {
public static class CompressorTest {
private PerMessageDeflate mCompression;
@Before
public void setup() {
mCompression = new PerMessageDeflate(null);
}
@Test
public void compressDecompress() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append("TestMessage");
}
byte[] source = sb.toString().getBytes("UTF-8");
ByteBuffer compressed = mCompression.compress(ByteBuffer.wrap(source));
System.out.println("Compressed: " + source.length + " to " + compressed.remaining());
ByteBuffer decompressed = mCompression.decompress(compressed);
System.out.println("Decompressed: " + decompressed.capacity());
assertThat(Arrays.equals(source, decompressed.array()), is(true));
}
@Test
public void compressDecompress2() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append("TestMessage");
}
byte[] source = sb.toString().getBytes("UTF-8");
ByteBuffer compressed = mCompression.compress(ByteBuffer.wrap(source));
System.out.println("Compressed: " + source.length + " to " + compressed.remaining());
ByteBuffer decompressed = mCompression.decompress(compressed);
System.out.println("Decompressed: " + decompressed.capacity());
assertThat(Arrays.equals(source, decompressed.array()), is(true));
compressed = mCompression.compress(ByteBuffer.wrap(source));
System.out.println("Compressed: " + source.length + " to " + compressed.remaining());
decompressed = mCompression.decompress(compressed);
System.out.println("Decompressed: " + decompressed.capacity());
assertThat(Arrays.equals(source, decompressed.array()), is(true));
}
}
public static class BuilderTest {
@Test(expected = UnsupportedOperationException.class)
public void maxClientWindowBits() {
new DeflateRequest.Builder().setMaxClientWindowBits(10);
}
@Test(expected = IllegalArgumentException.class)
public void maxServerWindowBitsLow() {
new DeflateRequest.Builder().setMaxServerWindowBits(7);
}
@Test(expected = IllegalArgumentException.class)
public void maxServerWindowBitsHigh() {
new DeflateRequest.Builder().setMaxServerWindowBits(16);
}
@Test
public void maxServerWindowBitsInRange() {
new DeflateRequest.Builder()
.setMaxServerWindowBits(8)
.setMaxServerWindowBits(9)
.setMaxServerWindowBits(10)
.setMaxServerWindowBits(11)
.setMaxServerWindowBits(12)
.setMaxServerWindowBits(13)
.setMaxServerWindowBits(14)
.setMaxServerWindowBits(15);
}
}
public static class IntegrationDeflateTest {
private static TestWebSocketServer server = new TestWebSocketServer(10000);
@BeforeClass
public static void setupClass() throws Exception {
Base64.setEncoder(new Base64Encoder());
server.registerExtension(TestWebSocketServer.Extension.DEFLATE);
server.boot();
}
@AfterClass
public static void teardownClass() throws Exception {
server.shutdown();
}
@Test
public void fixedTextCompressionWindow15() throws ExecutionException, InterruptedException, TimeoutException, IOException {
fixedTextCompressionByWindowSize(15, 4096);
}
@Test
public void fixedTextCompressionWindow8() throws ExecutionException, InterruptedException, TimeoutException, IOException {
fixedTextCompressionByWindowSize(8, 4096);
}
@Test
public void smallText() throws InterruptedException, ExecutionException, TimeoutException, IOException {
fixedTextCompressionByWindowSize(15, 1);
}
private void fixedTextCompressionByWindowSize(int windowSize, int msgSize) throws IOException, InterruptedException, ExecutionException, TimeoutException {
final CustomLatch latch = new CustomLatch(1);
final String data = TestUtil.fixedLengthFixedString(msgSize);
DeflateRequest extReq = new DeflateRequest.Builder()
.setMaxServerWindowBits(windowSize)
.setStrategy(new CompressionStrategy() {
@Override
public int minSizeInBytes() {
return 100;
}
})
.build();
SessionRequest seed = new SessionRequest.Builder(URI.create("ws://127.0.0.1:10000"), new SilentEventHandler() {
@Override
public void onClosed(int code, String reason) {
latch.unlockByFailure();
}
@Override
public void onTextMessage(String message) {
if (data.equals(message)) {
latch.countDown();
} else {
System.out.println("Text message not matched");
latch.unlockByFailure();
}
}
}).setExtensions(Collections.<ExtensionRequest>singletonList(extReq))
.setMaxResponsePayloadSizeInBytes(msgSize * 5)
.build();
WebSocketFactory factory = new WebSocketFactory();
WebSocket ws = null;
try {
Future<WebSocket> future = factory.openAsync(seed);
ws = future.get(1000, TimeUnit.MILLISECONDS);
assertThat(ws.extensions().size(), is(1));
assertThat(ws.extensions().get(0), instanceOf(PerMessageDeflate.class));
ws.sendTextMessageAsync(data);
assertThat(latch.await(10000, TimeUnit.MILLISECONDS), is(true));
assertThat(latch.isUnlockedByFailure(), is(false));
} finally {
if (ws != null) {
ws.closeNow();
}
factory.destroy();
}
}
@Test
public void randomTextCompressionWindow15() throws ExecutionException, InterruptedException, TimeoutException, IOException {
randomTextCompressionByWindowSize(15);
}
@Test
public void randomTextCompressionWindow8() throws ExecutionException, InterruptedException, TimeoutException, IOException {
randomTextCompressionByWindowSize(8);
}
private void randomTextCompressionByWindowSize(int size) throws IOException, InterruptedException, ExecutionException, TimeoutException {
final int MESSAGE_SIZE = 4096;
final CustomLatch latch = new CustomLatch(1);
final String data = TestUtil.fixedLengthRandomString(MESSAGE_SIZE);
DeflateRequest extReq = new DeflateRequest.Builder()
.setMaxServerWindowBits(size)
.build();
SessionRequest seed = new SessionRequest.Builder(URI.create("ws://127.0.0.1:10000"), new SilentEventHandler() {
@Override
public void onClosed(int code, String reason) {
latch.unlockByFailure();
}
@Override
public void onTextMessage(String message) {
if (data.equals(message)) {
latch.countDown();
} else {
System.out.println("Text message not matched");
latch.unlockByFailure();
}
}
}).setExtensions(Collections.<ExtensionRequest>singletonList(extReq))
.setMaxResponsePayloadSizeInBytes(MESSAGE_SIZE * 5)
.build();
WebSocketFactory factory = new WebSocketFactory();
WebSocket ws = null;
try {
Future<WebSocket> future = factory.openAsync(seed);
ws = future.get(1000, TimeUnit.MILLISECONDS);
assertThat(ws.extensions().size(), is(1));
assertThat(ws.extensions().get(0), instanceOf(PerMessageDeflate.class));
ws.sendTextMessageAsync(data);
assertThat(latch.await(10000, TimeUnit.MILLISECONDS), is(true));
assertThat(latch.isUnlockedByFailure(), is(false));
} finally {
if (ws != null) {
ws.closeNow();
}
factory.destroy();
}
}
@Test
public void fixedBinaryCompressionWindow8() throws InterruptedException, ExecutionException, TimeoutException, IOException {
fixedBinaryCompressionByWindowSize(8, 4096);
}
@Test
public void fixedBinaryCompressionWindow15() throws InterruptedException, ExecutionException, TimeoutException, IOException {
fixedBinaryCompressionByWindowSize(15, 4096);
}
@Test
public void smallBinary() throws InterruptedException, ExecutionException, TimeoutException, IOException {
fixedBinaryCompressionByWindowSize(15, 1);
}
private void fixedBinaryCompressionByWindowSize(int serverWindowSize, final int msgSize) throws ExecutionException, InterruptedException, TimeoutException, IOException {
final CustomLatch latch = new CustomLatch(1);
final byte[] data = TestUtil.fixedLengthFixedByteArray(msgSize);
final byte[] copy = Arrays.copyOf(data, data.length);
DeflateRequest extReq = new DeflateRequest.Builder()
.setMaxServerWindowBits(serverWindowSize)
.setStrategy(new CompressionStrategy() {
@Override
public int minSizeInBytes() {
return 100;
}
})
.build();
SessionRequest seed = new SessionRequest.Builder(URI.create("ws://127.0.0.1:10000"), new SilentEventHandler() {
@Override
public void onClosed(int code, String reason) {
latch.unlockByFailure();
}
@Override
public void onBinaryMessage(byte[] message) {
if (Arrays.equals(copy, message)) {
latch.countDown();
} else {
System.out.println("Text message not matched");
latch.unlockByFailure();
}
}
}).setExtensions(Collections.<ExtensionRequest>singletonList(extReq))
.setMaxResponsePayloadSizeInBytes(msgSize * 5)
.build();
WebSocketFactory factory = new WebSocketFactory();
WebSocket ws = null;
try {
Future<WebSocket> future = factory.openAsync(seed);
ws = future.get(1000, TimeUnit.MILLISECONDS);
assertThat(ws.handshake().extensions().size(), is(1));
assertThat(ws.handshake().extensions().get(0), instanceOf(PerMessageDeflate.class));
ws.sendBinaryMessageAsync(data);
assertThat(latch.await(10000, TimeUnit.MILLISECONDS), is(true));
assertThat(latch.isUnlockedByFailure(), is(false));
} finally {
if (ws != null) {
ws.closeNow();
}
factory.destroy();
}
}
@Test
public void randomBinaryCompressionWindow8() throws InterruptedException, ExecutionException, TimeoutException, IOException {
randomBinaryCompressionByWindowSize(8);
}
@Test
public void randomBinaryCompressionWindow15() throws InterruptedException, ExecutionException, TimeoutException, IOException {
randomBinaryCompressionByWindowSize(15);
}
private void randomBinaryCompressionByWindowSize(int size) throws ExecutionException, InterruptedException, TimeoutException, IOException {
final int MESSAGE_SIZE = 4096;
final CustomLatch latch = new CustomLatch(1);
final byte[] data = TestUtil.fixedLengthRandomByteArray(MESSAGE_SIZE);
final byte[] copy = Arrays.copyOf(data, data.length);
DeflateRequest extReq = new DeflateRequest.Builder()
.setMaxServerWindowBits(size)
.build();
SessionRequest seed = new SessionRequest.Builder(URI.create("ws://127.0.0.1:10000"), new SilentEventHandler() {
@Override
public void onClosed(int code, String reason) {
latch.unlockByFailure();
}
@Override
public void onBinaryMessage(byte[] message) {
if (Arrays.equals(copy, message)) {
latch.countDown();
} else {
System.out.println("Text message not matched");
latch.unlockByFailure();
}
}
}).setExtensions(Collections.<ExtensionRequest>singletonList(extReq))
.setMaxResponsePayloadSizeInBytes(MESSAGE_SIZE * 5)
.build();
WebSocketFactory factory = new WebSocketFactory();
WebSocket ws = null;
try {
Future<WebSocket> future = factory.openAsync(seed);
ws = future.get(1000, TimeUnit.MILLISECONDS);
assertThat(ws.handshake().extensions().size(), is(1));
assertThat(ws.handshake().extensions().get(0), instanceOf(PerMessageDeflate.class));
ws.sendBinaryMessageAsync(data);
assertThat(latch.await(10000, TimeUnit.MILLISECONDS), is(true));
assertThat(latch.isUnlockedByFailure(), is(false));
} finally {
if (ws != null) {
ws.closeNow();
}
factory.destroy();
}
}
}
public static class CompressionStrategyTest {
private static final int SIZE_BASE = 200;
private PerMessageDeflate mCompression;
@Before
public void setup() {
mCompression = new PerMessageDeflate(new CompressionStrategy() {
@Override
public int minSizeInBytes() {
return SIZE_BASE;
}
});
}
@Test
public void dataSizeSmallerThanCompressionMinRange() throws IOException {
final byte[] original = TestUtil.fixedLengthFixedByteArray(SIZE_BASE - 1);
final byte[] copy = Arrays.copyOf(original, original.length);
byte[] compressed = mCompression.compress(ByteBuffer.wrap(original)).array();
assertThat(Arrays.equals(copy, compressed), is(true)); // If data size is smaller than min, it should not be compressed.
}
@Test
public void dataSizeEqualsCompressionMinRange() throws IOException {
final byte[] original = TestUtil.fixedLengthFixedByteArray(SIZE_BASE);
final byte[] copy = Arrays.copyOf(original, original.length);
byte[] compressed = mCompression.compress(ByteBuffer.wrap(original)).array();
assertThat(Arrays.equals(copy, compressed), is(false));
}
@Test
public void dataSizeLargerThanCompressionMinRange() throws IOException {
final byte[] original = TestUtil.fixedLengthFixedByteArray(SIZE_BASE + 1);
final byte[] copy = Arrays.copyOf(original, original.length);
byte[] compressed = mCompression.compress(ByteBuffer.wrap(original)).array();
assertThat(Arrays.equals(copy, compressed), is(false));
}
@Test
public void requestBuilder() throws IOException {
CompressionStrategy storategy = new CompressionStrategy() {
@Override
public int minSizeInBytes() {
return 2;
}
};
DeflateRequest req = new DeflateRequest.Builder()
.setStrategy(storategy)
.build();
PerMessageDeflate deflate = ((PerMessageDeflate) req.extension());
byte[] one = {(byte) 0x11};
assertThat(Arrays.equals(deflate.compress(ByteBuffer.wrap(one)).array(), one), is(true));
byte[] two = {(byte) 0x11, (byte) 0x11};
assertThat(Arrays.equals(deflate.compress(ByteBuffer.wrap(two)).array(), two), is(false));
}
}
}
| Fix permessage-deflate test
| wirespider/permessage-deflate/src/test/java/net/kazyx/wirespider/ExtensionDeflateTest.java | Fix permessage-deflate test |
|
Java | mit | fb94351c9c6509aeae7c1d2231b656e72c0f3d6b | 0 | bcgit/bc-java,bcgit/bc-java,bcgit/bc-java | package org.bouncycastle.jce.provider.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.DSAParameterSpec;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;
import org.bouncycastle.crypto.params.DSAParameters;
import org.bouncycastle.crypto.params.DSAPublicKeyParameters;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.signers.DSASigner;
import org.bouncycastle.internal.asn1.eac.EACObjectIdentifiers;
import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.BigIntegers;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.FixedSecureRandom;
import org.bouncycastle.util.test.SimpleTest;
import org.bouncycastle.util.test.TestRandomBigInteger;
import org.bouncycastle.util.test.TestRandomData;
public class DSATest
extends SimpleTest
{
byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3");
byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded");
SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 });
// DSA modified signatures, courtesy of the Google security team
static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec(
// x
new BigInteger(
"15382583218386677486843706921635237927801862255437148328980464126979"),
// p
new BigInteger(
"181118486631420055711787706248812146965913392568235070235446058914"
+ "1170708161715231951918020125044061516370042605439640379530343556"
+ "4101919053459832890139496933938670005799610981765220283775567361"
+ "4836626483403394052203488713085936276470766894079318754834062443"
+ "1033792580942743268186462355159813630244169054658542719322425431"
+ "4088256212718983105131138772434658820375111735710449331518776858"
+ "7867938758654181244292694091187568128410190746310049564097068770"
+ "8161261634790060655580211122402292101772553741704724263582994973"
+ "9109274666495826205002104010355456981211025738812433088757102520"
+ "562459649777989718122219159982614304359"),
// q
new BigInteger(
"19689526866605154788513693571065914024068069442724893395618704484701"),
// g
new BigInteger(
"2859278237642201956931085611015389087970918161297522023542900348"
+ "0877180630984239764282523693409675060100542360520959501692726128"
+ "3149190229583566074777557293475747419473934711587072321756053067"
+ "2532404847508798651915566434553729839971841903983916294692452760"
+ "2490198571084091890169933809199002313226100830607842692992570749"
+ "0504363602970812128803790973955960534785317485341020833424202774"
+ "0275688698461842637641566056165699733710043802697192696426360843"
+ "1736206792141319514001488556117408586108219135730880594044593648"
+ "9237302749293603778933701187571075920849848690861126195402696457"
+ "4111219599568903257472567764789616958430"));
static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec(
new BigInteger(
"3846308446317351758462473207111709291533523711306097971550086650"
+ "2577333637930103311673872185522385807498738696446063139653693222"
+ "3528823234976869516765207838304932337200968476150071617737755913"
+ "3181601169463467065599372409821150709457431511200322947508290005"
+ "1780020974429072640276810306302799924668893998032630777409440831"
+ "4314588994475223696460940116068336991199969153649625334724122468"
+ "7497038281983541563359385775312520539189474547346202842754393945"
+ "8755803223951078082197762886933401284142487322057236814878262166"
+ "5072306622943221607031324846468109901964841479558565694763440972"
+ "5447389416166053148132419345627682740529"),
PRIVATE_KEY.getP(),
PRIVATE_KEY.getQ(),
PRIVATE_KEY.getG());
// The following test vectors check for signature malleability and bugs. That means the test
// vectors are derived from a valid signature by modifying the ASN encoding. A correct
// implementation of DSA should only accept correct DER encoding and properly handle the others.
// Allowing alternative BER encodings is in many cases benign. An example where this kind of
// signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability
static final String[] MODIFIED_SIGNATURES = {
"303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f"
+ "9ef41dd424a4e1c8f16967cf3365813fe8786236",
"303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f"
+ "9ef41dd424a4e1c8f16967cf3365813fe8786236",
"303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f"
+ "9ef41dd424a4e1c8f16967cf3365813fe8786236",
"303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4"
+ "1dd424a4e1c8f16967cf3365813fe87862360000",
"3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100",
"303e021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca802811d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3"
};
private void testModified()
throws Exception
{
KeyFactory kFact = KeyFactory.getInstance("DSA", "BC");
PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY);
Signature sig = Signature.getInstance("DSA", "BC");
for (int i = 0; i != MODIFIED_SIGNATURES.length; i++)
{
sig.initVerify(pubKey);
sig.update(Strings.toByteArray("Hello"));
boolean failed;
try
{
failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i]));
}
catch (SignatureException e)
{
failed = true;
}
isTrue("sig verified when shouldn't", failed);
}
}
private void testCompat()
throws Exception
{
if (Security.getProvider("SUN") == null)
{
return;
}
Signature s = Signature.getInstance("DSA", "SUN");
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
g.initialize(512, new SecureRandom());
KeyPair p = g.generateKeyPair();
PrivateKey sKey = p.getPrivate();
PublicKey vKey = p.getPublic();
//
// sign SUN - verify with BC
//
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("DSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("SUN -> BC verification failed");
}
//
// sign BC - verify with SUN
//
s.initSign(sKey);
s.update(data);
sigBytes = s.sign();
s = Signature.getInstance("DSA", "SUN");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("BC -> SUN verification failed");
}
//
// key encoding test - BC decoding Sun keys
//
KeyFactory f = KeyFactory.getInstance("DSA", "BC");
X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded());
DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s);
checkPublic(k1, vKey);
PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded());
DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8);
checkPrivateKey(k2, sKey);
//
// key decoding test - SUN decoding BC keys
//
f = KeyFactory.getInstance("DSA", "SUN");
x509s = new X509EncodedKeySpec(k1.getEncoded());
vKey = (DSAPublicKey)f.generatePublic(x509s);
checkPublic(k1, vKey);
pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded());
sKey = f.generatePrivate(pkcs8);
checkPrivateKey(k2, sKey);
}
private void testNullParameters()
throws Exception
{
KeyFactory f = KeyFactory.getInstance("DSA", "BC");
X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded());
DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s);
DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s);
isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null);
isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode());
isTrue("not equal", key1.equals(key2));
isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded()));
}
private void testValidate()
throws Exception
{
DSAParameterSpec dsaParams = new DSAParameterSpec(
new BigInteger(
"F56C2A7D366E3EBDEAA1891FD2A0D099" +
"436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
"D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
"69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
"5909132627F51A0C866877E672E555342BDF9355347DBD43" +
"B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
"31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
"EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
"F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
"1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
"531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16),
new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16),
new BigInteger(
"8DC6CC814CAE4A1C05A3E186A6FE27EA" +
"BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
"29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
"6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
"513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
"7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
"A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
"45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
"FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
"428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
"EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)
);
KeyFactory f = KeyFactory.getInstance("DSA", "BC");
try
{
f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ()));
fail("no exception");
}
catch (Exception e)
{
isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage()));
}
}
private void testNONEwithDSA()
throws Exception
{
byte[] dummySha1 = Hex.decode("01020304050607080910111213141516");
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC");
kpGen.initialize(512);
KeyPair kp = kpGen.generateKeyPair();
Signature sig = Signature.getInstance("NONEwithDSA", "BC");
sig.initSign(kp.getPrivate());
sig.update(dummySha1);
byte[] sigBytes = sig.sign();
sig.initVerify(kp.getPublic());
sig.update(dummySha1);
sig.verify(sigBytes);
// reset test
sig.update(dummySha1);
if (!sig.verify(sigBytes))
{
fail("NONEwithDSA failed to reset");
}
// lightweight test
DSAPublicKey key = (DSAPublicKey)kp.getPublic();
DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG());
DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params);
DSASigner signer = new DSASigner();
ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes));
signer.init(false, keyParams);
if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue()))
{
fail("NONEwithDSA not really NONE!");
}
}
private void testRIPEMD160withDSA()
throws Exception
{
byte[] msg = Hex.decode("01020304050607080910111213141516");
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
Signature sig = Signature.getInstance("RIPEMD160withDSA", "BC");
sig.initSign(kp.getPrivate());
sig.update(msg);
byte[] sigBytes = sig.sign();
sig.initVerify(kp.getPublic());
sig.update(msg);
isTrue(sig.verify(sigBytes));
// reset test
sig.update(msg);
if (!sig.verify(sigBytes))
{
fail("NONEwithDSA failed to reset");
}
// lightweight test
RIPEMD160Digest dig = new RIPEMD160Digest();
byte[] digest = new byte[dig.getDigestSize()];
dig.update(msg, 0, msg.length);
dig.doFinal(digest, 0);
DSAPublicKey key = (DSAPublicKey)kp.getPublic();
DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG());
DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params);
DSASigner signer = new DSASigner();
ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes));
signer.init(false, keyParams);
if (!signer.verifySignature(digest, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue()))
{
fail("RIPEMD160withDSA not really RIPEMD160!");
}
}
private void checkPublic(DSAPublicKey k1, PublicKey vKey)
{
if (!k1.getY().equals(((DSAPublicKey)vKey).getY()))
{
fail("public number not decoded properly");
}
if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG()))
{
fail("public generator not decoded properly");
}
if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP()))
{
fail("public p value not decoded properly");
}
if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ()))
{
fail("public q value not decoded properly");
}
}
private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey)
{
if (!k2.getX().equals(((DSAPrivateKey)sKey).getX()))
{
fail("private number not decoded properly");
}
if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG()))
{
fail("private generator not decoded properly");
}
if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP()))
{
fail("private p value not decoded properly");
}
if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ()))
{
fail("private q value not decoded properly");
}
}
private Object serializeDeserialize(Object o)
throws Exception
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ObjectOutputStream oOut = new ObjectOutputStream(bOut);
oOut.writeObject(o);
oOut.close();
ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray()));
return oIn.readObject();
}
/**
* X9.62 - 1998,<br>
* J.3.2, Page 155, ECDSA over the field Fp<br>
* an example with 239 bit prime
*/
private void testECDSA239bitPrime()
throws Exception
{
BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176");
BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783");
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));
SecureRandom k = new TestRandomBigInteger(kData);
X9ECParameters x9 = ECNamedCurveTable.getByName("prime239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec spec = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
spec);
Signature sgr = Signature.getInstance("ECDSA", "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKey);
PublicKey vKey = f.generatePublic(pubKey);
sgr.initSign(sKey, k);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.update(message);
byte[] sigBytes = sgr.sign();
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail("239 Bit EC verification failed");
}
BigInteger[] sig = derDecode(sigBytes);
if (!r.equals(sig[0]))
{
fail("r component wrong." + Strings.lineSeparator()
+ " expecting: " + r + Strings.lineSeparator()
+ " got : " + sig[0]);
}
if (!s.equals(sig[1]))
{
fail("s component wrong." + Strings.lineSeparator()
+ " expecting: " + s + Strings.lineSeparator()
+ " got : " + sig[1]);
}
}
private void testNONEwithECDSA239bitPrime()
throws Exception
{
X9ECParameters x9 = ECNamedCurveTable.getByName("prime239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec spec = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
spec);
Signature sgr = Signature.getInstance("NONEwithECDSA", "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKey);
PublicKey vKey = f.generatePublic(pubKey);
byte[] message = "abc".getBytes();
byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d");
checkMessage(sgr, sKey, vKey, message, sig);
message = "abcdefghijklmnopqrstuvwxyz".getBytes();
sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c");
checkMessage(sgr, sKey, vKey, message, sig);
message = "a very very long message gauranteed to cause an overflow".getBytes();
sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a");
checkMessage(sgr, sKey, vKey, message, sig);
}
private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s)
throws Exception
{
X9ECParameters p = NISTNamedCurves.getByName("P-256");
KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC");
ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH());
ECCurve curve = p.getCurve();
ECParameterSpec spec = new ECParameterSpec(
curve,
p.getG(), // G
p.getN()); // n
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q
spec);
doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey);
doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey);
}
private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException
{
SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335")));
byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");
Signature dsa = Signature.getInstance(sigName, "BC");
dsa.initSign(ecKeyFact.generatePrivate(priKey), k);
dsa.update(M, 0, M.length);
byte[] encSig = dsa.sign();
ASN1Sequence sig = ASN1Sequence.getInstance(encSig);
BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384");
BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue();
if (!r.equals(sigR))
{
fail("r component wrong." + Strings.lineSeparator()
+ " expecting: " + r.toString(16) + Strings.lineSeparator()
+ " got : " + sigR.toString(16));
}
BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue();
if (!s.equals(sigS))
{
fail("s component wrong." + Strings.lineSeparator()
+ " expecting: " + s.toString(16) + Strings.lineSeparator()
+ " got : " + sigS.toString(16));
}
// Verify the signature
dsa.initVerify(ecKeyFact.generatePublic(pubKey));
dsa.update(M, 0, M.length);
if (!dsa.verify(encSig))
{
fail("signature fails");
}
}
private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s)
throws Exception
{
DSAParameterSpec dsaParams = new DSAParameterSpec(
new BigInteger(
"F56C2A7D366E3EBDEAA1891FD2A0D099" +
"436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
"D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
"69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
"5909132627F51A0C866877E672E555342BDF9355347DBD43" +
"B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
"31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
"EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
"F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
"1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
"531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16),
new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16),
new BigInteger(
"8DC6CC814CAE4A1C05A3E186A6FE27EA" +
"BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
"29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
"6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
"513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
"7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
"A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
"45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
"FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
"428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
"EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)
);
BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16);
BigInteger y = new BigInteger(
"2828003D7C747199143C370FDD07A286" +
"1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
"1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
"CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
"C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
"2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
"9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
"41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
"7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
"C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
"A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16);
DSAPrivateKeySpec priKey = new DSAPrivateKeySpec(
x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());
DSAPublicKeySpec pubKey = new DSAPublicKeySpec(
y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());
KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC");
doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey);
doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey);
}
private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException
{
SecureRandom k = new FixedSecureRandom(
new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))),
new FixedSecureRandom.Data(Hex.decode("01020304")) });
byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");
Signature dsa = Signature.getInstance(sigName, "BC");
dsa.initSign(ecKeyFact.generatePrivate(priKey), k);
dsa.update(M, 0, M.length);
byte[] encSig = dsa.sign();
ASN1Sequence sig = ASN1Sequence.getInstance(encSig);
BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16);
BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue();
if (!r.equals(sigR))
{
fail("r component wrong." + Strings.lineSeparator()
+ " expecting: " + r.toString(16) + Strings.lineSeparator()
+ " got : " + sigR.toString(16));
}
BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue();
if (!s.equals(sigS))
{
fail("s component wrong." + Strings.lineSeparator()
+ " expecting: " + s.toString(16) + Strings.lineSeparator()
+ " got : " + sigS.toString(16));
}
// Verify the signature
dsa.initVerify(ecKeyFact.generatePublic(pubKey));
dsa.update(M, 0, M.length);
if (!dsa.verify(encSig))
{
fail("signature fails");
}
}
private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig)
throws InvalidKeyException, SignatureException
{
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));
SecureRandom k = new TestRandomBigInteger(kData);
sgr.initSign(sKey, k);
sgr.update(message);
byte[] sigBytes = sgr.sign();
if (!Arrays.areEqual(sigBytes, sig))
{
fail(new String(message) + " signature incorrect");
}
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail(new String(message) + " verification failed");
}
}
/**
* X9.62 - 1998,<br>
* J.2.1, Page 100, ECDSA over the field F2m<br>
* an example with 191 bit binary field
*/
private void testECDSA239bitBinary()
throws Exception
{
BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174");
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));
SecureRandom k = new TestRandomBigInteger(kData);
X9ECParameters x9 = ECNamedCurveTable.getByName("c2tnb239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec params = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec(
new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
params);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
params);
Signature sgr = Signature.getInstance("ECDSA", "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKeySpec);
PublicKey vKey = f.generatePublic(pubKeySpec);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.initSign(sKey, k);
sgr.update(message);
byte[] sigBytes = sgr.sign();
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail("239 Bit EC verification failed");
}
BigInteger[] sig = derDecode(sigBytes);
if (!r.equals(sig[0]))
{
fail("r component wrong." + Strings.lineSeparator()
+ " expecting: " + r + Strings.lineSeparator()
+ " got : " + sig[0]);
}
if (!s.equals(sig[1]))
{
fail("s component wrong." + Strings.lineSeparator()
+ " expecting: " + s + Strings.lineSeparator()
+ " got : " + sig[1]);
}
}
private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid)
throws Exception
{
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));
SecureRandom k = new TestRandomBigInteger(kData);
X9ECParameters x9 = ECNamedCurveTable.getByName("c2tnb239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec params = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec(
new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
params);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
params);
Signature sgr = Signature.getInstance(algorithm, "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKeySpec);
PublicKey vKey = f.generatePublic(pubKeySpec);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.initSign(sKey, k);
sgr.update(message);
byte[] sigBytes = sgr.sign();
sgr = Signature.getInstance(oid.getId(), "BC");
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail("239 Bit EC RIPEMD160 verification failed");
}
}
private void testGeneration()
throws Exception
{
Signature s = Signature.getInstance("DSA", "BC");
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
// test exception
//
try
{
g.initialize(513, new SecureRandom());
fail("illegal parameter 513 check failed.");
}
catch (IllegalArgumentException e)
{
// expected
}
try
{
g.initialize(510, new SecureRandom());
fail("illegal parameter 510 check failed.");
}
catch (IllegalArgumentException e)
{
// expected
}
try
{
g.initialize(1025, new SecureRandom());
fail("illegal parameter 1025 check failed.");
}
catch (IllegalArgumentException e)
{
// expected
}
g.initialize(512, new SecureRandom());
KeyPair p = g.generateKeyPair();
PrivateKey sKey = p.getPrivate();
PublicKey vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("DSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("DSA verification failed");
}
//
// key decoding test - serialisation test
//
DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey);
checkPublic(k1, vKey);
checkEquals(k1, vKey);
DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey);
checkPrivateKey(k2, sKey);
checkEquals(k2, sKey);
if (!(k2 instanceof PKCS12BagAttributeCarrier))
{
fail("private key not implementing PKCS12 attribute carrier");
}
//
// ECDSA Fp generation test
//
s = Signature.getInstance("ECDSA", "BC");
g = KeyPairGenerator.getInstance("ECDSA", "BC");
X9ECParameters x9 = ECNamedCurveTable.getByName("prime239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec ecSpec = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
g.initialize(ecSpec, new SecureRandom());
p = g.generateKeyPair();
sKey = p.getPrivate();
vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
sigBytes = s.sign();
s = Signature.getInstance("ECDSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("ECDSA verification failed");
}
//
// key decoding test - serialisation test
//
PublicKey eck1 = (PublicKey)serializeDeserialize(vKey);
checkEquals(eck1, vKey);
PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey);
checkEquals(eck2, sKey);
// Named curve parameter
g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom());
p = g.generateKeyPair();
sKey = p.getPrivate();
vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
sigBytes = s.sign();
s = Signature.getInstance("ECDSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("ECDSA verification failed");
}
//
// key decoding test - serialisation test
//
eck1 = (PublicKey)serializeDeserialize(vKey);
checkEquals(eck1, vKey);
eck2 = (PrivateKey)serializeDeserialize(sKey);
checkEquals(eck2, sKey);
//
// ECDSA F2m generation test
//
s = Signature.getInstance("ECDSA", "BC");
g = KeyPairGenerator.getInstance("ECDSA", "BC");
x9 = ECNamedCurveTable.getByName("c2tnb239v1");
curve = x9.getCurve();
ecSpec = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
g.initialize(ecSpec, new SecureRandom());
p = g.generateKeyPair();
sKey = p.getPrivate();
vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
sigBytes = s.sign();
s = Signature.getInstance("ECDSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("ECDSA verification failed");
}
//
// key decoding test - serialisation test
//
eck1 = (PublicKey)serializeDeserialize(vKey);
checkEquals(eck1, vKey);
eck2 = (PrivateKey)serializeDeserialize(sKey);
checkEquals(eck2, sKey);
if (!(eck2 instanceof PKCS12BagAttributeCarrier))
{
fail("private key not implementing PKCS12 attribute carrier");
}
}
private void checkEquals(Object o1, Object o2)
{
if (!o1.equals(o2))
{
fail("comparison test failed");
}
if (o1.hashCode() != o2.hashCode())
{
fail("hashCode test failed");
}
}
private void testParameters()
throws Exception
{
AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
a.init(512, random);
AlgorithmParameters params = a.generateParameters();
byte[] encodeParams = params.getEncoded();
AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
a2.init(encodeParams);
// a and a2 should be equivalent!
byte[] encodeParams_2 = a2.getEncoded();
if (!areEqual(encodeParams, encodeParams_2))
{
fail("encode/decode parameters failed");
}
DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class);
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC");
g.initialize(dsaP, new SecureRandom());
KeyPair p = g.generateKeyPair();
PrivateKey sKey = p.getPrivate();
PublicKey vKey = p.getPublic();
Signature s = Signature.getInstance("DSA", "BC");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("DSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("DSA verification failed");
}
}
private void testDSA2Parameters()
throws Exception
{
byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0");
AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
a.init(2048, new DSATestSecureRandom(seed));
AlgorithmParameters params = a.generateParameters();
DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class);
if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16)))
{
fail("Q incorrect");
}
if (!dsaP.getP().equals(new BigInteger(
"F56C2A7D366E3EBDEAA1891FD2A0D099" +
"436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
"D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
"69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
"5909132627F51A0C866877E672E555342BDF9355347DBD43" +
"B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
"31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
"EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
"F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
"1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
"531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16)))
{
fail("P incorrect");
}
if (!dsaP.getG().equals(new BigInteger(
"8DC6CC814CAE4A1C05A3E186A6FE27EA" +
"BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
"29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
"6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
"513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
"7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
"A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
"45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
"FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
"428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
"EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)))
{
fail("G incorrect");
}
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC");
g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")));
KeyPair p = g.generateKeyPair();
DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate();
DSAPublicKey vKey = (DSAPublicKey)p.getPublic();
if (!vKey.getY().equals(new BigInteger(
"2828003D7C747199143C370FDD07A286" +
"1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
"1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
"CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
"C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
"2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
"9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
"41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
"7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
"C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
"A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16)))
{
fail("Y value incorrect");
}
if (!sKey.getX().equals(
new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16)))
{
fail("X value incorrect");
}
byte[] encodeParams = params.getEncoded();
AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
a2.init(encodeParams);
// a and a2 should be equivalent!
byte[] encodeParams_2 = a2.getEncoded();
if (!areEqual(encodeParams, encodeParams_2))
{
fail("encode/decode parameters failed");
}
Signature s = Signature.getInstance("DSA", "BC");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("DSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("DSA verification failed");
}
}
private void testKeyGeneration(int keysize)
throws Exception
{
KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA", "BC");
generator.initialize(keysize);
KeyPair keyPair = generator.generateKeyPair();
DSAPrivateKey priv = (DSAPrivateKey)keyPair.getPrivate();
DSAParams params = priv.getParams();
isTrue("keysize mismatch", keysize == params.getP().bitLength());
// The NIST standard does not fully specify the size of q that
// must be used for a given key size. Hence there are differences.
// For example if keysize = 2048, then OpenSSL uses 256 bit q's by default,
// but the SUN provider uses 224 bits. Both are acceptable sizes.
// The tests below simply asserts that the size of q does not decrease the
// overall security of the DSA.
int qsize = params.getQ().bitLength();
switch (keysize)
{
case 1024:
isTrue("Invalid qsize for 1024 bit key:" + qsize, qsize >= 160);
break;
case 2048:
isTrue("Invalid qsize for 2048 bit key:" + qsize, qsize >= 224);
break;
case 3072:
isTrue("Invalid qsize for 3072 bit key:" + qsize, qsize >= 256);
break;
default:
fail("Invalid key size:" + keysize);
}
// Check the length of the private key.
// For example GPG4Browsers or the KJUR library derived from it use
// q.bitCount() instead of q.bitLength() to determine the size of the private key
// and hence would generate keys that are much too small.
isTrue("privkey error", priv.getX().bitLength() >= qsize - 32);
}
private void testKeyGenerationAll()
throws Exception
{
testKeyGeneration(1024);
testKeyGeneration(2048);
testKeyGeneration(3072);
}
public void performTest()
throws Exception
{
testCompat();
testNONEwithDSA();
testRIPEMD160withDSA();
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16));
testECDSA239bitPrime();
testNONEwithECDSA239bitPrime();
testECDSA239bitBinary();
testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160);
testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1);
testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224);
testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256);
testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384);
testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512);
testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1);
testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224);
testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256);
testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384);
testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512);
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16));
testGeneration();
testParameters();
testDSA2Parameters();
testNullParameters();
testValidate();
testModified();
testKeyGenerationAll();
}
protected BigInteger[] derDecode(
byte[] encoding)
throws IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);
ASN1InputStream aIn = new ASN1InputStream(bIn);
ASN1Sequence s = (ASN1Sequence)aIn.readObject();
BigInteger[] sig = new BigInteger[2];
sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue();
sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue();
return sig;
}
public String getName()
{
return "DSA/ECDSA";
}
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new DSATest());
}
private class DSATestSecureRandom
extends TestRandomData
{
private boolean first = true;
public DSATestSecureRandom(byte[] value)
{
super(value);
}
public void nextBytes(byte[] bytes)
{
if (first)
{
super.nextBytes(bytes);
first = false;
}
else
{
bytes[bytes.length - 1] = 2;
}
}
}
}
| prov/src/test/java/org/bouncycastle/jce/provider/test/DSATest.java | package org.bouncycastle.jce.provider.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.DSAParameterSpec;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.internal.asn1.eac.EACObjectIdentifiers;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.crypto.params.DSAParameters;
import org.bouncycastle.crypto.params.DSAPublicKeyParameters;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.signers.DSASigner;
import org.bouncycastle.jcajce.provider.digest.RIPEMD160;
import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.BigIntegers;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.FixedSecureRandom;
import org.bouncycastle.util.test.SimpleTest;
import org.bouncycastle.util.test.TestRandomBigInteger;
import org.bouncycastle.util.test.TestRandomData;
public class DSATest
extends SimpleTest
{
byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3");
byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded");
SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 });
// DSA modified signatures, courtesy of the Google security team
static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec(
// x
new BigInteger(
"15382583218386677486843706921635237927801862255437148328980464126979"),
// p
new BigInteger(
"181118486631420055711787706248812146965913392568235070235446058914"
+ "1170708161715231951918020125044061516370042605439640379530343556"
+ "4101919053459832890139496933938670005799610981765220283775567361"
+ "4836626483403394052203488713085936276470766894079318754834062443"
+ "1033792580942743268186462355159813630244169054658542719322425431"
+ "4088256212718983105131138772434658820375111735710449331518776858"
+ "7867938758654181244292694091187568128410190746310049564097068770"
+ "8161261634790060655580211122402292101772553741704724263582994973"
+ "9109274666495826205002104010355456981211025738812433088757102520"
+ "562459649777989718122219159982614304359"),
// q
new BigInteger(
"19689526866605154788513693571065914024068069442724893395618704484701"),
// g
new BigInteger(
"2859278237642201956931085611015389087970918161297522023542900348"
+ "0877180630984239764282523693409675060100542360520959501692726128"
+ "3149190229583566074777557293475747419473934711587072321756053067"
+ "2532404847508798651915566434553729839971841903983916294692452760"
+ "2490198571084091890169933809199002313226100830607842692992570749"
+ "0504363602970812128803790973955960534785317485341020833424202774"
+ "0275688698461842637641566056165699733710043802697192696426360843"
+ "1736206792141319514001488556117408586108219135730880594044593648"
+ "9237302749293603778933701187571075920849848690861126195402696457"
+ "4111219599568903257472567764789616958430"));
static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec(
new BigInteger(
"3846308446317351758462473207111709291533523711306097971550086650"
+ "2577333637930103311673872185522385807498738696446063139653693222"
+ "3528823234976869516765207838304932337200968476150071617737755913"
+ "3181601169463467065599372409821150709457431511200322947508290005"
+ "1780020974429072640276810306302799924668893998032630777409440831"
+ "4314588994475223696460940116068336991199969153649625334724122468"
+ "7497038281983541563359385775312520539189474547346202842754393945"
+ "8755803223951078082197762886933401284142487322057236814878262166"
+ "5072306622943221607031324846468109901964841479558565694763440972"
+ "5447389416166053148132419345627682740529"),
PRIVATE_KEY.getP(),
PRIVATE_KEY.getQ(),
PRIVATE_KEY.getG());
// The following test vectors check for signature malleability and bugs. That means the test
// vectors are derived from a valid signature by modifying the ASN encoding. A correct
// implementation of DSA should only accept correct DER encoding and properly handle the others.
// Allowing alternative BER encodings is in many cases benign. An example where this kind of
// signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability
static final String[] MODIFIED_SIGNATURES = {
"303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f"
+ "9ef41dd424a4e1c8f16967cf3365813fe8786236",
"303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f"
+ "9ef41dd424a4e1c8f16967cf3365813fe8786236",
"303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e"
+ "f41dd424a4e1c8f16967cf3365813fe8786236",
"3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f"
+ "9ef41dd424a4e1c8f16967cf3365813fe8786236",
"303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4"
+ "1dd424a4e1c8f16967cf3365813fe87862360000",
"3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100",
"303e021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca802811d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3"
};
private void testModified()
throws Exception
{
KeyFactory kFact = KeyFactory.getInstance("DSA", "BC");
PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY);
Signature sig = Signature.getInstance("DSA", "BC");
for (int i = 0; i != MODIFIED_SIGNATURES.length; i++)
{
sig.initVerify(pubKey);
sig.update(Strings.toByteArray("Hello"));
boolean failed;
try
{
failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i]));
}
catch (SignatureException e)
{
failed = true;
}
isTrue("sig verified when shouldn't", failed);
}
}
private void testCompat()
throws Exception
{
if (Security.getProvider("SUN") == null)
{
return;
}
Signature s = Signature.getInstance("DSA", "SUN");
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
g.initialize(512, new SecureRandom());
KeyPair p = g.generateKeyPair();
PrivateKey sKey = p.getPrivate();
PublicKey vKey = p.getPublic();
//
// sign SUN - verify with BC
//
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("DSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("SUN -> BC verification failed");
}
//
// sign BC - verify with SUN
//
s.initSign(sKey);
s.update(data);
sigBytes = s.sign();
s = Signature.getInstance("DSA", "SUN");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("BC -> SUN verification failed");
}
//
// key encoding test - BC decoding Sun keys
//
KeyFactory f = KeyFactory.getInstance("DSA", "BC");
X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded());
DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s);
checkPublic(k1, vKey);
PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded());
DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8);
checkPrivateKey(k2, sKey);
//
// key decoding test - SUN decoding BC keys
//
f = KeyFactory.getInstance("DSA", "SUN");
x509s = new X509EncodedKeySpec(k1.getEncoded());
vKey = (DSAPublicKey)f.generatePublic(x509s);
checkPublic(k1, vKey);
pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded());
sKey = f.generatePrivate(pkcs8);
checkPrivateKey(k2, sKey);
}
private void testNullParameters()
throws Exception
{
KeyFactory f = KeyFactory.getInstance("DSA", "BC");
X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded());
DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s);
DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s);
isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null);
isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode());
isTrue("not equal", key1.equals(key2));
isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded()));
}
private void testValidate()
throws Exception
{
DSAParameterSpec dsaParams = new DSAParameterSpec(
new BigInteger(
"F56C2A7D366E3EBDEAA1891FD2A0D099" +
"436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
"D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
"69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
"5909132627F51A0C866877E672E555342BDF9355347DBD43" +
"B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
"31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
"EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
"F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
"1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
"531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16),
new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16),
new BigInteger(
"8DC6CC814CAE4A1C05A3E186A6FE27EA" +
"BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
"29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
"6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
"513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
"7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
"A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
"45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
"FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
"428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
"EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)
);
KeyFactory f = KeyFactory.getInstance("DSA", "BC");
try
{
f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ()));
fail("no exception");
}
catch (Exception e)
{
isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage()));
}
}
private void testNONEwithDSA()
throws Exception
{
byte[] dummySha1 = Hex.decode("01020304050607080910111213141516");
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC");
kpGen.initialize(512);
KeyPair kp = kpGen.generateKeyPair();
Signature sig = Signature.getInstance("NONEwithDSA", "BC");
sig.initSign(kp.getPrivate());
sig.update(dummySha1);
byte[] sigBytes = sig.sign();
sig.initVerify(kp.getPublic());
sig.update(dummySha1);
sig.verify(sigBytes);
// reset test
sig.update(dummySha1);
if (!sig.verify(sigBytes))
{
fail("NONEwithDSA failed to reset");
}
// lightweight test
DSAPublicKey key = (DSAPublicKey)kp.getPublic();
DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG());
DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params);
DSASigner signer = new DSASigner();
ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes));
signer.init(false, keyParams);
if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue()))
{
fail("NONEwithDSA not really NONE!");
}
}
private void testRIPEMD160withDSA()
throws Exception
{
byte[] msg = Hex.decode("01020304050607080910111213141516");
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
Signature sig = Signature.getInstance("RIPEMD160withDSA", "BC");
sig.initSign(kp.getPrivate());
sig.update(msg);
byte[] sigBytes = sig.sign();
sig.initVerify(kp.getPublic());
sig.update(msg);
isTrue(sig.verify(sigBytes));
// reset test
sig.update(msg);
if (!sig.verify(sigBytes))
{
fail("NONEwithDSA failed to reset");
}
// lightweight test
RIPEMD160Digest dig = new RIPEMD160Digest();
byte[] digest = new byte[dig.getDigestSize()];
dig.update(msg, 0, msg.length);
dig.doFinal(digest, 0);
DSAPublicKey key = (DSAPublicKey)kp.getPublic();
DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG());
DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params);
DSASigner signer = new DSASigner();
ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes));
signer.init(false, keyParams);
if (!signer.verifySignature(digest, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue()))
{
fail("RIPEMD160withDSA not really RIPEMD160!");
}
}
private void checkPublic(DSAPublicKey k1, PublicKey vKey)
{
if (!k1.getY().equals(((DSAPublicKey)vKey).getY()))
{
fail("public number not decoded properly");
}
if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG()))
{
fail("public generator not decoded properly");
}
if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP()))
{
fail("public p value not decoded properly");
}
if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ()))
{
fail("public q value not decoded properly");
}
}
private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey)
{
if (!k2.getX().equals(((DSAPrivateKey)sKey).getX()))
{
fail("private number not decoded properly");
}
if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG()))
{
fail("private generator not decoded properly");
}
if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP()))
{
fail("private p value not decoded properly");
}
if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ()))
{
fail("private q value not decoded properly");
}
}
private Object serializeDeserialize(Object o)
throws Exception
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ObjectOutputStream oOut = new ObjectOutputStream(bOut);
oOut.writeObject(o);
oOut.close();
ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray()));
return oIn.readObject();
}
/**
* X9.62 - 1998,<br>
* J.3.2, Page 155, ECDSA over the field Fp<br>
* an example with 239 bit prime
*/
private void testECDSA239bitPrime()
throws Exception
{
BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176");
BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783");
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));
SecureRandom k = new TestRandomBigInteger(kData);
X9ECParameters x9 = ECNamedCurveTable.getByName("prime239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec spec = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
spec);
Signature sgr = Signature.getInstance("ECDSA", "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKey);
PublicKey vKey = f.generatePublic(pubKey);
sgr.initSign(sKey, k);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.update(message);
byte[] sigBytes = sgr.sign();
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail("239 Bit EC verification failed");
}
BigInteger[] sig = derDecode(sigBytes);
if (!r.equals(sig[0]))
{
fail("r component wrong." + Strings.lineSeparator()
+ " expecting: " + r + Strings.lineSeparator()
+ " got : " + sig[0]);
}
if (!s.equals(sig[1]))
{
fail("s component wrong." + Strings.lineSeparator()
+ " expecting: " + s + Strings.lineSeparator()
+ " got : " + sig[1]);
}
}
private void testNONEwithECDSA239bitPrime()
throws Exception
{
X9ECParameters x9 = ECNamedCurveTable.getByName("prime239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec spec = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
spec);
Signature sgr = Signature.getInstance("NONEwithECDSA", "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKey);
PublicKey vKey = f.generatePublic(pubKey);
byte[] message = "abc".getBytes();
byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d");
checkMessage(sgr, sKey, vKey, message, sig);
message = "abcdefghijklmnopqrstuvwxyz".getBytes();
sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c");
checkMessage(sgr, sKey, vKey, message, sig);
message = "a very very long message gauranteed to cause an overflow".getBytes();
sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a");
checkMessage(sgr, sKey, vKey, message, sig);
}
private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s)
throws Exception
{
X9ECParameters p = NISTNamedCurves.getByName("P-256");
KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC");
ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH());
ECCurve curve = p.getCurve();
ECParameterSpec spec = new ECParameterSpec(
curve,
p.getG(), // G
p.getN()); // n
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q
spec);
doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey);
doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey);
}
private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException
{
SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335")));
byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");
Signature dsa = Signature.getInstance(sigName, "BC");
dsa.initSign(ecKeyFact.generatePrivate(priKey), k);
dsa.update(M, 0, M.length);
byte[] encSig = dsa.sign();
ASN1Sequence sig = ASN1Sequence.getInstance(encSig);
BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384");
BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue();
if (!r.equals(sigR))
{
fail("r component wrong." + Strings.lineSeparator()
+ " expecting: " + r.toString(16) + Strings.lineSeparator()
+ " got : " + sigR.toString(16));
}
BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue();
if (!s.equals(sigS))
{
fail("s component wrong." + Strings.lineSeparator()
+ " expecting: " + s.toString(16) + Strings.lineSeparator()
+ " got : " + sigS.toString(16));
}
// Verify the signature
dsa.initVerify(ecKeyFact.generatePublic(pubKey));
dsa.update(M, 0, M.length);
if (!dsa.verify(encSig))
{
fail("signature fails");
}
}
private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s)
throws Exception
{
DSAParameterSpec dsaParams = new DSAParameterSpec(
new BigInteger(
"F56C2A7D366E3EBDEAA1891FD2A0D099" +
"436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
"D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
"69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
"5909132627F51A0C866877E672E555342BDF9355347DBD43" +
"B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
"31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
"EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
"F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
"1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
"531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16),
new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16),
new BigInteger(
"8DC6CC814CAE4A1C05A3E186A6FE27EA" +
"BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
"29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
"6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
"513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
"7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
"A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
"45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
"FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
"428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
"EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)
);
BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16);
BigInteger y = new BigInteger(
"2828003D7C747199143C370FDD07A286" +
"1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
"1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
"CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
"C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
"2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
"9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
"41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
"7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
"C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
"A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16);
DSAPrivateKeySpec priKey = new DSAPrivateKeySpec(
x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());
DSAPublicKeySpec pubKey = new DSAPublicKeySpec(
y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());
KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC");
doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey);
doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey);
}
private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException
{
SecureRandom k = new FixedSecureRandom(
new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))),
new FixedSecureRandom.Data(Hex.decode("01020304")) });
byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");
Signature dsa = Signature.getInstance(sigName, "BC");
dsa.initSign(ecKeyFact.generatePrivate(priKey), k);
dsa.update(M, 0, M.length);
byte[] encSig = dsa.sign();
ASN1Sequence sig = ASN1Sequence.getInstance(encSig);
BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16);
BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue();
if (!r.equals(sigR))
{
fail("r component wrong." + Strings.lineSeparator()
+ " expecting: " + r.toString(16) + Strings.lineSeparator()
+ " got : " + sigR.toString(16));
}
BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue();
if (!s.equals(sigS))
{
fail("s component wrong." + Strings.lineSeparator()
+ " expecting: " + s.toString(16) + Strings.lineSeparator()
+ " got : " + sigS.toString(16));
}
// Verify the signature
dsa.initVerify(ecKeyFact.generatePublic(pubKey));
dsa.update(M, 0, M.length);
if (!dsa.verify(encSig))
{
fail("signature fails");
}
}
private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig)
throws InvalidKeyException, SignatureException
{
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));
SecureRandom k = new TestRandomBigInteger(kData);
sgr.initSign(sKey, k);
sgr.update(message);
byte[] sigBytes = sgr.sign();
if (!Arrays.areEqual(sigBytes, sig))
{
fail(new String(message) + " signature incorrect");
}
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail(new String(message) + " verification failed");
}
}
/**
* X9.62 - 1998,<br>
* J.2.1, Page 100, ECDSA over the field F2m<br>
* an example with 191 bit binary field
*/
private void testECDSA239bitBinary()
throws Exception
{
BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174");
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));
SecureRandom k = new TestRandomBigInteger(kData);
X9ECParameters x9 = ECNamedCurveTable.getByName("c2tnb239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec params = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec(
new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
params);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
params);
Signature sgr = Signature.getInstance("ECDSA", "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKeySpec);
PublicKey vKey = f.generatePublic(pubKeySpec);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.initSign(sKey, k);
sgr.update(message);
byte[] sigBytes = sgr.sign();
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail("239 Bit EC verification failed");
}
BigInteger[] sig = derDecode(sigBytes);
if (!r.equals(sig[0]))
{
fail("r component wrong." + Strings.lineSeparator()
+ " expecting: " + r + Strings.lineSeparator()
+ " got : " + sig[0]);
}
if (!s.equals(sig[1]))
{
fail("s component wrong." + Strings.lineSeparator()
+ " expecting: " + s + Strings.lineSeparator()
+ " got : " + sig[1]);
}
}
private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid)
throws Exception
{
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));
SecureRandom k = new TestRandomBigInteger(kData);
X9ECParameters x9 = ECNamedCurveTable.getByName("c2tnb239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec params = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec(
new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
params);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
params);
Signature sgr = Signature.getInstance(algorithm, "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKeySpec);
PublicKey vKey = f.generatePublic(pubKeySpec);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.initSign(sKey, k);
sgr.update(message);
byte[] sigBytes = sgr.sign();
sgr = Signature.getInstance(oid.getId(), "BC");
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail("239 Bit EC RIPEMD160 verification failed");
}
}
private void testGeneration()
throws Exception
{
Signature s = Signature.getInstance("DSA", "BC");
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
// test exception
//
try
{
g.initialize(513, new SecureRandom());
fail("illegal parameter 513 check failed.");
}
catch (IllegalArgumentException e)
{
// expected
}
try
{
g.initialize(510, new SecureRandom());
fail("illegal parameter 510 check failed.");
}
catch (IllegalArgumentException e)
{
// expected
}
try
{
g.initialize(1025, new SecureRandom());
fail("illegal parameter 1025 check failed.");
}
catch (IllegalArgumentException e)
{
// expected
}
g.initialize(512, new SecureRandom());
KeyPair p = g.generateKeyPair();
PrivateKey sKey = p.getPrivate();
PublicKey vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("DSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("DSA verification failed");
}
//
// key decoding test - serialisation test
//
DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey);
checkPublic(k1, vKey);
checkEquals(k1, vKey);
DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey);
checkPrivateKey(k2, sKey);
checkEquals(k2, sKey);
if (!(k2 instanceof PKCS12BagAttributeCarrier))
{
fail("private key not implementing PKCS12 attribute carrier");
}
//
// ECDSA Fp generation test
//
s = Signature.getInstance("ECDSA", "BC");
g = KeyPairGenerator.getInstance("ECDSA", "BC");
X9ECParameters x9 = ECNamedCurveTable.getByName("prime239v1");
ECCurve curve = x9.getCurve();
ECParameterSpec ecSpec = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
g.initialize(ecSpec, new SecureRandom());
p = g.generateKeyPair();
sKey = p.getPrivate();
vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
sigBytes = s.sign();
s = Signature.getInstance("ECDSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("ECDSA verification failed");
}
//
// key decoding test - serialisation test
//
PublicKey eck1 = (PublicKey)serializeDeserialize(vKey);
checkEquals(eck1, vKey);
PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey);
checkEquals(eck2, sKey);
// Named curve parameter
g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom());
p = g.generateKeyPair();
sKey = p.getPrivate();
vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
sigBytes = s.sign();
s = Signature.getInstance("ECDSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("ECDSA verification failed");
}
//
// key decoding test - serialisation test
//
eck1 = (PublicKey)serializeDeserialize(vKey);
checkEquals(eck1, vKey);
eck2 = (PrivateKey)serializeDeserialize(sKey);
checkEquals(eck2, sKey);
//
// ECDSA F2m generation test
//
s = Signature.getInstance("ECDSA", "BC");
g = KeyPairGenerator.getInstance("ECDSA", "BC");
x9 = ECNamedCurveTable.getByName("c2tnb239v1");
curve = x9.getCurve();
ecSpec = new ECParameterSpec(curve, x9.getG(), x9.getN(), x9.getH());
g.initialize(ecSpec, new SecureRandom());
p = g.generateKeyPair();
sKey = p.getPrivate();
vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
sigBytes = s.sign();
s = Signature.getInstance("ECDSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("ECDSA verification failed");
}
//
// key decoding test - serialisation test
//
eck1 = (PublicKey)serializeDeserialize(vKey);
checkEquals(eck1, vKey);
eck2 = (PrivateKey)serializeDeserialize(sKey);
checkEquals(eck2, sKey);
if (!(eck2 instanceof PKCS12BagAttributeCarrier))
{
fail("private key not implementing PKCS12 attribute carrier");
}
}
private void checkEquals(Object o1, Object o2)
{
if (!o1.equals(o2))
{
fail("comparison test failed");
}
if (o1.hashCode() != o2.hashCode())
{
fail("hashCode test failed");
}
}
private void testParameters()
throws Exception
{
AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
a.init(512, random);
AlgorithmParameters params = a.generateParameters();
byte[] encodeParams = params.getEncoded();
AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
a2.init(encodeParams);
// a and a2 should be equivalent!
byte[] encodeParams_2 = a2.getEncoded();
if (!areEqual(encodeParams, encodeParams_2))
{
fail("encode/decode parameters failed");
}
DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class);
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC");
g.initialize(dsaP, new SecureRandom());
KeyPair p = g.generateKeyPair();
PrivateKey sKey = p.getPrivate();
PublicKey vKey = p.getPublic();
Signature s = Signature.getInstance("DSA", "BC");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("DSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("DSA verification failed");
}
}
private void testDSA2Parameters()
throws Exception
{
byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0");
AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
a.init(2048, new DSATestSecureRandom(seed));
AlgorithmParameters params = a.generateParameters();
DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class);
if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16)))
{
fail("Q incorrect");
}
if (!dsaP.getP().equals(new BigInteger(
"F56C2A7D366E3EBDEAA1891FD2A0D099" +
"436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
"D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
"69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
"5909132627F51A0C866877E672E555342BDF9355347DBD43" +
"B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
"31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
"EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
"F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
"1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
"531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16)))
{
fail("P incorrect");
}
if (!dsaP.getG().equals(new BigInteger(
"8DC6CC814CAE4A1C05A3E186A6FE27EA" +
"BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
"29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
"6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
"513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
"7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
"A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
"45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
"FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
"428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
"EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)))
{
fail("G incorrect");
}
KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC");
g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")));
KeyPair p = g.generateKeyPair();
DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate();
DSAPublicKey vKey = (DSAPublicKey)p.getPublic();
if (!vKey.getY().equals(new BigInteger(
"2828003D7C747199143C370FDD07A286" +
"1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
"1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
"CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
"C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
"2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
"9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
"41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
"7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
"C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
"A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16)))
{
fail("Y value incorrect");
}
if (!sKey.getX().equals(
new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16)))
{
fail("X value incorrect");
}
byte[] encodeParams = params.getEncoded();
AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
a2.init(encodeParams);
// a and a2 should be equivalent!
byte[] encodeParams_2 = a2.getEncoded();
if (!areEqual(encodeParams, encodeParams_2))
{
fail("encode/decode parameters failed");
}
Signature s = Signature.getInstance("DSA", "BC");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("DSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("DSA verification failed");
}
}
private void testKeyGeneration(int keysize)
throws Exception
{
KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA", "BC");
generator.initialize(keysize);
KeyPair keyPair = generator.generateKeyPair();
DSAPrivateKey priv = (DSAPrivateKey)keyPair.getPrivate();
DSAParams params = priv.getParams();
isTrue("keysize mismatch", keysize == params.getP().bitLength());
// The NIST standard does not fully specify the size of q that
// must be used for a given key size. Hence there are differences.
// For example if keysize = 2048, then OpenSSL uses 256 bit q's by default,
// but the SUN provider uses 224 bits. Both are acceptable sizes.
// The tests below simply asserts that the size of q does not decrease the
// overall security of the DSA.
int qsize = params.getQ().bitLength();
switch (keysize)
{
case 1024:
isTrue("Invalid qsize for 1024 bit key:" + qsize, qsize >= 160);
break;
case 2048:
isTrue("Invalid qsize for 2048 bit key:" + qsize, qsize >= 224);
break;
case 3072:
isTrue("Invalid qsize for 3072 bit key:" + qsize, qsize >= 256);
break;
default:
fail("Invalid key size:" + keysize);
}
// Check the length of the private key.
// For example GPG4Browsers or the KJUR library derived from it use
// q.bitCount() instead of q.bitLength() to determine the size of the private key
// and hence would generate keys that are much too small.
isTrue("privkey error", priv.getX().bitLength() >= qsize - 32);
}
private void testKeyGenerationAll()
throws Exception
{
testKeyGeneration(1024);
testKeyGeneration(2048);
testKeyGeneration(3072);
}
public void performTest()
throws Exception
{
testCompat();
testNONEwithDSA();
testRIPEMD160withDSA();
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16));
testECDSA239bitPrime();
testNONEwithECDSA239bitPrime();
testECDSA239bitBinary();
testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160);
testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1);
testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224);
testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256);
testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384);
testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512);
testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1);
testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224);
testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256);
testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384);
testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512);
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16));
testGeneration();
testParameters();
testDSA2Parameters();
testNullParameters();
testValidate();
testModified();
testKeyGenerationAll();
}
protected BigInteger[] derDecode(
byte[] encoding)
throws IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);
ASN1InputStream aIn = new ASN1InputStream(bIn);
ASN1Sequence s = (ASN1Sequence)aIn.readObject();
BigInteger[] sig = new BigInteger[2];
sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue();
sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue();
return sig;
}
public String getName()
{
return "DSA/ECDSA";
}
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new DSATest());
}
private class DSATestSecureRandom
extends TestRandomData
{
private boolean first = true;
public DSATestSecureRandom(byte[] value)
{
super(value);
}
public void nextBytes(byte[] bytes)
{
if (first)
{
super.nextBytes(bytes);
first = false;
}
else
{
bytes[bytes.length - 1] = 2;
}
}
}
}
| import cleanup
| prov/src/test/java/org/bouncycastle/jce/provider/test/DSATest.java | import cleanup |
|
Java | epl-1.0 | 2a33efcf59165861e3ed6bb9387c1f2ab5046ec6 | 0 | G-vdBeck/camunda-modeler,camunda/camunda-eclipse-plugin,G-vdBeck/camunda-modeler,camunda/camunda-eclipse-plugin | /*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*
* @author Bob Brodt
******************************************************************************/
package org.eclipse.bpmn2.modeler.ui.property;
import org.eclipse.bpmn2.modeler.core.features.AbstractBpmn2CreateConnectionFeature;
import org.eclipse.bpmn2.modeler.core.features.AbstractBpmn2CreateFeature;
import org.eclipse.bpmn2.modeler.core.features.AbstractCreateFlowElementFeature;
import org.eclipse.bpmn2.modeler.core.features.BusinessObjectUtil;
import org.eclipse.bpmn2.modeler.ui.diagram.BPMNFeatureProvider;
import org.eclipse.bpmn2.modeler.ui.editor.BPMN2Editor;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.RootEditPart;
import org.eclipse.gef.ui.parts.GraphicalEditor;
import org.eclipse.graphiti.dt.IDiagramType;
import org.eclipse.graphiti.dt.IDiagramTypeProvider;
import org.eclipse.graphiti.features.IAddFeature;
import org.eclipse.graphiti.features.ICreateConnectionFeature;
import org.eclipse.graphiti.features.ICreateFeature;
import org.eclipse.graphiti.features.IFeature;
import org.eclipse.graphiti.features.context.impl.AddContext;
import org.eclipse.graphiti.mm.algorithms.GraphicsAlgorithm;
import org.eclipse.graphiti.mm.algorithms.impl.ImageImpl;
import org.eclipse.graphiti.mm.pictograms.Connection;
import org.eclipse.graphiti.mm.pictograms.ContainerShape;
import org.eclipse.graphiti.mm.pictograms.Diagram;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import org.eclipse.graphiti.mm.pictograms.Shape;
import org.eclipse.graphiti.services.Graphiti;
import org.eclipse.graphiti.ui.editor.DiagramEditor;
import org.eclipse.graphiti.ui.internal.editor.DiagramEditorInternal;
import org.eclipse.graphiti.ui.services.GraphitiUi;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.internal.Workbench;
/**
* @author Bob Brodt
*
*/
public class PropertyLabelProvider extends LabelProvider {
@Override
public Image getImage(Object element) {
IWorkbenchWindow workbenchWindow = Workbench.getInstance().getActiveWorkbenchWindow();
if (workbenchWindow==null || workbenchWindow.getActivePage()==null)
return null;
BPMN2Editor editor = (BPMN2Editor)workbenchWindow.getActivePage().getActiveEditor();
if (editor==null)
return null;
BPMNFeatureProvider fp = (BPMNFeatureProvider)editor.getDiagramTypeProvider().getFeatureProvider();
PictogramElement pe = getPictogramElement(element);
IFeature cf = fp.getCreateFeatureForPictogramElement(pe);
if (cf instanceof AbstractBpmn2CreateFeature) {
return GraphitiUi.getImageService().getImageForId(
((AbstractBpmn2CreateFeature)cf).getCreateImageId());
}
if (cf instanceof AbstractBpmn2CreateConnectionFeature) {
return GraphitiUi.getImageService().getImageForId(
((AbstractBpmn2CreateConnectionFeature)cf).getCreateImageId());
}
return super.getImage(element);
}
@Override
public String getText(Object element) {
PictogramElement pe = getPictogramElement(element);
if (pe!=null) {
EObject be = BusinessObjectUtil.getFirstElementOfType(pe, EObject.class);
if (be!=null) {
EStructuralFeature feature = be.eClass().getEStructuralFeature("name");
if (feature!=null) {
String name = (String)be.eGet(feature);
if (name==null || name.isEmpty())
name = "Unnamed " + be.eClass().getName();
else
name = be.eClass().getName() + " \"" + name + "\"";
return name;
}
return be.eClass().getName();
}
}
return super.getText(element);
}
EditPart getEditPart(Object element) {
if (element instanceof IStructuredSelection &&
((IStructuredSelection) element).isEmpty()==false) {
Object firstElement = ((IStructuredSelection) element).getFirstElement();
EditPart editPart = null;
if (firstElement instanceof EditPart) {
editPart = (EditPart) firstElement;
} else if (firstElement instanceof IAdaptable) {
editPart = (EditPart) ((IAdaptable) firstElement).getAdapter(EditPart.class);
}
return editPart;
}
return null;
}
PictogramElement getPictogramElement(Object element) {
EditPart editPart = getEditPart(element);
if (editPart != null && editPart.getModel() instanceof PictogramElement) {
return (PictogramElement) editPart.getModel();
}
return null;
}
}
| org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/property/PropertyLabelProvider.java | /*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*
* @author Bob Brodt
******************************************************************************/
package org.eclipse.bpmn2.modeler.ui.property;
import org.eclipse.bpmn2.modeler.core.features.AbstractBpmn2CreateConnectionFeature;
import org.eclipse.bpmn2.modeler.core.features.AbstractBpmn2CreateFeature;
import org.eclipse.bpmn2.modeler.core.features.AbstractCreateFlowElementFeature;
import org.eclipse.bpmn2.modeler.core.features.BusinessObjectUtil;
import org.eclipse.bpmn2.modeler.ui.diagram.BPMNFeatureProvider;
import org.eclipse.bpmn2.modeler.ui.editor.BPMN2Editor;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.RootEditPart;
import org.eclipse.gef.ui.parts.GraphicalEditor;
import org.eclipse.graphiti.dt.IDiagramType;
import org.eclipse.graphiti.dt.IDiagramTypeProvider;
import org.eclipse.graphiti.features.IAddFeature;
import org.eclipse.graphiti.features.ICreateConnectionFeature;
import org.eclipse.graphiti.features.ICreateFeature;
import org.eclipse.graphiti.features.IFeature;
import org.eclipse.graphiti.features.context.impl.AddContext;
import org.eclipse.graphiti.mm.algorithms.GraphicsAlgorithm;
import org.eclipse.graphiti.mm.algorithms.impl.ImageImpl;
import org.eclipse.graphiti.mm.pictograms.Connection;
import org.eclipse.graphiti.mm.pictograms.ContainerShape;
import org.eclipse.graphiti.mm.pictograms.Diagram;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import org.eclipse.graphiti.mm.pictograms.Shape;
import org.eclipse.graphiti.services.Graphiti;
import org.eclipse.graphiti.ui.editor.DiagramEditor;
import org.eclipse.graphiti.ui.internal.editor.DiagramEditorInternal;
import org.eclipse.graphiti.ui.services.GraphitiUi;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.internal.Workbench;
/**
* @author Bob Brodt
*
*/
public class PropertyLabelProvider extends LabelProvider {
@Override
public Image getImage(Object element) {
IWorkbenchWindow workbenchWindow = Workbench.getInstance().getActiveWorkbenchWindow();
if (workbenchWindow==null || workbenchWindow.getActivePage()==null)
return null;
BPMN2Editor editor = (BPMN2Editor)workbenchWindow.getActivePage().getActiveEditor();
if (editor==null)
return null;
BPMNFeatureProvider fp = (BPMNFeatureProvider)editor.getDiagramTypeProvider().getFeatureProvider();
PictogramElement pe = getPictogramElement(element);
if (pe!=null) {
EObject be = Graphiti.getLinkService().getBusinessObjectForLinkedPictogramElement(pe);
IFeature cf = fp.getCreateFeatureForPictogramElement(pe);
if (cf instanceof AbstractBpmn2CreateConnectionFeature) {
AbstractBpmn2CreateConnectionFeature acf = (AbstractBpmn2CreateConnectionFeature)cf;
Class beclass = be.getClass();
Class feclass = acf.getBusinessObjectClass();
if (feclass.isInterface()) {
Class[] ifs = beclass.getInterfaces();
if (ifs.length>0 && ifs[0].equals(feclass)) {
return GraphitiUi.getImageService().getImageForId(acf.getCreateImageId());
}
}
}
else if (cf instanceof AbstractBpmn2CreateFeature) {
AbstractBpmn2CreateFeature acf = (AbstractBpmn2CreateFeature)cf;
Class beclass = be.getClass();
Class feclass = acf.getBusinessObjectClass();
if (feclass.isInterface()) {
Class[] ifs = beclass.getInterfaces();
if (ifs.length>0 && ifs[0].equals(feclass)) {
return GraphitiUi.getImageService().getImageForId(acf.getCreateImageId());
}
}
}
}
return super.getImage(element);
}
@Override
public String getText(Object element) {
PictogramElement pe = getPictogramElement(element);
if (pe!=null) {
EObject be = BusinessObjectUtil.getFirstElementOfType(pe, EObject.class);
if (be!=null) {
EStructuralFeature feature = be.eClass().getEStructuralFeature("name");
if (feature!=null) {
String name = (String)be.eGet(feature);
if (name==null || name.isEmpty())
name = "Unnamed " + be.eClass().getName();
else
name = be.eClass().getName() + " \"" + name + "\"";
return name;
}
return be.eClass().getName();
}
}
return super.getText(element);
}
EditPart getEditPart(Object element) {
if (element instanceof IStructuredSelection &&
((IStructuredSelection) element).isEmpty()==false) {
Object firstElement = ((IStructuredSelection) element).getFirstElement();
EditPart editPart = null;
if (firstElement instanceof EditPart) {
editPart = (EditPart) firstElement;
} else if (firstElement instanceof IAdaptable) {
editPart = (EditPart) ((IAdaptable) firstElement).getAdapter(EditPart.class);
}
return editPart;
}
return null;
}
PictogramElement getPictogramElement(Object element) {
EditPart editPart = getEditPart(element);
if (editPart != null && editPart.getModel() instanceof PictogramElement) {
return (PictogramElement) editPart.getModel();
}
return null;
}
}
| Changed PropertLabelProvider to use new BPMNFeatureProvider methods | org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/property/PropertyLabelProvider.java | Changed PropertLabelProvider to use new BPMNFeatureProvider methods |
|
Java | lgpl-2.1 | eb8670a560794ac44de539b1a33d86d522894e20 | 0 | wolfgangmm/exist,windauer/exist,windauer/exist,lcahlander/exist,windauer/exist,windauer/exist,lcahlander/exist,wolfgangmm/exist,dizzzz/exist,lcahlander/exist,eXist-db/exist,windauer/exist,eXist-db/exist,wolfgangmm/exist,adamretter/exist,eXist-db/exist,adamretter/exist,lcahlander/exist,windauer/exist,adamretter/exist,eXist-db/exist,dizzzz/exist,dizzzz/exist,wolfgangmm/exist,wolfgangmm/exist,lcahlander/exist,dizzzz/exist,eXist-db/exist,adamretter/exist,lcahlander/exist,dizzzz/exist,adamretter/exist,eXist-db/exist,wolfgangmm/exist,dizzzz/exist,adamretter/exist | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* [email protected]
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.protocolhandler.embedded;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import com.evolvedbinary.j8fu.Either;
import com.evolvedbinary.j8fu.lazy.LazyValE;
import net.jcip.annotations.NotThreadSafe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.dom.persistent.BinaryDocument;
import org.exist.dom.persistent.DocumentImpl;
import org.exist.dom.persistent.LockedDocument;
import org.exist.protocolhandler.xmldb.XmldbURL;
import org.exist.security.PermissionDeniedException;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.lock.Lock;
import org.exist.storage.serializers.EXistOutputKeys;
import org.exist.storage.serializers.Serializer;
import org.exist.util.io.CloseNotifyingInputStream;
import org.exist.util.io.TemporaryFileManager;
import org.exist.xmldb.XmldbURI;
import org.xml.sax.SAXException;
import javax.annotation.Nullable;
import static com.evolvedbinary.j8fu.Either.Left;
import static com.evolvedbinary.j8fu.Either.Right;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Read document from embedded database as an InputStream.
*
* @author <a href="mailto:[email protected]">Adam Retter</a>
* @author Dannes Wessels
*/
@NotThreadSafe
public class EmbeddedInputStream extends InputStream {
private static final Logger LOG = LogManager.getLogger(EmbeddedInputStream.class);
private final XmldbURL url;
private final LazyValE<InputStream, IOException> underlyingStream;
private boolean closed = false;
/**
* @param url Location of document in database.
*
* @throws IOException if there is a problem accessing the database instance.
*/
public EmbeddedInputStream(final XmldbURL url) throws IOException {
this(null, url);
}
/**
* @param brokerPool the database instance.
* @param url Location of document in database.
*
* @throws IOException if there is a problem accessing the database instance.
*/
public EmbeddedInputStream(@Nullable final BrokerPool brokerPool, final XmldbURL url) throws IOException {
try {
this.url = url;
final BrokerPool pool = brokerPool == null ? BrokerPool.getInstance(url.getInstanceName()) : brokerPool;
this.underlyingStream = new LazyValE<>(() -> openStream(pool, url));
} catch (final EXistException e) {
throw new IOException(e);
}
}
private static Either<IOException, InputStream> openStream(final BrokerPool pool, final XmldbURL url) {
if (LOG.isDebugEnabled()) {
LOG.debug("Begin document download");
}
try {
final XmldbURI path = XmldbURI.create(url.getPath());
try (final DBBroker broker = pool.getBroker()) {
try(final LockedDocument lockedResource = broker.getXMLResource(path, Lock.LockMode.READ_LOCK)) {
if (lockedResource == null) {
// Test for collection
try(final Collection collection = broker.openCollection(path, Lock.LockMode.READ_LOCK)) {
if (collection == null) {
// No collection, no document
return Left(new IOException("Resource " + url.getPath() + " not found."));
} else {
// Collection
return Left(new IOException("Resource " + url.getPath() + " is a collection."));
}
}
} else {
final DocumentImpl resource = lockedResource.getDocument();
if (resource.getResourceType() == DocumentImpl.XML_FILE) {
// final Serializer serializer = broker.getSerializer();
// serializer.reset();
// TODO(AR) broker's serializer may already be in the process of serializing a document when this is called (e.g. XSL Processing Instruction), switch Broker to have a Pool of Serializer and remove its newSerializer method in favour of borrowing!
final Serializer serializer = broker.newSerializer();
// Preserve doctype
serializer.setProperty(EXistOutputKeys.OUTPUT_DOCTYPE, "yes");
// serialize the XML to a temporary file
final TemporaryFileManager tempFileManager = TemporaryFileManager.getInstance();
final Path tempFile = tempFileManager.getTemporaryFile();
try (final Writer writer = Files.newBufferedWriter(tempFile, UTF_8, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
serializer.serialize(resource, writer);
}
// NOTE: the temp file will be returned to the manager when the InputStream is closed
return Right(new CloseNotifyingInputStream(Files.newInputStream(tempFile, StandardOpenOption.READ), () -> tempFileManager.returnTemporaryFile(tempFile)));
} else if (resource.getResourceType() == BinaryDocument.BINARY_FILE) {
return Right(broker.getBinaryResource((BinaryDocument) resource));
} else {
return Left(new IOException("Unknown resource type " + url.getPath() + ": " + resource.getResourceType()));
}
}
} finally {
if (LOG.isDebugEnabled()) {
LOG.debug("End document download");
}
}
}
} catch (final EXistException | PermissionDeniedException | SAXException e) {
LOG.error(e);
return Left(new IOException(e.getMessage(), e));
} catch (final IOException e) {
return Left(e);
}
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
if (closed) {
throw new IOException("The underlying stream is closed");
}
return underlyingStream.get().read(b, off, len);
}
@Override
public int read(final byte[] b) throws IOException {
if (closed) {
throw new IOException("The underlying stream is closed");
}
return underlyingStream.get().read(b, 0, b.length);
}
@Override
public long skip(final long n) throws IOException {
if (closed) {
throw new IOException("The underlying stream is closed");
}
return underlyingStream.get().skip(n);
}
@Override
public boolean markSupported() {
if (closed) {
return false;
}
try {
return underlyingStream.get().markSupported();
} catch (final IOException e) {
LOG.error(e);
return false;
}
}
@Override
public void mark(final int readlimit) {
if (closed) {
return;
}
try {
underlyingStream.get().mark(readlimit);
} catch (final IOException e) {
LOG.error(e);
}
}
@Override
public void reset() throws IOException {
if (closed) {
return;
}
underlyingStream.get().reset();
}
@Override
public int read() throws IOException {
if (closed) {
return -1;
}
return underlyingStream.get().read();
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
try {
if (underlyingStream.isInitialized()) {
underlyingStream.get().close();
}
} finally {
closed = true;
}
}
@Override
public int available() throws IOException {
if (closed) {
return 0;
}
return underlyingStream.get().available();
}
}
| exist-core/src/main/java/org/exist/protocolhandler/embedded/EmbeddedInputStream.java | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* [email protected]
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.protocolhandler.embedded;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import com.evolvedbinary.j8fu.Either;
import com.evolvedbinary.j8fu.lazy.LazyValE;
import net.jcip.annotations.NotThreadSafe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.dom.persistent.BinaryDocument;
import org.exist.dom.persistent.DocumentImpl;
import org.exist.dom.persistent.LockedDocument;
import org.exist.protocolhandler.xmldb.XmldbURL;
import org.exist.security.PermissionDeniedException;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.lock.Lock;
import org.exist.storage.serializers.EXistOutputKeys;
import org.exist.storage.serializers.Serializer;
import org.exist.util.io.CloseNotifyingInputStream;
import org.exist.util.io.TemporaryFileManager;
import org.exist.xmldb.XmldbURI;
import org.xml.sax.SAXException;
import javax.annotation.Nullable;
import static com.evolvedbinary.j8fu.Either.Left;
import static com.evolvedbinary.j8fu.Either.Right;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Read document from embedded database as an InputStream.
*
* @author <a href="mailto:[email protected]">Adam Retter</a>
* @author Dannes Wessels
*/
@NotThreadSafe
public class EmbeddedInputStream extends InputStream {
private static final Logger LOG = LogManager.getLogger(EmbeddedInputStream.class);
private final XmldbURL url;
private final LazyValE<InputStream, IOException> underlyingStream;
private boolean closed = false;
/**
* @param url Location of document in database.
*
* @throws IOException if there is a problem accessing the database instance.
*/
public EmbeddedInputStream(final XmldbURL url) throws IOException {
this(null, url);
}
/**
* @param brokerPool the database instance.
* @param url Location of document in database.
*
* @throws IOException if there is a problem accessing the database instance.
*/
public EmbeddedInputStream(@Nullable final BrokerPool brokerPool, final XmldbURL url) throws IOException {
try {
this.url = url;
final BrokerPool pool = brokerPool == null ? BrokerPool.getInstance(url.getInstanceName()) : brokerPool;
this.underlyingStream = new LazyValE<>(() -> openStream(pool, url));
} catch (final EXistException e) {
throw new IOException(e);
}
}
private static Either<IOException, InputStream> openStream(final BrokerPool pool, final XmldbURL url) {
if (LOG.isDebugEnabled()) {
LOG.debug("Begin document download");
}
try {
final XmldbURI path = XmldbURI.create(url.getPath());
try (final DBBroker broker = pool.getBroker()) {
try(final LockedDocument lockedResource = broker.getXMLResource(path, Lock.LockMode.READ_LOCK)) {
if (lockedResource == null) {
// Test for collection
try(final Collection collection = broker.openCollection(path, Lock.LockMode.READ_LOCK)) {
if (collection == null) {
// No collection, no document
return Left(new IOException("Resource " + url.getPath() + " not found."));
} else {
// Collection
return Left(new IOException("Resource " + url.getPath() + " is a collection."));
}
}
} else {
final DocumentImpl resource = lockedResource.getDocument();
if (resource.getResourceType() == DocumentImpl.XML_FILE) {
final Serializer serializer = broker.getSerializer();
serializer.reset();
// Preserve doctype
serializer.setProperty(EXistOutputKeys.OUTPUT_DOCTYPE, "yes");
// serialize the XML to a temporary file
final TemporaryFileManager tempFileManager = TemporaryFileManager.getInstance();
final Path tempFile = tempFileManager.getTemporaryFile();
try (final Writer writer = Files.newBufferedWriter(tempFile, UTF_8, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
serializer.serialize(resource, writer);
}
// NOTE: the temp file will be returned to the manager when the InputStream is closed
return Right(new CloseNotifyingInputStream(Files.newInputStream(tempFile, StandardOpenOption.READ), () -> tempFileManager.returnTemporaryFile(tempFile)));
} else if (resource.getResourceType() == BinaryDocument.BINARY_FILE) {
return Right(broker.getBinaryResource((BinaryDocument) resource));
} else {
return Left(new IOException("Unknown resource type " + url.getPath() + ": " + resource.getResourceType()));
}
}
} finally {
if (LOG.isDebugEnabled()) {
LOG.debug("End document download");
}
}
}
} catch (final EXistException | PermissionDeniedException | SAXException e) {
LOG.error(e);
return Left(new IOException(e.getMessage(), e));
} catch (final IOException e) {
return Left(e);
}
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
if (closed) {
throw new IOException("The underlying stream is closed");
}
return underlyingStream.get().read(b, off, len);
}
@Override
public int read(final byte[] b) throws IOException {
if (closed) {
throw new IOException("The underlying stream is closed");
}
return underlyingStream.get().read(b, 0, b.length);
}
@Override
public long skip(final long n) throws IOException {
if (closed) {
throw new IOException("The underlying stream is closed");
}
return underlyingStream.get().skip(n);
}
@Override
public boolean markSupported() {
if (closed) {
return false;
}
try {
return underlyingStream.get().markSupported();
} catch (final IOException e) {
LOG.error(e);
return false;
}
}
@Override
public void mark(final int readlimit) {
if (closed) {
return;
}
try {
underlyingStream.get().mark(readlimit);
} catch (final IOException e) {
LOG.error(e);
}
}
@Override
public void reset() throws IOException {
if (closed) {
return;
}
underlyingStream.get().reset();
}
@Override
public int read() throws IOException {
if (closed) {
return -1;
}
return underlyingStream.get().read();
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
try {
if (underlyingStream.isInitialized()) {
underlyingStream.get().close();
}
} finally {
closed = true;
}
}
@Override
public int available() throws IOException {
if (closed) {
return 0;
}
return underlyingStream.get().available();
}
}
| [bugfix] Cannot use Serializer if called from with Serializer, e.g. when processing an XSL Processing Instruction
| exist-core/src/main/java/org/exist/protocolhandler/embedded/EmbeddedInputStream.java | [bugfix] Cannot use Serializer if called from with Serializer, e.g. when processing an XSL Processing Instruction |
|
Java | unlicense | 92501ec3aaee47ced677e96a6a444fac99a4725c | 0 | EgonOlsen71/basicv2,EgonOlsen71/basicv2 | package com.sixtyfour.cbmnative.mos6502.generators;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.sixtyfour.Logger;
import com.sixtyfour.elements.Type;
public class Movb extends GeneratorBase {
private static int MOV_CNT=0;
@Override
public String getMnemonic() {
return "MOVB";
}
@Override
public void generateCode(GeneratorContext context, String line, List<String> nCode, List<String> subCode, Map<String, String> name2label) {
Operands ops = new Operands(line, name2label);
Logger.log(line + " -- " + ops.getTarget() + " ||| " + ops.getSource());
MOV_CNT++;
Operand source = ops.getSource();
Operand target = ops.getTarget();
context.setLastMoveSource(source);
context.setLastMoveTarget(target);
if (!source.isIndexed() && !target.isIndexed()) {
if (source.getType() == Type.INTEGER) {
noIndexIntegerSource(nCode, source, target);
} else {
noIndexRealSource(nCode, source, target);
}
} else {
if (target.isIndexed() && source.isIndexed()) {
throw new RuntimeException("Invalid index mode (both sides are indexed!): " + line);
}
if (!target.isRegister() || !source.isRegister()) {
if (target.isRegister() && source.isConstant()) {
indexedTargetWithConstant(nCode, source, target);
} else {
throw new RuntimeException("Invalid index mode (at least one side isn't a register and source isn't a constant value either!): " + line);
}
} else {
if (target.isIndexed()) {
indexedTarget(nCode, source, target);
} else {
indexedSource(nCode, source, target);
}
}
}
}
private void indexedTargetWithConstant(List<String> nCode, Operand source, Operand target) {
createIndexedTargetCode(nCode, target);
nCode.add("LDA #$" + Integer.toHexString(Integer.parseInt(source.getValue().substring(1))).toUpperCase(Locale.ENGLISH));
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("STA $FFFF");
}
private void createIndexedTargetCode(List<String> nCode, Operand target) {
if (target.getType() == Type.INTEGER) {
nCode.add("LDY " + target.getRegisterName());
nCode.add("LDA " + createAddress(target.getRegisterName(), 1));
nCode.add("STY TMP_REG");
nCode.add("STA TMP_REG+1");
} else {
nCode.add("LDA #<" + target.getRegisterName());
nCode.add("LDY #>" + target.getRegisterName());
nCode.add("; Real in (A/Y) to FAC");
nCode.add("JSR REALFAC"); // Real in (A/Y) to FAC
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
String lab="MOVBSELF"+MOV_CNT;
nCode.add("STY "+lab+"+1");
nCode.add("STA "+lab+"+2");
}
}
private void indexedSource(List<String> nCode, Operand source, Operand target) {
createIndexedTargetCode(nCode, source);
if (target.getType() == Type.INTEGER) {
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("LDA $FFFF");
nCode.add("STA " + target.getRegisterName());
nCode.add("STY " + createAddress(target.getRegisterName(), 1));
} else {
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("LDY $FFFF");
nCode.add("LDA #0");
nCode.add("; integer in Y/A to FAC");
nCode.add("JSR INTFAC"); // integer in A/Y to FAC
nCode.add("LDX #<" + target.getRegisterName());
nCode.add("LDY #>" + target.getRegisterName());
nCode.add("; FAC to (X/Y)");
nCode.add("JSR FACMEM"); // FAC to (X/Y)
}
}
private void indexedTarget(List<String> nCode, Operand source, Operand target) {
createIndexedTargetCode(nCode, target);
if (source.getType() == Type.INTEGER) {
nCode.add("LDA " + source.getRegisterName());
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("STA $FFFF");
} else {
nCode.add("LDA #<" + source.getRegisterName());
nCode.add("LDY #>" + source.getRegisterName());
nCode.add("; Real in (A/Y) to FAC");
nCode.add("JSR REALFAC"); // Real in (A/Y) to FAC
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("STY $FFFF");
}
}
private void noIndexRealSource(List<String> nCode, Operand source, Operand target) {
// Source is REAL
if (source.isRegister()) {
nCode.add("LDA #<" + source.getRegisterName());
nCode.add("LDY #>" + source.getRegisterName());
} else {
checkSpecialReadVars(nCode, source);
nCode.add("LDA #<" + source.getAddress());
nCode.add("LDY #>" + source.getAddress());
}
nCode.add("; Real in (A/Y) to FAC");
nCode.add("JSR REALFAC"); // Real in (A/Y) to FAC
if (target.isAddress()) {
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("STY " + target.getAddress());
} else {
if (target.getType() == Type.INTEGER) {
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("STY " + target.getRegisterName());
nCode.add("STA " + this.createAddress(target.getRegisterName(), 1));
} else {
nCode.add("LDX #<" + target.getRegisterName());
nCode.add("LDY #>" + target.getRegisterName());
nCode.add("; FAC to (X/Y)");
nCode.add("JSR FACMEM"); // FAC to (X/Y)
}
}
}
private void noIndexIntegerSource(List<String> nCode, Operand source, Operand target) {
// Source is INTEGER
if (source.isRegister()) {
nCode.add("LDY " + source.getRegisterName());
nCode.add("LDA #0");
} else {
nCode.add("LDY " + source.getAddress());
nCode.add("LDA #0");
}
if (target.getType() == Type.INTEGER) {
nCode.add("STY " + target.getAddress());
} else {
nCode.add("; integer in Y/A to FAC");
nCode.add("JSR INTFAC"); // integer in Y/A to FAC
if (target.isAddress()) {
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("STY " + target.getAddress());
} else {
if (target.getType() == Type.INTEGER) {
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("STY " + target.getRegisterName());
nCode.add("STA " + this.createAddress(target.getRegisterName(), 1));
} else {
nCode.add("LDX #<" + target.getRegisterName());
nCode.add("LDY #>" + target.getRegisterName());
nCode.add("; FAC to (X/Y)");
nCode.add("JSR FACMEM"); // FAC to (X/Y)
}
}
}
}
}
| src/main/java/com/sixtyfour/cbmnative/mos6502/generators/Movb.java | package com.sixtyfour.cbmnative.mos6502.generators;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.sixtyfour.Logger;
import com.sixtyfour.elements.Type;
public class Movb extends GeneratorBase {
private static int MOV_CNT=0;
@Override
public String getMnemonic() {
return "MOVB";
}
@Override
public void generateCode(GeneratorContext context, String line, List<String> nCode, List<String> subCode, Map<String, String> name2label) {
Operands ops = new Operands(line, name2label);
Logger.log(line + " -- " + ops.getTarget() + " ||| " + ops.getSource());
MOV_CNT++;
Operand source = ops.getSource();
Operand target = ops.getTarget();
context.setLastMoveSource(source);
context.setLastMoveTarget(target);
if (!source.isIndexed() && !target.isIndexed()) {
if (source.getType() == Type.INTEGER) {
noIndexIntegerSource(nCode, source, target);
} else {
noIndexRealSource(nCode, source, target);
}
} else {
if (target.isIndexed() && source.isIndexed()) {
throw new RuntimeException("Invalid index mode (both sides are indexed!): " + line);
}
if (!target.isRegister() || !source.isRegister()) {
if (target.isRegister() && source.isConstant()) {
indexedTargetWithConstant(nCode, source, target);
} else {
throw new RuntimeException("Invalid index mode (at least one side isn't a register and source isn't a constant value either!): " + line);
}
} else {
if (target.isIndexed()) {
indexedTarget(nCode, source, target);
} else {
indexedSource(nCode, source, target);
}
}
}
}
private void indexedTargetWithConstant(List<String> nCode, Operand source, Operand target) {
createIndexedTargetCode(nCode, target);
nCode.add("LDA #$" + Integer.toHexString(Integer.parseInt(source.getValue().substring(1))).toUpperCase(Locale.ENGLISH));
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("STA $FFFF");
}
private void createIndexedTargetCode(List<String> nCode, Operand target) {
if (target.getType() == Type.INTEGER) {
nCode.add("LDY " + target.getRegisterName());
nCode.add("LDA " + createAddress(target.getRegisterName(), 1));
nCode.add("STY TMP_REG");
nCode.add("STA TMP_REG+1");
} else {
nCode.add("LDA #<" + target.getRegisterName());
nCode.add("LDY #>" + target.getRegisterName());
nCode.add("; Real in (A/Y) to FAC");
nCode.add("JSR REALFAC"); // Real in (A/Y) to FAC
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
String lab="MOVBSELF"+MOV_CNT;
nCode.add("STY "+lab+"+1");
nCode.add("STA "+lab+"+2");
}
}
private void indexedSource(List<String> nCode, Operand source, Operand target) {
createIndexedTargetCode(nCode, source);
if (target.getType() == Type.INTEGER) {
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("LDA $FFFF");
nCode.add("STA " + target.getRegisterName());
nCode.add("STY " + createAddress(target.getRegisterName(), 1));
} else {
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("LDA $FFFF");
nCode.add("TAY");
nCode.add("LDA #0");
nCode.add("; integer in Y/A to FAC");
nCode.add("JSR INTFAC"); // integer in A/Y to FAC
nCode.add("LDX #<" + target.getRegisterName());
nCode.add("LDY #>" + target.getRegisterName());
nCode.add("; FAC to (X/Y)");
nCode.add("JSR FACMEM"); // FAC to (X/Y)
}
}
private void indexedTarget(List<String> nCode, Operand source, Operand target) {
createIndexedTargetCode(nCode, target);
if (source.getType() == Type.INTEGER) {
nCode.add("LDA " + source.getRegisterName());
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("STA $FFFF");
} else {
nCode.add("LDA #<" + source.getRegisterName());
nCode.add("LDY #>" + source.getRegisterName());
nCode.add("; Real in (A/Y) to FAC");
nCode.add("JSR REALFAC"); // Real in (A/Y) to FAC
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("MOVBSELF"+MOV_CNT+":");
nCode.add("STY $FFFF");
}
}
private void noIndexRealSource(List<String> nCode, Operand source, Operand target) {
// Source is REAL
if (source.isRegister()) {
nCode.add("LDA #<" + source.getRegisterName());
nCode.add("LDY #>" + source.getRegisterName());
} else {
checkSpecialReadVars(nCode, source);
nCode.add("LDA #<" + source.getAddress());
nCode.add("LDY #>" + source.getAddress());
}
nCode.add("; Real in (A/Y) to FAC");
nCode.add("JSR REALFAC"); // Real in (A/Y) to FAC
if (target.isAddress()) {
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("STY " + target.getAddress());
} else {
if (target.getType() == Type.INTEGER) {
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("STY " + target.getRegisterName());
nCode.add("STA " + this.createAddress(target.getRegisterName(), 1));
} else {
nCode.add("LDX #<" + target.getRegisterName());
nCode.add("LDY #>" + target.getRegisterName());
nCode.add("; FAC to (X/Y)");
nCode.add("JSR FACMEM"); // FAC to (X/Y)
}
}
}
private void noIndexIntegerSource(List<String> nCode, Operand source, Operand target) {
// Source is INTEGER
if (source.isRegister()) {
nCode.add("LDY " + source.getRegisterName());
nCode.add("LDA #0");
} else {
nCode.add("LDY " + source.getAddress());
nCode.add("LDA #0");
}
if (target.getType() == Type.INTEGER) {
nCode.add("STY " + target.getAddress());
} else {
nCode.add("; integer in Y/A to FAC");
nCode.add("JSR INTFAC"); // integer in Y/A to FAC
if (target.isAddress()) {
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("STY " + target.getAddress());
} else {
if (target.getType() == Type.INTEGER) {
nCode.add("; FAC to integer in Y/A");
nCode.add("JSR FACWORD"); // FAC to integer in Y/A
nCode.add("STY " + target.getRegisterName());
nCode.add("STA " + this.createAddress(target.getRegisterName(), 1));
} else {
nCode.add("LDX #<" + target.getRegisterName());
nCode.add("LDY #>" + target.getRegisterName());
nCode.add("; FAC to (X/Y)");
nCode.add("JSR FACMEM"); // FAC to (X/Y)
}
}
}
}
}
| Small tweak | src/main/java/com/sixtyfour/cbmnative/mos6502/generators/Movb.java | Small tweak |
|
Java | apache-2.0 | 9173d32256e5d66ca2273fb4eaaae658554aff10 | 0 | missioncommand/emp3-android,missioncommand/emp3-android | package mil.emp3.core.editors;
import org.cmapi.primitives.GeoPosition;
import org.cmapi.primitives.IGeoPosition;
import java.util.ArrayList;
import java.util.List;
import mil.emp3.api.enums.FeatureEditUpdateTypeEnum;
import mil.emp3.api.exceptions.EMP_Exception;
import mil.emp3.api.interfaces.IFeature;
import mil.emp3.api.listeners.IDrawEventListener;
import mil.emp3.api.listeners.IEditEventListener;
import mil.emp3.api.utils.GeographicLib;
import mil.emp3.mapengine.interfaces.IMapInstance;
/**
* This abstract class handles features that rare single point type features.
*/
public abstract class AbstractSinglePointEditor<T extends IFeature> extends AbstractDrawEditEditor<T> {
protected AbstractSinglePointEditor(IMapInstance map, T feature, IEditEventListener oEventListener, boolean bUsesCP) throws EMP_Exception {
super(map, feature, oEventListener, bUsesCP);
}
protected AbstractSinglePointEditor(IMapInstance map, T feature, IDrawEventListener oEventListener, boolean bUsesCP, boolean newFeature) throws EMP_Exception {
super(map, feature, oEventListener, bUsesCP, newFeature);
}
@Override
protected void prepareForDraw() throws EMP_Exception {
if (!this.isNewFeature()) {
// A feature that already exists should have all of its properties set already.
return;
}
this.oFeature.getPositions().add(getCenter());
}
@Override
protected boolean moveIconTo(IGeoPosition oLatLng) {
IGeoPosition oPos = this.getFeature().getPositions().get(0);
oPos.setLatitude(oLatLng.getLatitude());
oPos.setLongitude(oLatLng.getLongitude());
return true;
}
@Override
protected boolean doFeatureMove(double dBearing, double dDistance) {
IFeature oFeature = this.getFeature();
IGeoPosition oPos = oFeature.getPositions().get(0);
GeographicLib.computePositionAt(dBearing, dDistance, oPos, oPos);
// this.addUpdateEventData(FeatureEditUpdateTypeEnum.COORDINATE_MOVED, new int[]{0}); TODO causes duplicate events.
return true;
}
}
| sdk/sdk-core/aar/src/main/java/mil/emp3/core/editors/AbstractSinglePointEditor.java | package mil.emp3.core.editors;
import org.cmapi.primitives.GeoPosition;
import org.cmapi.primitives.IGeoPosition;
import java.util.ArrayList;
import java.util.List;
import mil.emp3.api.enums.FeatureEditUpdateTypeEnum;
import mil.emp3.api.exceptions.EMP_Exception;
import mil.emp3.api.interfaces.IFeature;
import mil.emp3.api.listeners.IDrawEventListener;
import mil.emp3.api.listeners.IEditEventListener;
import mil.emp3.api.utils.GeoLibrary;
import mil.emp3.mapengine.interfaces.IMapInstance;
/**
* This abstract class handles features that rare single point type features.
*/
public abstract class AbstractSinglePointEditor<T extends IFeature> extends AbstractDrawEditEditor<T> {
protected AbstractSinglePointEditor(IMapInstance map, T feature, IEditEventListener oEventListener, boolean bUsesCP) throws EMP_Exception {
super(map, feature, oEventListener, bUsesCP);
}
protected AbstractSinglePointEditor(IMapInstance map, T feature, IDrawEventListener oEventListener, boolean bUsesCP, boolean newFeature) throws EMP_Exception {
super(map, feature, oEventListener, bUsesCP, newFeature);
}
@Override
protected void prepareForDraw() throws EMP_Exception {
if (!this.isNewFeature()) {
// A feature that already exists should have all of its properties set already.
return;
}
this.oFeature.getPositions().add(getCenter());
}
@Override
protected boolean moveIconTo(IGeoPosition oLatLng) {
IGeoPosition oPos = this.getFeature().getPositions().get(0);
oPos.setLatitude(oLatLng.getLatitude());
oPos.setLongitude(oLatLng.getLongitude());
return true;
}
@Override
protected boolean doFeatureMove(double dBearing, double dDistance) {
IFeature oFeature = this.getFeature();
IGeoPosition oPos = oFeature.getPositions().get(0);
GeoLibrary.computePositionAt(dBearing, dDistance, oPos, oPos);
// this.addUpdateEventData(FeatureEditUpdateTypeEnum.COORDINATE_MOVED, new int[]{0}); TODO causes duplicate events.
return true;
}
}
| Updated AbstractSinglePointEditor to use GeographicLib
| sdk/sdk-core/aar/src/main/java/mil/emp3/core/editors/AbstractSinglePointEditor.java | Updated AbstractSinglePointEditor to use GeographicLib |
|
Java | apache-2.0 | b5711d607d36688a7ffa6b8431b95d20044ab692 | 0 | lincoln-lil/flink,zentol/flink,shaoxuan-wang/flink,clarkyzl/flink,gyfora/flink,sunjincheng121/flink,tony810430/flink,apache/flink,mbode/flink,GJL/flink,aljoscha/flink,godfreyhe/flink,zjureel/flink,StephanEwen/incubator-flink,zentol/flink,greghogan/flink,darionyaphet/flink,shaoxuan-wang/flink,kaibozhou/flink,hequn8128/flink,zentol/flink,tzulitai/flink,rmetzger/flink,hequn8128/flink,bowenli86/flink,GJL/flink,apache/flink,xccui/flink,lincoln-lil/flink,tillrohrmann/flink,kaibozhou/flink,clarkyzl/flink,tzulitai/flink,bowenli86/flink,darionyaphet/flink,twalthr/flink,xccui/flink,tillrohrmann/flink,jinglining/flink,kl0u/flink,godfreyhe/flink,aljoscha/flink,gyfora/flink,zjureel/flink,darionyaphet/flink,shaoxuan-wang/flink,mbode/flink,shaoxuan-wang/flink,lincoln-lil/flink,kl0u/flink,kl0u/flink,lincoln-lil/flink,fhueske/flink,apache/flink,jinglining/flink,godfreyhe/flink,tzulitai/flink,fhueske/flink,rmetzger/flink,fhueske/flink,sunjincheng121/flink,greghogan/flink,StephanEwen/incubator-flink,xccui/flink,gyfora/flink,kaibozhou/flink,kaibozhou/flink,shaoxuan-wang/flink,kaibozhou/flink,apache/flink,mbode/flink,lincoln-lil/flink,wwjiang007/flink,rmetzger/flink,tillrohrmann/flink,wwjiang007/flink,greghogan/flink,hequn8128/flink,rmetzger/flink,tony810430/flink,mbode/flink,jinglining/flink,tzulitai/flink,rmetzger/flink,godfreyhe/flink,hequn8128/flink,xccui/flink,lincoln-lil/flink,clarkyzl/flink,GJL/flink,tzulitai/flink,wwjiang007/flink,godfreyhe/flink,wwjiang007/flink,aljoscha/flink,kl0u/flink,twalthr/flink,GJL/flink,sunjincheng121/flink,tillrohrmann/flink,tillrohrmann/flink,shaoxuan-wang/flink,wwjiang007/flink,fhueske/flink,zentol/flink,zjureel/flink,StephanEwen/incubator-flink,jinglining/flink,StephanEwen/incubator-flink,godfreyhe/flink,kl0u/flink,GJL/flink,tzulitai/flink,gyfora/flink,greghogan/flink,aljoscha/flink,sunjincheng121/flink,hequn8128/flink,jinglining/flink,wwjiang007/flink,zentol/flink,jinglining/flink,twalthr/flink,kaibozhou/flink,godfreyhe/flink,tillrohrmann/flink,rmetzger/flink,tony810430/flink,kl0u/flink,gyfora/flink,bowenli86/flink,xccui/flink,aljoscha/flink,zjureel/flink,zjureel/flink,clarkyzl/flink,darionyaphet/flink,wwjiang007/flink,aljoscha/flink,StephanEwen/incubator-flink,twalthr/flink,tony810430/flink,zentol/flink,fhueske/flink,tony810430/flink,lincoln-lil/flink,GJL/flink,xccui/flink,gyfora/flink,zentol/flink,bowenli86/flink,zjureel/flink,greghogan/flink,zjureel/flink,darionyaphet/flink,mbode/flink,fhueske/flink,rmetzger/flink,sunjincheng121/flink,gyfora/flink,hequn8128/flink,twalthr/flink,tony810430/flink,bowenli86/flink,twalthr/flink,apache/flink,StephanEwen/incubator-flink,xccui/flink,apache/flink,twalthr/flink,sunjincheng121/flink,bowenli86/flink,tillrohrmann/flink,tony810430/flink,apache/flink,greghogan/flink,clarkyzl/flink | /*
* 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.flink.runtime.state;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.core.fs.CloseableRegistry;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.Preconditions;
import javax.annotation.Nonnull;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.RunnableFuture;
/**
* This class is a default implementation for StateSnapshotContext.
*/
public class StateSnapshotContextSynchronousImpl implements StateSnapshotContext, Closeable {
/** Checkpoint id of the snapshot. */
private final long checkpointId;
/** Checkpoint timestamp of the snapshot. */
private final long checkpointTimestamp;
/** Factory for the checkpointing stream */
private final CheckpointStreamFactory streamFactory;
/** Key group range for the operator that created this context. Only for keyed operators */
private final KeyGroupRange keyGroupRange;
/**
* Registry for opened streams to participate in the lifecycle of the stream task. Hence, this registry should be
* obtained from and managed by the stream task.
*/
private final CloseableRegistry closableRegistry;
/** Output stream for the raw keyed state. */
private KeyedStateCheckpointOutputStream keyedStateCheckpointOutputStream;
/** Output stream for the raw operator state. */
private OperatorStateCheckpointOutputStream operatorStateCheckpointOutputStream;
@VisibleForTesting
public StateSnapshotContextSynchronousImpl(long checkpointId, long checkpointTimestamp) {
this.checkpointId = checkpointId;
this.checkpointTimestamp = checkpointTimestamp;
this.streamFactory = null;
this.keyGroupRange = KeyGroupRange.EMPTY_KEY_GROUP_RANGE;
this.closableRegistry = null;
}
public StateSnapshotContextSynchronousImpl(
long checkpointId,
long checkpointTimestamp,
CheckpointStreamFactory streamFactory,
KeyGroupRange keyGroupRange,
CloseableRegistry closableRegistry) {
this.checkpointId = checkpointId;
this.checkpointTimestamp = checkpointTimestamp;
this.streamFactory = Preconditions.checkNotNull(streamFactory);
this.keyGroupRange = Preconditions.checkNotNull(keyGroupRange);
this.closableRegistry = Preconditions.checkNotNull(closableRegistry);
}
@Override
public long getCheckpointId() {
return checkpointId;
}
@Override
public long getCheckpointTimestamp() {
return checkpointTimestamp;
}
private CheckpointStreamFactory.CheckpointStateOutputStream openAndRegisterNewStream() throws Exception {
CheckpointStreamFactory.CheckpointStateOutputStream cout =
streamFactory.createCheckpointStateOutputStream(CheckpointedStateScope.EXCLUSIVE);
closableRegistry.registerCloseable(cout);
return cout;
}
@Override
public KeyedStateCheckpointOutputStream getRawKeyedOperatorStateOutput() throws Exception {
if (null == keyedStateCheckpointOutputStream) {
Preconditions.checkState(keyGroupRange != KeyGroupRange.EMPTY_KEY_GROUP_RANGE, "Not a keyed operator");
keyedStateCheckpointOutputStream = new KeyedStateCheckpointOutputStream(openAndRegisterNewStream(), keyGroupRange);
}
return keyedStateCheckpointOutputStream;
}
@Override
public OperatorStateCheckpointOutputStream getRawOperatorStateOutput() throws Exception {
if (null == operatorStateCheckpointOutputStream) {
operatorStateCheckpointOutputStream = new OperatorStateCheckpointOutputStream(openAndRegisterNewStream());
}
return operatorStateCheckpointOutputStream;
}
@Nonnull
public RunnableFuture<SnapshotResult<KeyedStateHandle>> getKeyedStateStreamFuture() throws IOException {
KeyedStateHandle keyGroupsStateHandle =
closeAndUnregisterStreamToObtainStateHandle(keyedStateCheckpointOutputStream);
return toDoneFutureOfSnapshotResult(keyGroupsStateHandle);
}
@Nonnull
public RunnableFuture<SnapshotResult<OperatorStateHandle>> getOperatorStateStreamFuture() throws IOException {
OperatorStateHandle operatorStateHandle =
closeAndUnregisterStreamToObtainStateHandle(operatorStateCheckpointOutputStream);
return toDoneFutureOfSnapshotResult(operatorStateHandle);
}
private <T extends StateObject> RunnableFuture<SnapshotResult<T>> toDoneFutureOfSnapshotResult(T handle) {
SnapshotResult<T> snapshotResult = SnapshotResult.of(handle);
return DoneFuture.of(snapshotResult);
}
private <T extends StreamStateHandle> T closeAndUnregisterStreamToObtainStateHandle(
NonClosingCheckpointOutputStream<T> stream) throws IOException {
if (stream != null && closableRegistry.unregisterCloseable(stream.getDelegate())) {
return stream.closeAndGetHandle();
} else {
return null;
}
}
private <T extends StreamStateHandle> void closeAndUnregisterStream(
NonClosingCheckpointOutputStream<? extends T> stream) throws IOException {
Preconditions.checkNotNull(stream);
CheckpointStreamFactory.CheckpointStateOutputStream delegate = stream.getDelegate();
if (closableRegistry.unregisterCloseable(delegate)) {
delegate.close();
}
}
@Override
public void close() throws IOException {
IOException exception = null;
if (keyedStateCheckpointOutputStream != null) {
try {
closeAndUnregisterStream(keyedStateCheckpointOutputStream);
} catch (IOException e) {
exception = new IOException("Could not close the raw keyed state checkpoint output stream.", e);
}
}
if (operatorStateCheckpointOutputStream != null) {
try {
closeAndUnregisterStream(operatorStateCheckpointOutputStream);
} catch (IOException e) {
exception = ExceptionUtils.firstOrSuppressed(
new IOException("Could not close the raw operator state checkpoint output stream.", e),
exception);
}
}
if (exception != null) {
throw exception;
}
}
}
| flink-runtime/src/main/java/org/apache/flink/runtime/state/StateSnapshotContextSynchronousImpl.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.flink.runtime.state;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.core.fs.CloseableRegistry;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.Preconditions;
import javax.annotation.Nonnull;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.RunnableFuture;
/**
* This class is a default implementation for StateSnapshotContext.
*/
public class StateSnapshotContextSynchronousImpl implements StateSnapshotContext, Closeable {
/** Checkpoint id of the snapshot. */
private final long checkpointId;
/** Checkpoint timestamp of the snapshot. */
private final long checkpointTimestamp;
/** Factory for he checkpointing stream */
private final CheckpointStreamFactory streamFactory;
/** Key group range for the operator that created this context. Only for keyed operators */
private final KeyGroupRange keyGroupRange;
/**
* Registry for opened streams to participate in the lifecycle of the stream task. Hence, this registry should be
* obtained from and managed by the stream task.
*/
private final CloseableRegistry closableRegistry;
/** Output stream for the raw keyed state. */
private KeyedStateCheckpointOutputStream keyedStateCheckpointOutputStream;
/** Output stream for the raw operator state. */
private OperatorStateCheckpointOutputStream operatorStateCheckpointOutputStream;
@VisibleForTesting
public StateSnapshotContextSynchronousImpl(long checkpointId, long checkpointTimestamp) {
this.checkpointId = checkpointId;
this.checkpointTimestamp = checkpointTimestamp;
this.streamFactory = null;
this.keyGroupRange = KeyGroupRange.EMPTY_KEY_GROUP_RANGE;
this.closableRegistry = null;
}
public StateSnapshotContextSynchronousImpl(
long checkpointId,
long checkpointTimestamp,
CheckpointStreamFactory streamFactory,
KeyGroupRange keyGroupRange,
CloseableRegistry closableRegistry) {
this.checkpointId = checkpointId;
this.checkpointTimestamp = checkpointTimestamp;
this.streamFactory = Preconditions.checkNotNull(streamFactory);
this.keyGroupRange = Preconditions.checkNotNull(keyGroupRange);
this.closableRegistry = Preconditions.checkNotNull(closableRegistry);
}
@Override
public long getCheckpointId() {
return checkpointId;
}
@Override
public long getCheckpointTimestamp() {
return checkpointTimestamp;
}
private CheckpointStreamFactory.CheckpointStateOutputStream openAndRegisterNewStream() throws Exception {
CheckpointStreamFactory.CheckpointStateOutputStream cout =
streamFactory.createCheckpointStateOutputStream(CheckpointedStateScope.EXCLUSIVE);
closableRegistry.registerCloseable(cout);
return cout;
}
@Override
public KeyedStateCheckpointOutputStream getRawKeyedOperatorStateOutput() throws Exception {
if (null == keyedStateCheckpointOutputStream) {
Preconditions.checkState(keyGroupRange != KeyGroupRange.EMPTY_KEY_GROUP_RANGE, "Not a keyed operator");
keyedStateCheckpointOutputStream = new KeyedStateCheckpointOutputStream(openAndRegisterNewStream(), keyGroupRange);
}
return keyedStateCheckpointOutputStream;
}
@Override
public OperatorStateCheckpointOutputStream getRawOperatorStateOutput() throws Exception {
if (null == operatorStateCheckpointOutputStream) {
operatorStateCheckpointOutputStream = new OperatorStateCheckpointOutputStream(openAndRegisterNewStream());
}
return operatorStateCheckpointOutputStream;
}
@Nonnull
public RunnableFuture<SnapshotResult<KeyedStateHandle>> getKeyedStateStreamFuture() throws IOException {
KeyedStateHandle keyGroupsStateHandle =
closeAndUnregisterStreamToObtainStateHandle(keyedStateCheckpointOutputStream);
return toDoneFutureOfSnapshotResult(keyGroupsStateHandle);
}
@Nonnull
public RunnableFuture<SnapshotResult<OperatorStateHandle>> getOperatorStateStreamFuture() throws IOException {
OperatorStateHandle operatorStateHandle =
closeAndUnregisterStreamToObtainStateHandle(operatorStateCheckpointOutputStream);
return toDoneFutureOfSnapshotResult(operatorStateHandle);
}
private <T extends StateObject> RunnableFuture<SnapshotResult<T>> toDoneFutureOfSnapshotResult(T handle) {
SnapshotResult<T> snapshotResult = SnapshotResult.of(handle);
return DoneFuture.of(snapshotResult);
}
private <T extends StreamStateHandle> T closeAndUnregisterStreamToObtainStateHandle(
NonClosingCheckpointOutputStream<T> stream) throws IOException {
if (stream != null && closableRegistry.unregisterCloseable(stream.getDelegate())) {
return stream.closeAndGetHandle();
} else {
return null;
}
}
private <T extends StreamStateHandle> void closeAndUnregisterStream(
NonClosingCheckpointOutputStream<? extends T> stream) throws IOException {
Preconditions.checkNotNull(stream);
CheckpointStreamFactory.CheckpointStateOutputStream delegate = stream.getDelegate();
if (closableRegistry.unregisterCloseable(delegate)) {
delegate.close();
}
}
@Override
public void close() throws IOException {
IOException exception = null;
if (keyedStateCheckpointOutputStream != null) {
try {
closeAndUnregisterStream(keyedStateCheckpointOutputStream);
} catch (IOException e) {
exception = new IOException("Could not close the raw keyed state checkpoint output stream.", e);
}
}
if (operatorStateCheckpointOutputStream != null) {
try {
closeAndUnregisterStream(operatorStateCheckpointOutputStream);
} catch (IOException e) {
exception = ExceptionUtils.firstOrSuppressed(
new IOException("Could not close the raw operator state checkpoint output stream.", e),
exception);
}
}
if (exception != null) {
throw exception;
}
}
}
| [hotfix] Fix typo in javadoc of StateSnapshotContextSynchronousImpl
This closes #8650.
| flink-runtime/src/main/java/org/apache/flink/runtime/state/StateSnapshotContextSynchronousImpl.java | [hotfix] Fix typo in javadoc of StateSnapshotContextSynchronousImpl |
|
Java | apache-2.0 | 9775a3e37b697aee59d00602a2a57de3f7c1c2d9 | 0 | backpaper0/jaxrs-samples,backpaper0/jaxrs-samples | package sample;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterTypeDiscovery;
import javax.enterprise.inject.spi.AnnotatedConstructor;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.util.AnnotationLiteral;
public class ResourceClassAutoRegister implements Extension {
public void register(@Observes AfterTypeDiscovery context, BeanManager bm) {
// HelloApiクラスをハードコーディングしてるから汎用的ではない!!!
// リソースクラスをスキャンする方法を考えないといけない〜
AnnotatedType<?> type = bm.createAnnotatedType(HelloApi.class);
String id = HelloApi.class.getName();
context.addAnnotatedType(new AnnotatedTypeImpl<>(type), id);
}
/*
* すべてのリソースクラスを登録するようなまどろっこしい真似をしなくても
* BeforeBeanDiscovery.addStereotypeを使えば良いと思ったんだけど、
* バグってるっぽい、、、
* https://issues.jboss.org/browse/WELD-1624
*/
// public void addPathAsStereotype(@Observes BeforeBeanDiscovery context, BeanManager bm) {
// context.addStereotype(ResourceClass.class, new StereotypeImpl(), new RequestScopedImpl());
// }
private static class AnnotatedTypeImpl<X> implements AnnotatedType<X> {
private final AnnotatedType<X> type;
private final RequestScoped requestScoped = new RequestScopedImpl();
public AnnotatedTypeImpl(AnnotatedType<X> type) {
this.type = type;
}
@Override
public Type getBaseType() {
return type.getBaseType();
}
@Override
public Set<Type> getTypeClosure() {
return type.getTypeClosure();
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
if (annotationType == RequestScoped.class) {
return (T) requestScoped;
}
return type.getAnnotation(annotationType);
}
@Override
public Set<Annotation> getAnnotations() {
return Stream.concat(Stream.of(requestScoped), type.getAnnotations().stream())
.collect(Collectors.toSet());
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
if (annotationType == RequestScoped.class) {
return true;
}
return type.isAnnotationPresent(annotationType);
}
@Override
public Class<X> getJavaClass() {
return type.getJavaClass();
}
@Override
public Set<AnnotatedConstructor<X>> getConstructors() {
return type.getConstructors();
}
@Override
public Set<AnnotatedMethod<? super X>> getMethods() {
return type.getMethods();
}
@Override
public Set<AnnotatedField<? super X>> getFields() {
return type.getFields();
}
}
private static class RequestScopedImpl extends AnnotationLiteral<RequestScoped>
implements RequestScoped {
}
} | jaxrs-cdi-without-scope-annotation-sample/src/main/java/sample/ResourceClassAutoRegister.java | package sample;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterTypeDiscovery;
import javax.enterprise.inject.spi.AnnotatedConstructor;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.util.AnnotationLiteral;
public class ResourceClassAutoRegister implements Extension {
public void register(@Observes AfterTypeDiscovery context, BeanManager bm) {
// HelloApiクラスをハードコーディングしてるから汎用的ではない!!!
// リソースクラスをスキャンする方法を考えないといけない〜
AnnotatedType<?> type = bm.createAnnotatedType(HelloApi.class);
String id = HelloApi.class.getName();
context.addAnnotatedType(new AnnotatedTypeImpl<>(type), id);
}
private static class AnnotatedTypeImpl<X> implements AnnotatedType<X> {
private final AnnotatedType<X> type;
private final RequestScoped requestScoped = new RequestScopedImpl();
public AnnotatedTypeImpl(AnnotatedType<X> type) {
this.type = type;
}
@Override
public Type getBaseType() {
return type.getBaseType();
}
@Override
public Set<Type> getTypeClosure() {
return type.getTypeClosure();
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
if (annotationType == RequestScoped.class) {
return (T) requestScoped;
}
return type.getAnnotation(annotationType);
}
@Override
public Set<Annotation> getAnnotations() {
return Stream.concat(Stream.of(requestScoped), type.getAnnotations().stream())
.collect(Collectors.toSet());
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
if (annotationType == RequestScoped.class) {
return true;
}
return type.isAnnotationPresent(annotationType);
}
@Override
public Class<X> getJavaClass() {
return type.getJavaClass();
}
@Override
public Set<AnnotatedConstructor<X>> getConstructors() {
return type.getConstructors();
}
@Override
public Set<AnnotatedMethod<? super X>> getMethods() {
return type.getMethods();
}
@Override
public Set<AnnotatedField<? super X>> getFields() {
return type.getFields();
}
}
private static class RequestScopedImpl extends AnnotationLiteral<RequestScoped>
implements RequestScoped {
}
} | BeforeBeanDiscovery.addStereotypeしたい(´・ω・)
| jaxrs-cdi-without-scope-annotation-sample/src/main/java/sample/ResourceClassAutoRegister.java | BeforeBeanDiscovery.addStereotypeしたい(´・ω・) |
|
Java | apache-2.0 | 2f9158e0f8d8e2a150c6f116c8f6359190b79b49 | 0 | JonZeolla/incubator-metron,JonZeolla/metron,anandsubbu/incubator-metron,ottobackwards/metron,dlyle65535/metron,mattf-horton/incubator-metron,mmiklavc/metron,ottobackwards/incubator-metron,nickwallen/metron,kylerichardson/incubator-metron,basvdl/incubator-metron,zezutom/metron,dlyle65535/metron,justinleet/incubator-metron,nickwallen/incubator-metron,nickwallen/metron,anandsubbu/incubator-metron,dlyle65535/incubator-metron,nickwallen/metron,apache/incubator-metron,JonZeolla/metron,dlyle65535/incubator-metron,kylerichardson/metron,justinleet/metron,anandsubbu/incubator-metron,JonZeolla/incubator-metron,anandsubbu/incubator-metron,cestella/incubator-metron,cestella/incubator-metron,iraghumitra/incubator-metron,mattf-horton/incubator-metron,apache/incubator-metron,kylerichardson/metron,nickwallen/metron,basvdl/incubator-metron,justinleet/metron,apache/incubator-metron,apache/incubator-metron,mattf-horton/incubator-metron,justinleet/incubator-metron,jjmeyer0/incubator-metron,zezutom/metron,JonZeolla/incubator-metron,mmiklavc/metron,iraghumitra/incubator-metron,dlyle65535/metron,jjmeyer0/incubator-metron,JonZeolla/metron,cestella/incubator-metron,kylerichardson/metron,dlyle65535/metron,justinleet/metron,dlyle65535/metron,anandsubbu/incubator-metron,mmiklavc/incubator-metron,kylerichardson/metron,mmiklavc/incubator-metron,ottobackwards/metron,mattf-horton/incubator-metron,mattf-horton/incubator-metron,ottobackwards/metron,nickwallen/incubator-metron,anandsubbu/incubator-metron,cestella/incubator-metron,mmiklavc/incubator-metron,kylerichardson/incubator-metron,zezutom/metron,mattf-horton/incubator-metron,ottobackwards/metron,mmiklavc/metron,dlyle65535/incubator-metron,ottobackwards/metron,zezutom/metron,mmiklavc/metron,nickwallen/metron,mmiklavc/incubator-metron,apache/incubator-metron,justinleet/metron,JonZeolla/incubator-metron,JonZeolla/metron,jjmeyer0/incubator-metron,JonZeolla/incubator-metron,basvdl/incubator-metron,iraghumitra/incubator-metron,nickwallen/metron,mattf-horton/metron,JonZeolla/metron,basvdl/incubator-metron,apache/incubator-metron,kylerichardson/incubator-metron,anandsubbu/incubator-metron,mattf-horton/metron,mattf-horton/metron,mattf-horton/metron,justinleet/metron,kylerichardson/metron,kylerichardson/incubator-metron,dlyle65535/metron,dlyle65535/metron,JonZeolla/incubator-metron,mmiklavc/metron,nickwallen/incubator-metron,ottobackwards/incubator-metron,zezutom/metron,kylerichardson/metron,cestella/incubator-metron,zezutom/metron,mattf-horton/incubator-metron,jjmeyer0/incubator-metron,ottobackwards/incubator-metron,jjmeyer0/incubator-metron,justinleet/incubator-metron,zezutom/metron,nickwallen/incubator-metron,ottobackwards/incubator-metron,justinleet/incubator-metron,dlyle65535/incubator-metron,dlyle65535/incubator-metron,apache/incubator-metron,kylerichardson/metron,basvdl/incubator-metron,justinleet/incubator-metron,zezutom/metron,kylerichardson/metron,ottobackwards/incubator-metron,mattf-horton/metron,nickwallen/incubator-metron,ottobackwards/metron,jjmeyer0/incubator-metron,mattf-horton/metron,justinleet/metron,iraghumitra/incubator-metron,dlyle65535/metron,kylerichardson/incubator-metron,dlyle65535/incubator-metron,mmiklavc/metron,dlyle65535/incubator-metron,iraghumitra/incubator-metron,mmiklavc/incubator-metron,mmiklavc/incubator-metron,mmiklavc/incubator-metron,jjmeyer0/incubator-metron,nickwallen/metron,dlyle65535/metron,justinleet/incubator-metron,ottobackwards/incubator-metron,nickwallen/incubator-metron,nickwallen/incubator-metron,iraghumitra/incubator-metron,basvdl/incubator-metron,ottobackwards/incubator-metron,kylerichardson/incubator-metron,justinleet/incubator-metron,nickwallen/incubator-metron,basvdl/incubator-metron,mattf-horton/metron,zezutom/metron,ottobackwards/incubator-metron,iraghumitra/incubator-metron,iraghumitra/incubator-metron,kylerichardson/incubator-metron,mmiklavc/metron,apache/incubator-metron,ottobackwards/metron,kylerichardson/incubator-metron,dlyle65535/incubator-metron,justinleet/incubator-metron,mattf-horton/metron,anandsubbu/incubator-metron,JonZeolla/metron,JonZeolla/metron,apache/incubator-metron,ottobackwards/incubator-metron,basvdl/incubator-metron,mmiklavc/incubator-metron,justinleet/metron,JonZeolla/incubator-metron,dlyle65535/incubator-metron,ottobackwards/metron,mmiklavc/metron,mattf-horton/incubator-metron,nickwallen/incubator-metron,cestella/incubator-metron,justinleet/incubator-metron,basvdl/incubator-metron,JonZeolla/incubator-metron,mmiklavc/incubator-metron,JonZeolla/incubator-metron,cestella/incubator-metron,mattf-horton/incubator-metron,cestella/incubator-metron,JonZeolla/metron,jjmeyer0/incubator-metron,nickwallen/metron,justinleet/metron | /**
* 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.metron.parsers.asa;
import com.google.common.collect.ImmutableMap;
import oi.thekraken.grok.api.Grok;
import oi.thekraken.grok.api.Match;
import oi.thekraken.grok.api.exception.GrokException;
import org.apache.metron.common.Constants;
import org.apache.metron.parsers.BasicParser;
import org.apache.metron.parsers.ParseException;
import org.apache.metron.parsers.utils.SyslogUtils;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.time.Clock;
import java.time.ZoneId;
import java.util.*;
public class BasicAsaParser extends BasicParser {
protected static final Logger LOG = LoggerFactory.getLogger(BasicAsaParser.class);
private Grok asaGrok;
protected Clock deviceClock;
private static final Map<String, String> patternMap = ImmutableMap.<String, String>builder()
.put("ASA-2-106001", "CISCOFW106001")
.put("ASA-2-106006", "CISCOFW106006_106007_106010")
.put("ASA-2-106007", "CISCOFW106006_106007_106010")
.put("ASA-2-106010", "CISCOFW106006_106007_106010")
.put("ASA-3-106014", "CISCOFW106014")
.put("ASA-6-106015", "CISCOFW106015")
.put("ASA-1-106021", "CISCOFW106021")
.put("ASA-4-106023", "CISCOFW106023")
.put("ASA-5-106100", "CISCOFW106100")
.put("ASA-6-110002", "CISCOFW110002")
.put("ASA-6-302010", "CISCOFW302010")
.put("ASA-6-302013", "CISCOFW302013_302014_302015_302016")
.put("ASA-6-302014", "CISCOFW302013_302014_302015_302016")
.put("ASA-6-302015", "CISCOFW302013_302014_302015_302016")
.put("ASA-6-302016", "CISCOFW302013_302014_302015_302016")
.put("ASA-6-302020", "CISCOFW302020_302021")
.put("ASA-6-302021", "CISCOFW302020_302021")
.put("ASA-6-305011", "CISCOFW305011")
.put("ASA-3-313001", "CISCOFW313001_313004_313008")
.put("ASA-3-313004", "CISCOFW313001_313004_313008")
.put("ASA-3-313008", "CISCOFW313001_313004_313008")
.put("ASA-4-313005", "CISCOFW313005")
.put("ASA-4-402117", "CISCOFW402117")
.put("ASA-4-402119", "CISCOFW402119")
.put("ASA-4-419001", "CISCOFW419001")
.put("ASA-4-419002", "CISCOFW419002")
.put("ASA-4-500004", "CISCOFW500004")
.put("ASA-6-602303", "CISCOFW602303_602304")
.put("ASA-6-602304", "CISCOFW602303_602304")
.put("ASA-7-710001", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-7-710002", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-7-710003", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-7-710005", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-7-710006", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-6-713172", "CISCOFW713172")
.put("ASA-4-733100", "CISCOFW733100")
.put("ASA-6-305012", "CISCOFW305012")
.put("ASA-7-609001", "CISCOFW609001")
.put("ASA-7-609002", "CISCOFW609002")
.put("ASA-5-713041", "CISCOFW713041")
.build();
@Override
public void configure(Map<String, Object> parserConfig) {
String timeZone = (String) parserConfig.get("deviceTimeZone");
if (timeZone != null)
deviceClock = Clock.system(ZoneId.of(timeZone));
else {
deviceClock = Clock.systemUTC();
LOG.warn("[Metron] No device time zone provided; defaulting to UTC");
}
}
@Override
public void init() {
asaGrok = new Grok();
InputStream patternStream = this.getClass().getResourceAsStream("/patterns/asa");
try {
asaGrok.addPatternFromReader(new InputStreamReader(patternStream));
} catch (GrokException e) {
LOG.error("[Metron] Failed to load grok patterns from jar", e);
throw new RuntimeException(e.getMessage(), e);
}
LOG.info("[Metron] CISCO ASA Parser Initialized");
}
@Override
public List<JSONObject> parse(byte[] rawMessage) {
String logLine = "";
String syslogPattern = "%{CISCO_TAGGED_SYSLOG}";
String messagePattern = "";
JSONObject metronJson = new JSONObject();
List<JSONObject> messages = new ArrayList<>();
Map<String, Object> syslogJson = new HashMap<String, Object>();
try {
logLine = new String(rawMessage, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOG.error("[Metron] Could not read raw message", e);
throw new RuntimeException(e.getMessage(), e);
}
try {
LOG.debug("[Metron] Started parsing raw message: {}", logLine);
asaGrok.compile(syslogPattern);
Match syslogMatch = asaGrok.match(logLine);
syslogMatch.captures();
if(!syslogMatch.isNull()) {
syslogJson = syslogMatch.toMap();
LOG.trace("[Metron] Grok CISCO ASA syslog matches: {}", syslogMatch.toJson());
metronJson.put(Constants.Fields.ORIGINAL.getName(), logLine);
metronJson.put(Constants.Fields.TIMESTAMP.getName(),
SyslogUtils.parseTimestampToEpochMillis((String) syslogJson.get("CISCOTIMESTAMP"), deviceClock));
metronJson.put("ciscotag", syslogJson.get("CISCOTAG"));
metronJson.put("syslog_severity", SyslogUtils.getSeverityFromPriority((int) syslogJson.get("syslog_pri")));
metronJson.put("syslog_facility", SyslogUtils.getFacilityFromPriority((int) syslogJson.get("syslog_pri")));
if (syslogJson.get("syslog_host")!=null) {
metronJson.put("syslog_host", syslogJson.get("syslog_host"));
}
if (syslogJson.get("syslog_prog")!=null) {
metronJson.put("syslog_prog", syslogJson.get("syslog_prog"));
}
}
else
throw new RuntimeException(String.format("[Metron] Message '%s' does not match pattern '%s'", logLine, syslogPattern));
} catch (GrokException e) {
LOG.error(String.format("[Metron] Could not compile grok pattern '%s'", syslogPattern), e);
throw new RuntimeException(e.getMessage(), e);
} catch (ParseException e) {
LOG.error("[Metron] Could not parse message timestamp", e);
throw new RuntimeException(e.getMessage(), e);
} catch (RuntimeException e) {
LOG.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
try {
messagePattern = patternMap.get(syslogJson.get("CISCOTAG"));
if (messagePattern == null)
LOG.info("[Metron] No pattern for ciscotag '{}'", syslogJson.get("CISCOTAG"));
else {
asaGrok.compile("%{" + messagePattern + "}");
Match messageMatch = asaGrok.match((String) syslogJson.get("message"));
messageMatch.captures();
if (!messageMatch.isNull()) {
Map<String, Object> messageJson = messageMatch.toMap();
LOG.trace("[Metron] Grok CISCO ASA message matches: {}", messageMatch.toJson());
String src_ip = (String) messageJson.get("src_ip");
if (src_ip != null)
metronJson.put(Constants.Fields.SRC_ADDR.getName(), src_ip);
Integer src_port = (Integer) messageJson.get("src_port");
if (src_port != null)
metronJson.put(Constants.Fields.SRC_PORT.getName(), src_port);
String dst_ip = (String) messageJson.get("dst_ip");
if (dst_ip != null)
metronJson.put(Constants.Fields.DST_ADDR.getName(), dst_ip);
Integer dst_port = (Integer) messageJson.get("dst_port");
if (dst_port != null)
metronJson.put(Constants.Fields.DST_PORT.getName(), dst_port);
String protocol = (String) messageJson.get("protocol");
if (protocol != null)
metronJson.put(Constants.Fields.PROTOCOL.getName(), protocol.toLowerCase());
String action = (String) messageJson.get("action");
if (action != null)
metronJson.put("action", action.toLowerCase());
}
else
LOG.warn("[Metron] Message '{}' did not match pattern for ciscotag '{}'", logLine, syslogJson.get("CISCOTAG"));
}
LOG.debug("[Metron] Final normalized message: {}", metronJson.toString());
} catch (GrokException e) {
LOG.error(String.format("[Metron] Could not compile grok pattern '%s'", messagePattern), e);
throw new RuntimeException(e.getMessage(), e);
} catch (RuntimeException e) {
LOG.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
messages.add(metronJson);
return messages;
}
}
| metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/asa/BasicAsaParser.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.metron.parsers.asa;
import com.google.common.collect.ImmutableMap;
import oi.thekraken.grok.api.Grok;
import oi.thekraken.grok.api.Match;
import oi.thekraken.grok.api.exception.GrokException;
import org.apache.metron.common.Constants;
import org.apache.metron.parsers.BasicParser;
import org.apache.metron.parsers.ParseException;
import org.apache.metron.parsers.utils.SyslogUtils;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.time.Clock;
import java.time.ZoneId;
import java.util.*;
public class BasicAsaParser extends BasicParser {
protected static final Logger LOG = LoggerFactory.getLogger(BasicAsaParser.class);
private Grok asaGrok;
protected Clock deviceClock;
private static final Map<String, String> patternMap = ImmutableMap.<String, String>builder()
.put("ASA-2-106001", "CISCOFW106001")
.put("ASA-2-106006", "CISCOFW106006_106007_106010")
.put("ASA-2-106007", "CISCOFW106006_106007_106010")
.put("ASA-2-106010", "CISCOFW106006_106007_106010")
.put("ASA-3-106014", "CISCOFW106014")
.put("ASA-6-106015", "CISCOFW106015")
.put("ASA-1-106021", "CISCOFW106021")
.put("ASA-4-106023", "CISCOFW106023")
.put("ASA-5-106100", "CISCOFW106100")
.put("ASA-6-110002", "CISCOFW110002")
.put("ASA-6-302010", "CISCOFW302010")
.put("ASA-6-302013", "CISCOFW302013_302014_302015_302016")
.put("ASA-6-302014", "CISCOFW302013_302014_302015_302016")
.put("ASA-6-302015", "CISCOFW302013_302014_302015_302016")
.put("ASA-6-302016", "CISCOFW302013_302014_302015_302016")
.put("ASA-6-302020", "CISCOFW302020_302021")
.put("ASA-6-302021", "CISCOFW302020_302021")
.put("ASA-6-305011", "CISCOFW305011")
.put("ASA-3-313001", "CISCOFW313001_313004_313008")
.put("ASA-3-313004", "CISCOFW313001_313004_313008")
.put("ASA-3-313008", "CISCOFW313001_313004_313008")
.put("ASA-4-313005", "CISCOFW313005")
.put("ASA-4-402117", "CISCOFW402117")
.put("ASA-4-402119", "CISCOFW402119")
.put("ASA-4-419001", "CISCOFW419001")
.put("ASA-4-419002", "CISCOFW419002")
.put("ASA-4-500004", "CISCOFW500004")
.put("ASA-6-602303", "CISCOFW602303_602304")
.put("ASA-6-602304", "CISCOFW602303_602304")
.put("ASA-7-710001", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-7-710002", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-7-710003", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-7-710005", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-7-710006", "CISCOFW710001_710002_710003_710005_710006")
.put("ASA-6-713172", "CISCOFW713172")
.put("ASA-4-733100", "CISCOFW733100")
.put("ASA-6-305012", "CISCOFW305012")
.put("ASA-7-609001", "CISCOFW609001")
.put("ASA-7-609002", "CISCOFW609002")
.put("ASA-5-713041", "CISCOFW713041")
.build();
@Override
public void configure(Map<String, Object> parserConfig) {
String timeZone = (String) parserConfig.get("deviceTimeZone");
if (timeZone != null)
deviceClock = Clock.system(ZoneId.of(timeZone));
else {
deviceClock = Clock.systemUTC();
LOG.warn("[Metron] No device time zone provided; defaulting to UTC");
}
}
@Override
public void init() {
asaGrok = new Grok();
InputStream patternStream = this.getClass().getClassLoader().getResourceAsStream("patterns/asa");
try {
asaGrok.addPatternFromReader(new InputStreamReader(patternStream));
} catch (GrokException e) {
LOG.error("[Metron] Failed to load grok patterns from jar", e);
throw new RuntimeException(e.getMessage(), e);
}
LOG.info("[Metron] CISCO ASA Parser Initialized");
}
@Override
public List<JSONObject> parse(byte[] rawMessage) {
String logLine = "";
String syslogPattern = "%{CISCO_TAGGED_SYSLOG}";
String messagePattern = "";
JSONObject metronJson = new JSONObject();
List<JSONObject> messages = new ArrayList<>();
Map<String, Object> syslogJson = new HashMap<String, Object>();
try {
logLine = new String(rawMessage, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOG.error("[Metron] Could not read raw message", e);
throw new RuntimeException(e.getMessage(), e);
}
try {
LOG.debug("[Metron] Started parsing raw message: {}", logLine);
asaGrok.compile(syslogPattern);
Match syslogMatch = asaGrok.match(logLine);
syslogMatch.captures();
if(!syslogMatch.isNull()) {
syslogJson = syslogMatch.toMap();
LOG.trace("[Metron] Grok CISCO ASA syslog matches: {}", syslogMatch.toJson());
metronJson.put(Constants.Fields.ORIGINAL.getName(), logLine);
metronJson.put(Constants.Fields.TIMESTAMP.getName(),
SyslogUtils.parseTimestampToEpochMillis((String) syslogJson.get("CISCOTIMESTAMP"), deviceClock));
metronJson.put("ciscotag", syslogJson.get("CISCOTAG"));
metronJson.put("syslog_severity", SyslogUtils.getSeverityFromPriority((int) syslogJson.get("syslog_pri")));
metronJson.put("syslog_facility", SyslogUtils.getFacilityFromPriority((int) syslogJson.get("syslog_pri")));
if (syslogJson.get("syslog_host")!=null) {
metronJson.put("syslog_host", syslogJson.get("syslog_host"));
}
if (syslogJson.get("syslog_prog")!=null) {
metronJson.put("syslog_prog", syslogJson.get("syslog_prog"));
}
}
else
throw new RuntimeException(String.format("[Metron] Message '%s' does not match pattern '%s'", logLine, syslogPattern));
} catch (GrokException e) {
LOG.error(String.format("[Metron] Could not compile grok pattern '%s'", syslogPattern), e);
throw new RuntimeException(e.getMessage(), e);
} catch (ParseException e) {
LOG.error("[Metron] Could not parse message timestamp", e);
throw new RuntimeException(e.getMessage(), e);
} catch (RuntimeException e) {
LOG.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
try {
messagePattern = patternMap.get(syslogJson.get("CISCOTAG"));
if (messagePattern == null)
LOG.info("[Metron] No pattern for ciscotag '{}'", syslogJson.get("CISCOTAG"));
else {
asaGrok.compile("%{" + messagePattern + "}");
Match messageMatch = asaGrok.match((String) syslogJson.get("message"));
messageMatch.captures();
if (!messageMatch.isNull()) {
Map<String, Object> messageJson = messageMatch.toMap();
LOG.trace("[Metron] Grok CISCO ASA message matches: {}", messageMatch.toJson());
String src_ip = (String) messageJson.get("src_ip");
if (src_ip != null)
metronJson.put(Constants.Fields.SRC_ADDR.getName(), src_ip);
Integer src_port = (Integer) messageJson.get("src_port");
if (src_port != null)
metronJson.put(Constants.Fields.SRC_PORT.getName(), src_port);
String dst_ip = (String) messageJson.get("dst_ip");
if (dst_ip != null)
metronJson.put(Constants.Fields.DST_ADDR.getName(), dst_ip);
Integer dst_port = (Integer) messageJson.get("dst_port");
if (dst_port != null)
metronJson.put(Constants.Fields.DST_PORT.getName(), dst_port);
String protocol = (String) messageJson.get("protocol");
if (protocol != null)
metronJson.put(Constants.Fields.PROTOCOL.getName(), protocol.toLowerCase());
String action = (String) messageJson.get("action");
if (action != null)
metronJson.put("action", action.toLowerCase());
}
else
LOG.warn("[Metron] Message '{}' did not match pattern for ciscotag '{}'", logLine, syslogJson.get("CISCOTAG"));
}
LOG.debug("[Metron] Final normalized message: {}", metronJson.toString());
} catch (GrokException e) {
LOG.error(String.format("[Metron] Could not compile grok pattern '%s'", messagePattern), e);
throw new RuntimeException(e.getMessage(), e);
} catch (RuntimeException e) {
LOG.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
messages.add(metronJson);
return messages;
}
}
| METRON-807 Changed resources to use non-relative path (simonellistonball via merrimanr) closes apache/incubator-metron#493
| metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/asa/BasicAsaParser.java | METRON-807 Changed resources to use non-relative path (simonellistonball via merrimanr) closes apache/incubator-metron#493 |
|
Java | apache-2.0 | d55170bf939da3ffca5bf3748187d22bce2afc18 | 0 | code-distillery/jackrabbit-oak,stillalex/jackrabbit-oak,chetanmeh/jackrabbit-oak,francescomari/jackrabbit-oak,alexparvulescu/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,catholicon/jackrabbit-oak,catholicon/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexparvulescu/jackrabbit-oak,code-distillery/jackrabbit-oak,alexparvulescu/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,francescomari/jackrabbit-oak,alexkli/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexparvulescu/jackrabbit-oak,chetanmeh/jackrabbit-oak,anchela/jackrabbit-oak,stillalex/jackrabbit-oak,francescomari/jackrabbit-oak,stillalex/jackrabbit-oak,alexkli/jackrabbit-oak,catholicon/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,chetanmeh/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,chetanmeh/jackrabbit-oak,alexkli/jackrabbit-oak,francescomari/jackrabbit-oak,stillalex/jackrabbit-oak,chetanmeh/jackrabbit-oak,code-distillery/jackrabbit-oak,anchela/jackrabbit-oak,stillalex/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexparvulescu/jackrabbit-oak,catholicon/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,code-distillery/jackrabbit-oak,catholicon/jackrabbit-oak | /*
* 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.jackrabbit.oak.plugins.document;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.jackrabbit.oak.commons.IOUtils.closeQuietly;
import static org.apache.jackrabbit.oak.commons.PropertiesUtil.toBoolean;
import static org.apache.jackrabbit.oak.commons.PropertiesUtil.toInteger;
import static org.apache.jackrabbit.oak.commons.PropertiesUtil.toLong;
import static org.apache.jackrabbit.oak.osgi.OsgiUtil.lookupFrameworkThenConfiguration;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_CACHE_SEGMENT_COUNT;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_CACHE_STACK_MOVE_DISTANCE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_CHILDREN_CACHE_PERCENTAGE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_DIFF_CACHE_PERCENTAGE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_MEMORY_CACHE_SIZE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_NODE_CACHE_PERCENTAGE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_PREV_DOC_CACHE_PERCENTAGE;
import static org.apache.jackrabbit.oak.spi.blob.osgi.SplitBlobStoreService.ONLY_STANDALONE_TARGET;
import static org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils.registerMBean;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import com.google.common.base.Strings;
import com.google.common.io.Closer;
import com.mongodb.MongoClientURI;
import org.apache.commons.io.FilenameUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyOption;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.jackrabbit.commons.SimpleValueFactory;
import org.apache.jackrabbit.oak.api.Descriptors;
import org.apache.jackrabbit.oak.api.jmx.CacheStatsMBean;
import org.apache.jackrabbit.oak.api.jmx.CheckpointMBean;
import org.apache.jackrabbit.oak.api.jmx.PersistentCacheStatsMBean;
import org.apache.jackrabbit.oak.cache.CacheStats;
import org.apache.jackrabbit.oak.commons.PropertiesUtil;
import org.apache.jackrabbit.oak.spi.commit.ObserverTracker;
import org.apache.jackrabbit.oak.osgi.OsgiWhiteboard;
import org.apache.jackrabbit.oak.plugins.blob.BlobGC;
import org.apache.jackrabbit.oak.plugins.blob.BlobGCMBean;
import org.apache.jackrabbit.oak.plugins.blob.BlobGarbageCollector;
import org.apache.jackrabbit.oak.plugins.blob.BlobStoreStats;
import org.apache.jackrabbit.oak.plugins.blob.BlobTrackingStore;
import org.apache.jackrabbit.oak.plugins.blob.SharedDataStore;
import org.apache.jackrabbit.oak.plugins.blob.datastore.BlobIdTracker;
import org.apache.jackrabbit.oak.plugins.blob.datastore.SharedDataStoreUtils;
import org.apache.jackrabbit.oak.plugins.document.persistentCache.CacheType;
import org.apache.jackrabbit.oak.plugins.document.persistentCache.PersistentCacheStats;
import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection;
import org.apache.jackrabbit.oak.spi.cluster.ClusterRepositoryInfo;
import org.apache.jackrabbit.oak.spi.blob.BlobStore;
import org.apache.jackrabbit.oak.spi.blob.BlobStoreWrapper;
import org.apache.jackrabbit.oak.spi.blob.GarbageCollectableBlobStore;
import org.apache.jackrabbit.oak.spi.blob.stats.BlobStoreStatsMBean;
import org.apache.jackrabbit.oak.spi.commit.BackgroundObserverMBean;
import org.apache.jackrabbit.oak.spi.state.Clusterable;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.spi.state.NodeStoreProvider;
import org.apache.jackrabbit.oak.spi.state.RevisionGC;
import org.apache.jackrabbit.oak.spi.state.RevisionGCMBean;
import org.apache.jackrabbit.oak.spi.whiteboard.AbstractServiceTracker;
import org.apache.jackrabbit.oak.spi.whiteboard.Registration;
import org.apache.jackrabbit.oak.spi.whiteboard.Whiteboard;
import org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardExecutor;
import org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils;
import org.apache.jackrabbit.oak.stats.StatisticsProvider;
import org.apache.jackrabbit.oak.spi.descriptors.GenericDescriptors;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The OSGi service to start/stop a DocumentNodeStore instance.
*/
@Component(policy = ConfigurationPolicy.REQUIRE,
metatype = true,
label = "Apache Jackrabbit Oak Document NodeStore Service",
description = "NodeStore implementation based on Document model. For configuration option refer " +
"to http://jackrabbit.apache.org/oak/docs/osgi_config.html#DocumentNodeStore. Note that for system " +
"stability purpose it is advisable to not change these settings at runtime. Instead the config change " +
"should be done via file system based config file and this view should ONLY be used to determine which " +
"options are supported"
)
public class DocumentNodeStoreService {
private static final long MB = 1024 * 1024;
private static final String DEFAULT_URI = "mongodb://localhost:27017/oak";
private static final int DEFAULT_CACHE = (int) (DEFAULT_MEMORY_CACHE_SIZE / MB);
private static final int DEFAULT_BLOB_CACHE_SIZE = 16;
private static final String DEFAULT_DB = "oak";
private static final String DEFAULT_PERSISTENT_CACHE = "cache,binary=0";
private static final String DEFAULT_JOURNAL_CACHE = "diff-cache";
private static final String PREFIX = "oak.documentstore.";
private static final String DESCRIPTION = "oak.nodestore.description";
/**
* Name of framework property to configure Mongo Connection URI
*/
private static final String FWK_PROP_URI = "oak.mongo.uri";
/**
* Name of framework property to configure Mongo Database name
* to use
*/
private static final String FWK_PROP_DB = "oak.mongo.db";
@Property(value = DEFAULT_URI,
label = "Mongo URI",
description = "Mongo connection URI used to connect to Mongo. Refer to " +
"http://docs.mongodb.org/manual/reference/connection-string/ for details. Note that this value " +
"can be overridden via framework property 'oak.mongo.uri'"
)
private static final String PROP_URI = "mongouri";
@Property(value = DEFAULT_DB,
label = "Mongo DB name",
description = "Name of the database in Mongo. Note that this value " +
"can be overridden via framework property 'oak.mongo.db'"
)
private static final String PROP_DB = "db";
@Property(intValue = DEFAULT_CACHE,
label = "Cache Size (in MB)",
description = "Cache size in MB. This is distributed among various caches used in DocumentNodeStore"
)
private static final String PROP_CACHE = "cache";
@Property(intValue = DEFAULT_NODE_CACHE_PERCENTAGE,
label = "NodeState Cache",
description = "Percentage of cache to be allocated towards Node cache"
)
private static final String PROP_NODE_CACHE_PERCENTAGE = "nodeCachePercentage";
@Property(intValue = DEFAULT_PREV_DOC_CACHE_PERCENTAGE,
label = "PreviousDocument Cache",
description = "Percentage of cache to be allocated towards Previous Document cache"
)
private static final String PROP_PREV_DOC_CACHE_PERCENTAGE = "prevDocCachePercentage";
@Property(intValue = DocumentMK.Builder.DEFAULT_CHILDREN_CACHE_PERCENTAGE,
label = "NodeState Children Cache",
description = "Percentage of cache to be allocated towards Children cache"
)
private static final String PROP_CHILDREN_CACHE_PERCENTAGE = "childrenCachePercentage";
@Property(intValue = DocumentMK.Builder.DEFAULT_DIFF_CACHE_PERCENTAGE,
label = "Diff Cache",
description = "Percentage of cache to be allocated towards Diff cache"
)
private static final String PROP_DIFF_CACHE_PERCENTAGE = "diffCachePercentage";
@Property(intValue = DEFAULT_CACHE_SEGMENT_COUNT,
label = "LIRS Cache Segment Count",
description = "The number of segments in the LIRS cache " +
"(default 16, a higher count means higher concurrency " +
"but slightly lower cache hit rate)"
)
private static final String PROP_CACHE_SEGMENT_COUNT = "cacheSegmentCount";
@Property(intValue = DEFAULT_CACHE_STACK_MOVE_DISTANCE,
label = "LIRS Cache Stack Move Distance",
description = "The delay to move entries to the head of the queue " +
"in the LIRS cache " +
"(default 16, a higher value means higher concurrency " +
"but slightly lower cache hit rate)"
)
private static final String PROP_CACHE_STACK_MOVE_DISTANCE = "cacheStackMoveDistance";
@Property(intValue = DEFAULT_BLOB_CACHE_SIZE,
label = "Blob Cache Size (in MB)",
description = "Cache size to store blobs in memory. Used only with default BlobStore " +
"(as per DocumentStore type)"
)
private static final String PROP_BLOB_CACHE_SIZE = "blobCacheSize";
@Property(value = DEFAULT_PERSISTENT_CACHE,
label = "Persistent Cache Config",
description = "Configuration for persistent cache. Refer to " +
"http://jackrabbit.apache.org/oak/docs/nodestore/persistent-cache.html for various options"
)
private static final String PROP_PERSISTENT_CACHE = "persistentCache";
@Property(value = DEFAULT_JOURNAL_CACHE,
label = "Journal Cache Config",
description = "Configuration for journal cache. Refer to " +
"http://jackrabbit.apache.org/oak/docs/nodestore/persistent-cache.html for various options"
)
private static final String PROP_JOURNAL_CACHE = "journalCache";
@Property(boolValue = false,
label = "Custom BlobStore",
description = "Boolean value indicating that a custom BlobStore is to be used. " +
"By default, for MongoDB, MongoBlobStore is used; for RDB, RDBBlobStore is used."
)
public static final String CUSTOM_BLOB_STORE = "customBlobStore";
private static final long DEFAULT_JOURNAL_GC_INTERVAL_MILLIS = 5*60*1000; // default is 5min
@Property(longValue = DEFAULT_JOURNAL_GC_INTERVAL_MILLIS,
label = "Journal Garbage Collection Interval (millis)",
description = "Long value indicating interval (in milliseconds) with which the "
+ "journal (for external changes) is cleaned up. Default is " + DEFAULT_JOURNAL_GC_INTERVAL_MILLIS
)
private static final String PROP_JOURNAL_GC_INTERVAL_MILLIS = "journalGCInterval";
private static final long DEFAULT_JOURNAL_GC_MAX_AGE_MILLIS = 6*60*60*1000; // default is 6hours
@Property(longValue = DEFAULT_JOURNAL_GC_MAX_AGE_MILLIS,
label = "Maximum Age of Journal Entries (millis)",
description = "Long value indicating max age (in milliseconds) that "
+ "journal (for external changes) entries are kept (older ones are candidates for gc). "
+ "Default is " + DEFAULT_JOURNAL_GC_MAX_AGE_MILLIS
)
private static final String PROP_JOURNAL_GC_MAX_AGE_MILLIS = "journalGCMaxAge";
@Property (boolValue = false,
label = "Pre-fetch external changes",
description = "Boolean value indicating if external changes should " +
"be pre-fetched in a background thread."
)
public static final String PROP_PREFETCH_EXTERNAL_CHANGES = "prefetchExternalChanges";
@Property(
label = "NodeStoreProvider role",
description = "Property indicating that this component will not register as a NodeStore but as a NodeStoreProvider with given role"
)
public static final String PROP_ROLE = "role";
private static enum DocumentStoreType {
MONGO, RDB;
static DocumentStoreType fromString(String type) {
if (type == null) {
return MONGO;
}
return valueOf(type.toUpperCase(Locale.ROOT));
}
}
private final Logger log = LoggerFactory.getLogger(this.getClass());
private ServiceRegistration nodeStoreReg;
private Closer closer;
private WhiteboardExecutor executor;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC, target = ONLY_STANDALONE_TARGET)
private volatile BlobStore blobStore;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC,
target = "(datasource.name=oak)"
)
private volatile DataSource dataSource;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC,
target = "(datasource.name=oak)"
)
private volatile DataSource blobDataSource;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC)
private volatile DocumentNodeStateCache nodeStateCache;
private DocumentNodeStore nodeStore;
private ObserverTracker observerTracker;
private JournalPropertyHandlerFactory journalPropertyHandlerFactory = new JournalPropertyHandlerFactory();
private ComponentContext context;
private Whiteboard whiteboard;
private long deactivationTimestamp = 0;
/**
* Revisions older than this time would be garbage collected
*/
private static final long DEFAULT_VER_GC_MAX_AGE = 24 * 60 * 60; //TimeUnit.DAYS.toSeconds(1);
@Property (longValue = DEFAULT_VER_GC_MAX_AGE,
label = "Version GC Max Age (in secs)",
description = "Version Garbage Collector (GC) logic will only consider those deleted for GC which " +
"are not accessed recently (currentTime - lastModifiedTime > versionGcMaxAgeInSecs). For " +
"example as per default only those document which have been *marked* deleted 24 hrs ago will be " +
"considered for GC. This also applies how older revision of live document are GC."
)
public static final String PROP_VER_GC_MAX_AGE = "versionGcMaxAgeInSecs";
public static final String PROP_REV_RECOVERY_INTERVAL = "lastRevRecoveryJobIntervalInSecs";
/**
* Blob modified before this time duration would be considered for Blob GC
*/
private static final long DEFAULT_BLOB_GC_MAX_AGE = 24 * 60 * 60;
@Property (longValue = DEFAULT_BLOB_GC_MAX_AGE,
label = "Blob GC Max Age (in secs)",
description = "Blob Garbage Collector (GC) logic will only consider those blobs for GC which " +
"are not accessed recently (currentTime - lastModifiedTime > blobGcMaxAgeInSecs). For " +
"example as per default only those blobs which have been created 24 hrs ago will be " +
"considered for GC"
)
public static final String PROP_BLOB_GC_MAX_AGE = "blobGcMaxAgeInSecs";
/**
* Default interval for taking snapshots of locally tracked blob ids.
*/
private static final long DEFAULT_BLOB_SNAPSHOT_INTERVAL = 12 * 60 * 60;
@Property (longValue = DEFAULT_BLOB_SNAPSHOT_INTERVAL,
label = "Blob tracking snapshot interval (in secs)",
description = "This is the default interval in which the snapshots of locally tracked blob ids will"
+ "be taken and synchronized with the blob store. This should be configured to be less than the "
+ "frequency of blob GC so that deletions during blob GC can be accounted for "
+ "in the next GC execution."
)
public static final String PROP_BLOB_SNAPSHOT_INTERVAL = "blobTrackSnapshotIntervalInSecs";
private static final String DEFAULT_PROP_HOME = "./repository";
@Property(
label = "Root directory",
description = "Root directory for local tracking of blob ids. This service " +
"will first lookup the 'repository.home' framework property and " +
"then a component context property with the same name. If none " +
"of them is defined, a sub directory 'repository' relative to " +
"the current working directory is used."
)
private static final String PROP_HOME = "repository.home";
private static final long DEFAULT_MAX_REPLICATION_LAG = 6 * 60 * 60;
@Property(longValue = DEFAULT_MAX_REPLICATION_LAG,
label = "Max Replication Lag (in secs)",
description = "Value in seconds. Determines the duration beyond which it can be safely assumed " +
"that the state on the secondaries is consistent with the primary, and it is safe to read from them"
)
public static final String PROP_REPLICATION_LAG = "maxReplicationLagInSecs";
private long maxReplicationLagInSecs = DEFAULT_MAX_REPLICATION_LAG;
@Property(options = {
@PropertyOption(name = "MONGO", value = "MONGO"),
@PropertyOption(name = "RDB", value = "RDB")
},
value = "MONGO",
label = "DocumentStore Type",
description = "Type of DocumentStore to use for persistence. Defaults to MONGO"
)
public static final String PROP_DS_TYPE = "documentStoreType";
private static final boolean DEFAULT_BUNDLING_DISABLED = false;
@Property(boolValue = DEFAULT_BUNDLING_DISABLED,
label = "Bundling Disabled",
description = "Boolean value indicating that Node bundling is disabled"
)
private static final String PROP_BUNDLING_DISABLED = "bundlingDisabled";
@Property(
label = "DocumentNodeStore update.limit",
description = "Number of content updates that need to happen before " +
"the updates are automatically purged to the private branch."
)
public static final String PROP_UPDATE_LIMIT = "updateLimit";
private DocumentStoreType documentStoreType;
@Reference
private StatisticsProvider statisticsProvider;
private boolean customBlobStore;
private ServiceRegistration blobStoreReg;
private BlobStore defaultBlobStore;
@Activate
protected void activate(ComponentContext context, Map<String, ?> config) throws Exception {
closer = Closer.create();
this.context = context;
whiteboard = new OsgiWhiteboard(context.getBundleContext());
executor = new WhiteboardExecutor();
executor.start(whiteboard);
maxReplicationLagInSecs = toLong(config.get(PROP_REPLICATION_LAG), DEFAULT_MAX_REPLICATION_LAG);
customBlobStore = toBoolean(prop(CUSTOM_BLOB_STORE), false);
documentStoreType = DocumentStoreType.fromString(PropertiesUtil.toString(config.get(PROP_DS_TYPE), "MONGO"));
registerNodeStoreIfPossible();
}
private void registerNodeStoreIfPossible() throws IOException {
// disallow attempts to restart (OAK-3420)
if (deactivationTimestamp != 0) {
log.info("DocumentNodeStore was already unregistered ({}ms ago)", System.currentTimeMillis() - deactivationTimestamp);
} else if (context == null) {
log.info("Component still not activated. Ignoring the initialization call");
} else if (customBlobStore && blobStore == null) {
log.info("Custom BlobStore use enabled. DocumentNodeStoreService would be initialized when "
+ "BlobStore would be available");
} else if (documentStoreType == DocumentStoreType.RDB && (dataSource == null || blobDataSource == null)) {
log.info("DataSource use enabled. DocumentNodeStoreService would be initialized when "
+ "DataSource would be available (currently available: nodes: {}, blobs: {})", dataSource, blobDataSource);
} else {
registerNodeStore();
}
}
private void registerNodeStore() throws IOException {
String uri = PropertiesUtil.toString(prop(PROP_URI, FWK_PROP_URI), DEFAULT_URI);
String db = PropertiesUtil.toString(prop(PROP_DB, FWK_PROP_DB), DEFAULT_DB);
int cacheSize = toInteger(prop(PROP_CACHE), DEFAULT_CACHE);
int nodeCachePercentage = toInteger(prop(PROP_NODE_CACHE_PERCENTAGE), DEFAULT_NODE_CACHE_PERCENTAGE);
int prevDocCachePercentage = toInteger(prop(PROP_PREV_DOC_CACHE_PERCENTAGE), DEFAULT_NODE_CACHE_PERCENTAGE);
int childrenCachePercentage = toInteger(prop(PROP_CHILDREN_CACHE_PERCENTAGE), DEFAULT_CHILDREN_CACHE_PERCENTAGE);
int diffCachePercentage = toInteger(prop(PROP_DIFF_CACHE_PERCENTAGE), DEFAULT_DIFF_CACHE_PERCENTAGE);
int blobCacheSize = toInteger(prop(PROP_BLOB_CACHE_SIZE), DEFAULT_BLOB_CACHE_SIZE);
String persistentCache = getPath(PROP_PERSISTENT_CACHE, DEFAULT_PERSISTENT_CACHE);
String journalCache = getPath(PROP_JOURNAL_CACHE, DEFAULT_JOURNAL_CACHE);
int cacheSegmentCount = toInteger(prop(PROP_CACHE_SEGMENT_COUNT), DEFAULT_CACHE_SEGMENT_COUNT);
int cacheStackMoveDistance = toInteger(prop(PROP_CACHE_STACK_MOVE_DISTANCE), DEFAULT_CACHE_STACK_MOVE_DISTANCE);
boolean bundlingDisabled = toBoolean(prop(PROP_BUNDLING_DISABLED), DEFAULT_BUNDLING_DISABLED);
boolean prefetchExternalChanges = toBoolean(prop(PROP_PREFETCH_EXTERNAL_CHANGES), false);
int updateLimit = toInteger(prop(PROP_UPDATE_LIMIT), DocumentMK.UPDATE_LIMIT);
DocumentMK.Builder mkBuilder =
new DocumentMK.Builder().
setStatisticsProvider(statisticsProvider).
memoryCacheSize(cacheSize * MB).
memoryCacheDistribution(
nodeCachePercentage,
prevDocCachePercentage,
childrenCachePercentage,
diffCachePercentage).
setCacheSegmentCount(cacheSegmentCount).
setCacheStackMoveDistance(cacheStackMoveDistance).
setBundlingDisabled(bundlingDisabled).
setJournalPropertyHandlerFactory(journalPropertyHandlerFactory).
setLeaseCheck(!ClusterNodeInfo.DEFAULT_LEASE_CHECK_DISABLED /* OAK-2739: enabled by default */).
setLeaseFailureHandler(new LeaseFailureHandler() {
@Override
public void handleLeaseFailure() {
try {
// plan A: try stopping oak-core
log.error("handleLeaseFailure: stopping oak-core...");
Bundle bundle = context.getBundleContext().getBundle();
bundle.stop(Bundle.STOP_TRANSIENT);
log.error("handleLeaseFailure: stopped oak-core.");
// plan A worked, perfect!
} catch (BundleException e) {
log.error("handleLeaseFailure: exception while stopping oak-core: "+e, e);
// plan B: stop only DocumentNodeStoreService (to stop the background threads)
log.error("handleLeaseFailure: stopping DocumentNodeStoreService...");
context.disableComponent(DocumentNodeStoreService.class.getName());
log.error("handleLeaseFailure: stopped DocumentNodeStoreService");
// plan B succeeded.
}
}
}).
setPrefetchExternalChanges(prefetchExternalChanges).
setUpdateLimit(updateLimit);
if (!Strings.isNullOrEmpty(persistentCache)) {
mkBuilder.setPersistentCache(persistentCache);
}
if (!Strings.isNullOrEmpty(journalCache)) {
mkBuilder.setJournalCache(journalCache);
}
boolean wrappingCustomBlobStore = customBlobStore && blobStore instanceof BlobStoreWrapper;
//Set blobstore before setting the DB
if (customBlobStore && !wrappingCustomBlobStore) {
checkNotNull(blobStore, "Use of custom BlobStore enabled via [%s] but blobStore reference not " +
"initialized", CUSTOM_BLOB_STORE);
mkBuilder.setBlobStore(blobStore);
}
if (documentStoreType == DocumentStoreType.RDB) {
checkNotNull(dataSource, "DataStore type set [%s] but DataSource reference not initialized", PROP_DS_TYPE);
if (!customBlobStore) {
checkNotNull(blobDataSource, "DataStore type set [%s] but BlobDataSource reference not initialized", PROP_DS_TYPE);
mkBuilder.setRDBConnection(dataSource, blobDataSource);
log.info("Connected to datasources {} {}", dataSource, blobDataSource);
} else {
if (blobDataSource != null && blobDataSource != dataSource) {
log.info("Ignoring blobDataSource {} as custom blob store takes precedence.", blobDataSource);
}
mkBuilder.setRDBConnection(dataSource);
log.info("Connected to datasource {}", dataSource);
}
} else {
MongoClientURI mongoURI = new MongoClientURI(uri);
if (log.isInfoEnabled()) {
// Take care around not logging the uri directly as it
// might contain passwords
log.info("Starting DocumentNodeStore with host={}, db={}, cache size (MB)={}, persistentCache={}, " +
"journalCache={}, blobCacheSize (MB)={}, maxReplicationLagInSecs={}",
mongoURI.getHosts(), db, cacheSize, persistentCache,
journalCache, blobCacheSize, maxReplicationLagInSecs);
log.info("Mongo Connection details {}", MongoConnection.toString(mongoURI.getOptions()));
}
mkBuilder.setMaxReplicationLag(maxReplicationLagInSecs, TimeUnit.SECONDS);
mkBuilder.setMongoDB(uri, db, blobCacheSize);
log.info("Connected to database '{}'", db);
}
if (!customBlobStore){
defaultBlobStore = mkBuilder.getBlobStore();
log.info("Registering the BlobStore with ServiceRegistry");
blobStoreReg = context.getBundleContext().registerService(BlobStore.class.getName(),
defaultBlobStore , null);
}
//Set wrapping blob store after setting the DB
if (wrappingCustomBlobStore) {
((BlobStoreWrapper) blobStore).setBlobStore(mkBuilder.getBlobStore());
mkBuilder.setBlobStore(blobStore);
}
mkBuilder.setExecutor(executor);
nodeStore = mkBuilder.getNodeStore();
// ensure a clusterId is initialized
// and expose it as 'oak.clusterid' repository descriptor
GenericDescriptors clusterIdDesc = new GenericDescriptors();
clusterIdDesc.put(ClusterRepositoryInfo.OAK_CLUSTERID_REPOSITORY_DESCRIPTOR_KEY,
new SimpleValueFactory().createValue(
ClusterRepositoryInfo.getOrCreateId(nodeStore)), true, false);
whiteboard.register(Descriptors.class, clusterIdDesc, Collections.emptyMap());
// If a shared data store register the repo id in the data store
if (SharedDataStoreUtils.isShared(blobStore)) {
String repoId = null;
try {
repoId = ClusterRepositoryInfo.getOrCreateId(nodeStore);
((SharedDataStore) blobStore).addMetadataRecord(new ByteArrayInputStream(new byte[0]),
SharedDataStoreUtils.SharedStoreRecordType.REPOSITORY.getNameFromId(repoId));
} catch (Exception e) {
throw new IOException("Could not register a unique repositoryId", e);
}
if (blobStore instanceof BlobTrackingStore) {
final long trackSnapshotInterval = toLong(prop(PROP_BLOB_SNAPSHOT_INTERVAL),
DEFAULT_BLOB_SNAPSHOT_INTERVAL);
String root = getRepositoryHome();
BlobTrackingStore trackingStore = (BlobTrackingStore) blobStore;
if (trackingStore.getTracker() != null) {
trackingStore.getTracker().close();
}
((BlobTrackingStore) blobStore).addTracker(
new BlobIdTracker(root, repoId, trackSnapshotInterval, (SharedDataStore)
blobStore));
}
}
registerJMXBeans(nodeStore, mkBuilder);
registerLastRevRecoveryJob(nodeStore);
registerJournalGC(nodeStore);
if (!isNodeStoreProvider()) {
observerTracker = new ObserverTracker(nodeStore);
observerTracker.start(context.getBundleContext());
}
journalPropertyHandlerFactory.start(whiteboard);
DocumentStore ds = nodeStore.getDocumentStore();
// OAK-2682: time difference detection applied at startup with a default
// max time diff of 2000 millis (2sec)
final long maxDiff = Long.parseLong(System.getProperty("oak.documentMK.maxServerTimeDiffMillis", "2000"));
try {
if (maxDiff>=0) {
final long timeDiff = ds.determineServerTimeDifferenceMillis();
log.info("registerNodeStore: server time difference: {}ms (max allowed: {}ms)", timeDiff, maxDiff);
if (Math.abs(timeDiff) > maxDiff) {
throw new AssertionError("Server clock seems off (" + timeDiff + "ms) by more than configured amount ("
+ maxDiff + "ms)");
}
}
} catch (RuntimeException e) { // no checked exception
// in case of a RuntimeException, just log but continue
log.warn("registerNodeStore: got RuntimeException while trying to determine time difference to server: " + e, e);
}
String[] serviceClasses;
if (isNodeStoreProvider()) {
registerNodeStoreProvider(nodeStore);
serviceClasses = new String[]{
DocumentNodeStore.class.getName(),
Clusterable.class.getName()
};
} else {
serviceClasses = new String[]{
NodeStore.class.getName(),
DocumentNodeStore.class.getName(),
Clusterable.class.getName()
};
}
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, DocumentNodeStore.class.getName());
props.put(DESCRIPTION, getMetadata(ds));
// OAK-2844: in order to allow DocumentDiscoveryLiteService to directly
// require a service DocumentNodeStore (instead of having to do an 'instanceof')
// the registration is now done for both NodeStore and DocumentNodeStore here.
nodeStoreReg = context.getBundleContext().registerService(
serviceClasses,
nodeStore, props);
}
private boolean isNodeStoreProvider() {
return prop(PROP_ROLE) != null;
}
private void registerNodeStoreProvider(final NodeStore ns) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(NodeStoreProvider.ROLE, prop(PROP_ROLE));
nodeStoreReg = context.getBundleContext().registerService(NodeStoreProvider.class.getName(), new NodeStoreProvider() {
@Override
public NodeStore getNodeStore() {
return ns;
}
},
props);
log.info("Registered NodeStoreProvider backed by DocumentNodeStore");
}
@Deactivate
protected void deactivate() {
if (observerTracker != null) {
observerTracker.stop();
}
if (journalPropertyHandlerFactory != null){
journalPropertyHandlerFactory.stop();
}
unregisterNodeStore();
}
@SuppressWarnings("UnusedDeclaration")
protected void bindBlobStore(BlobStore blobStore) throws IOException {
if (defaultBlobStore == blobStore){
return;
}
log.info("Initializing DocumentNodeStore with BlobStore [{}]", blobStore);
this.blobStore = blobStore;
registerNodeStoreIfPossible();
}
@SuppressWarnings("UnusedDeclaration")
protected void unbindBlobStore(BlobStore blobStore) {
if (defaultBlobStore == blobStore){
return;
}
this.blobStore = null;
unregisterNodeStore();
}
@SuppressWarnings("UnusedDeclaration")
protected void bindDataSource(DataSource dataSource) throws IOException {
if (this.dataSource != null) {
log.info("Ignoring bindDataSource [{}] because dataSource [{}] is already bound", dataSource, this.dataSource);
} else {
log.info("Initializing DocumentNodeStore with dataSource [{}]", dataSource);
this.dataSource = dataSource;
registerNodeStoreIfPossible();
}
}
@SuppressWarnings("UnusedDeclaration")
protected void unbindDataSource(DataSource dataSource) {
if (this.dataSource != dataSource) {
log.info("Ignoring unbindDataSource [{}] because dataSource is bound to [{}]", dataSource, this.dataSource);
} else {
log.info("Unregistering DocumentNodeStore because dataSource [{}] was unbound", dataSource);
this.dataSource = null;
unregisterNodeStore();
}
}
@SuppressWarnings("UnusedDeclaration")
protected void bindBlobDataSource(DataSource dataSource) throws IOException {
if (this.blobDataSource != null) {
log.info("Ignoring bindBlobDataSource [{}] because blobDataSource [{}] is already bound", dataSource,
this.blobDataSource);
} else {
log.info("Initializing DocumentNodeStore with blobDataSource [{}]", dataSource);
this.blobDataSource = dataSource;
registerNodeStoreIfPossible();
}
}
@SuppressWarnings("UnusedDeclaration")
protected void unbindBlobDataSource(DataSource dataSource) {
if (this.blobDataSource != dataSource) {
log.info("Ignoring unbindBlobDataSource [{}] because dataSource is bound to [{}]", dataSource, this.blobDataSource);
} else {
log.info("Unregistering DocumentNodeStore because blobDataSource [{}] was unbound", dataSource);
this.blobDataSource = null;
unregisterNodeStore();
}
}
@SuppressWarnings("UnusedDeclaration")
protected void bindNodeStateCache(DocumentNodeStateCache nodeStateCache) throws IOException {
if (nodeStore != null){
log.info("Registered DocumentNodeStateCache [{}] with DocumentNodeStore", nodeStateCache);
nodeStore.setNodeStateCache(nodeStateCache);
}
}
@SuppressWarnings("UnusedDeclaration")
protected void unbindNodeStateCache(DocumentNodeStateCache nodeStateCache) {
if (nodeStore != null){
nodeStore.setNodeStateCache(DocumentNodeStateCache.NOOP);
}
}
private void unregisterNodeStore() {
deactivationTimestamp = System.currentTimeMillis();
closeQuietly(closer);
if (nodeStoreReg != null) {
nodeStoreReg.unregister();
nodeStoreReg = null;
}
//If we exposed our BlobStore then unregister it *after*
//NodeStore service. This ensures that if any other component
//like SecondaryStoreCache depends on this then it remains active
//untill DocumentNodeStore get deactivated
if (blobStoreReg != null){
blobStoreReg.unregister();
blobStoreReg = null;
}
if (nodeStore != null) {
nodeStore.dispose();
nodeStore = null;
}
if (executor != null) {
executor.stop();
executor = null;
}
}
private void registerJMXBeans(final DocumentNodeStore store, DocumentMK.Builder mkBuilder) throws
IOException {
addRegistration(
registerMBean(whiteboard,
CacheStatsMBean.class,
store.getNodeCacheStats(),
CacheStatsMBean.TYPE,
store.getNodeCacheStats().getName()));
addRegistration(
registerMBean(whiteboard,
CacheStatsMBean.class,
store.getNodeChildrenCacheStats(),
CacheStatsMBean.TYPE,
store.getNodeChildrenCacheStats().getName())
);
for (CacheStats cs : store.getDiffCacheStats()) {
addRegistration(
registerMBean(whiteboard,
CacheStatsMBean.class, cs,
CacheStatsMBean.TYPE, cs.getName()));
}
DocumentStore ds = store.getDocumentStore();
if (ds.getCacheStats() != null) {
for (CacheStats cacheStats : ds.getCacheStats()) {
addRegistration(
registerMBean(whiteboard,
CacheStatsMBean.class,
cacheStats,
CacheStatsMBean.TYPE,
cacheStats.getName())
);
}
}
addRegistration(
registerMBean(whiteboard,
CheckpointMBean.class,
new DocumentCheckpointMBean(store),
CheckpointMBean.TYPE,
"Document node store checkpoint management")
);
addRegistration(
registerMBean(whiteboard,
DocumentNodeStoreMBean.class,
store.getMBean(),
DocumentNodeStoreMBean.TYPE,
"Document node store management")
);
if (mkBuilder.getBlobStoreCacheStats() != null) {
addRegistration(
registerMBean(whiteboard,
CacheStatsMBean.class,
mkBuilder.getBlobStoreCacheStats(),
CacheStatsMBean.TYPE,
mkBuilder.getBlobStoreCacheStats().getName())
);
}
if (mkBuilder.getDocumentStoreStatsCollector() instanceof DocumentStoreStatsMBean) {
addRegistration(
registerMBean(whiteboard,
DocumentStoreStatsMBean.class,
(DocumentStoreStatsMBean) mkBuilder.getDocumentStoreStatsCollector(),
DocumentStoreStatsMBean.TYPE,
"DocumentStore Statistics")
);
}
// register persistent cache stats
Map<CacheType, PersistentCacheStats> persistenceCacheStats = mkBuilder.getPersistenceCacheStats();
for (PersistentCacheStats pcs: persistenceCacheStats.values()) {
addRegistration(
registerMBean(whiteboard,
PersistentCacheStatsMBean.class,
pcs,
PersistentCacheStatsMBean.TYPE,
pcs.getName())
);
}
final long versionGcMaxAgeInSecs = toLong(prop(PROP_VER_GC_MAX_AGE), DEFAULT_VER_GC_MAX_AGE);
final long blobGcMaxAgeInSecs = toLong(prop(PROP_BLOB_GC_MAX_AGE), DEFAULT_BLOB_GC_MAX_AGE);
if (store.getBlobStore() instanceof GarbageCollectableBlobStore) {
BlobGarbageCollector gc = store.createBlobGarbageCollector(blobGcMaxAgeInSecs,
ClusterRepositoryInfo.getOrCreateId(nodeStore));
addRegistration(registerMBean(whiteboard, BlobGCMBean.class, new BlobGC(gc, executor),
BlobGCMBean.TYPE, "Document node store blob garbage collection"));
}
Runnable startGC = new Runnable() {
@Override
public void run() {
try {
store.getVersionGarbageCollector().gc(versionGcMaxAgeInSecs, TimeUnit.SECONDS);
} catch (IOException e) {
log.warn("Error occurred while executing the Version Garbage Collector", e);
}
}
};
Runnable cancelGC = new Runnable() {
@Override
public void run() {
store.getVersionGarbageCollector().cancel();
}
};
RevisionGC revisionGC = new RevisionGC(startGC, cancelGC, executor);
addRegistration(registerMBean(whiteboard, RevisionGCMBean.class, revisionGC,
RevisionGCMBean.TYPE, "Document node store revision garbage collection"));
BlobStoreStats blobStoreStats = mkBuilder.getBlobStoreStats();
if (!customBlobStore && blobStoreStats != null) {
addRegistration(registerMBean(whiteboard,
BlobStoreStatsMBean.class,
blobStoreStats,
BlobStoreStatsMBean.TYPE,
ds.getClass().getSimpleName()));
}
if (!mkBuilder.isBundlingDisabled()){
addRegistration(registerMBean(whiteboard,
BackgroundObserverMBean.class,
store.getBundlingConfigHandler().getMBean(),
BackgroundObserverMBean.TYPE,
"BundlingConfigObserver"));
}
}
private void registerLastRevRecoveryJob(final DocumentNodeStore nodeStore) {
long leaseTime = toLong(context.getProperties().get(PROP_REV_RECOVERY_INTERVAL),
ClusterNodeInfo.DEFAULT_LEASE_UPDATE_INTERVAL_MILLIS);
Runnable recoverJob = new Runnable() {
@Override
public void run() {
nodeStore.getLastRevRecoveryAgent().performRecoveryIfNeeded();
}
};
addRegistration(WhiteboardUtils.scheduleWithFixedDelay(whiteboard,
recoverJob, TimeUnit.MILLISECONDS.toSeconds(leaseTime),
false/*runOnSingleClusterNode*/, true /*use dedicated pool*/));
}
private void registerJournalGC(final DocumentNodeStore nodeStore) {
long journalGCInterval = toLong(context.getProperties().get(PROP_JOURNAL_GC_INTERVAL_MILLIS),
DEFAULT_JOURNAL_GC_INTERVAL_MILLIS);
final long journalGCMaxAge = toLong(context.getProperties().get(PROP_JOURNAL_GC_MAX_AGE_MILLIS),
DEFAULT_JOURNAL_GC_MAX_AGE_MILLIS);
Runnable journalGCJob = new Runnable() {
@Override
public void run() {
nodeStore.getJournalGarbageCollector().gc(journalGCMaxAge, TimeUnit.MILLISECONDS);
}
};
addRegistration(WhiteboardUtils.scheduleWithFixedDelay(whiteboard,
journalGCJob, TimeUnit.MILLISECONDS.toSeconds(journalGCInterval),
true/*runOnSingleClusterNode*/, true /*use dedicated pool*/));
}
private String prop(String propName) {
return prop(propName, PREFIX + propName);
}
private String prop(String propName, String fwkPropName) {
return lookupFrameworkThenConfiguration(context, propName, fwkPropName);
}
private String getPath(String propName, String defaultValue) {
String path = PropertiesUtil.toString(prop(propName), defaultValue);
if (Strings.isNullOrEmpty(path)) {
return path;
}
if ("-".equals(path)) {
// disable this path configuration
return "";
}
// resolve as relative to repository.home
return FilenameUtils.concat(getRepositoryHome(), path);
}
private String getRepositoryHome() {
String repoHome = prop(PROP_HOME, PROP_HOME);
if (Strings.isNullOrEmpty(repoHome)) {
repoHome = DEFAULT_PROP_HOME;
}
return repoHome;
}
private static String[] getMetadata(DocumentStore ds) {
Map<String, String> meta = new HashMap<String, String>(ds.getMetadata());
meta.put("nodeStoreType", "document");
String[] result = new String[meta.size()];
int i = 0;
for (Map.Entry<String, String> e : meta.entrySet()) {
result[i++] = e.getKey() + "=" + e.getValue();
}
return result;
}
private void addRegistration(@Nonnull Registration reg) {
closer.register(asCloseable(reg));
}
private static Closeable asCloseable(@Nonnull final Registration reg) {
checkNotNull(reg);
return new Closeable() {
@Override
public void close() throws IOException {
reg.unregister();
}
};
}
private static Closeable asCloseable(@Nonnull final AbstractServiceTracker t) {
checkNotNull(t);
return new Closeable() {
@Override
public void close() throws IOException {
t.stop();
}
};
}
}
| oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStoreService.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.jackrabbit.oak.plugins.document;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.jackrabbit.oak.commons.PropertiesUtil.toBoolean;
import static org.apache.jackrabbit.oak.commons.PropertiesUtil.toInteger;
import static org.apache.jackrabbit.oak.commons.PropertiesUtil.toLong;
import static org.apache.jackrabbit.oak.osgi.OsgiUtil.lookupFrameworkThenConfiguration;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_CACHE_SEGMENT_COUNT;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_CACHE_STACK_MOVE_DISTANCE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_CHILDREN_CACHE_PERCENTAGE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_DIFF_CACHE_PERCENTAGE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_MEMORY_CACHE_SIZE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_NODE_CACHE_PERCENTAGE;
import static org.apache.jackrabbit.oak.plugins.document.DocumentMK.Builder.DEFAULT_PREV_DOC_CACHE_PERCENTAGE;
import static org.apache.jackrabbit.oak.spi.blob.osgi.SplitBlobStoreService.ONLY_STANDALONE_TARGET;
import static org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils.registerMBean;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import com.google.common.base.Strings;
import com.mongodb.MongoClientURI;
import org.apache.commons.io.FilenameUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyOption;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.jackrabbit.commons.SimpleValueFactory;
import org.apache.jackrabbit.oak.api.Descriptors;
import org.apache.jackrabbit.oak.api.jmx.CacheStatsMBean;
import org.apache.jackrabbit.oak.api.jmx.CheckpointMBean;
import org.apache.jackrabbit.oak.api.jmx.PersistentCacheStatsMBean;
import org.apache.jackrabbit.oak.cache.CacheStats;
import org.apache.jackrabbit.oak.commons.PropertiesUtil;
import org.apache.jackrabbit.oak.spi.commit.ObserverTracker;
import org.apache.jackrabbit.oak.osgi.OsgiWhiteboard;
import org.apache.jackrabbit.oak.plugins.blob.BlobGC;
import org.apache.jackrabbit.oak.plugins.blob.BlobGCMBean;
import org.apache.jackrabbit.oak.plugins.blob.BlobGarbageCollector;
import org.apache.jackrabbit.oak.plugins.blob.BlobStoreStats;
import org.apache.jackrabbit.oak.plugins.blob.BlobTrackingStore;
import org.apache.jackrabbit.oak.plugins.blob.SharedDataStore;
import org.apache.jackrabbit.oak.plugins.blob.datastore.BlobIdTracker;
import org.apache.jackrabbit.oak.plugins.blob.datastore.SharedDataStoreUtils;
import org.apache.jackrabbit.oak.plugins.document.persistentCache.CacheType;
import org.apache.jackrabbit.oak.plugins.document.persistentCache.PersistentCacheStats;
import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection;
import org.apache.jackrabbit.oak.spi.cluster.ClusterRepositoryInfo;
import org.apache.jackrabbit.oak.spi.blob.BlobStore;
import org.apache.jackrabbit.oak.spi.blob.BlobStoreWrapper;
import org.apache.jackrabbit.oak.spi.blob.GarbageCollectableBlobStore;
import org.apache.jackrabbit.oak.spi.blob.stats.BlobStoreStatsMBean;
import org.apache.jackrabbit.oak.spi.commit.BackgroundObserverMBean;
import org.apache.jackrabbit.oak.spi.state.Clusterable;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.spi.state.NodeStoreProvider;
import org.apache.jackrabbit.oak.spi.state.RevisionGC;
import org.apache.jackrabbit.oak.spi.state.RevisionGCMBean;
import org.apache.jackrabbit.oak.spi.whiteboard.Registration;
import org.apache.jackrabbit.oak.spi.whiteboard.Whiteboard;
import org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardExecutor;
import org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils;
import org.apache.jackrabbit.oak.stats.StatisticsProvider;
import org.apache.jackrabbit.oak.spi.descriptors.GenericDescriptors;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The OSGi service to start/stop a DocumentNodeStore instance.
*/
@Component(policy = ConfigurationPolicy.REQUIRE,
metatype = true,
label = "Apache Jackrabbit Oak Document NodeStore Service",
description = "NodeStore implementation based on Document model. For configuration option refer " +
"to http://jackrabbit.apache.org/oak/docs/osgi_config.html#DocumentNodeStore. Note that for system " +
"stability purpose it is advisable to not change these settings at runtime. Instead the config change " +
"should be done via file system based config file and this view should ONLY be used to determine which " +
"options are supported"
)
public class DocumentNodeStoreService {
private static final long MB = 1024 * 1024;
private static final String DEFAULT_URI = "mongodb://localhost:27017/oak";
private static final int DEFAULT_CACHE = (int) (DEFAULT_MEMORY_CACHE_SIZE / MB);
private static final int DEFAULT_BLOB_CACHE_SIZE = 16;
private static final String DEFAULT_DB = "oak";
private static final String DEFAULT_PERSISTENT_CACHE = "cache,binary=0";
private static final String DEFAULT_JOURNAL_CACHE = "diff-cache";
private static final String PREFIX = "oak.documentstore.";
private static final String DESCRIPTION = "oak.nodestore.description";
/**
* Name of framework property to configure Mongo Connection URI
*/
private static final String FWK_PROP_URI = "oak.mongo.uri";
/**
* Name of framework property to configure Mongo Database name
* to use
*/
private static final String FWK_PROP_DB = "oak.mongo.db";
@Property(value = DEFAULT_URI,
label = "Mongo URI",
description = "Mongo connection URI used to connect to Mongo. Refer to " +
"http://docs.mongodb.org/manual/reference/connection-string/ for details. Note that this value " +
"can be overridden via framework property 'oak.mongo.uri'"
)
private static final String PROP_URI = "mongouri";
@Property(value = DEFAULT_DB,
label = "Mongo DB name",
description = "Name of the database in Mongo. Note that this value " +
"can be overridden via framework property 'oak.mongo.db'"
)
private static final String PROP_DB = "db";
@Property(intValue = DEFAULT_CACHE,
label = "Cache Size (in MB)",
description = "Cache size in MB. This is distributed among various caches used in DocumentNodeStore"
)
private static final String PROP_CACHE = "cache";
@Property(intValue = DEFAULT_NODE_CACHE_PERCENTAGE,
label = "NodeState Cache",
description = "Percentage of cache to be allocated towards Node cache"
)
private static final String PROP_NODE_CACHE_PERCENTAGE = "nodeCachePercentage";
@Property(intValue = DEFAULT_PREV_DOC_CACHE_PERCENTAGE,
label = "PreviousDocument Cache",
description = "Percentage of cache to be allocated towards Previous Document cache"
)
private static final String PROP_PREV_DOC_CACHE_PERCENTAGE = "prevDocCachePercentage";
@Property(intValue = DocumentMK.Builder.DEFAULT_CHILDREN_CACHE_PERCENTAGE,
label = "NodeState Children Cache",
description = "Percentage of cache to be allocated towards Children cache"
)
private static final String PROP_CHILDREN_CACHE_PERCENTAGE = "childrenCachePercentage";
@Property(intValue = DocumentMK.Builder.DEFAULT_DIFF_CACHE_PERCENTAGE,
label = "Diff Cache",
description = "Percentage of cache to be allocated towards Diff cache"
)
private static final String PROP_DIFF_CACHE_PERCENTAGE = "diffCachePercentage";
@Property(intValue = DEFAULT_CACHE_SEGMENT_COUNT,
label = "LIRS Cache Segment Count",
description = "The number of segments in the LIRS cache " +
"(default 16, a higher count means higher concurrency " +
"but slightly lower cache hit rate)"
)
private static final String PROP_CACHE_SEGMENT_COUNT = "cacheSegmentCount";
@Property(intValue = DEFAULT_CACHE_STACK_MOVE_DISTANCE,
label = "LIRS Cache Stack Move Distance",
description = "The delay to move entries to the head of the queue " +
"in the LIRS cache " +
"(default 16, a higher value means higher concurrency " +
"but slightly lower cache hit rate)"
)
private static final String PROP_CACHE_STACK_MOVE_DISTANCE = "cacheStackMoveDistance";
@Property(intValue = DEFAULT_BLOB_CACHE_SIZE,
label = "Blob Cache Size (in MB)",
description = "Cache size to store blobs in memory. Used only with default BlobStore " +
"(as per DocumentStore type)"
)
private static final String PROP_BLOB_CACHE_SIZE = "blobCacheSize";
@Property(value = DEFAULT_PERSISTENT_CACHE,
label = "Persistent Cache Config",
description = "Configuration for persistent cache. Refer to " +
"http://jackrabbit.apache.org/oak/docs/nodestore/persistent-cache.html for various options"
)
private static final String PROP_PERSISTENT_CACHE = "persistentCache";
@Property(value = DEFAULT_JOURNAL_CACHE,
label = "Journal Cache Config",
description = "Configuration for journal cache. Refer to " +
"http://jackrabbit.apache.org/oak/docs/nodestore/persistent-cache.html for various options"
)
private static final String PROP_JOURNAL_CACHE = "journalCache";
@Property(boolValue = false,
label = "Custom BlobStore",
description = "Boolean value indicating that a custom BlobStore is to be used. " +
"By default, for MongoDB, MongoBlobStore is used; for RDB, RDBBlobStore is used."
)
public static final String CUSTOM_BLOB_STORE = "customBlobStore";
private static final long DEFAULT_JOURNAL_GC_INTERVAL_MILLIS = 5*60*1000; // default is 5min
@Property(longValue = DEFAULT_JOURNAL_GC_INTERVAL_MILLIS,
label = "Journal Garbage Collection Interval (millis)",
description = "Long value indicating interval (in milliseconds) with which the "
+ "journal (for external changes) is cleaned up. Default is " + DEFAULT_JOURNAL_GC_INTERVAL_MILLIS
)
private static final String PROP_JOURNAL_GC_INTERVAL_MILLIS = "journalGCInterval";
private static final long DEFAULT_JOURNAL_GC_MAX_AGE_MILLIS = 6*60*60*1000; // default is 6hours
@Property(longValue = DEFAULT_JOURNAL_GC_MAX_AGE_MILLIS,
label = "Maximum Age of Journal Entries (millis)",
description = "Long value indicating max age (in milliseconds) that "
+ "journal (for external changes) entries are kept (older ones are candidates for gc). "
+ "Default is " + DEFAULT_JOURNAL_GC_MAX_AGE_MILLIS
)
private static final String PROP_JOURNAL_GC_MAX_AGE_MILLIS = "journalGCMaxAge";
@Property (boolValue = false,
label = "Pre-fetch external changes",
description = "Boolean value indicating if external changes should " +
"be pre-fetched in a background thread."
)
public static final String PROP_PREFETCH_EXTERNAL_CHANGES = "prefetchExternalChanges";
@Property(
label = "NodeStoreProvider role",
description = "Property indicating that this component will not register as a NodeStore but as a NodeStoreProvider with given role"
)
public static final String PROP_ROLE = "role";
private static enum DocumentStoreType {
MONGO, RDB;
static DocumentStoreType fromString(String type) {
if (type == null) {
return MONGO;
}
return valueOf(type.toUpperCase(Locale.ROOT));
}
}
private final Logger log = LoggerFactory.getLogger(this.getClass());
private ServiceRegistration nodeStoreReg;
private final List<Registration> registrations = new ArrayList<Registration>();
private WhiteboardExecutor executor;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC, target = ONLY_STANDALONE_TARGET)
private volatile BlobStore blobStore;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC,
target = "(datasource.name=oak)"
)
private volatile DataSource dataSource;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC,
target = "(datasource.name=oak)"
)
private volatile DataSource blobDataSource;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC)
private volatile DocumentNodeStateCache nodeStateCache;
private DocumentNodeStore nodeStore;
private ObserverTracker observerTracker;
private JournalPropertyHandlerFactory journalPropertyHandlerFactory = new JournalPropertyHandlerFactory();
private ComponentContext context;
private Whiteboard whiteboard;
private long deactivationTimestamp = 0;
/**
* Revisions older than this time would be garbage collected
*/
private static final long DEFAULT_VER_GC_MAX_AGE = 24 * 60 * 60; //TimeUnit.DAYS.toSeconds(1);
@Property (longValue = DEFAULT_VER_GC_MAX_AGE,
label = "Version GC Max Age (in secs)",
description = "Version Garbage Collector (GC) logic will only consider those deleted for GC which " +
"are not accessed recently (currentTime - lastModifiedTime > versionGcMaxAgeInSecs). For " +
"example as per default only those document which have been *marked* deleted 24 hrs ago will be " +
"considered for GC. This also applies how older revision of live document are GC."
)
public static final String PROP_VER_GC_MAX_AGE = "versionGcMaxAgeInSecs";
public static final String PROP_REV_RECOVERY_INTERVAL = "lastRevRecoveryJobIntervalInSecs";
/**
* Blob modified before this time duration would be considered for Blob GC
*/
private static final long DEFAULT_BLOB_GC_MAX_AGE = 24 * 60 * 60;
@Property (longValue = DEFAULT_BLOB_GC_MAX_AGE,
label = "Blob GC Max Age (in secs)",
description = "Blob Garbage Collector (GC) logic will only consider those blobs for GC which " +
"are not accessed recently (currentTime - lastModifiedTime > blobGcMaxAgeInSecs). For " +
"example as per default only those blobs which have been created 24 hrs ago will be " +
"considered for GC"
)
public static final String PROP_BLOB_GC_MAX_AGE = "blobGcMaxAgeInSecs";
/**
* Default interval for taking snapshots of locally tracked blob ids.
*/
private static final long DEFAULT_BLOB_SNAPSHOT_INTERVAL = 12 * 60 * 60;
@Property (longValue = DEFAULT_BLOB_SNAPSHOT_INTERVAL,
label = "Blob tracking snapshot interval (in secs)",
description = "This is the default interval in which the snapshots of locally tracked blob ids will"
+ "be taken and synchronized with the blob store. This should be configured to be less than the "
+ "frequency of blob GC so that deletions during blob GC can be accounted for "
+ "in the next GC execution."
)
public static final String PROP_BLOB_SNAPSHOT_INTERVAL = "blobTrackSnapshotIntervalInSecs";
private static final String DEFAULT_PROP_HOME = "./repository";
@Property(
label = "Root directory",
description = "Root directory for local tracking of blob ids. This service " +
"will first lookup the 'repository.home' framework property and " +
"then a component context property with the same name. If none " +
"of them is defined, a sub directory 'repository' relative to " +
"the current working directory is used."
)
private static final String PROP_HOME = "repository.home";
private static final long DEFAULT_MAX_REPLICATION_LAG = 6 * 60 * 60;
@Property(longValue = DEFAULT_MAX_REPLICATION_LAG,
label = "Max Replication Lag (in secs)",
description = "Value in seconds. Determines the duration beyond which it can be safely assumed " +
"that the state on the secondaries is consistent with the primary, and it is safe to read from them"
)
public static final String PROP_REPLICATION_LAG = "maxReplicationLagInSecs";
private long maxReplicationLagInSecs = DEFAULT_MAX_REPLICATION_LAG;
@Property(options = {
@PropertyOption(name = "MONGO", value = "MONGO"),
@PropertyOption(name = "RDB", value = "RDB")
},
value = "MONGO",
label = "DocumentStore Type",
description = "Type of DocumentStore to use for persistence. Defaults to MONGO"
)
public static final String PROP_DS_TYPE = "documentStoreType";
private static final boolean DEFAULT_BUNDLING_DISABLED = false;
@Property(boolValue = DEFAULT_BUNDLING_DISABLED,
label = "Bundling Disabled",
description = "Boolean value indicating that Node bundling is disabled"
)
private static final String PROP_BUNDLING_DISABLED = "bundlingDisabled";
@Property(
label = "DocumentNodeStore update.limit",
description = "Number of content updates that need to happen before " +
"the updates are automatically purged to the private branch."
)
public static final String PROP_UPDATE_LIMIT = "updateLimit";
private DocumentStoreType documentStoreType;
@Reference
private StatisticsProvider statisticsProvider;
private boolean customBlobStore;
private ServiceRegistration blobStoreReg;
private BlobStore defaultBlobStore;
@Activate
protected void activate(ComponentContext context, Map<String, ?> config) throws Exception {
this.context = context;
whiteboard = new OsgiWhiteboard(context.getBundleContext());
executor = new WhiteboardExecutor();
executor.start(whiteboard);
maxReplicationLagInSecs = toLong(config.get(PROP_REPLICATION_LAG), DEFAULT_MAX_REPLICATION_LAG);
customBlobStore = toBoolean(prop(CUSTOM_BLOB_STORE), false);
documentStoreType = DocumentStoreType.fromString(PropertiesUtil.toString(config.get(PROP_DS_TYPE), "MONGO"));
registerNodeStoreIfPossible();
}
private void registerNodeStoreIfPossible() throws IOException {
// disallow attempts to restart (OAK-3420)
if (deactivationTimestamp != 0) {
log.info("DocumentNodeStore was already unregistered ({}ms ago)", System.currentTimeMillis() - deactivationTimestamp);
} else if (context == null) {
log.info("Component still not activated. Ignoring the initialization call");
} else if (customBlobStore && blobStore == null) {
log.info("Custom BlobStore use enabled. DocumentNodeStoreService would be initialized when "
+ "BlobStore would be available");
} else if (documentStoreType == DocumentStoreType.RDB && (dataSource == null || blobDataSource == null)) {
log.info("DataSource use enabled. DocumentNodeStoreService would be initialized when "
+ "DataSource would be available (currently available: nodes: {}, blobs: {})", dataSource, blobDataSource);
} else {
registerNodeStore();
}
}
private void registerNodeStore() throws IOException {
String uri = PropertiesUtil.toString(prop(PROP_URI, FWK_PROP_URI), DEFAULT_URI);
String db = PropertiesUtil.toString(prop(PROP_DB, FWK_PROP_DB), DEFAULT_DB);
int cacheSize = toInteger(prop(PROP_CACHE), DEFAULT_CACHE);
int nodeCachePercentage = toInteger(prop(PROP_NODE_CACHE_PERCENTAGE), DEFAULT_NODE_CACHE_PERCENTAGE);
int prevDocCachePercentage = toInteger(prop(PROP_PREV_DOC_CACHE_PERCENTAGE), DEFAULT_NODE_CACHE_PERCENTAGE);
int childrenCachePercentage = toInteger(prop(PROP_CHILDREN_CACHE_PERCENTAGE), DEFAULT_CHILDREN_CACHE_PERCENTAGE);
int diffCachePercentage = toInteger(prop(PROP_DIFF_CACHE_PERCENTAGE), DEFAULT_DIFF_CACHE_PERCENTAGE);
int blobCacheSize = toInteger(prop(PROP_BLOB_CACHE_SIZE), DEFAULT_BLOB_CACHE_SIZE);
String persistentCache = getPath(PROP_PERSISTENT_CACHE, DEFAULT_PERSISTENT_CACHE);
String journalCache = getPath(PROP_JOURNAL_CACHE, DEFAULT_JOURNAL_CACHE);
int cacheSegmentCount = toInteger(prop(PROP_CACHE_SEGMENT_COUNT), DEFAULT_CACHE_SEGMENT_COUNT);
int cacheStackMoveDistance = toInteger(prop(PROP_CACHE_STACK_MOVE_DISTANCE), DEFAULT_CACHE_STACK_MOVE_DISTANCE);
boolean bundlingDisabled = toBoolean(prop(PROP_BUNDLING_DISABLED), DEFAULT_BUNDLING_DISABLED);
boolean prefetchExternalChanges = toBoolean(prop(PROP_PREFETCH_EXTERNAL_CHANGES), false);
int updateLimit = toInteger(prop(PROP_UPDATE_LIMIT), DocumentMK.UPDATE_LIMIT);
DocumentMK.Builder mkBuilder =
new DocumentMK.Builder().
setStatisticsProvider(statisticsProvider).
memoryCacheSize(cacheSize * MB).
memoryCacheDistribution(
nodeCachePercentage,
prevDocCachePercentage,
childrenCachePercentage,
diffCachePercentage).
setCacheSegmentCount(cacheSegmentCount).
setCacheStackMoveDistance(cacheStackMoveDistance).
setBundlingDisabled(bundlingDisabled).
setJournalPropertyHandlerFactory(journalPropertyHandlerFactory).
setLeaseCheck(!ClusterNodeInfo.DEFAULT_LEASE_CHECK_DISABLED /* OAK-2739: enabled by default */).
setLeaseFailureHandler(new LeaseFailureHandler() {
@Override
public void handleLeaseFailure() {
try {
// plan A: try stopping oak-core
log.error("handleLeaseFailure: stopping oak-core...");
Bundle bundle = context.getBundleContext().getBundle();
bundle.stop(Bundle.STOP_TRANSIENT);
log.error("handleLeaseFailure: stopped oak-core.");
// plan A worked, perfect!
} catch (BundleException e) {
log.error("handleLeaseFailure: exception while stopping oak-core: "+e, e);
// plan B: stop only DocumentNodeStoreService (to stop the background threads)
log.error("handleLeaseFailure: stopping DocumentNodeStoreService...");
context.disableComponent(DocumentNodeStoreService.class.getName());
log.error("handleLeaseFailure: stopped DocumentNodeStoreService");
// plan B succeeded.
}
}
}).
setPrefetchExternalChanges(prefetchExternalChanges).
setUpdateLimit(updateLimit);
if (!Strings.isNullOrEmpty(persistentCache)) {
mkBuilder.setPersistentCache(persistentCache);
}
if (!Strings.isNullOrEmpty(journalCache)) {
mkBuilder.setJournalCache(journalCache);
}
boolean wrappingCustomBlobStore = customBlobStore && blobStore instanceof BlobStoreWrapper;
//Set blobstore before setting the DB
if (customBlobStore && !wrappingCustomBlobStore) {
checkNotNull(blobStore, "Use of custom BlobStore enabled via [%s] but blobStore reference not " +
"initialized", CUSTOM_BLOB_STORE);
mkBuilder.setBlobStore(blobStore);
}
if (documentStoreType == DocumentStoreType.RDB) {
checkNotNull(dataSource, "DataStore type set [%s] but DataSource reference not initialized", PROP_DS_TYPE);
if (!customBlobStore) {
checkNotNull(blobDataSource, "DataStore type set [%s] but BlobDataSource reference not initialized", PROP_DS_TYPE);
mkBuilder.setRDBConnection(dataSource, blobDataSource);
log.info("Connected to datasources {} {}", dataSource, blobDataSource);
} else {
if (blobDataSource != null && blobDataSource != dataSource) {
log.info("Ignoring blobDataSource {} as custom blob store takes precedence.", blobDataSource);
}
mkBuilder.setRDBConnection(dataSource);
log.info("Connected to datasource {}", dataSource);
}
} else {
MongoClientURI mongoURI = new MongoClientURI(uri);
if (log.isInfoEnabled()) {
// Take care around not logging the uri directly as it
// might contain passwords
log.info("Starting DocumentNodeStore with host={}, db={}, cache size (MB)={}, persistentCache={}, " +
"journalCache={}, blobCacheSize (MB)={}, maxReplicationLagInSecs={}",
mongoURI.getHosts(), db, cacheSize, persistentCache,
journalCache, blobCacheSize, maxReplicationLagInSecs);
log.info("Mongo Connection details {}", MongoConnection.toString(mongoURI.getOptions()));
}
mkBuilder.setMaxReplicationLag(maxReplicationLagInSecs, TimeUnit.SECONDS);
mkBuilder.setMongoDB(uri, db, blobCacheSize);
log.info("Connected to database '{}'", db);
}
if (!customBlobStore){
defaultBlobStore = mkBuilder.getBlobStore();
log.info("Registering the BlobStore with ServiceRegistry");
blobStoreReg = context.getBundleContext().registerService(BlobStore.class.getName(),
defaultBlobStore , null);
}
//Set wrapping blob store after setting the DB
if (wrappingCustomBlobStore) {
((BlobStoreWrapper) blobStore).setBlobStore(mkBuilder.getBlobStore());
mkBuilder.setBlobStore(blobStore);
}
mkBuilder.setExecutor(executor);
nodeStore = mkBuilder.getNodeStore();
// ensure a clusterId is initialized
// and expose it as 'oak.clusterid' repository descriptor
GenericDescriptors clusterIdDesc = new GenericDescriptors();
clusterIdDesc.put(ClusterRepositoryInfo.OAK_CLUSTERID_REPOSITORY_DESCRIPTOR_KEY,
new SimpleValueFactory().createValue(
ClusterRepositoryInfo.getOrCreateId(nodeStore)), true, false);
whiteboard.register(Descriptors.class, clusterIdDesc, Collections.emptyMap());
// If a shared data store register the repo id in the data store
if (SharedDataStoreUtils.isShared(blobStore)) {
String repoId = null;
try {
repoId = ClusterRepositoryInfo.getOrCreateId(nodeStore);
((SharedDataStore) blobStore).addMetadataRecord(new ByteArrayInputStream(new byte[0]),
SharedDataStoreUtils.SharedStoreRecordType.REPOSITORY.getNameFromId(repoId));
} catch (Exception e) {
throw new IOException("Could not register a unique repositoryId", e);
}
if (blobStore instanceof BlobTrackingStore) {
final long trackSnapshotInterval = toLong(prop(PROP_BLOB_SNAPSHOT_INTERVAL),
DEFAULT_BLOB_SNAPSHOT_INTERVAL);
String root = getRepositoryHome();
BlobTrackingStore trackingStore = (BlobTrackingStore) blobStore;
if (trackingStore.getTracker() != null) {
trackingStore.getTracker().close();
}
((BlobTrackingStore) blobStore).addTracker(
new BlobIdTracker(root, repoId, trackSnapshotInterval, (SharedDataStore)
blobStore));
}
}
registerJMXBeans(nodeStore, mkBuilder);
registerLastRevRecoveryJob(nodeStore);
registerJournalGC(nodeStore);
if (!isNodeStoreProvider()) {
observerTracker = new ObserverTracker(nodeStore);
observerTracker.start(context.getBundleContext());
}
journalPropertyHandlerFactory.start(whiteboard);
DocumentStore ds = nodeStore.getDocumentStore();
// OAK-2682: time difference detection applied at startup with a default
// max time diff of 2000 millis (2sec)
final long maxDiff = Long.parseLong(System.getProperty("oak.documentMK.maxServerTimeDiffMillis", "2000"));
try {
if (maxDiff>=0) {
final long timeDiff = ds.determineServerTimeDifferenceMillis();
log.info("registerNodeStore: server time difference: {}ms (max allowed: {}ms)", timeDiff, maxDiff);
if (Math.abs(timeDiff) > maxDiff) {
throw new AssertionError("Server clock seems off (" + timeDiff + "ms) by more than configured amount ("
+ maxDiff + "ms)");
}
}
} catch (RuntimeException e) { // no checked exception
// in case of a RuntimeException, just log but continue
log.warn("registerNodeStore: got RuntimeException while trying to determine time difference to server: " + e, e);
}
String[] serviceClasses;
if (isNodeStoreProvider()) {
registerNodeStoreProvider(nodeStore);
serviceClasses = new String[]{
DocumentNodeStore.class.getName(),
Clusterable.class.getName()
};
} else {
serviceClasses = new String[]{
NodeStore.class.getName(),
DocumentNodeStore.class.getName(),
Clusterable.class.getName()
};
}
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, DocumentNodeStore.class.getName());
props.put(DESCRIPTION, getMetadata(ds));
// OAK-2844: in order to allow DocumentDiscoveryLiteService to directly
// require a service DocumentNodeStore (instead of having to do an 'instanceof')
// the registration is now done for both NodeStore and DocumentNodeStore here.
nodeStoreReg = context.getBundleContext().registerService(
serviceClasses,
nodeStore, props);
}
private boolean isNodeStoreProvider() {
return prop(PROP_ROLE) != null;
}
private void registerNodeStoreProvider(final NodeStore ns) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(NodeStoreProvider.ROLE, prop(PROP_ROLE));
nodeStoreReg = context.getBundleContext().registerService(NodeStoreProvider.class.getName(), new NodeStoreProvider() {
@Override
public NodeStore getNodeStore() {
return ns;
}
},
props);
log.info("Registered NodeStoreProvider backed by DocumentNodeStore");
}
@Deactivate
protected void deactivate() {
if (observerTracker != null) {
observerTracker.stop();
}
if (journalPropertyHandlerFactory != null){
journalPropertyHandlerFactory.stop();
}
unregisterNodeStore();
}
@SuppressWarnings("UnusedDeclaration")
protected void bindBlobStore(BlobStore blobStore) throws IOException {
if (defaultBlobStore == blobStore){
return;
}
log.info("Initializing DocumentNodeStore with BlobStore [{}]", blobStore);
this.blobStore = blobStore;
registerNodeStoreIfPossible();
}
@SuppressWarnings("UnusedDeclaration")
protected void unbindBlobStore(BlobStore blobStore) {
if (defaultBlobStore == blobStore){
return;
}
this.blobStore = null;
unregisterNodeStore();
}
@SuppressWarnings("UnusedDeclaration")
protected void bindDataSource(DataSource dataSource) throws IOException {
if (this.dataSource != null) {
log.info("Ignoring bindDataSource [{}] because dataSource [{}] is already bound", dataSource, this.dataSource);
} else {
log.info("Initializing DocumentNodeStore with dataSource [{}]", dataSource);
this.dataSource = dataSource;
registerNodeStoreIfPossible();
}
}
@SuppressWarnings("UnusedDeclaration")
protected void unbindDataSource(DataSource dataSource) {
if (this.dataSource != dataSource) {
log.info("Ignoring unbindDataSource [{}] because dataSource is bound to [{}]", dataSource, this.dataSource);
} else {
log.info("Unregistering DocumentNodeStore because dataSource [{}] was unbound", dataSource);
this.dataSource = null;
unregisterNodeStore();
}
}
@SuppressWarnings("UnusedDeclaration")
protected void bindBlobDataSource(DataSource dataSource) throws IOException {
if (this.blobDataSource != null) {
log.info("Ignoring bindBlobDataSource [{}] because blobDataSource [{}] is already bound", dataSource,
this.blobDataSource);
} else {
log.info("Initializing DocumentNodeStore with blobDataSource [{}]", dataSource);
this.blobDataSource = dataSource;
registerNodeStoreIfPossible();
}
}
@SuppressWarnings("UnusedDeclaration")
protected void unbindBlobDataSource(DataSource dataSource) {
if (this.blobDataSource != dataSource) {
log.info("Ignoring unbindBlobDataSource [{}] because dataSource is bound to [{}]", dataSource, this.blobDataSource);
} else {
log.info("Unregistering DocumentNodeStore because blobDataSource [{}] was unbound", dataSource);
this.blobDataSource = null;
unregisterNodeStore();
}
}
@SuppressWarnings("UnusedDeclaration")
protected void bindNodeStateCache(DocumentNodeStateCache nodeStateCache) throws IOException {
if (nodeStore != null){
log.info("Registered DocumentNodeStateCache [{}] with DocumentNodeStore", nodeStateCache);
nodeStore.setNodeStateCache(nodeStateCache);
}
}
@SuppressWarnings("UnusedDeclaration")
protected void unbindNodeStateCache(DocumentNodeStateCache nodeStateCache) {
if (nodeStore != null){
nodeStore.setNodeStateCache(DocumentNodeStateCache.NOOP);
}
}
private void unregisterNodeStore() {
deactivationTimestamp = System.currentTimeMillis();
for (Registration r : registrations) {
r.unregister();
}
registrations.clear();
if (nodeStoreReg != null) {
nodeStoreReg.unregister();
nodeStoreReg = null;
}
//If we exposed our BlobStore then unregister it *after*
//NodeStore service. This ensures that if any other component
//like SecondaryStoreCache depends on this then it remains active
//untill DocumentNodeStore get deactivated
if (blobStoreReg != null){
blobStoreReg.unregister();
blobStoreReg = null;
}
if (nodeStore != null) {
nodeStore.dispose();
nodeStore = null;
}
if (executor != null) {
executor.stop();
executor = null;
}
}
private void registerJMXBeans(final DocumentNodeStore store, DocumentMK.Builder mkBuilder) throws
IOException {
registrations.add(
registerMBean(whiteboard,
CacheStatsMBean.class,
store.getNodeCacheStats(),
CacheStatsMBean.TYPE,
store.getNodeCacheStats().getName()));
registrations.add(
registerMBean(whiteboard,
CacheStatsMBean.class,
store.getNodeChildrenCacheStats(),
CacheStatsMBean.TYPE,
store.getNodeChildrenCacheStats().getName())
);
for (CacheStats cs : store.getDiffCacheStats()) {
registrations.add(
registerMBean(whiteboard,
CacheStatsMBean.class, cs,
CacheStatsMBean.TYPE, cs.getName()));
}
DocumentStore ds = store.getDocumentStore();
if (ds.getCacheStats() != null) {
for (CacheStats cacheStats : ds.getCacheStats()) {
registrations.add(
registerMBean(whiteboard,
CacheStatsMBean.class,
cacheStats,
CacheStatsMBean.TYPE,
cacheStats.getName())
);
}
}
registrations.add(
registerMBean(whiteboard,
CheckpointMBean.class,
new DocumentCheckpointMBean(store),
CheckpointMBean.TYPE,
"Document node store checkpoint management")
);
registrations.add(
registerMBean(whiteboard,
DocumentNodeStoreMBean.class,
store.getMBean(),
DocumentNodeStoreMBean.TYPE,
"Document node store management")
);
if (mkBuilder.getBlobStoreCacheStats() != null) {
registrations.add(
registerMBean(whiteboard,
CacheStatsMBean.class,
mkBuilder.getBlobStoreCacheStats(),
CacheStatsMBean.TYPE,
mkBuilder.getBlobStoreCacheStats().getName())
);
}
if (mkBuilder.getDocumentStoreStatsCollector() instanceof DocumentStoreStatsMBean) {
registrations.add(
registerMBean(whiteboard,
DocumentStoreStatsMBean.class,
(DocumentStoreStatsMBean) mkBuilder.getDocumentStoreStatsCollector(),
DocumentStoreStatsMBean.TYPE,
"DocumentStore Statistics")
);
}
// register persistent cache stats
Map<CacheType, PersistentCacheStats> persistenceCacheStats = mkBuilder.getPersistenceCacheStats();
for (PersistentCacheStats pcs: persistenceCacheStats.values()) {
registrations.add(
registerMBean(whiteboard,
PersistentCacheStatsMBean.class,
pcs,
PersistentCacheStatsMBean.TYPE,
pcs.getName())
);
}
final long versionGcMaxAgeInSecs = toLong(prop(PROP_VER_GC_MAX_AGE), DEFAULT_VER_GC_MAX_AGE);
final long blobGcMaxAgeInSecs = toLong(prop(PROP_BLOB_GC_MAX_AGE), DEFAULT_BLOB_GC_MAX_AGE);
if (store.getBlobStore() instanceof GarbageCollectableBlobStore) {
BlobGarbageCollector gc = store.createBlobGarbageCollector(blobGcMaxAgeInSecs,
ClusterRepositoryInfo.getOrCreateId(nodeStore));
registrations.add(registerMBean(whiteboard, BlobGCMBean.class, new BlobGC(gc, executor),
BlobGCMBean.TYPE, "Document node store blob garbage collection"));
}
Runnable startGC = new Runnable() {
@Override
public void run() {
try {
store.getVersionGarbageCollector().gc(versionGcMaxAgeInSecs, TimeUnit.SECONDS);
} catch (IOException e) {
log.warn("Error occurred while executing the Version Garbage Collector", e);
}
}
};
Runnable cancelGC = new Runnable() {
@Override
public void run() {
store.getVersionGarbageCollector().cancel();
}
};
RevisionGC revisionGC = new RevisionGC(startGC, cancelGC, executor);
registrations.add(registerMBean(whiteboard, RevisionGCMBean.class, revisionGC,
RevisionGCMBean.TYPE, "Document node store revision garbage collection"));
BlobStoreStats blobStoreStats = mkBuilder.getBlobStoreStats();
if (!customBlobStore && blobStoreStats != null) {
registrations.add(registerMBean(whiteboard,
BlobStoreStatsMBean.class,
blobStoreStats,
BlobStoreStatsMBean.TYPE,
ds.getClass().getSimpleName()));
}
if (!mkBuilder.isBundlingDisabled()){
registrations.add(registerMBean(whiteboard,
BackgroundObserverMBean.class,
store.getBundlingConfigHandler().getMBean(),
BackgroundObserverMBean.TYPE,
"BundlingConfigObserver"));
}
}
private void registerLastRevRecoveryJob(final DocumentNodeStore nodeStore) {
long leaseTime = toLong(context.getProperties().get(PROP_REV_RECOVERY_INTERVAL),
ClusterNodeInfo.DEFAULT_LEASE_UPDATE_INTERVAL_MILLIS);
Runnable recoverJob = new Runnable() {
@Override
public void run() {
nodeStore.getLastRevRecoveryAgent().performRecoveryIfNeeded();
}
};
registrations.add(WhiteboardUtils.scheduleWithFixedDelay(whiteboard,
recoverJob, TimeUnit.MILLISECONDS.toSeconds(leaseTime),
false/*runOnSingleClusterNode*/, true /*use dedicated pool*/));
}
private void registerJournalGC(final DocumentNodeStore nodeStore) {
long journalGCInterval = toLong(context.getProperties().get(PROP_JOURNAL_GC_INTERVAL_MILLIS),
DEFAULT_JOURNAL_GC_INTERVAL_MILLIS);
final long journalGCMaxAge = toLong(context.getProperties().get(PROP_JOURNAL_GC_MAX_AGE_MILLIS),
DEFAULT_JOURNAL_GC_MAX_AGE_MILLIS);
Runnable journalGCJob = new Runnable() {
@Override
public void run() {
nodeStore.getJournalGarbageCollector().gc(journalGCMaxAge, TimeUnit.MILLISECONDS);
}
};
registrations.add(WhiteboardUtils.scheduleWithFixedDelay(whiteboard,
journalGCJob, TimeUnit.MILLISECONDS.toSeconds(journalGCInterval),
true/*runOnSingleClusterNode*/, true /*use dedicated pool*/));
}
private String prop(String propName) {
return prop(propName, PREFIX + propName);
}
private String prop(String propName, String fwkPropName) {
return lookupFrameworkThenConfiguration(context, propName, fwkPropName);
}
private String getPath(String propName, String defaultValue) {
String path = PropertiesUtil.toString(prop(propName), defaultValue);
if (Strings.isNullOrEmpty(path)) {
return path;
}
if ("-".equals(path)) {
// disable this path configuration
return "";
}
// resolve as relative to repository.home
return FilenameUtils.concat(getRepositoryHome(), path);
}
private String getRepositoryHome() {
String repoHome = prop(PROP_HOME, PROP_HOME);
if (Strings.isNullOrEmpty(repoHome)) {
repoHome = DEFAULT_PROP_HOME;
}
return repoHome;
}
private static String[] getMetadata(DocumentStore ds) {
Map<String, String> meta = new HashMap<String, String>(ds.getMetadata());
meta.put("nodeStoreType", "document");
String[] result = new String[meta.size()];
int i = 0;
for (Map.Entry<String, String> e : meta.entrySet()) {
result[i++] = e.getKey() + "=" + e.getValue();
}
return result;
}
}
| OAK-6154: Use Closer in DocumentNodeStoreService
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1793625 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStoreService.java | OAK-6154: Use Closer in DocumentNodeStoreService |
|
Java | apache-2.0 | 61cfb774a285025e86d60f9e69e4394feb7129dd | 0 | jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package org.jenetics.util;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
/**
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @version 3.0 — <em>$Date: 2014-07-14 $</em>
* @since 3.0
*/
public class RandomEnginePerf {
@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public static abstract class Base {
public Random random;
@Benchmark
public int nextInt() {
return random.nextInt();
}
@Benchmark
public long nextLong() {
return random.nextLong();
}
@Benchmark
public float nextFloat() {
return random.nextFloat();
}
@Benchmark
public double nextDouble() {
return random.nextDouble();
}
}
public static class LCG64ShiftRandomPerf extends Base {
{random = new LCG64ShiftRandom();}
}
public static class RandomPerf extends Base {
{random = new Random();}
}
public static class ThreadLocalRandomPerf extends Base {
{random = ThreadLocalRandom.current();}
}
public static void main(String[] args) throws RunnerException {
final Options opt = new OptionsBuilder()
.include(".*" + RandomEnginePerf.class.getSimpleName() + ".*")
.warmupIterations(3)
.measurementIterations(5)
.threads(1)
.forks(1)
.build();
new Runner(opt).run();
}
}
| org.jenetics/src/jmh/java/org/jenetics/util/RandomEnginePerf.java | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package org.jenetics.util;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
/**
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @version 3.0 — <em>$Date: 2014-07-14 $</em>
* @since 3.0
*/
public class RandomEnginePerf {
@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public static abstract class Base {
public Random random;
@Benchmark
public int nextInt() {
return random.nextInt();
}
@Benchmark
public long nextLong() {
return random.nextLong();
}
@Benchmark
public float nextFloat() {
return random.nextFloat();
}
@Benchmark
public double nextDouble() {
return random.nextDouble();
}
}
public static class LCG64ShiftRandomPerf extends Base {
{random = new LCG64ShiftRandom();}
}
public static class RandomPerf extends Base {
{random = new Random();}
}
public static class ThreadLocalRandomPerf extends Base {
{random = ThreadLocalRandom.current();}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + RandomEnginePerf.class.getSimpleName() + ".*")
.warmupIterations(3)
.measurementIterations(5)
.threads(1)
.forks(1)
.build();
new Runner(opt).run();
}
}
| Make local variable final.
| org.jenetics/src/jmh/java/org/jenetics/util/RandomEnginePerf.java | Make local variable final. |
|
Java | apache-2.0 | 0e03a776aa5b9720cfcb093547a4466e4641d187 | 0 | ouit0408/sakai,puramshetty/sakai,puramshetty/sakai,conder/sakai,frasese/sakai,OpenCollabZA/sakai,hackbuteer59/sakai,bzhouduke123/sakai,conder/sakai,bkirschn/sakai,hackbuteer59/sakai,surya-janani/sakai,joserabal/sakai,OpenCollabZA/sakai,whumph/sakai,udayg/sakai,whumph/sakai,rodriguezdevera/sakai,liubo404/sakai,noondaysun/sakai,zqian/sakai,hackbuteer59/sakai,joserabal/sakai,willkara/sakai,kingmook/sakai,whumph/sakai,wfuedu/sakai,kwedoff1/sakai,colczr/sakai,zqian/sakai,kwedoff1/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,surya-janani/sakai,bkirschn/sakai,clhedrick/sakai,kwedoff1/sakai,buckett/sakai-gitflow,bkirschn/sakai,colczr/sakai,introp-software/sakai,noondaysun/sakai,ouit0408/sakai,lorenamgUMU/sakai,pushyamig/sakai,OpenCollabZA/sakai,pushyamig/sakai,kingmook/sakai,tl-its-umich-edu/sakai,conder/sakai,zqian/sakai,ktakacs/sakai,bkirschn/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,kingmook/sakai,zqian/sakai,ouit0408/sakai,frasese/sakai,wfuedu/sakai,liubo404/sakai,kingmook/sakai,puramshetty/sakai,udayg/sakai,frasese/sakai,rodriguezdevera/sakai,kingmook/sakai,rodriguezdevera/sakai,clhedrick/sakai,kingmook/sakai,wfuedu/sakai,ktakacs/sakai,willkara/sakai,noondaysun/sakai,kwedoff1/sakai,kwedoff1/sakai,pushyamig/sakai,clhedrick/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,bzhouduke123/sakai,kwedoff1/sakai,ktakacs/sakai,bkirschn/sakai,ouit0408/sakai,liubo404/sakai,hackbuteer59/sakai,kingmook/sakai,colczr/sakai,pushyamig/sakai,hackbuteer59/sakai,whumph/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,kwedoff1/sakai,buckett/sakai-gitflow,liubo404/sakai,bzhouduke123/sakai,bkirschn/sakai,wfuedu/sakai,joserabal/sakai,bzhouduke123/sakai,rodriguezdevera/sakai,pushyamig/sakai,willkara/sakai,ouit0408/sakai,ktakacs/sakai,joserabal/sakai,conder/sakai,Fudan-University/sakai,lorenamgUMU/sakai,whumph/sakai,whumph/sakai,noondaysun/sakai,udayg/sakai,zqian/sakai,Fudan-University/sakai,ouit0408/sakai,conder/sakai,colczr/sakai,willkara/sakai,introp-software/sakai,lorenamgUMU/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,liubo404/sakai,frasese/sakai,introp-software/sakai,willkara/sakai,joserabal/sakai,zqian/sakai,clhedrick/sakai,colczr/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,udayg/sakai,rodriguezdevera/sakai,puramshetty/sakai,duke-compsci290-spring2016/sakai,Fudan-University/sakai,OpenCollabZA/sakai,frasese/sakai,ktakacs/sakai,introp-software/sakai,conder/sakai,buckett/sakai-gitflow,introp-software/sakai,puramshetty/sakai,OpenCollabZA/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,kwedoff1/sakai,lorenamgUMU/sakai,hackbuteer59/sakai,ktakacs/sakai,ktakacs/sakai,kingmook/sakai,bkirschn/sakai,udayg/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,whumph/sakai,surya-janani/sakai,duke-compsci290-spring2016/sakai,conder/sakai,udayg/sakai,wfuedu/sakai,introp-software/sakai,surya-janani/sakai,OpenCollabZA/sakai,surya-janani/sakai,puramshetty/sakai,willkara/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,zqian/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,colczr/sakai,Fudan-University/sakai,surya-janani/sakai,liubo404/sakai,surya-janani/sakai,ouit0408/sakai,pushyamig/sakai,clhedrick/sakai,surya-janani/sakai,introp-software/sakai,joserabal/sakai,bzhouduke123/sakai,willkara/sakai,joserabal/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,wfuedu/sakai,noondaysun/sakai,udayg/sakai,pushyamig/sakai,liubo404/sakai,Fudan-University/sakai,clhedrick/sakai,udayg/sakai,colczr/sakai,clhedrick/sakai,noondaysun/sakai,bkirschn/sakai,bzhouduke123/sakai,bzhouduke123/sakai,noondaysun/sakai,hackbuteer59/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,colczr/sakai,willkara/sakai,zqian/sakai,Fudan-University/sakai,Fudan-University/sakai,wfuedu/sakai,whumph/sakai,lorenamgUMU/sakai,joserabal/sakai,frasese/sakai,conder/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,buckett/sakai-gitflow,lorenamgUMU/sakai,frasese/sakai,frasese/sakai,buckett/sakai-gitflow,pushyamig/sakai,liubo404/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,ouit0408/sakai | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.site.tool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.EmailValidator;
import org.apache.velocity.tools.generic.SortTool;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.api.privacy.PrivacyManager;
import org.sakaiproject.archive.api.ImportMetadata;
import org.sakaiproject.archive.cover.ArchiveService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityAdvisor.SecurityAdvice;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.coursemanagement.api.AcademicSession;
import org.sakaiproject.coursemanagement.api.CourseOffering;
import org.sakaiproject.coursemanagement.api.CourseSet;
import org.sakaiproject.coursemanagement.api.Section;
import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.EntityTransferrerRefMigrator;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.ImportException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.importer.api.ImportDataSource;
import org.sakaiproject.importer.api.ImportService;
import org.sakaiproject.importer.api.ResetOnCloseInputStream;
import org.sakaiproject.importer.api.SakaiArchive;
import org.sakaiproject.importer.api.ResetOnCloseInputStream;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.lti.api.LTIService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.SiteService.SortType;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.site.util.Participant;
import org.sakaiproject.site.util.SiteComparator;
import org.sakaiproject.site.util.SiteConstants;
import org.sakaiproject.site.util.SiteParticipantHelper;
import org.sakaiproject.site.util.SiteSetupQuestionFileParser;
import org.sakaiproject.site.util.SiteTextEditUtil;
import org.sakaiproject.site.util.SiteTypeUtil;
import org.sakaiproject.site.util.ToolComparator;
import org.sakaiproject.sitemanage.api.SectionField;
import org.sakaiproject.sitemanage.api.SiteHelper;
import org.sakaiproject.sitemanage.api.model.SiteSetupQuestion;
import org.sakaiproject.sitemanage.api.model.SiteSetupQuestionAnswer;
import org.sakaiproject.sitemanage.api.model.SiteSetupUserAnswer;
import org.sakaiproject.sitemanage.api.model.SiteTypeQuestions;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolException;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.userauditservice.api.UserAuditRegistration;
import org.sakaiproject.userauditservice.api.UserAuditService;
import org.sakaiproject.util.*;
// for basiclti integration
/**
* <p>
* SiteAction controls the interface for worksite setup.
* </p>
*/
public class SiteAction extends PagedResourceActionII {
// SAK-23491 add template_used property
private static final String TEMPLATE_USED = "template_used";
/** Our log (commons). */
private static Log M_log = LogFactory.getLog(SiteAction.class);
private LTIService m_ltiService = (LTIService) ComponentManager.get("org.sakaiproject.lti.api.LTIService");
private ContentHostingService m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
private ImportService importService = org.sakaiproject.importer.cover.ImportService
.getInstance();
private static String showOrphanedMembers = ServerConfigurationService.getString("site.setup.showOrphanedMembers", "admins");
/** portlet configuration parameter values* */
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric");
private static ResourceLoader cfgRb = new ResourceLoader("multipletools");
private Locale comparator_locale = rb.getLocale();
private org.sakaiproject.user.api.UserDirectoryService userDirectoryService = (org.sakaiproject.user.api.UserDirectoryService) ComponentManager.get(
org.sakaiproject.user.api.UserDirectoryService.class );
private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager
.get(org.sakaiproject.coursemanagement.api.CourseManagementService.class);
private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager
.get(org.sakaiproject.authz.api.GroupProvider.class);
private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager
.get(org.sakaiproject.authz.api.AuthzGroupService.class);
private org.sakaiproject.archive.api.ArchiveService archiveService = (org.sakaiproject.archive.api.ArchiveService) ComponentManager
.get(org.sakaiproject.archive.api.ArchiveService.class);
private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class);
private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class);
private org.sakaiproject.sitemanage.api.SiteTypeProvider siteTypeProvider = (org.sakaiproject.sitemanage.api.SiteTypeProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.SiteTypeProvider.class);
private static org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService questionService = (org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService) ComponentManager
.get(org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService.class);
private static org.sakaiproject.sitemanage.api.UserNotificationProvider userNotificationProvider = (org.sakaiproject.sitemanage.api.UserNotificationProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.UserNotificationProvider.class);
private static final String SITE_MODE_SITESETUP = "sitesetup";
private static final String SITE_MODE_SITEINFO = "siteinfo";
private static final String SITE_MODE_HELPER = "helper";
private static final String SITE_MODE_HELPER_DONE = "helper.done";
private static final String STATE_SITE_MODE = "site_mode";
private static final String TERM_OPTION_ALL = "-1";
protected final static String[] TEMPLATE = {
"-list",// 0
"-type",
"",// combined with 13
"",// chef_site-editFeatures.vm deleted. Functions are combined with chef_site-editToolGroupFeatures.vm
"-editToolGroupFeatures",
"",// moved to participant helper
"",
"",
"-siteDeleteConfirm",
"",
"-newSiteConfirm",// 10
"",
"-siteInfo-list",// 12
"-siteInfo-editInfo",
"-siteInfo-editInfoConfirm",
"-addRemoveFeatureConfirm",// 15
"",
"",
"-siteInfo-editAccess",
"",
"",// 20
"",
"",
"",
"",
"",// 25
"-modifyENW",
"-importSites",
"-siteInfo-import",
"-siteInfo-duplicate",
"",// 30
"",// 31
"",// 32
"",// 33
"",// 34
"",// 35
"-newSiteCourse",// 36
"-newSiteCourseManual",// 37
"",// 38
"",// 39
"",// 40
"",// 41
"-type-confirm",// 42
"-siteInfo-editClass",// 43
"-siteInfo-addCourseConfirm",// 44
"-siteInfo-importMtrlMaster", // 45 -- htripath for import
// material from a file
"-siteInfo-importMtrlCopy", // 46
"-siteInfo-importMtrlCopyConfirm",
"-siteInfo-importMtrlCopyConfirmMsg", // 48
"",//"-siteInfo-group", // 49 moved to the group helper
"",//"-siteInfo-groupedit", // 50 moved to the group helper
"",//"-siteInfo-groupDeleteConfirm", // 51, moved to the group helper
"",
"-findCourse", // 53
"-questions", // 54
"",// 55
"",// 56
"",// 57
"-siteInfo-importSelection", //58
"-siteInfo-importMigrate", //59
"-importSitesMigrate", //60
"-siteInfo-importUser",
"-uploadArchive"
};
/** Name of state attribute for Site instance id */
private static final String STATE_SITE_INSTANCE_ID = "site.instance.id";
/** Name of state attribute for Site Information */
private static final String STATE_SITE_INFO = "site.info";
private static final String STATE_SITE_TYPE = "site-type";
/** Name of state attribute for possible site types */
private static final String STATE_SITE_TYPES = "site_types";
private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type";
private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types";
private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types";
private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types";
private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types";
private final static String PROP_SITE_LANGUAGE = "locale_string";
/**
* Name of the state attribute holding the site list column list is sorted
* by
*/
private static final String SORTED_BY = "site.sorted.by";
/** Name of the state attribute holding the site list column to sort by */
private static final String SORTED_ASC = "site.sort.asc";
/** State attribute for list of sites to be deleted. */
private static final String STATE_SITE_REMOVALS = "site.removals";
/** Name of the state attribute holding the site list View selected */
private static final String STATE_VIEW_SELECTED = "site.view.selected";
private static final String STATE_TERM_VIEW_SELECTED = "site.termview.selected";
/*******************
* SAK-16600
*
* Refactor methods to update these values in state/context
*/
/** Names of lists related to tools groups */
private static final String STATE_TOOL_GROUP_LIST = "toolsByGroup";
/** Names of lists related to tools groups */
private static final String STATE_TOOL_GROUP_MULTIPLES = "toolGroupMultiples";
/** Names of lists related to tools */
private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList";
private static final String STATE_TOOL_REGISTRATION_TITLE_LIST = "toolRegistrationTitleList";
private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome";
private static final String STATE_EXTRA_SELECTED_TOOL_LIST = "extraSelectedToolList";
private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected";
private static final String UNGROUPED_TOOL_TITLE = "systoolgroups.ungrouped";
private static final String LTI_TOOL_TITLE = "systoolgroups.lti";
//********************
private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress";
private static final String STATE_PROJECT_TOOL_LIST = "projectToolList";
private final static String STATE_MULTIPLE_TOOL_ID_SET = "multipleToolIdSet";
private final static String STATE_MULTIPLE_TOOL_ID_TITLE_MAP = "multipleToolIdTitleMap";
private final static String STATE_MULTIPLE_TOOL_CONFIGURATION = "multipleToolConfiguration";
private final static String SITE_DEFAULT_LIST = ServerConfigurationService
.getString("site.types");
private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname";
private static final String STATE_SITE_ADD_COURSE = "canAddCourse";
private static final String STATE_SITE_ADD_PORTFOLIO = "canAddPortfolio";
private static final String STATE_PORTFOLIO_SITE_TYPE = "portfolio";
private static final String STATE_SITE_ADD_PROJECT = "canAddProject";
private static final String STATE_PROJECT_SITE_TYPE = "project";
private static final String STATE_SITE_IMPORT_ARCHIVE = "canImportArchive";
// SAK-23468
private static final String STATE_NEW_SITE_STATUS_ISPUBLISHED = "newSiteStatusIsPublished";
private static final String STATE_NEW_SITE_STATUS_TITLE = "newSiteStatusTitle";
private static final String STATE_NEW_SITE_STATUS_ID = "newSiteStatusID";
// %%% get rid of the IdAndText tool lists and just use ToolConfiguration or
// ToolRegistration lists
// %%% same for CourseItems
// Names for other state attributes that are lists
private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the
// list
// of
// site
// pages
// consistent
// with
// Worksite
// Setup
// page
// patterns
/**
* The name of the state form field containing additional information for a
* course request
*/
private static final String FORM_ADDITIONAL = "form.additional";
/** %%% in transition from putting all form variables in state */
private final static String FORM_TITLE = "form_title";
private final static String FORM_SITE_URL_BASE = "form_site_url_base";
private final static String FORM_SITE_ALIAS = "form_site_alias";
private final static String FORM_DESCRIPTION = "form_description";
private final static String FORM_HONORIFIC = "form_honorific";
private final static String FORM_INSTITUTION = "form_institution";
private final static String FORM_SUBJECT = "form_subject";
private final static String FORM_PHONE = "form_phone";
private final static String FORM_EMAIL = "form_email";
private final static String FORM_REUSE = "form_reuse";
private final static String FORM_RELATED_CLASS = "form_related_class";
private final static String FORM_RELATED_PROJECT = "form_related_project";
private final static String FORM_NAME = "form_name";
private final static String FORM_SHORT_DESCRIPTION = "form_short_description";
private final static String FORM_ICON_URL = "iconUrl";
private final static String FORM_SITEINFO_URL_BASE = "form_site_url_base";
private final static String FORM_SITEINFO_ALIASES = "form_site_aliases";
private final static String FORM_WILL_NOTIFY = "form_will_notify";
/** Context action */
private static final String CONTEXT_ACTION = "SiteAction";
/** The name of the Attribute for display template index */
private static final String STATE_TEMPLATE_INDEX = "site.templateIndex";
/** The name of the Attribute for display template index */
private static final String STATE_OVERRIDE_TEMPLATE_INDEX = "site.overrideTemplateIndex";
/** The name of the Attribute to indicate we are operating in shortcut mode */
private static final String STATE_IN_SHORTCUT = "site.currentlyInShortcut";
/** State attribute for state initialization. */
private static final String STATE_INITIALIZED = "site.initialized";
/** State attributes for using templates in site creation. */
private static final String STATE_TEMPLATE_SITE = "site.templateSite";
private static final String STATE_TEMPLATE_SITE_COPY_USERS = "site.templateSiteCopyUsers";
private static final String STATE_TEMPLATE_SITE_COPY_CONTENT = "site.templateSiteCopyContent";
private static final String STATE_TEMPLATE_PUBLISH = "site.templateSitePublish";
/** The action for menu */
private static final String STATE_ACTION = "site.action";
/** The user copyright string */
private static final String STATE_MY_COPYRIGHT = "resources.mycopyright";
/** The copyright character */
private static final String COPYRIGHT_SYMBOL = "copyright (c)";
/** The null/empty string */
private static final String NULL_STRING = "";
/** The state attribute alerting user of a sent course request */
private static final String REQUEST_SENT = "site.request.sent";
/** The state attributes in the make public vm */
private static final String STATE_JOINABLE = "state_joinable";
private static final String STATE_JOINERROLE = "state_joinerRole";
private static final String STATE_SITE_ACCESS_PUBLISH = "state_site_access_publish";
private static final String STATE_SITE_ACCESS_INCLUDE = "state_site_access_include";
/** the list of selected user */
private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list";
private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles";
private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants";
private static final String STATE_PARTICIPANT_LIST = "state_participant_list";
private static final String STATE_ADD_PARTICIPANTS = "state_add_participants";
/** for changing participant roles */
private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole";
private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role";
/** for remove user */
private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list";
private static final String STATE_IMPORT = "state_import";
private static final String STATE_IMPORT_SITES = "state_import_sites";
private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool";
/** for navigating between sites in site list */
private static final String STATE_SITES = "state_sites";
private static final String STATE_PREV_SITE = "state_prev_site";
private static final String STATE_NEXT_SITE = "state_next_site";
/** for course information */
private final static String STATE_TERM_COURSE_LIST = "state_term_course_list";
private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash";
private final static String STATE_TERM_SELECTED = "state_term_selected";
private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected";
private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected";
private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider";
private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen";
private final static String STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN = "state_add_class_provider_description_chosen";
private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual";
private final static String STATE_AUTO_ADD = "state_auto_add";
private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number";
private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields";
public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections";
public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list";
public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list";
private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates";
private final static String STATE_ICONS = "icons";
public static final String SITE_DUPLICATED = "site_duplicated";
public static final String SITE_DUPLICATED_NAME = "site_duplicated_named";
// types of site whose title can not be editable
public static final String TITLE_NOT_EDITABLE_SITE_TYPE = "title_not_editable_site_type";
// maximum length of a site title
private static final String STATE_SITE_TITLE_MAX = "site_title_max_length";
// types of site where site view roster permission is editable
public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type";
// htripath : for import material from file - classic import
private static final String ALL_ZIP_IMPORT_SITES = "allzipImports";
private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports";
private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports";
private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName";
private static final String SESSION_CONTEXT_ID = "sessionContextId";
// page size for worksite setup tool
private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup";
// page size for site info tool
private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo";
private static final String IMPORT_DATA_SOURCE = "import_data_source";
// Special tool id for Home page
private static final String SITE_INFORMATION_TOOL="sakai.iframe.site";
private static final String STATE_CM_LEVELS = "site.cm.levels";
private static final String STATE_CM_LEVEL_OPTS = "site.cm.level_opts";
private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections";
private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection";
private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested";
private static final String STATE_CM_SELECTED_SECTIONS = "site.cm.selectedSections";
private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list";
private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId";
private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list";
private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections";
private String cmSubjectCategory;
private boolean warnedNoSubjectCategory = false;
// the string marks the protocol part in url
private static final String PROTOCOL_STRING = "://";
/**
* {@link org.sakaiproject.component.api.ServerConfigurationService} property.
* If <code>false</code>, ensures that a site's joinability settings are not affected should
* that site be <em>edited</em> after its type has been enumerated by a
* "wsetup.disable.joinable" property. Code should cause this prop value to
* default to <code>true</code> to preserve backward compatibility. Property
* naming tries to match mini-convention established by "wsetup.disable.joinable"
* (which has no corresponding constant).
*
* <p>Has no effect on the site creation process -- only site editing</p>
*
* @see #doUpdate_site_access_joinable(RunData, SessionState, ParameterParser, Site)
*/
public static final String CONVERT_NULL_JOINABLE_TO_UNJOINABLE = "wsetup.convert.null.joinable.to.unjoinable";
private static final String SITE_TEMPLATE_PREFIX = "template";
private static final String STATE_TYPE_SELECTED = "state_type_selected";
// the template index after exist the question mode
private static final String STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE = "state_site_setup_question_next_template";
// SAK-12912, the answers to site setup questions
private static final String STATE_SITE_SETUP_QUESTION_ANSWER = "state_site_setup_question_answer";
// SAK-13389, the non-official participant
private static final String ADD_NON_OFFICIAL_PARTICIPANT = "add_non_official_participant";
// the list of visited templates
private static final String STATE_VISITED_TEMPLATES = "state_visited_templates";
private String STATE_GROUP_HELPER_ID = "state_group_helper_id";
// used in the configuration file to specify which tool attributes are configurable through WSetup tool, and what are the default value for them.
private String CONFIG_TOOL_ATTRIBUTE = "wsetup.config.tool.attribute_";
private String CONFIG_TOOL_ATTRIBUTE_DEFAULT = "wsetup.config.tool.attribute.default_";
// used in the configuration file to specify the default tool title
private String CONFIG_TOOL_TITLE = "wsetup.config.tool.title_";
// home tool id
private static final String TOOL_ID_HOME = "home";
// Site Info tool id
private static final String TOOL_ID_SITEINFO = "sakai.siteinfo";
// synoptic tool ids
private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar";
private static final String TOOL_ID_SYNOPTIC_ANNOUNCEMENT = "sakai.synoptic.announcement";
private static final String TOOL_ID_SYNOPTIC_CHAT = "sakai.synoptic.chat";
private static final String TOOL_ID_SYNOPTIC_MESSAGECENTER = "sakai.synoptic.messagecenter";
private static final String TOOL_ID_SYNOPTIC_DISCUSSION = "sakai.synoptic.discussion";
private static final String IMPORT_QUEUED = "import.queued";
// map of synoptic tool and the related tool ids
private final static Map<String, List<String>> SYNOPTIC_TOOL_ID_MAP;
static
{
SYNOPTIC_TOOL_ID_MAP = new HashMap<String, List<String>>();
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SUMMARY_CALENDAR, new ArrayList(Arrays.asList("sakai.schedule")));
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SYNOPTIC_ANNOUNCEMENT, new ArrayList(Arrays.asList("sakai.announcements")));
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SYNOPTIC_CHAT, new ArrayList(Arrays.asList("sakai.chat")));
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SYNOPTIC_MESSAGECENTER, new ArrayList(Arrays.asList("sakai.messages", "sakai.forums", "sakai.messagecenter")));
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SYNOPTIC_DISCUSSION, new ArrayList(Arrays.asList("sakai.discussion")));
}
// map of synoptic tool and message bundle properties, used to lookup an internationalized tool title
private final static Map<String, String> SYNOPTIC_TOOL_TITLE_MAP;
static
{
SYNOPTIC_TOOL_TITLE_MAP = new HashMap<String, String>();
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SUMMARY_CALENDAR, "java.reccal");
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SYNOPTIC_ANNOUNCEMENT, "java.recann");
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SYNOPTIC_CHAT, "java.recent");
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SYNOPTIC_MESSAGECENTER, "java.recmsg");
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SYNOPTIC_DISCUSSION, "java.recdisc");
}
/** the web content tool id **/
private final static String WEB_CONTENT_TOOL_ID = "sakai.iframe";
private final static String SITE_INFO_TOOL_ID = "sakai.iframe.site";
private final static String WEB_CONTENT_TOOL_SOURCE_CONFIG = "source";
private final static String WEB_CONTENT_TOOL_SOURCE_CONFIG_VALUE = "http://";
/** the news tool **/
private final static String NEWS_TOOL_ID = "sakai.news";
private final static String NEWS_TOOL_CHANNEL_CONFIG = "channel-url";
private final static String NEWS_TOOL_CHANNEL_CONFIG_VALUE = "http://sakaiproject.org/feed";
private final static int UUID_LENGTH = 36;
/** the course set definition from CourseManagementService **/
private final static String STATE_COURSE_SET = "state_course_set";
// the maximum tool title length enforced in UI
private final static int MAX_TOOL_TITLE_LENGTH = 20;
private final static String SORT_KEY_SESSION = "worksitesetup.sort.key.session";
private final static String SORT_ORDER_SESSION = "worksitesetup.sort.order.session";
private final static String SORT_KEY_COURSE_SET = "worksitesetup.sort.key.courseSet";
private final static String SORT_ORDER_COURSE_SET = "worksitesetup.sort.order.courseSet";
private final static String SORT_KEY_COURSE_OFFERING = "worksitesetup.sort.key.courseOffering";
private final static String SORT_ORDER_COURSE_OFFERING = "worksitesetup.sort.order.courseOffering";
private final static String SORT_KEY_SECTION = "worksitesetup.sort.key.section";
private final static String SORT_ORDER_SECTION = "worksitesetup.sort.order.section";
// bjones86 - SAK-23255
private final static String CONTEXT_IS_ADMIN = "isAdmin";
private final static String CONTEXT_SKIP_MANUAL_COURSE_CREATION = "skipManualCourseCreation";
private final static String CONTEXT_SKIP_COURSE_SECTION_SELECTION = "skipCourseSectionSelection";
private final static String CONTEXT_FILTER_TERMS = "filterTerms";
private final static String SAK_PROP_SKIP_MANUAL_COURSE_CREATION = "wsetup.skipManualCourseCreation";
private final static String SAK_PROP_SKIP_COURSE_SECTION_SELECTION = "wsetup.skipCourseSectionSelection";
private List prefLocales = new ArrayList();
private static final String VM_ALLOWED_ROLES_DROP_DOWN = "allowedRoles";
// bjones86 - SAK-23256
private static final String SAK_PROP_FILTER_TERMS = "worksitesetup.filtertermdropdowns";
private static final String CONTEXT_HAS_TERMS = "hasTerms";
// state variable for whether any multiple instance tool has been selected
private String STATE_MULTIPLE_TOOL_INSTANCE_SELECTED = "state_multiple_tool_instance_selected";
// state variable for lti tools
private String STATE_LTITOOL_LIST = "state_ltitool_list";
// state variable for selected lti tools in site
private String STATE_LTITOOL_EXISTING_SELECTED_LIST = "state_ltitool_existing_selected_list";
// state variable for selected lti tools during tool modification
private String STATE_LTITOOL_SELECTED_LIST = "state_ltitool_selected_list";
// special prefix String for basiclti tool ids
private String LTITOOL_ID_PREFIX = "lti_";
private String m_filePath;
private String moreInfoPath;
private String libraryPath;
private static final String STATE_CREATE_FROM_ARCHIVE = "createFromArchive";
private static final String STATE_UPLOADED_ARCHIVE_PATH = "uploadedArchivePath";
private static final String STATE_UPLOADED_ARCHIVE_NAME = "uploadedArchiveNAme";
private static UserAuditRegistration userAuditRegistration = (UserAuditRegistration) ComponentManager.get("org.sakaiproject.userauditservice.api.UserAuditRegistration.sitemanage");
private static UserAuditService userAuditService = (UserAuditService) ComponentManager.get(UserAuditService.class);
private PrivacyManager privacyManager = (PrivacyManager) ComponentManager.get(PrivacyManager.class);
/**
* what are the tool ids within Home page?
* If this is for a newly added Home tool, get the tool ids from template site or system set default
* Else if this is an existing Home tool, get the tool ids from the page
* @param state
* @param newHomeTool
* @param homePage
* @return
*/
private List<String> getHomeToolIds(SessionState state, boolean newHomeTool, SitePage homePage)
{
List<String> rv = new Vector<String>();
// if this is a new Home tool page to be added, get the tool ids from definition (template site first, and then configurations)
Site site = getStateSite(state);
String siteType = site != null? site.getType() : "";
// First: get the tool ids from configuration files
// initially by "wsetup.home.toolids" + site type, and if missing, use "wsetup.home.toolids"
if (ServerConfigurationService.getStrings("wsetup.home.toolids." + siteType) != null) {
rv = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("wsetup.home.toolids." + siteType)));
} else if (ServerConfigurationService.getStrings("wsetup.home.toolids") != null) {
rv = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("wsetup.home.toolids")));
}
// Second: if tool list is empty, get it from the template site settings
if (rv.isEmpty())
{
// template site
Site templateSite = null;
String templateSiteId = "";
if (SiteService.isUserSite(site.getId()))
{
// myworkspace type site: get user type first, and then get the template site
try
{
User user = UserDirectoryService.getUser(SiteService.getSiteUserId(site.getId()));
templateSiteId = SiteService.USER_SITE_TEMPLATE + "." + user.getType();
templateSite = SiteService.getSite(templateSiteId);
}
catch (Throwable t)
{
M_log.debug(this + ": getHomeToolIds cannot find site " + templateSiteId + t.getMessage());
// use the fall-back, user template site
try
{
templateSiteId = SiteService.USER_SITE_TEMPLATE;
templateSite = SiteService.getSite(templateSiteId);
}
catch (Throwable tt)
{
M_log.debug(this + ": getHomeToolIds cannot find site " + templateSiteId + tt.getMessage());
}
}
}
else
{
// not myworkspace site
// first: see whether it is during site creation process and using a template site
templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
if (templateSite == null)
{
// second: if no template is chosen by user, then use template based on site type
templateSiteId = SiteService.SITE_TEMPLATE + "." + siteType;
try
{
templateSite = SiteService.getSite(templateSiteId);
}
catch (Throwable t)
{
M_log.debug(this + ": getHomeToolIds cannot find site " + templateSiteId + t.getMessage());
// thrid: if cannot find template site with the site type, use the default template
templateSiteId = SiteService.SITE_TEMPLATE;
try
{
templateSite = SiteService.getSite(templateSiteId);
}
catch (Throwable tt)
{
M_log.debug(this + ": getHomeToolIds cannot find site " + templateSiteId + tt.getMessage());
}
}
}
}
if (templateSite != null)
{
// get Home page and embedded tool ids
for (SitePage page: (List<SitePage>)templateSite.getPages())
{
String title = page.getTitle();
if (isHomePage(page))
{
// found home page, add all tool ids to return value
for(ToolConfiguration tConfiguration : (List<ToolConfiguration>) page.getTools())
{
String toolId = tConfiguration.getToolId();
if (ToolManager.getTool(toolId) != null)
rv.add(toolId);
}
break;
}
}
}
}
// Third: if the tool id list is still empty because we cannot find any template site yet, use the default settings
if (rv.isEmpty())
{
if (siteType.equalsIgnoreCase("myworkspace"))
{
// first try with MOTD tool
if (ToolManager.getTool("sakai.motd") != null)
rv.add("sakai.motd");
if (rv.isEmpty())
{
// then try with the myworkspace information tool
if (ToolManager.getTool("sakai.iframe.myworkspace") != null)
rv.add("sakai.iframe.myworkspace");
}
}
else
{
// try the site information tool
if (ToolManager.getTool("sakai.iframe.site") != null)
rv.add("sakai.iframe.site");
}
// synoptical tools
if (ToolManager.getTool(TOOL_ID_SUMMARY_CALENDAR) != null)
{
rv.add(TOOL_ID_SUMMARY_CALENDAR);
}
if (ToolManager.getTool(TOOL_ID_SYNOPTIC_ANNOUNCEMENT) != null)
{
rv.add(TOOL_ID_SYNOPTIC_ANNOUNCEMENT);
}
if (ToolManager.getTool(TOOL_ID_SYNOPTIC_CHAT) != null)
{
rv.add(TOOL_ID_SYNOPTIC_CHAT);
}
if (ToolManager.getTool(TOOL_ID_SYNOPTIC_MESSAGECENTER) != null)
{
rv.add(TOOL_ID_SYNOPTIC_MESSAGECENTER);
}
}
// Fourth: if this is an existing Home tool page, get any extra tool ids in the page already back to the list
if (!newHomeTool)
{
// found home page, add all tool ids to return value
for(ToolConfiguration tConfiguration : (List<ToolConfiguration>) homePage.getTools())
{
String hToolId = tConfiguration.getToolId();
if (!rv.contains(hToolId))
{
rv.add(hToolId);
}
}
}
return rv;
}
/*
* Configure directory for moreInfo content
*/
private String setMoreInfoPath(ServletContext ctx) {
String rpath = ctx.getRealPath("");
String ctxPath = ctx.getServletContextName();
String rserve = StringUtils.remove(rpath,ctxPath);
return rserve;
}
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet,
JetspeedRunData rundata) {
ServletContext ctx = rundata.getRequest().getSession().getServletContext();
String serverContextPath = ServerConfigurationService.getString("config.sitemanage.moreInfoDir", "library/image/");
libraryPath = File.separator + serverContextPath;
moreInfoPath = setMoreInfoPath(ctx) + serverContextPath;
// Cleanout if the helper has been asked to start afresh.
if (state.getAttribute(SiteHelper.SITE_CREATE_START) != null) {
cleanState(state);
cleanStateHelper(state);
// Removed from possible previous invokations.
state.removeAttribute(SiteHelper.SITE_CREATE_START);
state.removeAttribute(SiteHelper.SITE_CREATE_CANCELLED);
state.removeAttribute(SiteHelper.SITE_CREATE_SITE_ID);
}
super.initState(state, portlet, rundata);
// store current userId in state
User user = UserDirectoryService.getCurrentUser();
String userId = user.getEid();
state.setAttribute(STATE_CM_CURRENT_USERID, userId);
PortletConfig config = portlet.getPortletConfig();
// types of sites that can either be public or private
String changeableTypes = StringUtils.trimToNull(config
.getInitParameter("publicChangeableSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) {
if (changeableTypes != null) {
state
.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new ArrayList(Arrays.asList(changeableTypes
.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new Vector());
}
}
// type of sites that are always public
String publicTypes = StringUtils.trimToNull(config
.getInitParameter("publicSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) {
if (publicTypes != null) {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList(
Arrays.asList(publicTypes.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector());
}
}
// types of sites that are always private
String privateTypes = StringUtils.trimToNull(config
.getInitParameter("privateSiteTypes"));
if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) {
if (privateTypes != null) {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList(
Arrays.asList(privateTypes.split(","))));
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// default site type
String defaultType = StringUtils.trimToNull(config
.getInitParameter("defaultSiteType"));
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) {
if (defaultType != null) {
state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType);
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// certain type(s) of site cannot get its "joinable" option set
if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) {
if (ServerConfigurationService
.getStrings("wsetup.disable.joinable") != null) {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new ArrayList(Arrays.asList(ServerConfigurationService
.getStrings("wsetup.disable.joinable"))));
} else {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new Vector());
}
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) {
state.setAttribute(STATE_TOP_PAGE_MESSAGE, Integer.valueOf(0));
}
// skins if any
if (state.getAttribute(STATE_ICONS) == null) {
setupIcons(state);
}
if (ServerConfigurationService.getStrings("site.type.titleNotEditable") != null) {
state.setAttribute(TITLE_NOT_EDITABLE_SITE_TYPE, new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("site.type.titleNotEditable"))));
} else {
state.setAttribute(TITLE_NOT_EDITABLE_SITE_TYPE, new ArrayList(Arrays
.asList(new String[]{ServerConfigurationService
.getString("courseSiteType", "course")})));
}
if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) {
List siteTypes = new Vector();
if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) {
siteTypes = new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("editViewRosterSiteType")));
}
state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes);
}
if (state.getAttribute(STATE_SITE_MODE) == null) {
// get site tool mode from tool registry
String site_mode = config.getInitParameter(STATE_SITE_MODE);
// When in helper mode we don't have
if (site_mode == null) {
site_mode = SITE_MODE_HELPER;
}
state.setAttribute(STATE_SITE_MODE, site_mode);
}
} // initState
/**
* cleanState removes the current site instance and it's properties from
* state
*/
private void cleanState(SessionState state) {
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.removeAttribute(STATE_SITE_INFO);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
// remove the state attributes related to multi-tool selection
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
state.removeAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION);
state.removeAttribute(STATE_TOOL_REGISTRATION_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST);
// remove those state attributes related to course site creation
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.removeAttribute(STATE_TERM_COURSE_HASH);
state.removeAttribute(STATE_TERM_SELECTED);
state.removeAttribute(STATE_INSTRUCTOR_SELECTED);
state.removeAttribute(STATE_FUTURE_TERM_SELECTED);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_PROVIDER_SECTION_LIST);
state.removeAttribute(STATE_CM_LEVELS);
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_CURRENT_USERID);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL); // don't we need to clean this
// too? -daisyf
state.removeAttribute(STATE_TEMPLATE_SITE);
state.removeAttribute(STATE_TYPE_SELECTED);
state.removeAttribute(STATE_SITE_SETUP_QUESTION_ANSWER);
state.removeAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE);
// lti tools
state.removeAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST);
state.removeAttribute(STATE_LTITOOL_SELECTED_LIST);
// bjones86 - SAK-24423 - remove joinable site settings from the state
JoinableSiteSettings.removeJoinableSiteSettingsFromState( state );
} // cleanState
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context) {
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = ToolManager.getCurrentPlacement().getContext();
String siteRef = SiteService.siteReference(contextString);
// if it is in Worksite setup tool, pass the selected site's reference
if (state.getAttribute(STATE_SITE_MODE) != null
&& ((String) state.getAttribute(STATE_SITE_MODE))
.equals(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
Site s = getStateSite(state);
if (s != null) {
siteRef = s.getReference();
}
}
}
// setup for editing the permissions of the site for this tool, using
// the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb
.getString("setperfor")
+ " " + SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "site.");
} // doPermissions
/**
* Build the context for shortcut display
*/
public String buildShortcutPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
return buildMainPanelContext(portlet, context, data, state, true);
}
/**
* Build the context for normal display
*/
public String buildMainPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
return buildMainPanelContext(portlet, context, data, state, false);
}
/**
* Build the context for normal/shortcut display and detect switches
*/
public String buildMainPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state,
boolean inShortcut) {
rb = new ResourceLoader("sitesetupgeneric");
context.put("tlang", rb);
context.put("clang", cfgRb);
// TODO: what is all this doing? if we are in helper mode, we are
// already setup and don't get called here now -ggolden
/*
* String helperMode = (String)
* state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode !=
* null) { Site site = getStateSite(state); if (site != null) { if
* (site.getType() != null && ((List)
* state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) {
* context.put("editViewRoster", Boolean.TRUE); } else {
* context.put("editViewRoster", Boolean.FALSE); } } else {
* context.put("editViewRoster", Boolean.FALSE); } // for new, don't
* show site.del in Permission page context.put("hiddenLock",
* "site.del");
*
* String template = PermissionsAction.buildHelperContext(portlet,
* context, data, state); if (template == null) { addAlert(state,
* rb.getString("theisa")); } else { return template; } }
*/
String template = null;
context.put("action", CONTEXT_ACTION);
// updatePortlet(state, portlet, data);
if (state.getAttribute(STATE_INITIALIZED) == null) {
init(portlet, data, state);
String overRideTemplate = (String) state.getAttribute(STATE_OVERRIDE_TEMPLATE_INDEX);
if ( overRideTemplate != null ) {
state.removeAttribute(STATE_OVERRIDE_TEMPLATE_INDEX);
state.setAttribute(STATE_TEMPLATE_INDEX, overRideTemplate);
}
}
// Track when we come into Main panel most recently from Shortcut Panel
// Reset the state and template if we *just* came into Main from Shortcut
if ( inShortcut ) {
state.setAttribute(STATE_IN_SHORTCUT, "true");
} else {
String fromShortcut = (String) state.getAttribute(STATE_IN_SHORTCUT);
if ( "true".equals(fromShortcut) ) {
cleanState(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
state.removeAttribute(STATE_IN_SHORTCUT);
}
String indexString = (String) state.getAttribute(STATE_TEMPLATE_INDEX);
// update the visited template list with the current template index
addIntoStateVisitedTemplates(state, indexString);
template = buildContextForTemplate(getPrevVisitedTemplate(state), Integer.valueOf(indexString), portlet, context, data, state);
return template;
} // buildMainPanelContext
/**
* add index into the visited template indices list
* @param state
* @param index
*/
private void addIntoStateVisitedTemplates(SessionState state, String index) {
List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (templateIndices == null)
{
templateIndices = new Vector<String>();
}
if (templateIndices.size() == 0 || !templateIndices.contains(index))
{
// this is to prevent from page refreshing accidentally updates the list
templateIndices.add(index);
state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices);
}
}
/**
* remove the last index
* @param state
*/
private void removeLastIndexInStateVisitedTemplates(SessionState state) {
List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (templateIndices!=null && templateIndices.size() > 0)
{
// this is to prevent from page refreshing accidentally updates the list
templateIndices.remove(templateIndices.size()-1);
state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices);
}
}
private String getPrevVisitedTemplate(SessionState state) {
List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (templateIndices != null && templateIndices.size() >1 )
{
return templateIndices.get(templateIndices.size()-2);
}
else
{
return null;
}
}
/**
* whether template indexed has been visited
* @param state
* @param templateIndex
* @return
*/
private boolean isTemplateVisited(SessionState state, String templateIndex)
{
boolean rv = false;
List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (templateIndices != null && templateIndices.size() >0 )
{
rv = templateIndices.contains(templateIndex);
}
return rv;
}
/**
* Build the context for each template using template_index parameter passed
* in a form hidden field. Each case is associated with a template. (Not all
* templates implemented). See String[] TEMPLATES.
*
* @param index
* is the number contained in the template's template_index
*/
private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
String alert=(String)state.getAttribute(STATE_MESSAGE);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
context.put("siteTextEdit", new SiteTextEditUtil());
// the last visited template index
if (preIndex != null)
context.put("backIndex", preIndex);
// SAK-16600 adjust index for toolGroup mode
if (index==3)
index = 4;
context.put("templateIndex", String.valueOf(index));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// all site types
context.put("courseSiteTypeStrings", SiteService.getSiteTypeStrings("course"));
context.put("portfolioSiteTypeStrings", SiteService.getSiteTypeStrings("portfolio"));
context.put("projectSiteTypeStrings", SiteService.getSiteTypeStrings("project"));
//can the user create course sites?
context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite());
// can the user create portfolio sites?
context.put("portfolioSiteType", STATE_PORTFOLIO_SITE_TYPE);
context.put(STATE_SITE_ADD_PORTFOLIO, SiteService.allowAddPortfolioSite());
// can the user create project sites?
context.put("projectSiteType", STATE_PROJECT_SITE_TYPE);
context.put(STATE_SITE_ADD_PROJECT, SiteService.allowAddProjectSite());
// can the user user create sites from archives?
context.put(STATE_SITE_IMPORT_ARCHIVE, SiteService.allowImportArchiveSite());
Site site = getStateSite(state);
List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
switch (index) {
case 0:
/*
* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
// make sure auto-updates are enabled
Hashtable views = new Hashtable();
// Allow a user to see their deleted sites.
if (ServerConfigurationService.getBoolean("site.soft.deletion", false)) {
views.put(SiteConstants.SITE_TYPE_DELETED, rb.getString("java.sites.deleted"));
if (SiteConstants.SITE_TYPE_DELETED.equals((String) state.getAttribute(STATE_VIEW_SELECTED))) {
context.put("canSeeSoftlyDeletedSites", true);
}
}
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
context.put("menu", bar);
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
// If we're in the restore view
context.put("showRestore", SiteConstants.SITE_TYPE_DELETED.equals((String) state.getAttribute(STATE_VIEW_SELECTED)));
if (SecurityService.isSuperUser()) {
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
}
views.put(SiteConstants.SITE_TYPE_ALL, rb.getString("java.allmy"));
views.put(SiteConstants.SITE_TYPE_MYWORKSPACE, rb.getFormattedMessage("java.sites", new Object[]{rb.getString("java.my")}));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type, rb.getFormattedMessage("java.sites", new Object[]{type}));
}
List<String> moreTypes = siteTypeProvider.getTypesForSiteList();
if (!moreTypes.isEmpty())
{
for(String mType : moreTypes)
{
views.put(mType, rb.getFormattedMessage("java.sites", new Object[]{mType}));
}
}
// Allow SuperUser to see all deleted sites.
if (ServerConfigurationService.getBoolean("site.soft.deletion", false)) {
views.put(SiteConstants.SITE_TYPE_DELETED, rb.getString("java.sites.deleted"));
}
// default view
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, SiteConstants.SITE_TYPE_ALL);
}
// sort the keys in the views lookup
List<String> viewKeys = Collections.list(views.keys());
Collections.sort(viewKeys);
context.put("viewKeys", viewKeys);
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
//term filter:
Hashtable termViews = new Hashtable();
termViews.put(TERM_OPTION_ALL, rb.getString("list.allTerms"));
// bjones86 - SAK-23256
List<AcademicSession> aSessions = setTermListForContext( context, state, false, false );
if(aSessions != null){
for(AcademicSession s : aSessions){
termViews.put(s.getTitle(), s.getTitle());
}
}
// default term view
if (state.getAttribute(STATE_TERM_VIEW_SELECTED) == null) {
state.setAttribute(STATE_TERM_VIEW_SELECTED, TERM_OPTION_ALL);
}else {
context.put("viewTermSelected", (String) state
.getAttribute(STATE_TERM_VIEW_SELECTED));
}
// sort the keys in the termViews lookup
List<String> termViewKeys = Collections.list(termViews.keys());
Collections.sort(termViewKeys);
context.put("termViewKeys", termViewKeys);
context.put("termViews", termViews);
if(termViews.size() == 1){
//this means the terms are empty, only the default option exist
context.put("hideTermFilter", true);
}else{
context.put("hideTermFilter", false);
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List<Site> allSites = prepPage(state);
state.setAttribute(STATE_SITES, allSites);
context.put("sites", allSites);
context.put("totalPageNumber", Integer.valueOf(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on
// each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
context.put("sortby_softlydeleted", SortType.SOFTLY_DELETED_ASC.toString());
// default to be no paging
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
//SAK-22438 if user can add one of these site types then they can see the link to add a new site
boolean allowAddSite = false;
if(SiteService.allowAddCourseSite()) {
allowAddSite = true;
} else if (SiteService.allowAddPortfolioSite()) {
allowAddSite = true;
} else if (SiteService.allowAddProjectSite()) {
allowAddSite = true;
}
context.put("allowAddSite",allowAddSite);
//SAK-23468 put create variables into context
addSiteCreationValuesIntoContext(context,state);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
/*
* buildContextForTemplate chef_site-type.vm
*
*/
List types = (List) state.getAttribute(STATE_SITE_TYPES);
List<String> mTypes = siteTypeProvider.getTypesForSiteCreation();
if (mTypes != null && !mTypes.isEmpty())
{
types.addAll(mTypes);
}
context.put("siteTypes", types);
context.put("templateControls", ServerConfigurationService.getString("templateControls", ""));
// put selected/default site type into context
String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED);
context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0));
// bjones86 - SAK-23256
Boolean hasTerms = Boolean.FALSE;
List<AcademicSession> termList = setTermListForContext( context, state, true, true ); // true => only
if( termList != null && termList.size() > 0 )
{
hasTerms = Boolean.TRUE;
}
context.put( CONTEXT_HAS_TERMS, hasTerms );
// upcoming terms
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
// template site
setTemplateListForContext(context, state);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 4:
/*
* buildContextForTemplate chef_site-editToolGroups.vm
*
*/
state.removeAttribute(STATE_TOOL_GROUP_LIST);
String type = (String) state.getAttribute(STATE_SITE_TYPE);
setTypeIntoContext(context, type);
Map<String,List> groupTools = getTools(state, type, site);
state.setAttribute(STATE_TOOL_GROUP_LIST, groupTools);
// information related to LTI tools
buildLTIToolContextForTemplate(context, state, site, true);
if (SecurityService.isSuperUser()) {
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
}
// save all lists to context
pageOrderToolTitleIntoContext(context, state, type, (site == null), site==null?null:site.getProperties().getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES));
Boolean checkToolGroupHome = (Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED);
context.put("check_home", checkToolGroupHome);
context.put("ltitool_id_prefix", LTITOOL_ID_PREFIX);
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
if (site != null)
{
MathJaxEnabler.addMathJaxSettingsToEditToolsContext(context, site, state); // SAK-22384
context.put("SiteTitle", site.getTitle());
context.put("existSite", Boolean.TRUE);
context.put("backIndex", "12"); // back to site info list page
}
else
{
context.put("existSite", Boolean.FALSE);
context.put("backIndex", "13"); // back to new site information page
}
context.put("homeToolId", TOOL_ID_HOME);
context.put("toolsByGroup", (LinkedHashMap<String,List>) state.getAttribute(STATE_TOOL_GROUP_LIST));
context.put("toolGroupMultiples", getToolGroupMultiples(state, (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST)));
return (String) getContext(data).get("template") + TEMPLATE[4];
case 8:
/*
* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
// Are we attempting to softly delete a site.
boolean softlyDeleting = ServerConfigurationService.getBoolean("site.soft.deletion", false);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
if (SiteService.allowRemoveSite(id)) {
try {
// check whether site exists
Site removeSite = SiteService.getSite(id);
//check site isn't already softly deleted
if(softlyDeleting && removeSite.isSoftlyDeleted()) {
softlyDeleting = false;
}
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id + e.getMessage());
addAlert(state, rb.getFormattedMessage("java.couldntlocate", new Object[]{id}));
}
} else {
addAlert(state, rb.getFormattedMessage("java.couldntdel", new Object[]{site_title}));
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
//check if soft deletes are activated
context.put("softDelete", softlyDeleting);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 10:
/*
* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (SiteTypeUtil.isCourseSite(siteType)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE);
context.put("isProjectSite", Boolean.FALSE);
putSelectedProviderCourseIntoContext(context, state);
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", Integer.valueOf(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
else if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("manualAddNumber", Integer.valueOf(((List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS)).size()));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtils.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (SiteTypeUtil.isProjectSite(siteType)) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtils.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("siteUrls", getSiteUrlsForAliasIds(siteInfo.siteRefAliases));
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
/// site language information
String locale_string_selected = (String) state.getAttribute("locale_string");
if(locale_string_selected == "" || locale_string_selected == null)
context.put("locale_string_selected", "");
else
{
Locale locale_selected = getLocaleFromString(locale_string_selected);
context.put("locale_string_selected", locale_selected);
}
// put tool selection into context
toolSelectionIntoContext(context, state, siteType, null, null/*site.getProperties().getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES)*/);
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", Boolean.valueOf(siteInfo.include));
context.put("published", Boolean.valueOf(siteInfo.published));
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
// bjones86 - SAK-24423 - add joinable site settings to context
JoinableSiteSettings.addJoinableSiteSettingsToNewSiteConfirmContext( context, siteInfo );
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("fromArchive", state.getAttribute(STATE_UPLOADED_ARCHIVE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 12:
/*
* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
// put the link for downloading participant
putPrintParticipantLinkIntoContext(context, data, site);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
if (site.getProviderGroupId() != null) {
M_log.debug("site has provider");
context.put("hasProviderSet", Boolean.TRUE);
} else {
M_log.debug("site has no provider");
context.put("hasProviderSet", Boolean.FALSE);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (StringUtils.equals(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteFriendlyUrls", getSiteUrlsForSite(site));
context.put("siteDefaultUrl", getDefaultSiteUrl(siteId));
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteId", site.getId());
if (unJoinableSiteTypes != null && !unJoinableSiteTypes.contains(siteType))
{
context.put("siteJoinable", Boolean.valueOf(site.isJoinable()));
}
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (allowUpdateSite)
{
// Site modified by information
User siteModifiedBy = site.getModifiedBy();
Time siteModifiedTime = site.getModifiedTime();
if (siteModifiedBy != null) {
context.put("siteModifiedBy", siteModifiedBy.getSortName());
}
if (siteModifiedTime != null) {
context.put("siteModifiedTime", siteModifiedTime.toStringLocalFull());
}
// top menu bar
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
// if the page order helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
// in particular, need to check site types for showing the tool or not
if (isPageOrderAllowed(siteType, siteProperties.getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES)))
{
b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
}
}
}
if (allowUpdateSiteMembership)
{
// show add participant menu
if (!isMyWorkspace) {
// if the add participant helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-manage-participant-helper")) {
b.add(new MenuEntry(rb.getString("java.addp"),
"doParticipantHelper"));
}
// show the Edit Class Roster menu
if (ServerConfigurationService.getBoolean("site.setup.allow.editRoster", true) && siteType != null && SiteTypeUtil.isCourseSite(siteType)) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
}
}
if (allowUpdateGroupMembership) {
// show Manage Groups menu
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
// if the manage group helper is available, not
// stealthed and not hidden, show the link
// read the helper name from configuration variable: wsetup.group.helper.name
// the default value is: "sakai-site-manage-group-section-role-helper"
// the older version of group helper which is not section/role aware is named:"sakai-site-manage-group-helper"
String groupHelper = ServerConfigurationService.getString("wsetup.group.helper.name", "sakai-site-manage-group-section-role-helper");
if (setHelper("wsetup.groupHelper", groupHelper, state, STATE_GROUP_HELPER_ID)) {
b.add(new MenuEntry(rb.getString("java.group"),
"doManageGroupHelper"));
}
}
}
if (allowUpdateSite)
{
// show add parent sites menu
if (!isMyWorkspace) {
if (notStealthOrHiddenTool("sakai-site-manage-link-helper")) {
b.add(new MenuEntry(rb.getString("java.link"),
"doLinkHelper"));
}
if (notStealthOrHiddenTool("sakai.basiclti.admin.helper")) {
b.add(new MenuEntry(rb.getString("java.external"),
"doExternalHelper"));
}
}
}
if (allowUpdateSite)
{
if (!isMyWorkspace) {
List<String> providedSiteTypes = siteTypeProvider.getTypes();
boolean isProvidedType = false;
if (siteType != null
&& providedSiteTypes.contains(siteType)) {
isProvidedType = true;
}
if (!isProvidedType) {
// hide site access for provided site types
// type of sites
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
// hide site duplicate and import
if (SiteService.allowAddSite(null) && ServerConfigurationService.getBoolean("site.setup.allowDuplicateSite", true))
{
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
}
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
// import link should be visible even if only one
// site
if (updatableSites.size() > 0) {
//a configuration param for showing/hiding Import From Site with Clean Up
String importFromSite = ServerConfigurationService.getString("clean.import.site",Boolean.TRUE.toString());
if (importFromSite.equalsIgnoreCase("true")) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_importSelection"));
}
else {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
}
// a configuration param for
// showing/hiding import
// from file choice
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
// htripath: June
// 4th added as per
// Kris and changed
// desc of above
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
}
if (allowUpdateSite)
{
// show add parent sites menu
if (!isMyWorkspace) {
boolean eventLog = "true".equals(ServerConfigurationService.getString("user_audit_log_display", "true"));
if (notStealthOrHiddenTool("sakai.useraudit") && eventLog) {
b.add(new MenuEntry(rb.getString("java.userAuditEventLog"),
"doUserAuditEventLog"));
}
}
}
if (b.size() > 0)
{
// add the menus to vm
context.put("menu", b);
}
if(state.getAttribute(IMPORT_QUEUED) != null){
context.put("importQueued", true);
state.removeAttribute(IMPORT_QUEUED);
if(UserDirectoryService.getCurrentUser().getEmail() == null || "".equals(UserDirectoryService.getCurrentUser().getEmail())){
context.put("importQueuedNoEmail", true);
}
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
// allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
// set participant list
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
Collection participantsCollection = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME);
sortedBy = SiteConstants.SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
context.put("participantListSize", Integer.valueOf(participantsCollection.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties.getProperty(Site.PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(Site.PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (SiteTypeUtil.isCourseSite(siteType)) {
context.put("isCourseSite", Boolean.TRUE);
coursesIntoContext(state, context, site);
context.put("term", siteProperties
.getProperty(Site.PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
Collection<Group> groups = null;
if (ServerConfigurationService.getBoolean("wsetup.group.support.summary", true))
{
if ((allowUpdateSite || allowUpdateGroupMembership)
&& (!isMyWorkspace && ServerConfigurationService.getBoolean("wsetup.group.support", true)))
{
// show all site groups
groups = site.getGroups();
}
else
{
// show groups that the current user is member of
groups = site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId());
}
}
if (groups != null)
{
// filter out only those groups that are manageable by site-info
Collection<Group> filteredGroups = new ArrayList<Group>();
Collection<Group> filteredSections = new ArrayList<Group>();
Collection<String> viewMembershipGroups = new ArrayList<String>();
Collection<String> unjoinableGroups = new ArrayList<String>();
for (Group g : groups)
{
Object gProp = g.getProperties().getProperty(g.GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString()))
{
filteredGroups.add(g);
}
else
{
filteredSections.add(g);
}
Object vProp = g.getProperties().getProperty(g.GROUP_PROP_VIEW_MEMBERS);
if (vProp != null && vProp.equals(Boolean.TRUE.toString())){
viewMembershipGroups.add(g.getId());
}
Object joinableProp = g.getProperties().getProperty(g.GROUP_PROP_JOINABLE_SET);
Object unjoinableProp = g.getProperties().getProperty(g.GROUP_PROP_JOINABLE_UNJOINABLE);
if (joinableProp != null && !"".equals(joinableProp.toString())
&& unjoinableProp != null && unjoinableProp.equals(Boolean.TRUE.toString())
&& g.getMember(UserDirectoryService.getCurrentUser().getId()) != null){
unjoinableGroups.add(g.getId());
}
}
context.put("groups", filteredGroups);
context.put("sections", filteredSections);
context.put("viewMembershipGroups", viewMembershipGroups);
context.put("unjoinableGroups", unjoinableGroups);
}
//joinable groups:
Collection<JoinableGroup> joinableGroups = new ArrayList<JoinableGroup>();
if(site.getGroups() != null){
//find a list of joinable-sets this user is already a member of
//in order to not display those groups as options
Set<String> joinableSetsMember = new HashSet<String>();
for(Group group : site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId())){
String joinableSet = group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET);
if(joinableSet != null && !"".equals(joinableSet.trim())){
joinableSetsMember.add(joinableSet);
}
}
for(Group group : site.getGroups()){
String joinableSet = group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET);
if(joinableSet != null && !"".equals(joinableSet.trim()) && !joinableSetsMember.contains(joinableSet)){
String reference = group.getReference();
String title = group.getTitle();
int max = 0;
try{
max = Integer.parseInt(group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET_MAX));
}catch (Exception e) {
}
boolean preview = Boolean.valueOf(group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET_PREVIEW));
String groupMembers = "";
int size = 0;
try
{
AuthzGroup g = authzGroupService.getAuthzGroup(group.getReference());
Collection<Member> gMembers = g != null ? g.getMembers():new Vector<Member>();
size = gMembers.size();
if (size > 0)
{
Set<String> hiddenUsers = new HashSet<String>();
boolean viewHidden = viewHidden = SecurityService.unlock("roster.viewHidden", site.getReference()) || SecurityService.unlock("roster.viewHidden", g.getReference());
if(!SiteService.allowViewRoster(siteId) && !viewHidden){
//find hidden users in this group:
//add hidden users to set so we can filter them out
Set<String> memberIds = new HashSet<String>();
for(Member member : gMembers){
memberIds.add(member.getUserId());
}
hiddenUsers = privacyManager.findHidden(site.getReference(), memberIds);
}
for (Iterator<Member> gItr=gMembers.iterator(); gItr.hasNext();){
Member p = (Member) gItr.next();
// exclude those user with provided roles and rosters
String userId = p.getUserId();
if(!hiddenUsers.contains(userId)){
try
{
User u = UserDirectoryService.getUser(userId);
if(!"".equals(groupMembers)){
groupMembers += ", ";
}
groupMembers += u.getDisplayName();
}
catch (Exception e)
{
M_log.debug(this + "joinablegroups: cannot find user with id " + userId);
// need to remove the group member
size--;
}
}
}
}
}
catch (GroupNotDefinedException e)
{
M_log.debug(this + "joinablegroups: cannot find group " + group.getReference());
}
joinableGroups.add(new JoinableGroup(reference, title, joinableSet, size, max, groupMembers, preview));
}
}
if(joinableGroups.size() > 0){
context.put("joinableGroups", joinableGroups);
}
}
} catch (Exception e) {
M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e);
}
roles = getRoles(state);
context.put("roles", roles);
// SAK-23257 - add the allowed roles to the context for UI rendering
context.put( VM_ALLOWED_ROLES_DROP_DOWN, SiteParticipantHelper.getAllowedRoles( site.getType(), roles ) );
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
// UVa add realm object to context so we can provide last modified time
realmId = SiteService.siteReference(site.getId());
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
context.put("realmModifiedTime",realm.getModifiedTime().toStringLocalFullZ());
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException " + realmId);
}
// SAK-22384 mathjax support
MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
/*
* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
if (site != null) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("continue", "14");
ResourcePropertiesEdit props = site.getPropertiesEdit();
String locale_string = StringUtils.trimToEmpty(props.getProperty(PROP_SITE_LANGUAGE));
context.put("locale_string",locale_string);
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("continue", "4");
// get the system default as locale string
context.put("locale_string", "");
}
boolean displaySiteAlias = displaySiteAlias();
context.put("displaySiteAlias", Boolean.valueOf(displaySiteAlias));
if (displaySiteAlias)
{
context.put(FORM_SITE_URL_BASE, getSiteBaseUrl());
context.put(FORM_SITE_ALIAS, siteInfo.getFirstAlias());
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("type", siteType);
context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, siteType)));
context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX));
if (SiteTypeUtil.isCourseSite(siteType)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
boolean hasRosterAttached = putSelectedProviderCourseIntoContext(context, state);
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
if (!hasRosterAttached && cmRequestedList.size() > 0)
{
hasRosterAttached = true;
}
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
if (!hasRosterAttached && cmAuthorizerSectionList.size() > 0)
{
hasRosterAttached = true;
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", Integer.valueOf(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (!hasRosterAttached)
{
hasRosterAttached = true;
}
} else {
if (site != null)
if (!hasRosterAttached)
{
hasRosterAttached = coursesIntoContext(state, context, site);
}
else
{
coursesIntoContext(state, context, site);
}
if (courseManagementIsImplemented()) {
} else {
context.put("templateIndex", "37");
}
}
context.put("hasRosterAttached", Boolean.valueOf(hasRosterAttached));
if (StringUtils.trimToNull(siteInfo.term) == null) {
if (site != null)
{
// existing site
siteInfo.term = site.getProperties().getProperty(Site.PROP_SITE_TERM);
}
else
{
// creating new site
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
siteInfo.term = t != null?t.getEid() : "";
}
}
context.put("selectedTerm", siteInfo.term != null? siteInfo.term:"");
} else {
context.put("isCourseSite", Boolean.FALSE);
if (SiteTypeUtil.isProjectSite(siteType)) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtils.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
}
// about skin and icon selection
skinIconSelection(context, state, SiteTypeUtil.isCourseSite(siteType), site, siteInfo);
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider.getRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("title", siteInfo.title);
context.put(FORM_SITE_URL_BASE, getSiteBaseUrl());
context.put(FORM_SITE_ALIAS, siteInfo.getFirstAlias());
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
context.put("site_aliases", state.getAttribute(FORM_SITEINFO_ALIASES));
context.put("site_url_base", state.getAttribute(FORM_SITEINFO_URL_BASE));
context.put("site_aliases_editable", aliasesEditable(state, site == null ? null:site.getReference()));
context.put("site_alias_assignable", aliasAssignmentForNewSitesEnabled(state));
// available languages in sakai.properties
List locales = getPrefLocales();
context.put("locales",locales);
// SAK-22384 mathjax support
MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
/*
* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("displaySiteAlias", Boolean.valueOf(displaySiteAlias()));
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (SiteTypeUtil.isCourseSite(siteType)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", siteInfo.term);
} else {
context.put("isCourseSite", Boolean.FALSE);
}
// about skin and icon selection
skinIconSelection(context, state, SiteTypeUtil.isCourseSite(siteType), site, siteInfo);
context.put("oTitle", site.getTitle());
context.put("title", siteInfo.title);
// get updated language
String new_locale_string = (String) state.getAttribute("locale_string");
if(new_locale_string == "" || new_locale_string == null)
context.put("new_locale", "");
else
{
Locale new_locale = getLocaleFromString(new_locale_string);
context.put("new_locale", new_locale);
}
// get site language saved
ResourcePropertiesEdit props = site.getPropertiesEdit();
String oLocale_string = props.getProperty(PROP_SITE_LANGUAGE);
if(oLocale_string == "" || oLocale_string == null)
context.put("oLocale", "");
else
{
Locale oLocale = getLocaleFromString(oLocale_string);
context.put("oLocale", oLocale);
}
context.put("description", siteInfo.description);
context.put("oDescription", site.getDescription());
context.put("short_description", siteInfo.short_description);
context.put("oShort_description", site.getShortDescription());
context.put("skin", siteInfo.iconUrl);
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", siteInfo.iconUrl);
context.put("include", siteInfo.include);
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", siteInfo.site_contact_name);
context.put("oName", siteProperties.getProperty(Site.PROP_SITE_CONTACT_NAME));
context.put("email", siteInfo.site_contact_email);
context.put("oEmail", siteProperties.getProperty(Site.PROP_SITE_CONTACT_EMAIL));
context.put("siteUrls", getSiteUrlsForAliasIds(siteInfo.siteRefAliases));
context.put("oSiteUrls", getSiteUrlsForSite(site));
// SAK-22384 mathjax support
MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
/*
* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
String overridePageOrderSiteTypes = site.getProperties().getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES);
// put tool selection into context
toolSelectionIntoContext(context, state, site_type, site.getId(), overridePageOrderSiteTypes);
MathJaxEnabler.addMathJaxSettingsToEditToolsConfirmationContext(context, site, state, STATE_TOOL_REGISTRATION_TITLE_LIST); // SAK-22384
return (String) getContext(data).get("template") + TEMPLATE[15];
case 18:
/*
* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
if (site != null) {
// editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("published", state.getAttribute(STATE_SITE_ACCESS_PUBLISH));
context.put("include", state.getAttribute(STATE_SITE_ACCESS_INCLUDE));
context.put("shoppingPeriodInstructorEditable", ServerConfigurationService.getBoolean("delegatedaccess.shopping.instructorEditable", false));
context.put("viewDelegatedAccessUsers", ServerConfigurationService.getBoolean("delegatedaccess.siteaccess.instructorViewable", false));
// bjones86 - SAK-24423 - add joinable site settings to context
JoinableSiteSettings.addJoinableSiteSettingsToEditAccessContextWhenSiteIsNotNull( context, state, site, !unJoinableSiteTypes.contains( siteType ) );
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// bjones86 - SAK-23257
context.put("roles", getJoinerRoles(site.getReference(), state, site.getType()));
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// bjones86 - SAK-24423 - add joinable site settings to context
JoinableSiteSettings.addJoinableSiteSettingsToEditAccessContextWhenSiteIsNull( context, siteInfo, true );
// the template site, if using one
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
// use the type's template, if defined
String realmTemplate = "!site.template";
// if create based on template, use the roles from the template
if (templateSite != null) {
realmTemplate = SiteService.siteReference(templateSite.getId());
} else if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate);
// bjones86 - SAK-23257
context.put("roles", getJoinerRoles(r.getId(), state, null));
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template");
// bjones86 - SAK-23257
context.put("roles", getJoinerRoles(rr.getId(), state, null));
} catch (GroupNotDefinedException ee) {
}
}
// new site, go to confirmation page
context.put("continue", "10");
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
setTypeIntoContext(context, siteType);
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 26:
/*
* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("continue", "15");
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
// all info related to multiple tools
multipleToolIntoContext(context, state);
// put the lti tool selection into context
if (state.getAttribute(STATE_LTITOOL_SELECTED_LIST) != null)
{
HashMap<String, Map<String, Object>> currentLtiTools = (HashMap<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_SELECTED_LIST);
for (Map.Entry<String, Map<String, Object>> entry : currentLtiTools.entrySet() ) {
Map<String, Object> toolMap = entry.getValue();
String toolId = entry.getKey();
// get the proper html for tool input
String ltiToolId = toolMap.get("id").toString();
String[] contentToolModel=m_ltiService.getContentModel(Long.valueOf(ltiToolId));
// attach the ltiToolId to each model attribute, so that we could have the tool configuration page for multiple tools
for(int k=0; k<contentToolModel.length;k++)
{
contentToolModel[k] = ltiToolId + "_" + contentToolModel[k];
}
Map<String, Object> ltiTool = m_ltiService.getTool(Long.valueOf(ltiToolId));
String formInput=m_ltiService.formInput(ltiTool, contentToolModel);
toolMap.put("formInput", formInput);
currentLtiTools.put(ltiToolId, toolMap);
}
context.put("ltiTools", currentLtiTools);
context.put("ltiService", m_ltiService);
context.put("oldLtiTools", state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST));
}
context.put("toolManager", ToolManager.getInstance());
AcademicSession thisAcademicSession = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
String emailId = null;
boolean prePopulateEmail = ServerConfigurationService.getBoolean("wsetup.mailarchive.prepopulate.email",true);
if(prePopulateEmail == true && state.getAttribute(STATE_TOOL_EMAIL_ADDRESS)==null){
if(thisAcademicSession!=null){
String siteTitle1 = siteInfo.title.replaceAll("[(].*[)]", "");
siteTitle1 = siteTitle1.trim();
siteTitle1 = siteTitle1.replaceAll(" ", "-");
emailId = siteTitle1;
}else{
emailId = StringUtils.deleteWhitespace(siteInfo.title);
}
}else{
emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (emailId != null) {
context.put("emailId", emailId);
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("homeToolId", TOOL_ID_HOME);
context.put("maxToolTitleLength", MAX_TOOL_TITLE_LENGTH);
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
/*
* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
// define the tools available for import. defaults to those tools in the "to" site
List<String> importableTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("step", "2");
context.put("currentSite", site);
// if the site exists, there may be other tools available for import
importableTools = getToolsAvailableForImport(state, importableTools);
} else {
// new site, go to edit access page
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put("existingSite", Boolean.valueOf(existingSite));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
originalToolIds((List<String>) importableTools, state), false));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
context.put("hideImportedContent", ServerConfigurationService.getBoolean("content.import.hidden", false));
if(ServerConfigurationService.getBoolean("site-manage.importoption.siteinfo", false)){
try{
String siteInfoToolTitle = ToolManager.getTool(SITE_INFO_TOOL_ID).getTitle();
context.put("siteInfoToolTitle", siteInfoToolTitle);
}catch(Exception e){
}
}
return (String) getContext(data).get("template") + TEMPLATE[27];
case 60:
/*
* buildContextForTemplate chef_site-importSitesMigrate.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("step", "2");
context.put("currentSite", site);
} else {
// new site, go to edit access page
context.put("back", "4");
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
// get the tool id list
List<String> toolIdList = new Vector<String>();
if (existingSite)
{
// list all site tools which are displayed on its own page
List<SitePage> sitePages = site.getPages();
if (sitePages != null)
{
for (SitePage page: sitePages)
{
List<ToolConfiguration> pageToolsList = page.getTools(0);
// we only handle one tool per page case
if ( page.getLayout() == SitePage.LAYOUT_SINGLE_COL && pageToolsList.size() == 1)
{
toolIdList.add(pageToolsList.get(0).getToolId());
}
}
}
}
else
{
// during site creation
toolIdList = (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdList);
// order it
SortedIterator iToolIdList = new SortedIterator(getToolsAvailableForImport(state, toolIdList).iterator(),new ToolComparator());
Hashtable<String, String> toolTitleTable = new Hashtable<String, String>();
for(;iToolIdList.hasNext();)
{
String toolId = (String) iToolIdList.next();
try
{
String toolTitle = ToolManager.getTool(toolId).getTitle();
toolTitleTable.put(toolId, toolTitle);
}
catch (Exception e)
{
Log.info("chef", this + " buildContexForTemplate case 60: cannot get tool title for " + toolId + e.getMessage());
}
}
context.put("selectedTools", toolTitleTable); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[60];
case 28:
/*
* buildContextForTemplate chef_siteinfo-import.vm
*
*/
putImportSitesInfoIntoContext(context, site, state, false);
return (String) getContext(data).get("template") + TEMPLATE[28];
case 58:
/*
* buildContextForTemplate chef_siteinfo-importSelection.vm
*
*/
putImportSitesInfoIntoContext(context, site, state, false);
return (String) getContext(data).get("template") + TEMPLATE[58];
case 59:
/*
* buildContextForTemplate chef_siteinfo-importMigrate.vm
*
*/
putImportSitesInfoIntoContext(context, site, state, false);
return (String) getContext(data).get("template") + TEMPLATE[59];
case 29:
/*
* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && SiteTypeUtil.isCourseSite(sType)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
Site.PROP_SITE_TERM));
// bjones86 - SAK-23256
setTermListForContext( context, state, true, false ); // true upcoming only
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
// SAK-20797 - display checkboxes only if sitespecific value exists
long quota = getSiteSpecificQuota(site);
if (quota > 0) {
context.put("hasSiteSpecificQuota", true);
context.put("quotaSize", formatSize(quota*1024));
}
else {
context.put("hasSiteSpecificQuota", false);
}
context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX));
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
// SAK-9824
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
coursesIntoContext(state, context, site);
// bjones86 - SAK-23256
List<AcademicSession> terms = setTermListForContext( context, state, true, false ); // true -> upcoming only
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
if (terms != null && terms.size() > 0)
{
boolean foundTerm = false;
for(AcademicSession testTerm : terms)
{
if (t != null && testTerm.getEid().equals(t.getEid()))
{
foundTerm = true;
break;
}
}
if (!foundTerm)
{
// if the term is no longer listed in the term list, choose the first term in the list instead
t = terms.get(0);
}
}
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (providerCourseList == null || !providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
} else {
// need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS
// contains sections that doens't belongs to current user and
// STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does -
// v2.4 daisyf
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
putSelectedProviderCourseIntoContext(context, state);
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
//authorizerList is a list of SectionObject
/*
String userId = null;
if (authorizerList != null) {
userId = (String) authorizerList.get(0);
}
List list2 = prepareSectionObject(
authorizerSectionList, userId);
*/
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state, STATE_CM_AUTHORIZER_LIST));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
// added for 2.4 -daisyf
context.put("campusDirectory", getCampusDirectory());
context.put("userId", state.getAttribute(STATE_INSTRUCTOR_SELECTED) != null ? (String) state.getAttribute(STATE_INSTRUCTOR_SELECTED) : UserDirectoryService.getCurrentUser().getId());
/*
* for measuring how long it takes to load sections java.util.Date
* date = new java.util.Date(); M_log.debug("***2. finish at:
* "+date); M_log.debug("***3. userId:"+(String) state
* .getAttribute(STATE_INSTRUCTOR_SELECTED));
*/
context.put("basedOnTemplate", state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE:Boolean.FALSE);
// bjones86 - SAK-21706
context.put( CONTEXT_SKIP_COURSE_SECTION_SELECTION,
ServerConfigurationService.getBoolean( SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE ) );
context.put( CONTEXT_SKIP_MANUAL_COURSE_CREATION,
ServerConfigurationService.getBoolean( SAK_PROP_SKIP_MANUAL_COURSE_CREATION, Boolean.FALSE ) );
context.put("siteType", state.getAttribute(STATE_TYPE_SELECTED));
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName", ""));
if (state.getAttribute(STATE_SITE_QUEST_UNIQNAME) == null)
{
context.put("value_uniqname", getAuthorizers(state, STATE_SITE_QUEST_UNIQNAME));
}
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", Integer.valueOf(number));
}
context.put("currentNumber", Integer.valueOf(number));
context.put("listSize", number>0?Integer.valueOf(number - 1):0);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0)
{
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
putSelectedProviderCourseIntoContext(context, state);
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("cmRequestedSections", l);
}
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (site == null) {
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
}
}
isFutureTermSelected(state);
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
context.put("basedOnTemplate", state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE:Boolean.FALSE);
context.put("requireAuthorizer", ServerConfigurationService.getString("wsetup.requireAuthorizer", "true").equals("true")?Boolean.TRUE:Boolean.FALSE);
// bjones86 - SAK-21706/SAK-23255
context.put( CONTEXT_IS_ADMIN, SecurityService.isSuperUser() );
context.put( CONTEXT_SKIP_COURSE_SECTION_SELECTION, ServerConfigurationService.getBoolean( SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE ) );
context.put( CONTEXT_FILTER_TERMS, ServerConfigurationService.getBoolean( SAK_PROP_FILTER_TERMS, Boolean.FALSE ) );
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
/*
* buildContextForTemplate chef_site-type-confirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%%
// use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", Boolean.valueOf(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
/*
* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
/*
* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
putSelectedProviderCourseIntoContext(context, state);
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null)
{
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null)
{
context.put("cmRequestedSections", state.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", Integer.valueOf(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
// htripath - import materials from classic
case 45:
/*
* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
// zip file
// context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
// case 49, 50, 51 have been implemented in helper mode
case 53: {
/*
* build context for chef_site-findCourse.vm
*/
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
if (cmLevels == null)
{
cmLevels = getCMLevelLabels(state);
}
List<SectionObject> selectedSect = (List<SectionObject>) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", Boolean.valueOf(true));
}
int cmLevelSize = 0;
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
// TODO: redirect to manual entry: case #37
} else {
cmLevelSize = cmLevels.size();
Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS);
int numSelections = 0;
if (selections != null)
{
numSelections = selections.size();
}
if (numSelections != 0)
{
// execution will fall through these statements based on number of selections already made
if (numSelections == cmLevelSize - 1)
{
levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1));
}
else if (numSelections == cmLevelSize - 2)
{
levelOpts[numSelections] = getCMCourseOfferings(getSelectionString(selections, numSelections), t.getEid());
}
else if (numSelections < cmLevelSize)
{
levelOpts[numSelections] = sortCourseSets(cms.findCourseSets(getSelectionString(selections, numSelections)));
}
}
// always set the top level
Set<CourseSet> courseSets = filterCourseSetList(getCourseSet(state));
levelOpts[0] = sortCourseSets(courseSets);
// clean further element inside the array
for (int i = numSelections + 1; i<cmLevelSize; i++)
{
levelOpts[i] = null;
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
context.put("cmBaseCourseSetLevel", Integer.valueOf((levelOpts.length-3) >= 0 ? (levelOpts.length-3) : 0)); // staring from that selection level, the lookup will be for CourseSet, CourseOffering, and Section
context.put("maxSelectionDepth", Integer.valueOf(levelOpts.length-1));
state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts);
}
putSelectedProviderCourseIntoContext(context, state);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", Integer.valueOf(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("cmRequestedSections", requestedSections);
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_TERM_COURSE_LIST) != null)
{
context.put("backIndex", "36");
}
else
{
context.put("backIndex", "1");
}
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "36");
}
context.put("authzGroupService", AuthzGroupService.getInstance());
if (selectedSect !=null && !selectedSect.isEmpty() && state.getAttribute(STATE_SITE_QUEST_UNIQNAME) == null){
context.put("value_uniqname", selectedSect.get(0).getAuthorizerString());
}
context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
context.put("basedOnTemplate", state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE:Boolean.FALSE);
// bjones86 - SAK-21706/SAK-23255
context.put( CONTEXT_IS_ADMIN, SecurityService.isSuperUser() );
context.put( CONTEXT_SKIP_MANUAL_COURSE_CREATION, ServerConfigurationService.getBoolean( SAK_PROP_SKIP_MANUAL_COURSE_CREATION, Boolean.FALSE ) );
context.put( CONTEXT_FILTER_TERMS, ServerConfigurationService.getBoolean( SAK_PROP_FILTER_TERMS, Boolean.FALSE ) );
return (String) getContext(data).get("template") + TEMPLATE[53];
}
case 54:
/*
* build context for chef_site-questions.vm
*/
SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE));
if (siteTypeQuestions != null)
{
context.put("questionSet", siteTypeQuestions);
context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER));
}
context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE));
return (String) getContext(data).get("template") + TEMPLATE[54];
case 61:
/*
* build context for chef_site-importUser.vm
*/
context.put("toIndex", "12");
// only show those sites with same site type
putImportSitesInfoIntoContext(context, site, state, true);
return (String) getContext(data).get("template") + TEMPLATE[61];
case 62:
/*
* build context for chef_site-uploadArchive.vm
*/
//back to access, continue to confirm
context.put("back", "18");
//now go to uploadArchive template
return (String) getContext(data).get("template") + TEMPLATE[62];
}
// should never be reached
return (String) getContext(data).get("template") + TEMPLATE[0];
}
private void toolSelectionIntoContext(Context context, SessionState state, String siteType, String siteId, String overridePageOrderSiteTypes) {
List toolRegistrationList;
List toolRegistrationSelectedList;
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
toolRegistrationList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList);
if (toolRegistrationSelectedList != null && toolRegistrationList != null)
{
// see if any tool is added outside of Site Info tool, which means the tool is outside of the allowed tool set for this site type
context.put("extraSelectedToolList", state.getAttribute(STATE_EXTRA_SELECTED_TOOL_LIST));
}
// put tool title into context if PageOrderHelper is enabled
pageOrderToolTitleIntoContext(context, state, siteType, false, overridePageOrderSiteTypes);
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, checkNullSiteType(state, siteType, siteId), toolRegistrationSelectedList, false));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
// all info related to multiple tools
multipleToolIntoContext(context, state);
context.put("homeToolId", TOOL_ID_HOME);
// put the lti tools information into context
context.put("ltiTools", state.getAttribute(STATE_LTITOOL_SELECTED_LIST));
context.put("oldLtiTools", state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST));
context.put("ltitool_id_prefix", LTITOOL_ID_PREFIX);
}
/**
* prepare lti tool information in context and state variables
* @param context
* @param state
* @param site
* @param updateToolRegistration
*/
private void buildLTIToolContextForTemplate(Context context,
SessionState state, Site site, boolean updateToolRegistration) {
List<Map<String, Object>> tools;
// get the list of available external lti tools
tools = m_ltiService.getTools(null,null,0,0);
if (tools != null && !tools.isEmpty())
{
HashMap<String, Map<String, Object>> ltiTools = new HashMap<String, Map<String, Object>>();
// get invoke count for all lti tools
List<Map<String,Object>> contents = m_ltiService.getContents(null,null,0,0);
HashMap<String, Map<String, Object>> linkedLtiContents = new HashMap<String, Map<String, Object>>();
for ( Map<String,Object> content : contents ) {
String ltiToolId = content.get(m_ltiService.LTI_TOOL_ID).toString();
String siteId = StringUtils.trimToNull((String) content.get(m_ltiService.LTI_SITE_ID));
if (siteId != null)
{
// whether the tool is already enabled in site
String pstr = (String) content.get(LTIService.LTI_PLACEMENT);
if (StringUtils.trimToNull(pstr) != null && site != null)
{
// the lti tool is enabled in the site
ToolConfiguration toolConfig = SiteService.findTool(pstr);
if (toolConfig != null && toolConfig.getSiteId().equals(siteId))
{
Map<String, Object> m = new HashMap<String, Object>();
Map<String, Object> ltiToolValues = m_ltiService.getTool(Long.valueOf(ltiToolId));
if ( ltiToolValues != null )
{
m.put("toolTitle", ltiToolValues.get(LTIService.LTI_TITLE));
m.put("pageTitle", ltiToolValues.get(LTIService.LTI_PAGETITLE));
m.put(LTIService.LTI_TITLE, (String) content.get(LTIService.LTI_TITLE));
m.put("contentKey", content.get(LTIService.LTI_ID));
linkedLtiContents.put(ltiToolId, m);
}
}
}
}
}
for (Map<String, Object> toolMap : tools ) {
String ltiToolId = toolMap.get("id").toString();
String siteId = StringUtils.trimToNull((String) toolMap.get(m_ltiService.LTI_SITE_ID));
toolMap.put("selected", linkedLtiContents.containsKey(ltiToolId));
if (siteId == null)
{
// only show the system-range lti tools
ltiTools.put(ltiToolId, toolMap);
}
else
{
// show the site-range lti tools only if
// 1. this is in Site Info editing existing site,
// and 2. the lti tool site_id equals to current site
if (site != null && siteId.equals(site.getId()))
{
ltiTools.put(ltiToolId, toolMap);
}
}
}
state.setAttribute(STATE_LTITOOL_LIST, ltiTools);
state.setAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST, linkedLtiContents);
context.put("ltiTools", ltiTools);
context.put("selectedLtiTools",linkedLtiContents);
if (updateToolRegistration)
{
// put the selected lti tool ids into state attribute
List<String> idSelected = state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST) != null? (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST):new ArrayList<String>();
for(String ltiId :linkedLtiContents.keySet())
{
// attach the prefix
idSelected.add(LTITOOL_ID_PREFIX+ltiId);
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected);
}
}
}
private String getSelectionString(List selections, int numSelections) {
StringBuffer eidBuffer = new StringBuffer();
for (int i = 0; i < numSelections;i++)
{
eidBuffer.append(selections.get(i)).append(",");
}
String eid = eidBuffer.toString();
// trim off last ","
if (eid.endsWith(","))
eid = eid.substring(0, eid.lastIndexOf(","));
return eid;
}
/**
* get CourseSet from CourseManagementService and update state attribute
* @param state
* @return
*/
private Set getCourseSet(SessionState state) {
Set courseSet = null;
if (state.getAttribute(STATE_COURSE_SET) != null)
{
courseSet = (Set) state.getAttribute(STATE_COURSE_SET);
}
else
{
courseSet = cms.getCourseSets();
state.setAttribute(STATE_COURSE_SET, courseSet);
}
return courseSet;
}
/**
* put customized page title into context during an editing process for an existing site and the PageOrder tool is enabled for this site
* @param context
* @param state
* @param siteType
* @param newSite
*/
private void pageOrderToolTitleIntoContext(Context context, SessionState state, String siteType, boolean newSite, String overrideSitePageOrderSetting) {
// check if this is an existing site and PageOrder is enabled for the site. If so, show tool title
if (!newSite && notStealthOrHiddenTool("sakai-site-pageorder-helper") && isPageOrderAllowed(siteType, overrideSitePageOrderSetting))
{
// the actual page titles
context.put(STATE_TOOL_REGISTRATION_TITLE_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST));
context.put("allowPageOrderHelper", Boolean.TRUE);
}
else
{
context.put("allowPageOrderHelper", Boolean.FALSE);
}
}
/**
* Depending on institutional setting, all or part of the CourseSet list will be shown in the dropdown list in find course page
* for example, sakai.properties could have following setting:
* sitemanage.cm.courseset.categories.count=1
* sitemanage.cm.courseset.categories.1=Department
* Hence, only CourseSet object with category of "Department" will be shown
* @param courseSets
* @return
*/
private Set<CourseSet> filterCourseSetList(Set<CourseSet> courseSets) {
if (ServerConfigurationService.getStrings("sitemanage.cm.courseset.categories") != null) {
List<String> showCourseSetTypes = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("sitemanage.cm.courseset.categories")));
Set<CourseSet> rv = new HashSet<CourseSet>();
for(CourseSet courseSet:courseSets)
{
if (showCourseSetTypes.contains(courseSet.getCategory()))
{
rv.add(courseSet);
}
}
courseSets = rv;
}
return courseSets;
}
/**
* put all info necessary for importing site into context
* @param context
* @param site
*/
private void putImportSitesInfoIntoContext(Context context, Site site, SessionState state, boolean ownTypeOnly) {
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
ownTypeOnly?site.getType():null, null, null, SortType.TITLE_ASC, null));
}
/**
* get the titles of list of selected provider courses into context
* @param context
* @param state
* @return true if there is selected provider course, false otherwise
*/
private boolean putSelectedProviderCourseIntoContext(Context context, SessionState state) {
boolean rv = false;
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List<String> providerSectionList = (List<String>) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", providerSectionList);
context.put("selectedProviderCourseDescription", state.getAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN));
if (providerSectionList != null && providerSectionList.size() > 0)
{
// roster attached
rv = true;
}
HashMap<String, String> providerSectionListTitles = new HashMap<String, String>();
if (providerSectionList != null)
{
for (String providerSectionId : providerSectionList)
{
try
{
Section s = cms.getSection(providerSectionId);
if (s != null)
{
providerSectionListTitles.put(s.getEid(), s.getTitle());
}
}
catch (IdNotFoundException e)
{
providerSectionListTitles.put(providerSectionId, providerSectionId);
M_log.warn("putSelectedProviderCourseIntoContext Cannot find section " + providerSectionId);
}
}
context.put("size", Integer.valueOf(providerSectionList.size() - 1));
}
context.put("selectedProviderCourseTitles", providerSectionListTitles);
}
return rv;
}
/**
* whether the PageOrderHelper is allowed to be shown in this site type
* @param siteType
* @param overrideSitePageOrderSetting
* @return
*/
private boolean isPageOrderAllowed(String siteType, String overrideSitePageOrderSetting) {
if (overrideSitePageOrderSetting != null && Boolean.valueOf(overrideSitePageOrderSetting))
{
// site-specific setting, show PageOrder tool
return true;
}
else
{
// read the setting from sakai properties
boolean rv = true;
String hidePageOrderSiteTypes = ServerConfigurationService.getString(SiteConstants.SAKAI_PROPERTY_HIDE_PAGEORDER_SITE_TYPES, "");
if ( hidePageOrderSiteTypes.length() != 0)
{
if (new ArrayList<String>(Arrays.asList(StringUtils.split(hidePageOrderSiteTypes, ","))).contains(siteType))
{
rv = false;
}
}
return rv;
}
}
/*
* SAK-16600 TooGroupMultiples come from toolregistrationselectedlist
* @param state current session
* @param list list of all tools
* @return set of tools that are multiples
*/
private Map getToolGroupMultiples(SessionState state, List list) {
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
Map<String,List> toolGroupMultiples = new HashMap<String, List>();
if ( list != null )
{
for(Iterator iter = list.iterator(); iter.hasNext();)
{
String toolId = ((MyTool)iter.next()).getId();
String originId = findOriginalToolId(state, toolId);
// is this tool in the list of multipeToolIds?
if (multipleToolIdSet.contains(originId)) {
// is this the original tool or a multiple having uniqueId+originalToolId?
if (!originId.equals(toolId)) {
if (!toolGroupMultiples.containsKey(originId)) {
toolGroupMultiples.put(originId, new ArrayList());
}
List tools = toolGroupMultiples.get(originId);
MyTool tool = new MyTool();
tool.id = toolId;
tool.title = (String) multipleToolIdTitleMap.get(toolId);
// tool comes from toolRegistrationSelectList so selected should be true
tool.selected = true;
// is a toolMultiple ever *required*?
tools.add(tool);
// update the tools list for this tool id
toolGroupMultiples.put(originId, tools);
}
}
}
}
return toolGroupMultiples;
}
private void multipleToolIntoContext(Context context, SessionState state) {
// titles for multiple tool instances
context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET ));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context.put(STATE_MULTIPLE_TOOL_CONFIGURATION, state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION));
context.put(STATE_MULTIPLE_TOOL_INSTANCE_SELECTED, state.getAttribute(STATE_MULTIPLE_TOOL_INSTANCE_SELECTED));
}
// SAK-23468 If this is after an add site, the
private void addSiteCreationValuesIntoContext(Context context, SessionState state) {
String siteID = (String) state.getAttribute(STATE_NEW_SITE_STATUS_ID);
if (siteID != null) { // make sure this message is only seen immediately after a new site is created.
context.put(STATE_NEW_SITE_STATUS_ISPUBLISHED, state.getAttribute(STATE_NEW_SITE_STATUS_ISPUBLISHED));
String siteTitle = (String) state.getAttribute(STATE_NEW_SITE_STATUS_TITLE);
context.put(STATE_NEW_SITE_STATUS_TITLE, siteTitle);
context.put(STATE_NEW_SITE_STATUS_ID, siteID);
// remove the values from state so the values are gone on the next call to chef_site-list
//clearNewSiteStateParameters(state);
}
}
// SAK-23468
private void setNewSiteStateParameters(Site site, SessionState state){
if (site != null) {
state.setAttribute(STATE_NEW_SITE_STATUS_ISPUBLISHED, Boolean.valueOf(site.isPublished()));
state.setAttribute(STATE_NEW_SITE_STATUS_ID, site.getId());
state.setAttribute(STATE_NEW_SITE_STATUS_TITLE, site.getTitle());
}
}
// SAK-23468
private void clearNewSiteStateParameters(SessionState state) {
state.removeAttribute(STATE_NEW_SITE_STATUS_ISPUBLISHED);
state.removeAttribute(STATE_NEW_SITE_STATUS_ID);
state.removeAttribute(STATE_NEW_SITE_STATUS_TITLE);
}
/**
* show site skin and icon selections or not
* @param state
* @param site
* @param siteInfo
*/
private void skinIconSelection(Context context, SessionState state, boolean isCourseSite, Site site, SiteInfo siteInfo) {
// 1. the skin list
// For course site, display skin list based on "disable.course.site.skin.selection" value set with sakai.properties file. The setting defaults to be false.
boolean disableCourseSkinChoice = ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true");
// For non-course site, display skin list based on "disable.noncourse.site.skin.selection" value set with sakai.properties file. The setting defaults to be true.
boolean disableNonCourseSkinChoice = ServerConfigurationService.getString("disable.noncourse.site.skin.selection", "true").equals("true");
if ((isCourseSite && !disableCourseSkinChoice) || (!isCourseSite && !disableNonCourseSkinChoice))
{
context.put("allowSkinChoice", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
}
else
{
context.put("allowSkinChoice", Boolean.FALSE);
}
if (siteInfo != null && StringUtils.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
} else if (site != null && site.getIconUrl() != null)
{
context.put("selectedIcon", site.getIconUrl());
}
}
/**
*
*/
public void doPageOrderHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// // sites other then the current site)
//
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-pageorder-helper");
}
/**
* Launch the participant Helper Tool -- for adding participant
*
* @see case 12
*
*/
public void doParticipantHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-manage-participant-helper");
}
/**
* Launch the Manage Group helper Tool -- for adding, editing and deleting groups
*
*/
public void doManageGroupHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), (String) state.getAttribute(STATE_GROUP_HELPER_ID));//"sakai-site-manage-group-helper");
}
/**
* Launch the Link Helper Tool -- for setting/clearing parent site
*
* @see case 12 // TODO
*
*/
public void doLinkHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-manage-link-helper");
}
/**
* Launch the External Tools Helper -- For managing external tools
*/
public void doExternalHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai.basiclti.admin.helper");
}
public void doUserAuditEventLog(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai.useraudit");
}
public boolean setHelper(String helperName, String defaultHelperId, SessionState state, String stateHelperString)
{
String helperId = ServerConfigurationService.getString(helperName, defaultHelperId);
// if the state variable regarding the helper is not set yet, set it with the configured helper id
if (state.getAttribute(stateHelperString) == null)
{
state.setAttribute(stateHelperString, helperId);
}
if (notStealthOrHiddenTool(helperId)) {
return true;
}
return false;
}
// htripath: import materials from classic
/**
* Master import -- for import materials from a file
*
* @see case 45
*
*/
public void doAttachmentsMtrlFrmFile(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// state.setAttribute(FILE_UPLOAD_MAX_SIZE,
// ServerConfigurationService.getString("content.upload.max", "1"));
state.setAttribute(STATE_TEMPLATE_INDEX, "45");
} // doImportMtrlFrmFile
/**
* Handle File Upload request
*
* @see case 46
* @throws Exception
*/
public void doUpload_Mtrl_Frm_File(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List allzipList = new Vector();
List finalzipList = new Vector();
List directcopyList = new Vector();
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = data.getParameters().getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString(
"content.upload.max", "1");
long max_bytes = 1024 * 1024;
try {
max_bytes = Long.parseLong(max_file_size_mb) * 1024 * 1024;
} catch (Exception e) {
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
M_log.warn(this + ".doUpload_Mtrl_Frm_File: wrong setting of content.upload.max = " + max_file_size_mb, e);
}
if (fileFromUpload == null) {
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getFormattedMessage("importFile.size", new Object[]{max_file_size_mb}));
} else if (fileFromUpload.getFileName() == null
|| fileFromUpload.getFileName().length() == 0) {
addAlert(state, rb.getString("importFile.choosefile"));
} else {
//Need some other kind of input stream?
ResetOnCloseInputStream fileInput = null;
long fileSize=0;
try {
// Write to temp file, this should probably be in the velocity util?
File tempFile = null;
tempFile = File.createTempFile("importFile", ".tmp");
// Delete temp file when program exits.
tempFile.deleteOnExit();
InputStream fileInputStream = fileFromUpload.getInputStream();
FileOutputStream outBuf = new FileOutputStream(tempFile);
byte[] bytes = new byte[102400];
int read = 0;
while ((read = fileInputStream.read(bytes)) != -1) {
outBuf.write(bytes, 0, read);
}
fileInputStream.close();
outBuf.flush();
outBuf.close();
fileSize = tempFile.length();
fileInput = new ResetOnCloseInputStream(tempFile);
}
catch (FileNotFoundException fnfe) {
M_log.warn("FileNotFoundException creating temp import file",fnfe);
}
catch (IOException ioe) {
M_log.warn("IOException creating temp import file",ioe);
}
if (fileSize >= max_bytes) {
addAlert(state, rb.getFormattedMessage("importFile.size", new Object[]{max_file_size_mb}));
}
else if (fileSize > 0) {
if (fileInput != null && importService.isValidArchive(fileInput)) {
ImportDataSource importDataSource = importService
.parseFromFile(fileInput);
Log.info("chef", "Getting import items from manifest.");
List lst = importDataSource.getItemCategories();
if (lst != null && lst.size() > 0) {
Iterator iter = lst.iterator();
while (iter.hasNext()) {
ImportMetadata importdata = (ImportMetadata) iter
.next();
// Log.info("chef","Preparing import
// item '" + importdata.getId() + "'");
if ((!importdata.isMandatory())
&& (importdata.getFileName()
.endsWith(".xml"))) {
allzipList.add(importdata);
} else {
directcopyList.add(importdata);
}
}
}
// set Attributes
state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList);
state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList);
state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName);
state.setAttribute(IMPORT_DATA_SOURCE, importDataSource);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} else { // uploaded file is not a valid archive
addAlert(state, rb.getString("importFile.invalidfile"));
}
}
}
} // doImportMtrlFrmFile
/**
* Handle addition to list request
*
* @param data
*/
public void doAdd_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("addImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
fnlList.add(removeItems(value, zipList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Helper class for Add and remove
*
* @param value
* @param items
* @return
*/
public ImportMetadata removeItems(String value, List items) {
ImportMetadata result = null;
for (int i = 0; i < items.size(); i++) {
ImportMetadata item = (ImportMetadata) items.get(i);
if (value.equals(item.getId())) {
result = (ImportMetadata) items.remove(i);
break;
}
}
return result;
}
/**
* Handle the request for remove
*
* @param data
*/
public void doRemove_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("removeImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
zipList.add(removeItems(value, fnlList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Handle the request for copy
*
* @param data
*/
public void doCopyMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "47");
} // doCopy_MtrlSite
/**
* Handle the request for Save
*
* @param data
* @throws ImportException
*/
public void doSaveMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES);
ImportDataSource importDataSource = (ImportDataSource) state
.getAttribute(IMPORT_DATA_SOURCE);
// combine the selected import items with the mandatory import items
fnlList.addAll(directList);
Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size()
+ " top level items");
Log.info("chef", "doSaveMtrlSite() the importDataSource is "
+ importDataSource.getClass().getName());
if (importDataSource instanceof SakaiArchive) {
Log.info("chef",
"doSaveMtrlSite() our data source is a Sakai format");
((SakaiArchive) importDataSource).buildSourceFolder(fnlList);
Log.info("chef", "doSaveMtrlSite() source folder is "
+ ((SakaiArchive) importDataSource).getSourceFolder());
ArchiveService.merge(((SakaiArchive) importDataSource)
.getSourceFolder(), siteId, null);
} else {
importService.doImportItems(importDataSource
.getItemsForCategories(fnlList), siteId);
}
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.removeAttribute(IMPORT_DATA_SOURCE);
state.setAttribute(STATE_TEMPLATE_INDEX, "48");
} // doSave_MtrlSite
public void doSaveMtrlSiteMsg(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
// htripath-end
/**
* Handle the site search request.
*/
public void doSite_search(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the search form field into the state object
String search = StringUtils.trimToNull(data.getParameters().getString(
FORM_SEARCH));
// set the flag to go to the prev page on the next list
if (search == null) {
state.removeAttribute(STATE_SEARCH);
} else {
state.setAttribute(STATE_SEARCH, search);
}
} // doSite_search
/**
* Handle a Search Clear request.
*/
public void doSite_search_clear(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// clear the search
state.removeAttribute(STATE_SEARCH);
} // doSite_search_clear
/**
*
* @param state
* @param context
* @param site
* @return true if there is any roster attached, false otherwise
*/
private boolean coursesIntoContext(SessionState state, Context context,
Site site) {
boolean rv = false;
List providerCourseList = SiteParticipantHelper.getProviderCourseList((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
if (providerCourseList != null && providerCourseList.size() > 0) {
rv = true;
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
Hashtable<String, String> sectionTitles = new Hashtable<String, String>();
for(int i = 0; i < providerCourseList.size(); i++)
{
String sectionId = (String) providerCourseList.get(i);
try
{
Section s = cms.getSection(sectionId);
if (s != null)
{
sectionTitles.put(sectionId, s.getTitle());
}
}
catch (IdNotFoundException e)
{
sectionTitles.put(sectionId, sectionId);
M_log.warn("coursesIntoContext: Cannot find section " + sectionId);
}
}
context.put("providerCourseTitles", sectionTitles);
context.put("providerCourseList", providerCourseList);
}
// put manual requested courses into context
boolean rv2 = courseListFromStringIntoContext(state, context, site, STATE_CM_REQUESTED_SECTIONS, STATE_CM_REQUESTED_SECTIONS, "cmRequestedCourseList");
// put manual requested courses into context
boolean rv3 = courseListFromStringIntoContext(state, context, site, PROP_SITE_REQUEST_COURSE, SITE_MANUAL_COURSE_LIST, "manualCourseList");
return (rv || rv2 || rv3);
}
/**
*
* @param state
* @param context
* @param site
* @param site_prop_name
* @param state_attribute_string
* @param context_string
* @return true if there is any roster attached; false otherwise
*/
private boolean courseListFromStringIntoContext(SessionState state, Context context, Site site, String site_prop_name, String state_attribute_string, String context_string) {
boolean rv = false;
String courseListString = StringUtils.trimToNull(site != null?site.getProperties().getProperty(site_prop_name):null);
if (courseListString != null) {
rv = true;
List courseList = new Vector();
if (courseListString.indexOf("+") != -1) {
courseList = new ArrayList(Arrays.asList(groupProvider.unpackId(courseListString)));
} else {
courseList.add(courseListString);
}
if (state_attribute_string.equals(STATE_CM_REQUESTED_SECTIONS))
{
// need to construct the list of SectionObjects
List<SectionObject> soList = new Vector();
for (int i=0; i<courseList.size();i++)
{
String courseEid = (String) courseList.get(i);
try
{
Section s = cms.getSection(courseEid);
if (s!=null)
{
soList.add(new SectionObject(s));
}
}
catch (IdNotFoundException e)
{
M_log.warn("courseListFromStringIntoContext: cannot find section " + courseEid);
}
}
if (soList.size() > 0)
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, soList);
}
else
{
// the list is of String objects
state.setAttribute(state_attribute_string, courseList);
}
}
context.put(context_string, state.getAttribute(state_attribute_string));
return rv;
}
/**
* buildInstructorSectionsList Build the CourseListItem list for this
* Instructor for the requested Term
*
*/
private void buildInstructorSectionsList(SessionState state,
ParameterParser params, Context context) {
// Site information
// The sections of the specified term having this person as Instructor
context.put("providerCourseSectionList", state
.getAttribute("providerCourseSectionList"));
context.put("manualCourseSectionList", state
.getAttribute("manualCourseSectionList"));
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
// bjones86 - SAK-23256
setTermListForContext( context, state, true, false ); //-> future terms only
context.put(STATE_TERM_COURSE_LIST, state
.getAttribute(STATE_TERM_COURSE_LIST));
context.put("tlang", rb);
} // buildInstructorSectionsList
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state) {
int size = 0;
String search = "";
String userId = SessionManager.getCurrentSessionUserId();
String term = (String) state.getAttribute(STATE_TERM_VIEW_SELECTED);
Map<String,String> termProp = null;
if(term != null && !"".equals(term) && !TERM_OPTION_ALL.equals(term)){
termProp = new HashMap<String,String>();
termProp.put(Site.PROP_SITE_TERM, term);
}
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
search = StringUtils.trimToNull((String) state
.getAttribute(STATE_SEARCH));
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(SiteConstants.SITE_TYPE_ALL)) {
// search for non-user sites, using
// the criteria
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, termProp);
} else if (view.equals(SiteConstants.SITE_TYPE_MYWORKSPACE)) {
// search for a specific user site
// for the particular user id in the
// criteria - exact match only
try {
SiteService.getSite(SiteService
.getUserSiteId(search));
size++;
} catch (IdUnusedException e) {
}
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_DELETED)) {
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY_DELETED,
null, search, null);
} else {
// search for specific type of sites
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
view, search, termProp);
}
}
} else {
Site userWorkspaceSite = null;
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn(this + "sizeResources, template index = 0: Cannot find user "
+ SessionManager.getCurrentSessionUserId()
+ "'s My Workspace site.", e);
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(SiteConstants.SITE_TYPE_ALL)) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
size++;
}
} else {
size++;
}
}
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null);
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_DELETED)) {
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.DELETED,
null,search, null);
} else if (view.equals(SiteConstants.SITE_TYPE_MYWORKSPACE)) {
// get the current user MyWorkspace site
try {
SiteService.getSite(SiteService
.getUserSiteId(userId));
size++;
} catch (IdUnusedException e) {
}
} else {
// search for specific type of sites
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, termProp);
}
}
}
}
// for SiteInfo list page
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
Collection l = (Collection) state.getAttribute(STATE_PARTICIPANT_LIST);
size = (l != null) ? l.size() : 0;
}
return size;
} // sizeResources
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last) {
String search = StringUtils.trimToNull((String) state
.getAttribute(STATE_SEARCH));
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
// get sort type
SortType sortType = null;
String sortBy = (String) state.getAttribute(SORTED_BY);
boolean sortAsc = (Boolean.valueOf((String) state
.getAttribute(SORTED_ASC))).booleanValue();
if (sortBy.equals(SortType.TITLE_ASC.toString())) {
sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC;
} else if (sortBy.equals(SortType.TYPE_ASC.toString())) {
sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC;
} else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_BY_ASC
: SortType.CREATED_BY_DESC;
} else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_ON_ASC
: SortType.CREATED_ON_DESC;
} else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) {
sortType = sortAsc ? SortType.PUBLISHED_ASC
: SortType.PUBLISHED_DESC;
} else if (sortBy.equals(SortType.SOFTLY_DELETED_ASC.toString())) {
sortType = sortAsc ? SortType.SOFTLY_DELETED_ASC
: SortType.SOFTLY_DELETED_DESC;
}
String term = (String) state.getAttribute(STATE_TERM_VIEW_SELECTED);
Map<String,String> termProp = null;
if(term != null && !"".equals(term) && !TERM_OPTION_ALL.equals(term)){
termProp = new HashMap<String,String>();
termProp.put(Site.PROP_SITE_TERM, term);
}
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(SiteConstants.SITE_TYPE_ALL)) {
// search for non-user sites, using the
// criteria
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, termProp, sortType,
new PagingPosition(first, last));
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_MYWORKSPACE)) {
// search for a specific user site for
// the particular user id in the
// criteria - exact match only
List rv = new Vector();
try {
Site userSite = SiteService.getSite(SiteService
.getUserSiteId(search));
rv.add(userSite);
} catch (IdUnusedException e) {
}
return rv;
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_DELETED)) {
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY_DELETED,
null,
search, null, sortType,
new PagingPosition(first, last));
} else {
// search for a specific site
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY,
view, search, termProp, sortType,
new PagingPosition(first, last));
}
}
} else {
List rv = new Vector();
Site userWorkspaceSite = null;
String userId = SessionManager.getCurrentSessionUserId();
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn(this + "readResourcesPage template index = 0 :Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.", e);
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(SiteConstants.SITE_TYPE_ALL)) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
rv.add(userWorkspaceSite);
}
} else {
rv.add(userWorkspaceSite);
}
}
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, termProp, sortType,
new PagingPosition(first, last)));
}
else if (view.equals(SiteConstants.SITE_TYPE_MYWORKSPACE)) {
// get the current user MyWorkspace site
try {
rv.add(SiteService.getSite(SiteService.getUserSiteId(userId)));
} catch (IdUnusedException e) {
}
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_DELETED)) {
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.DELETED,
null,
search, null, sortType,
new PagingPosition(first, last));
} else {
rv.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, termProp, sortType,
new PagingPosition(first, last)));
}
}
return rv;
}
}
// if in Site Info list view
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)): new Vector();
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
Iterator sortedParticipants = null;
if (sortedBy != null) {
sortedParticipants = new SortedIterator(participants
.iterator(), new SiteComparator(sortedBy,sortedAsc,comparator_locale));
participants.clear();
while (sortedParticipants.hasNext()) {
participants.add(sortedParticipants.next());
}
}
PagingPosition page = new PagingPosition(first, last);
page.validate(participants.size());
participants = participants.subList(page.getFirst() - 1, page.getLast());
return participants;
}
return null;
} // readResourcesPage
/**
* get the selected tool ids from import sites
*/
private boolean select_import_tools(ParameterParser params,
SessionState state) {
// has the user selected any tool for importing?
boolean anyToolSelected = false;
Hashtable importTools = new Hashtable();
// the tools for current site
List selectedTools = originalToolIds((List<String>) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST), state); // String
// toolId's
if (selectedTools != null)
{
for (int i = 0; i < selectedTools.size(); i++) {
// any tools chosen from import sites?
String toolId = (String) selectedTools.get(i);
if (params.getStrings(toolId) != null) {
importTools.put(toolId, new ArrayList(Arrays.asList(params
.getStrings(toolId))));
if (!anyToolSelected) {
anyToolSelected = true;
}
}
}
}
state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools);
return anyToolSelected;
} // select_import_tools
/**
* Is it from the ENW edit page?
*
* @return ture if the process went through the ENW page; false, otherwise
*/
private boolean fromENWModifyView(SessionState state) {
boolean fromENW = false;
List oTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
List toolList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (toolList != null)
{
for (int i = 0; i < toolList.size() && !fromENW; i++) {
String toolId = (String) toolList.get(i);
if ("sakai.mailbox".equals(toolId)
|| isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
if (oTools == null) {
// if during site creation proces
fromENW = true;
} else if (!oTools.contains(toolId)) {
// if user is adding either EmailArchive tool, News tool or
// Web Content tool, go to the Customize page for the tool
fromENW = true;
}
}
}
}
return fromENW;
}
/**
* doNew_site is called when the Site list tool bar New... button is clicked
*
*/
public void doNew_site(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// start clean
cleanState(state);
if (state.getAttribute(STATE_INITIALIZED) == null) {
state.setAttribute(STATE_OVERRIDE_TEMPLATE_INDEX, "1");
} else {
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
}
}
} // doNew_site
/**
* doMenu_site_delete is called when the Site list tool bar Delete button is
* clicked
*
*/
public void doMenu_site_delete(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] removals = (String[]) params.getStrings("selectedMembers");
state.setAttribute(STATE_SITE_REMOVALS, removals);
// present confirm delete template
state.setAttribute(STATE_TEMPLATE_INDEX, "8");
} // doMenu_site_delete
/**
* Restore a softly deleted site
*
*/
public void doMenu_site_restore(RunData data) {
SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] toRestore = (String[]) params.getStrings("selectedMembers");
for (String siteId: toRestore) {
try {
Site s = SiteService.getSite(siteId);
//check if softly deleted
if(!s.isSoftlyDeleted()){
M_log.warn("Tried to restore site that has not been marked for deletion: " + siteId);
continue;
}
//reverse it
s.setSoftlyDeleted(false);
SiteService.save(s);
} catch (IdUnusedException e) {
M_log.warn("Error restoring site:" + siteId + ":" + e.getClass() + ":" + e.getMessage());
addAlert(state, rb.getString("softly.deleted.invalidsite"));
} catch (PermissionException e) {
M_log.warn("Error restoring site:" + siteId + ":" + e.getClass() + ":" + e.getMessage());
addAlert(state, rb.getString("softly.deleted.restore.nopermission"));
}
}
} // doSite_restore
public void doSite_delete_confirmed(RunData data) {
if (!"POST".equals(data.getRequest().getMethod())) {
return;
}
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
M_log
.warn("SiteAction.doSite_delete_confirmed selectedMembers null");
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the
// site list
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked sites
if (!chosenList.isEmpty()) {
for (ListIterator i = chosenList.listIterator(); i.hasNext();) {
String id = (String) i.next();
String site_title = NULL_STRING;
if (SiteService.allowRemoveSite(id)) {
try {
Site site = SiteService.getSite(id);
site_title = site.getTitle();
//now delete the site
SiteService.removeSite(site);
M_log.debug("Removed site: " + site.getId());
} catch (IdUnusedException e) {
M_log.warn(this +".doSite_delete_confirmed - IdUnusedException " + id, e);
addAlert(state, rb.getFormattedMessage("java.couldnt", new Object[]{site_title,id}));
} catch (PermissionException e) {
M_log.warn(this + ".doSite_delete_confirmed - PermissionException, site " + site_title + "(" + id + ").", e);
addAlert(state, rb.getFormattedMessage("java.dontperm", new Object[]{site_title}));
}
} else {
M_log.warn(this + ".doSite_delete_confirmed - allowRemoveSite failed for site "+ id);
addAlert(state, rb.getFormattedMessage("java.dontperm", new Object[]{site_title}));
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site
// list
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
} // doSite_delete_confirmed
/**
* get the Site object based on SessionState attribute values
*
* @return Site object related to current state; null if no such Site object
* could be found
*/
protected Site getStateSite(SessionState state) {
return getStateSite(state, false);
} // getStateSite
/**
* get the Site object based on SessionState attribute values
*
* @param autoContext - If true, we fall back to a context if it exists
* @return Site object related to current state; null if no such Site object
* could be found
*/
protected Site getStateSite(SessionState state, boolean autoContext) {
Site site = null;
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
try {
site = SiteService.getSite((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
} catch (Exception ignore) {
}
}
if ( site == null && autoContext ) {
String siteId = ToolManager.getCurrentPlacement().getContext();
try {
site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, siteId);
} catch (Exception ignore) {
}
}
return site;
} // getStateSite
/**
* do called when "eventSubmit_do" is in the request parameters to c is
* called from site list menu entry Revise... to get a locked site as
* editable and to go to the correct template to begin DB version of writes
* changes to disk at site commit whereas XML version writes at server
* shutdown
*/
public void doGet_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// check form filled out correctly
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked
// sites
String siteId = "";
if (!chosenList.isEmpty()) {
if (chosenList.size() != 1) {
addAlert(state, rb.getString("java.please"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
siteId = (String) chosenList.get(0);
getReviseSite(state, siteId);
state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
// reset the paging info
resetPaging(state);
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_PAGESIZE_SITESETUP, state
.getAttribute(STATE_PAGESIZE));
}
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// when first entered Site Info, set the participant list size to
// 200 as default
state.setAttribute(STATE_PAGESIZE, Integer.valueOf(200));
// update
h.put(siteId, Integer.valueOf(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
} else {
// restore the page size in site info tool
state.setAttribute(STATE_PAGESIZE, h.get(siteId));
}
} // doGet_site
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_reuse(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// create a new Site object based on selected Site object and put in
// state
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_reuse
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_revise(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// get site as Site object, check SiteCreationStatus and SiteType of
// site, put in state, and set STATE_TEMPLATE_INDEX correctly
// set mode to state_mode_site_type
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_revise
/**
* doView_sites is called when "eventSubmit_doView_sites" is in the request
* parameters
*/
public void doView_sites(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_VIEW_SELECTED, params.getString("view"));
state.setAttribute(STATE_TERM_VIEW_SELECTED, params.getString("termview"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
resetPaging(state);
} // doView_sites
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doView(RunData data) throws Exception {
// called from chef_site-list.vm with a select option to build query of
// sites
//
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doView
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doSite_type(RunData data) {
/*
* for measuring how long it takes to load sections java.util.Date date =
* new java.util.Date(); M_log.debug("***1. start preparing
* section:"+date);
*/
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("templateIndex"))
.intValue();
actionForTemplate("continue", index, params, state, data);
List<String> pSiteTypes = siteTypeProvider.getTypesForSiteCreation();
String type = StringUtils.trimToNull(params.getString("itemType"));
if (type == null) {
addAlert(state, rb.getString("java.select") + " ");
} else {
state.setAttribute(STATE_TYPE_SELECTED, type);
setNewSiteType(state, type);
if (SiteTypeUtil.isCourseSite(type)) { // UMICH-1035
// redirect
redirectCourseCreation(params, state, "selectTerm");
} else if (SiteTypeUtil.isProjectSite(type)) { // UMICH-1035
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
} else if (pSiteTypes != null && pSiteTypes.contains(SiteTypeUtil.getTargetSiteType(type))) { // UMICH-1035
// if of customized type site use pre-defined site info and exclude
// from public listing
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
User currentUser = UserDirectoryService.getCurrentUser();
List<String> idList = new ArrayList<String>();
idList.add(currentUser.getEid());
List<String> nameList = new ArrayList<String>();
nameList.add(currentUser.getDisplayName());
siteInfo.title = siteTypeProvider.getSiteTitle(type, idList);
siteInfo.description = siteTypeProvider.getSiteDescription(type, nameList);
siteInfo.short_description = siteTypeProvider.getSiteShortDescription(type, idList);
siteInfo.include = false;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// skip directly to confirm creation of site
state.setAttribute(STATE_TEMPLATE_INDEX, "42");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
// get the user selected template
getSelectedTemplate(state, params, type);
}
redirectToQuestionVM(state, type);
} // doSite_type
/**
* see whether user selected any template
* @param state
* @param params
* @param type
*/
private void getSelectedTemplate(SessionState state,
ParameterParser params, String type) {
String templateSiteId = params.getString("selectTemplate" + type);
if (templateSiteId != null)
{
Site templateSite = null;
try
{
templateSite = SiteService.getSite(templateSiteId);
// save the template site in state
state.setAttribute(STATE_TEMPLATE_SITE, templateSite);
// the new site type is based on the template site
setNewSiteType(state, templateSite.getType());
}catch (Exception e) {
// should never happened, as the list of templates are generated
// from existing sites
M_log.warn(this + ".doSite_type" + e.getClass().getName(), e);
state.removeAttribute(STATE_TEMPLATE_SITE);
}
// grab site info from template
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
// copy information from template site
siteInfo.description = templateSite.getDescription();
siteInfo.short_description = templateSite.getShortDescription();
siteInfo.iconUrl = templateSite.getIconUrl();
siteInfo.infoUrl = templateSite.getInfoUrl();
siteInfo.joinable = templateSite.isJoinable();
siteInfo.joinerRole = templateSite.getJoinerRole();
//siteInfo.include = false;
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromSitePropertiesOnSelectTemplate( templateSite.getProperties(), siteInfo );
List<String> toolIdsSelected = new Vector<String>();
List pageList = templateSite.getPages();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
if (pageToolList != null && pageToolList.size() > 0)
{
Tool tConfig = ((ToolConfiguration) pageToolList.get(0)).getTool();
if (tConfig != null)
{
toolIdsSelected.add(tConfig.getId());
}
}
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdsSelected);
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
else
{
// no template selected
state.removeAttribute(STATE_TEMPLATE_SITE);
}
}
/**
* Depend on the setup question setting, redirect the site setup flow
* @param state
* @param type
*/
private void redirectToQuestionVM(SessionState state, String type) {
// SAK-12912: check whether there is any setup question defined
SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions(type);
if (siteTypeQuestions != null)
{
List questionList = siteTypeQuestions.getQuestions();
if (questionList != null && !questionList.isEmpty())
{
// there is at least one question defined for this type
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE, state.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, "54");
}
}
}
}
/**
* Determine whether the selected term is considered of "future term"
* @param state
* @param t
*/
private void isFutureTermSelected(SessionState state) {
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
int weeks = 0;
Calendar c = (Calendar) Calendar.getInstance().clone();
try {
weeks = Integer
.parseInt(ServerConfigurationService
.getString(
"roster.available.weeks.before.term.start",
"0"));
c.add(Calendar.DATE, weeks * 7);
} catch (Exception ignore) {
}
if (t != null && t.getStartDate() != null && c.getTimeInMillis() < t.getStartDate().getTime()) {
// if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.TRUE);
} else {
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.FALSE);
}
}
public void doChange_user(RunData data) {
doSite_type(data);
} // doChange_user
/**
*
*/
private void removeSection(SessionState state, ParameterParser params)
{
// v2.4 - added by daisyf
// RemoveSection - remove any selected course from a list of
// provider courses
// check if any section need to be removed
removeAnyFlagedSection(state, params);
List providerChosenList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
collectNewSiteInfo(state, params, providerChosenList);
}
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doManual_add_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) {
readCourseSectionInfo(state, params);
String uniqname = StringUtils.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
// update site information
SiteInfo siteInfo = state.getAttribute(STATE_SITE_INFO) != null? (SiteInfo) state.getAttribute(STATE_SITE_INFO):new SiteInfo();
if (params.getString("additional") != null) {
siteInfo.additional = params.getString("additional");
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (option.equalsIgnoreCase("add")) {
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null) {
addAlert(state, rb.getFormattedMessage("java.author", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
} else {
// in case of multiple instructors
List instructors = new ArrayList(Arrays.asList(uniqname.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
String eid = StringUtils.trimToEmpty((String) iInstructors.next());
try {
UserDirectoryService.getUserByEid(eid);
} catch (UserNotDefinedException e) {
addAlert(state, rb.getFormattedMessage("java.validAuthor", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
M_log.warn(this + ".doManual_add_course: cannot find user with eid=" + eid, e);
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_TEMPLATE_SITE) != null)
{
// create site based on template
doFinish(data);
}
else
{
if (getStateSite(state) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
}
}
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
} else if (option.equalsIgnoreCase("removeSection"))
{
// remove selected section
removeAnyFlagedSection(state, params);
}
} // doManual_add_course
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doSite_information(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("continue"))
{
doContinue(data);
// if create based on template, skip the feature selection
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
if (templateSite != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
} else if (option.equalsIgnoreCase("removeSection"))
{
// remove selected section
removeSection(state, params);
}
} // doSite_information
/**
* read the input information of subject, course and section in the manual
* site creation page
*/
private void readCourseSectionInfo(SessionState state,
ParameterParser params) {
String option = params.getString("option");
int oldNumber = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
oldNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
// read the user input
int validInputSites = 0;
boolean validInput = true;
List multiCourseInputs = new Vector();
for (int i = 0; i < oldNumber; i++) {
List requiredFields = sectionFieldProvider.getRequiredFields();
List aCourseInputs = new Vector();
int emptyInputNum = 0;
// iterate through all required fields
for (int k = 0; k < requiredFields.size(); k++) {
SectionField sectionField = (SectionField) requiredFields
.get(k);
String fieldLabel = sectionField.getLabelKey();
String fieldInput = StringUtils.trimToEmpty(params
.getString(fieldLabel + i));
sectionField.setValue(fieldInput);
aCourseInputs.add(sectionField);
if (fieldInput.length() == 0) {
// is this an empty String input?
emptyInputNum++;
}
}
// is any input invalid?
if (emptyInputNum == 0) {
// valid if all the inputs are not empty
multiCourseInputs.add(validInputSites++, aCourseInputs);
} else if (emptyInputNum == requiredFields.size()) {
// ignore if all inputs are empty
if (option.equalsIgnoreCase("change"))
{
multiCourseInputs.add(validInputSites++, aCourseInputs);
}
} else {
// input invalid
validInput = false;
}
}
// how many more course/section to include in the site?
if (option.equalsIgnoreCase("change")) {
if (params.getString("number") != null) {
int newNumber = Integer.parseInt(params.getString("number"));
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf(oldNumber + newNumber));
List requiredFields = sectionFieldProvider.getRequiredFields();
for (int j = 0; j < newNumber; j++) {
// add a new course input
List aCourseInputs = new Vector();
// iterate through all required fields
for (int m = 0; m < requiredFields.size(); m++) {
aCourseInputs = sectionFieldProvider.getRequiredFields();
}
multiCourseInputs.add(aCourseInputs);
}
}
}
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs);
if (!option.equalsIgnoreCase("change")) {
if (!validInput || validInputSites == 0) {
// not valid input
addAlert(state, rb.getString("java.miss"));
}
// valid input, adjust the add course number
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf( validInputSites>1?validInputSites:1));
}
// set state attributes
state.setAttribute(FORM_ADDITIONAL, StringUtils.trimToEmpty(params
.getString("additional")));
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
if (siteInfo.title == null || siteInfo.title.length() == 0)
{
// if SiteInfo doesn't have title, construct the title
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
if ((providerCourseList == null || providerCourseList.size() == 0)
&& multiCourseInputs.size() > 0) {
String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(),
(List) multiCourseInputs.get(0));
// default title
String title = sectionFieldProvider.getSectionTitle(t.getEid(), (List) multiCourseInputs.get(0));
try {
Section s = cms.getSection(sectionEid);
title = s != null?s.getTitle():title;
} catch (IdNotFoundException e) {
M_log.warn("readCourseSectionInfo: Cannot find section " + sectionEid);
}
siteInfo.title = title;
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
}
} // readCourseSectionInfo
/**
*
* @param state
* @param type
*/
private void setNewSiteType(SessionState state, String type) {
state.setAttribute(STATE_SITE_TYPE, type);
// start out with fresh site information
SiteInfo siteInfo = new SiteInfo();
siteInfo.site_type = type;
siteInfo.published = true;
User u = UserDirectoryService.getCurrentUser();
if (u != null)
{
siteInfo.site_contact_name=u.getDisplayName();
siteInfo.site_contact_email=u.getEmail();
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
// set tool registration list
if (!"copy".equals(type))
{
setToolRegistrationList(state, type);
}
}
/** SAK16600 insert current site type into context
* @param context current context
* @param type current type
* @return courseSiteType type of 'course'
*/
private void setTypeIntoContext(Context context, String type) {
if (type != null && SiteTypeUtil.isCourseSite(type)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (type != null && SiteTypeUtil.isProjectSite(type)) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
/**
* Set the state variables for tool registration list basd on current site type, save to STATE_TOOL_GROUP_LIST. This list should include
* all tool types - normal, home, multiples and blti. Note that if the toolOrder.xml is in the original format, this list will consist of
* all tools in a single group
* @param state
* @param is type
* @param site
*/
private Map<String,List> getTools(SessionState state, String type, Site site) {
boolean checkhome = state.getAttribute(STATE_TOOL_HOME_SELECTED) != null ?((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED)).booleanValue():true;
boolean isNewToolOrderType = ServerConfigurationService.getBoolean("config.sitemanage.useToolGroup", false);
Map<String,List> toolGroup = new LinkedHashMap<String,List>();
MyTool newTool = null;
File moreInfoDir = new File(moreInfoPath);
List toolList;
// if this is legacy format toolOrder.xml file, get all tools by siteType
if (isNewToolOrderType == false) {
String defaultGroupName = rb.getString("tool.group.default");
toolGroup.put(defaultGroupName, getOrderedToolList(state, defaultGroupName, type, checkhome));
} else {
// get all the groups that are available for this site type
List groups = ServerConfigurationService.getCategoryGroups(SiteTypeUtil.getTargetSiteType(type));
for(Iterator<String> itr = groups.iterator(); itr.hasNext();) {
String groupId = itr.next();
String groupName = getGroupName(groupId);
toolList = getGroupedToolList(groupId, groupName, type, checkhome, moreInfoDir);
if (toolList.size() > 0) {
toolGroup.put(groupName, toolList);
}
}
// add ungroups tools to end of toolGroup list
String ungroupedName = getGroupName(UNGROUPED_TOOL_TITLE);
List ungroupedList = getUngroupedTools(ungroupedName, toolGroup, state, moreInfoDir, site);
if (ungroupedList.size() > 0) {
toolGroup.put(ungroupedName, ungroupedList );
}
}
// add external tools to end of toolGroup list
String externaltoolgroupname = getGroupName(LTI_TOOL_TITLE);
List externalTools = getLtiToolGroup(externaltoolgroupname, moreInfoDir, site);
if (externalTools.size() > 0 )
toolGroup.put(externaltoolgroupname, externalTools);
// Home page should be auto-selected
if (checkhome==true) {
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(true));
}
// refresh selectedList
List<String> selectedTools = new ArrayList<String>();
for(Iterator itr = toolGroup.keySet().iterator(); itr.hasNext(); ) {
String key = (String) itr.next();
List toolGroupSelectedList =(List) toolGroup.get(key);
for (Iterator listItr = toolGroupSelectedList.iterator(); listItr.hasNext();) {
MyTool tool = (MyTool) listItr.next();
if (tool.selected) {
selectedTools.add(tool.id);
}
}
}
return toolGroup;
}
/**
* Get ordered, ungrouped list of tools
* @param groupName - name of default group to add all tools
* @param type - site type
* @param checkhome
*/
private List getOrderedToolList(SessionState state, String groupName, String type, boolean checkhome) {
MyTool newTool = null;
List toolsInOrderedList = new ArrayList();
// see setToolRegistrationList()
List toolList = (List)state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// mark the required tools
List requiredTools = ServerConfigurationService.getToolsRequired(SiteTypeUtil.getTargetSiteType(type));
// add Home tool only once
boolean hasHomeTool = false;
for (Iterator itr = toolList.iterator(); itr.hasNext(); )
{
MyTool tr = (MyTool)itr.next();
String toolId = tr.getId();
if (TOOL_ID_HOME.equals(tr.getId()))
{
hasHomeTool = true;
}
if (tr != null) {
newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
newTool.group = groupName;
if (requiredTools != null && requiredTools.contains(toolId))
newTool.required = true;
toolsInOrderedList.add(newTool);
}
}
if (!hasHomeTool)
{
// add Home tool to the front of the tool list
newTool = new MyTool();
newTool.id = TOOL_ID_HOME;
newTool.selected = checkhome;
newTool.required = false;
newTool.multiple = false;
toolsInOrderedList.add(0, newTool);
}
return toolsInOrderedList;
}
// SAK-23811
private List getGroupedToolList(String groupId, String groupName, String type, boolean checkhome, File moreInfoDir ) {
List toolsInGroup = new ArrayList();
MyTool newTool = null;
List toolList = ServerConfigurationService.getToolGroup(groupId);
// empty list
if (toolList != null) {
for(Iterator<String> iter = toolList.iterator(); iter.hasNext();) {
String id = iter.next();
String relativeWebPath = null;
if (id.equals(TOOL_ID_HOME)) { // SAK-23208
newTool = new MyTool();
newTool.id = id;
newTool.title = rb.getString("java.home");
newTool.description = rb.getString("java.home");
newTool.selected = checkhome;
newTool.required = ServerConfigurationService.toolGroupIsRequired(groupId,TOOL_ID_HOME);
newTool.multiple = false;
} else {
Tool tr = ToolManager.getTool(id);
if (tr != null)
{
String toolId = tr.getId();
if (isSiteTypeInToolCategory(SiteTypeUtil.getTargetSiteType(type), tr) && notStealthOrHiddenTool(toolId) ) // SAK 23808
{
newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = toolId;
newTool.description = tr.getDescription();
newTool.group = groupName;
newTool.moreInfo = getMoreInfoUrl(moreInfoDir, toolId);
newTool.required = ServerConfigurationService.toolGroupIsRequired(groupId,toolId);
newTool.selected = ServerConfigurationService.toolGroupIsSelected(groupId,toolId);
// does tool allow multiples and if so are they already defined?
newTool.multiple = isMultipleInstancesAllowed(toolId); // SAK-16600 - this flag will allow action for template#3 to massage list into new format
}
}
}
if (newTool != null) {
toolsInGroup.add(newTool);
newTool = null;
}
}
}
M_log.debug(groupName + ": loaded " + new Integer(toolsInGroup.size()).toString() + " tools");
return toolsInGroup;
}
/*
* Given groupId, return localized name from tools.properties
*/
private String getGroupName(String groupId) {
// undefined group will return standard '[missing key]' error string
return ToolManager.getLocalizedToolProperty(groupId,"title");
}
/*
* Using moreInfoDir, if toolId is found in the dir return path otherwise return null
*/
private String getMoreInfoImg(File infoDir, String toolId) {
String moreInfoUrl = null;
try {
Collection<File> files = FileUtils.listFiles(infoDir, new WildcardFileFilter(toolId+"*"), null);
if (files.isEmpty()==false) {
File mFile = files.iterator().next();
moreInfoUrl = libraryPath + mFile.getName(); // toolId;
}
} catch (Exception e) {
M_log.info("unable to read moreinfo: " + e.getMessage() );
}
return moreInfoUrl;
}
/*
* Using moreInfoDir, if toolId is found in the dir return path otherwise return null
*/
private String getMoreInfoUrl(File infoDir, String toolId) {
String moreInfoUrl = null;
try {
Collection<File> files = FileUtils.listFiles(infoDir, new WildcardFileFilter(toolId+"*"), null);
if (files.isEmpty()==false) {
File mFile = files.iterator().next();
moreInfoUrl = libraryPath + mFile.getName(); // toolId;
}
} catch (Exception e) {
M_log.info("unable to read moreinfo" + e.getMessage());
}
return moreInfoUrl;
}
/* SAK-16600 given list, return only those tools tha are BLTI
* NOTE - this method is not yet used
* @param selToolList list where tool.selected = true
* @return list of tools that are selected and blti
*/
private List<String> getToolGroupLtiTools(List<String> selToolList) {
List<String> onlyLtiTools = new ArrayList<String>();
List<Map<String, Object>> allTools = m_ltiService.getTools(null, null,0, 0);
if (allTools != null && !allTools.isEmpty()) {
for (Map<String, Object> tool : allTools) {
Set keySet = tool.keySet();
Integer ltiId = (Integer) tool.get("id");
if (ltiId != null) {
String toolId = ltiId.toString();
if (selToolList.contains(toolId)) {
onlyLtiTools.add(toolId);
}
}
}
}
return onlyLtiTools;
}
/* SAK-16600 return selected list with blti tools removed
* NOTE this method is not yet used
* @param selToolList list where tool.selected = true
* @return list of tools that are selected and not blti
*/
private List<String> removeLtiTools(List<String> selToolList) {
List<String> noLtiList = new ArrayList<String>();
noLtiList.addAll(selToolList);
List<String> ltiList = new ArrayList<String>();
List<Map<String, Object>> allTools = m_ltiService.getTools(null, null,0, 0);
if (allTools != null && !allTools.isEmpty()) {
for (Map<String, Object> tool : allTools) {
Set keySet = tool.keySet();
Integer ltiId = (Integer) tool.get("id");
if (ltiId != null) {
String toolId = ltiId.toString();
if (!ltiList.contains(toolId)) {
ltiList.add(toolId);
}
}
}
}
boolean result = noLtiList.removeAll(ltiList);
return noLtiList;
}
private List selectedLTITools(Site site) {
List selectedLTI = new ArrayList();
if (site !=null) {
String siteId = site.getId();
List<Map<String,Object>> contents = m_ltiService.getContents(null,null,0,0);
HashMap<String, Map<String, Object>> linkedLtiContents = new HashMap<String, Map<String, Object>>();
for ( Map<String,Object> content : contents ) {
String ltiToolId = content.get(m_ltiService.LTI_TOOL_ID).toString();
String ltiSiteId = StringUtils.trimToNull((String) content.get(m_ltiService.LTI_SITE_ID));
if ((ltiSiteId!=null) && ltiSiteId.equals(siteId)) {
selectedLTI.add(ltiToolId);
}
}
}
return selectedLTI;
}
// SAK-16600 find selected flag for ltiTool
// MAR25 create list of all selected ltitools
private boolean isLtiToolInSite(Long toolId, String siteId) {
if (siteId==null) return false;
Map<String,Object> toolProps= m_ltiService.getContent(toolId, siteId); // getTool(toolId);
if (toolProps==null){
return false;
} else {
String toolSite = StringUtils.trimToNull((String) toolProps.get(m_ltiService.LTI_SITE_ID));
return siteId.equals(toolSite);
}
}
/* SAK 16600 if toolGroup mode is active; and toolGroups don't use all available tools, put remaining tools into
* 'ungrouped' group having name 'GroupName'
* @param moreInfoDir file pointer to directory of MoreInfo content
* @param site current site
* @return list of MyTool items
*/
private List getUngroupedTools(String ungroupedName, Map<String,List> toolsByGroup, SessionState state, File moreInforDir, Site site) {
// Get all tools for site
List ungroupedToolsOld = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// copy the list of tools to avoid ConcurrentModificationException
List<MyTool> ungroupedTools = new Vector<MyTool>();
if ( ungroupedToolsOld != null )
ungroupedTools.addAll(ungroupedToolsOld);
// get all the tool groups that are available for this site
for (Iterator<String> toolgroupitr = toolsByGroup.keySet().iterator(); toolgroupitr.hasNext();) {
String groupName = toolgroupitr.next();
List toolList = toolsByGroup.get(groupName);
for (Iterator toollistitr = toolList.iterator(); toollistitr.hasNext();) {
MyTool ungroupedTool = (MyTool) toollistitr.next();
if (ungroupedTools.contains(ungroupedTool)) {
// remove all tools that are in a toolGroup list
ungroupedTools.remove(ungroupedTool);
}
}
}
// remove all toolMultiples
Map toolMultiples = getToolGroupMultiples(state, ungroupedTools);
if (toolMultiples != null) {
for(Iterator tmiter = toolMultiples.keySet().iterator(); tmiter.hasNext();) {
String toolId = (String) tmiter.next();
List multiToolList = (List) toolMultiples.get(toolId);
for (Iterator toollistitr = multiToolList.iterator(); toollistitr.hasNext();) {
MyTool multitoolId = (MyTool) toollistitr.next();
if (ungroupedTools.contains(multitoolId)){
ungroupedTools.remove(multitoolId);
}
}
}
}
// assign group name to all remaining tools
for (Iterator listitr = ungroupedTools.iterator(); listitr.hasNext(); ) {
MyTool tool = (MyTool) listitr.next();
tool.group = ungroupedName;
}
return ungroupedTools;
}
/* SAK 16600 Create list of ltitools to add to toolgroups; set selected for those
// tools already added to a sites with properties read to add to toolsByGroup list
* @param groupName name of the current group
* @param moreInfoDir file pointer to directory of MoreInfo content
* @param site current site
* @return list of MyTool items
*/
private List getLtiToolGroup(String groupName, File moreInfoDir, Site site) {
List ltiSelectedTools = selectedLTITools(site);
List ltiTools = new ArrayList();
List<Map<String, Object>> allTools = m_ltiService.getTools(null, null,
0, 0);
if (allTools != null && !allTools.isEmpty()) {
for (Map<String, Object> tool : allTools) {
Set keySet = tool.keySet();
String toolIdString = tool.get(m_ltiService.LTI_ID).toString();
try
{
// in Oracle, the lti tool id is returned as BigDecimal, which cannot be casted into Integer directly
Integer ltiId = Integer.valueOf(toolIdString);
if (ltiId != null) {
String ltiToolId = ltiId.toString();
if (ltiToolId != null) {
String relativeWebPath = null;
MyTool newTool = new MyTool();
newTool.title = tool.get("title").toString();
newTool.id = LTITOOL_ID_PREFIX + ltiToolId;
newTool.description = (String) tool.get("description");
newTool.group = groupName;
relativeWebPath = getMoreInfoUrl(moreInfoDir, ltiToolId);
if (relativeWebPath != null) {
newTool.moreInfo = relativeWebPath;
}
// SAK16600 should this be a property or specified in toolOrder.xml?
newTool.required = false;
newTool.selected = ltiSelectedTools.contains(ltiToolId);
ltiTools.add(newTool);
}
}
}
catch (NumberFormatException e)
{
M_log.error(this + " Cannot cast tool id String " + toolIdString + " into integer value.");
}
}
}
return ltiTools;
}
/**
* Set the state variables for tool registration list basd on site type
* @param state
* @param type
*/
private void setToolRegistrationList(SessionState state, String type) {
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
// get the tool id set which allows for multiple instances
Set multipleToolIdSet = new HashSet();
HashMap multipleToolConfiguration = new HashMap<String, HashMap<String, String>>();
// get registered tools list
Set categories = new HashSet();
categories.add(type);
categories.add(SiteTypeUtil.getTargetSiteType(type)); // UMICH-1035
Set toolRegistrations = ToolManager.findTools(categories, null);
if ((toolRegistrations == null || toolRegistrations.size() == 0)
&& state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
// use default site type and try getting tools again
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
categories.clear();
categories.add(SiteTypeUtil.getTargetSiteType(type)); //UMICH-1035
toolRegistrations = ToolManager.findTools(categories, null);
}
List tools = new Vector();
SortedIterator i = new SortedIterator(toolRegistrations.iterator(),
new ToolComparator());
for (; i.hasNext();) {
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
String originalToolId = findOriginalToolId(state, tr.getId());
if (isMultipleInstancesAllowed(originalToolId))
{
// of a tool which allows multiple instances
multipleToolIdSet.add(tr.getId());
// get the configuration for multiple instance
HashMap<String, String> toolConfigurations = getMultiToolConfiguration(originalToolId, null);
multipleToolConfiguration.put(tr.getId(), toolConfigurations);
}
tools.add(newTool);
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration);
}
/**
* Set the field on which to sort the list of students
*
*/
public void doSort_roster(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the field on which to sort the student list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort_roster
/**
* Set the field on which to sort the list of sites
*
*/
public void doSort_sites(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// call this method at the start of a sort for proper paging
resetPaging(state);
// get the field on which to sort the site list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
state.setAttribute(SORTED_BY, criterion);
} // doSort_sites
/**
* doContinue is called when "eventSubmit_doContinue" is in the request
* parameters
*/
public void doContinue(RunData data) {
// Put current form data in state and continue to the next template,
// make any permanent changes
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("templateIndex"))
.intValue();
// Let actionForTemplate know to make any permanent changes before
// continuing to the next template
String direction = "continue";
String option = params.getString("option");
actionForTemplate(direction, index, params, state, data);
if (state.getAttribute(STATE_MESSAGE) == null) {
if (index == 36 && ("add").equals(option)) {
// this is the Add extra Roster(s) case after a site is created
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
} else if (params.getString("continue") != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
}
}
}// doContinue
/**
* handle with continue add new course site options
*
*/
public void doContinue_new_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = data.getParameters().getString("option");
if ("continue".equals(option)) {
doContinue(data);
} else if ("cancel".equals(option)) {
doCancel_create(data);
} else if ("back".equals(option)) {
doBack(data);
} else if ("cancel".equals(option)) {
doCancel_create(data);
} else if ("norosters".equals(option)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
else if (option.equalsIgnoreCase("change_user")) { // SAK-22915
doChange_user(data);
}
else if (option.equalsIgnoreCase("change")) {
// change term
String termId = params.getString("selectTerm");
AcademicSession t = cms.getAcademicSession(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
isFutureTermSelected(state);
} else if (option.equalsIgnoreCase("cancel_edit")) {
// cancel
doCancel(data);
} else if (option.equalsIgnoreCase("add")) {
isFutureTermSelected(state);
// continue
doContinue(data);
}
} // doContinue_new_course
/**
* doBack is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward
* direction
*/
public void doBack(RunData data) {
// Put current form data in state and return to the previous template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int currentIndex = Integer.parseInt((String) state
.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
// Let actionForTemplate know not to make any permanent changes before
// continuing to the next template
String direction = "back";
actionForTemplate(direction, currentIndex, params, state, data);
// remove the last template index from the list
removeLastIndexInStateVisitedTemplates(state);
}// doBack
/**
* doFinish is called when a site has enough information to be saved as an
* unpublished site
*/
public void doFinish(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
addNewSite(params, state);
Site site = getStateSite(state);
// SAK-23468 Add new site params to state
setNewSiteStateParameters(site, state);
// Since the option to input aliases is presented to users prior to
// the new site actually being created, it doesn't really make sense
// to check permissions on the newly created site when we assign
// aliases, hence the advisor here.
//
// Set site aliases before dealing with tools b/c site aliases
// are more general and can, for example, serve the same purpose
// as mail channel aliases but the reverse is not true.
if ( aliasAssignmentForNewSitesEnabled(state) ) {
SecurityService.pushAdvisor(new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
if ( AliasService.SECURE_ADD_ALIAS.equals(function) ||
AliasService.SECURE_UPDATE_ALIAS.equals(function) ) {
return SecurityAdvice.ALLOWED;
}
return SecurityAdvice.PASS;
}
});
try {
setSiteReferenceAliases(state, site.getId()); // sets aliases for the site entity itself
} finally {
SecurityService.popAdvisor();
}
}
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
if (templateSite == null)
{
// normal site creation: add the features.
saveFeatures(params, state, site);
try {
site = SiteService.getSite(site.getId());
} catch (Exception ee) {
M_log.error(this + "doFinish: unable to reload site " + site.getId() + " after copying tools");
}
}
else
{
// creating based on template
if (state.getAttribute(STATE_TEMPLATE_SITE_COPY_CONTENT) != null)
{
// create based on template: skip add features, and copying all the contents from the tools in template site
importToolContent(templateSite.getId(), site, true);
try {
site = SiteService.getSite(site.getId());
} catch (Exception ee) {
M_log.error(this + "doFinish: unable to reload site " + site.getId() + " after importing tools");
}
}
// copy members
if(state.getAttribute(STATE_TEMPLATE_SITE_COPY_USERS) != null)
{
try
{
AuthzGroup templateGroup = authzGroupService.getAuthzGroup(templateSite.getReference());
AuthzGroup newGroup = authzGroupService.getAuthzGroup(site.getReference());
for(Iterator mi = templateGroup.getMembers().iterator();mi.hasNext();) {
Member member = (Member) mi.next();
if (newGroup.getMember(member.getUserId()) == null)
{
// only add those user who is not in the new site yet
newGroup.addMember(member.getUserId(), member.getRole().getId(), member.isActive(), member.isProvided());
}
}
authzGroupService.save(newGroup);
}
catch (Exception copyUserException)
{
M_log.warn(this + "doFinish: copy user exception template site =" + templateSite.getReference() + " new site =" + site.getReference() + " " + copyUserException.getMessage());
}
}
else
{
// if not bringing user over, remove the provider information
try
{
AuthzGroup newGroup = authzGroupService.getAuthzGroup(site.getReference());
newGroup.setProviderGroupId(null);
authzGroupService.save(newGroup);
// make sure current user stays in the site
newGroup = authzGroupService.getAuthzGroup(site.getReference());
String currentUserId = UserDirectoryService.getCurrentUser().getId();
if (newGroup.getUserRole(currentUserId) == null)
{
// add advisor
SecurityService.pushAdvisor(new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
});
newGroup.addMember(currentUserId, newGroup.getMaintainRole(), true, false);
authzGroupService.save(newGroup);
// remove advisor
SecurityService.popAdvisor();
}
}
catch (Exception removeProviderException)
{
M_log.warn(this + "doFinish: remove provider id " + " new site =" + site.getReference() + " " + removeProviderException.getMessage());
}
try {
site = SiteService.getSite(site.getId());
} catch (Exception ee) {
M_log.error(this + "doFinish: unable to reload site " + site.getId() + " after updating roster.");
}
}
// We don't want the new site to automatically be a template
site.getPropertiesEdit().removeProperty("template");
// publish the site or not based on the template choice
site.setPublished(state.getAttribute(STATE_TEMPLATE_PUBLISH) != null?true:false);
userNotificationProvider.notifyTemplateUse(templateSite, UserDirectoryService.getCurrentUser(), site);
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
// for course sites
String siteType = site.getType();
if (SiteTypeUtil.isCourseSite(siteType)) {
AcademicSession term = null;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
rp.addProperty(Site.PROP_SITE_TERM, term.getTitle());
rp.addProperty(Site.PROP_SITE_TERM_EID, term.getEid());
}
// update the site and related realm based on the rosters chosen or requested
updateCourseSiteSections(state, site.getId(), rp, term);
}
else
{
// for non course type site, send notification email
sendSiteNotification(state, getStateSite(state), null);
}
// commit site
commitSite(site);
//merge uploaded archive if required
if(state.getAttribute(STATE_CREATE_FROM_ARCHIVE) == Boolean.TRUE) {
doMergeArchiveIntoNewSite(site.getId(), state);
}
if (templateSite == null)
{
// save user answers
saveSiteSetupQuestionUserAnswers(state, site.getId());
}
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
// clean state variables
cleanState(state);
if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) {
state.setAttribute(SiteHelper.SITE_CREATE_SITE_ID, site.getId());
state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE);
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
}// doFinish
/**
* get one alias for site, if it exists
* @param reference
* @return
*/
private String getSiteAlias(String reference)
{
String alias = null;
if (reference != null)
{
// get the email alias when an Email Archive tool has been selected
List aliases = AliasService.getAliases(reference, 1, 1);
if (aliases.size() > 0) {
alias = ((Alias) aliases.get(0)).getId();
}
}
return alias;
}
/**
* Processes site entity aliases associated with the {@link SiteInfo}
* object currently cached in the session. Checked exceptions during
* processing of any given alias results in an alert and a log message,
* but all aliases will be processed. This behavior is an attempt to be
* consistent with established, heads-down style request processing
* behaviors, e.g. in {@link #doFinish(RunData)}.
*
* <p>Processing should work for both site creation and modification.</p>
*
* <p>Implements no permission checking of its own, so insufficient permissions
* will result in an alert being cached in the current session. Thus it
* is typically appropriate for the caller to check permissions first,
* especially because insufficient permissions may result in a
* misleading {@link SiteInfo) state. Specifically, the alias collection
* is likely empty, which is consistent with handling of other read-only
* fields in that object, but which would cause this method to attempt
* to delete all aliases for the current site.</p>
*
* <p>Exits quietly if no {@link SiteInfo} object has been cached under
* the {@link #STATE_SITE_INFO} key.</p>
*
* @param state
* @param siteId
*/
private void setSiteReferenceAliases(SessionState state, String siteId) {
SiteInfo siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
if ( siteInfo == null ) {
return;
}
String siteReference = SiteService.siteReference(siteId);
List<String> existingAliasIds = toIdList(AliasService.getAliases(siteReference));
Set<String> proposedAliasIds = siteInfo.siteRefAliases;
Set<String> aliasIdsToDelete = new HashSet<String>(existingAliasIds);
aliasIdsToDelete.removeAll(proposedAliasIds);
Set<String> aliasIdsToAdd = new HashSet<String>(proposedAliasIds);
aliasIdsToAdd.removeAll(existingAliasIds);
for ( String aliasId : aliasIdsToDelete ) {
try {
AliasService.removeAlias(aliasId);
} catch ( PermissionException e ) {
addAlert(state, rb.getFormattedMessage("java.delalias", new Object[]{aliasId}));
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getFormattedMessage("java.delalias", new Object[]{aliasId}), e);
} catch ( IdUnusedException e ) {
// no problem
} catch ( InUseException e ) {
addAlert(state, rb.getFormattedMessage("java.delalias", new Object[]{aliasId}) + rb.getFormattedMessage("java.alias.locked", new Object[]{aliasId}));
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getFormattedMessage("java.delalias", new Object[]{aliasId}) + rb.getFormattedMessage("java.alias.locked", new Object[]{aliasId}), e);
}
}
for ( String aliasId : aliasIdsToAdd ) {
try {
AliasService.setAlias(aliasId, siteReference);
} catch ( PermissionException e ) {
addAlert(state, rb.getString("java.addalias") + " ");
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getString("java.addalias"), e);
} catch ( IdInvalidException e ) {
addAlert(state, rb.getFormattedMessage("java.alias.isinval", new Object[]{aliasId}));
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getFormattedMessage("java.alias.isinval", new Object[]{aliasId}), e);
} catch ( IdUsedException e ) {
addAlert(state, rb.getFormattedMessage("java.alias.exists", new Object[]{aliasId}));
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getFormattedMessage("java.alias.exists", new Object[]{aliasId}), e);
}
}
}
/**
* save user answers
* @param state
* @param siteId
*/
private void saveSiteSetupQuestionUserAnswers(SessionState state,
String siteId) {
// update the database with user answers to SiteSetup questions
if (state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER) != null)
{
Set<SiteSetupUserAnswer> userAnswers = (Set<SiteSetupUserAnswer>) state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER);
for(Iterator<SiteSetupUserAnswer> aIterator = userAnswers.iterator(); aIterator.hasNext();)
{
SiteSetupUserAnswer userAnswer = aIterator.next();
userAnswer.setSiteId(siteId);
// save to db
questionService.saveSiteSetupUserAnswer(userAnswer);
}
}
}
/**
* Update course site and related realm based on the roster chosen or requested
* @param state
* @param siteId
* @param rp
* @param term
*/
private void updateCourseSiteSections(SessionState state, String siteId, ResourcePropertiesEdit rp, AcademicSession term) {
// whether this is in the process of editing a site?
boolean editingSite = ((String)state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITEINFO)?true:false;
List providerCourseList = state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) == null ? new ArrayList() : (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
int manualAddNumber = 0;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
manualAddNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
}
List<SectionObject> cmRequestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
String realm = SiteService.siteReference(siteId);
if ((providerCourseList != null)
&& (providerCourseList.size() != 0)) {
try {
AuthzGroup realmEdit = AuthzGroupService
.getAuthzGroup(realm);
String providerRealm = buildExternalRealm(siteId, state,
providerCourseList, StringUtils.trimToNull(realmEdit.getProviderGroupId()));
realmEdit.setProviderGroupId(providerRealm);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".updateCourseSiteSections: IdUnusedException, not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.realm"));
}
catch (AuthzPermissionException e)
{
M_log.warn(this + rb.getString("java.notaccess"));
addAlert(state, rb.getString("java.notaccess"));
}
sendSiteNotification(state, getStateSite(state), providerCourseList);
//Track add changes
trackRosterChanges(org.sakaiproject.site.api.SiteService.EVENT_SITE_ROSTER_ADD,providerCourseList);
}
if (manualAddNumber != 0) {
// set the manual sections to the site property
String manualSections = rp.getProperty(PROP_SITE_REQUEST_COURSE) != null?rp.getProperty(PROP_SITE_REQUEST_COURSE)+"+":"";
// manualCourseInputs is a list of a list of SectionField
List manualCourseInputs = (List) state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < manualAddNumber; j++) {
manualSections = manualSections.concat(
sectionFieldProvider.getSectionEid(
term.getEid(),
(List) manualCourseInputs.get(j)))
.concat("+");
}
// trim the trailing plus sign
manualSections = trimTrailingString(manualSections, "+");
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
// send request
sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs, "manual");
}
if (cmRequestedSections != null
&& cmRequestedSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) {
// set the cmRequest sections to the site property
String cmRequestedSectionString = "";
if (!editingSite)
{
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < cmRequestedSections.size(); j++) {
cmRequestedSectionString = cmRequestedSectionString.concat(( cmRequestedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+");
sendSiteRequest(state, "new", cmRequestedSections.size(), cmRequestedSections, "cmRequest");
}
else
{
cmRequestedSectionString = rp.getProperty(STATE_CM_REQUESTED_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_REQUESTED_SECTIONS):"";
// get the selected cm section
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null )
{
List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmRequestedSectionString.length() != 0)
{
cmRequestedSectionString = cmRequestedSectionString.concat("+");
}
for (int j = 0; j < cmSelectedSections.size(); j++) {
cmRequestedSectionString = cmRequestedSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+");
sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest");
}
}
// update site property
if (cmRequestedSectionString.length() > 0)
{
rp.addProperty(STATE_CM_REQUESTED_SECTIONS, cmRequestedSectionString);
}
else
{
rp.removeProperty(STATE_CM_REQUESTED_SECTIONS);
}
}
if (cmAuthorizerSections != null
&& cmAuthorizerSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) {
// set the cmAuthorizer sections to the site property
String cmAuthorizerSectionString = "";
if (!editingSite)
{
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < cmAuthorizerSections.size(); j++) {
cmAuthorizerSectionString = cmAuthorizerSectionString.concat(( cmAuthorizerSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmAuthorizerSectionString = trimTrailingString(cmAuthorizerSectionString, "+");
sendSiteRequest(state, "new", cmAuthorizerSections.size(), cmAuthorizerSections, "cmRequest");
}
else
{
cmAuthorizerSectionString = rp.getProperty(STATE_CM_AUTHORIZER_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_AUTHORIZER_SECTIONS):"";
// get the selected cm section
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null )
{
List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmAuthorizerSectionString.length() != 0)
{
cmAuthorizerSectionString = cmAuthorizerSectionString.concat("+");
}
for (int j = 0; j < cmSelectedSections.size(); j++) {
cmAuthorizerSectionString = cmAuthorizerSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmAuthorizerSectionString = trimTrailingString(cmAuthorizerSectionString, "+");
sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest");
}
}
// update site property
if (cmAuthorizerSectionString.length() > 0)
{
rp.addProperty(STATE_CM_AUTHORIZER_SECTIONS, cmAuthorizerSectionString);
}
else
{
rp.removeProperty(STATE_CM_AUTHORIZER_SECTIONS);
}
}
}
/**
* Trim the trailing occurance of specified string
* @param cmRequestedSectionString
* @param trailingString
* @return
*/
private String trimTrailingString(String cmRequestedSectionString, String trailingString) {
if (cmRequestedSectionString.endsWith(trailingString)) {
cmRequestedSectionString = cmRequestedSectionString.substring(0, cmRequestedSectionString.lastIndexOf(trailingString));
}
return cmRequestedSectionString;
}
/**
* buildExternalRealm creates a site/realm id in one of three formats, for a
* single section, for multiple sections of the same course, or for a
* cross-listing having multiple courses
*
* @param sectionList
* is a Vector of CourseListItem
* @param id
* The site id
*/
private String buildExternalRealm(String id, SessionState state,
List<String> providerIdList, String existingProviderIdString) {
String realm = SiteService.siteReference(id);
if (!AuthzGroupService.allowUpdate(realm)) {
addAlert(state, rb.getString("java.rosters"));
return null;
}
List<String> allProviderIdList = new Vector<String>();
// see if we need to keep existing provider settings
if (existingProviderIdString != null)
{
allProviderIdList.addAll(Arrays.asList(groupProvider.unpackId(existingProviderIdString)));
}
// update the list with newly added providers
allProviderIdList.addAll(providerIdList);
if (allProviderIdList == null || allProviderIdList.size() == 0)
return null;
String[] providers = new String[allProviderIdList.size()];
providers = (String[]) allProviderIdList.toArray(providers);
String providerId = groupProvider.packId(providers);
return providerId;
} // buildExternalRealm
/**
* Notification sent when a course site needs to be set up by Support
*
*/
private void sendSiteRequest(SessionState state, String request,
int requestListSize, List requestFields, String fromContext) {
User cUser = UserDirectoryService.getCurrentUser();
String sendEmailToRequestee = null;
StringBuilder buf = new StringBuilder();
boolean requireAuthorizer = ServerConfigurationService.getString("wsetup.requireAuthorizer", "true").equals("true")?true:false;
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
// get the request replyTo email from configuration
String requestReplyToEmail = getSetupRequestReplyToEmailAddress();
if (requestEmail != null) {
String officialAccountName = ServerConfigurationService
.getString("officialAccountName", "");
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
AcademicSession term = null;
boolean termExist = false;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
termExist = true;
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
}
String productionSiteName = ServerConfigurationService
.getServerName();
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String content = NULL_STRING;
String sessionUserName = cUser.getDisplayName();
String additional = NULL_STRING;
if ("new".equals(request)) {
additional = siteInfo.getAdditional();
} else {
additional = (String) state.getAttribute(FORM_ADDITIONAL);
}
boolean isFutureTerm = false;
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
isFutureTerm = true;
}
// there is no offical instructor for future term sites
String requestId = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
// SAK-18976:Site Requests Generated by entering instructor's User ID fail to add term properties and fail to send site request approval email
List<String> authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
if (authorizerList == null) {
authorizerList = new ArrayList();
}
if (requestId != null) {
// in case of multiple instructors
List instructors = new ArrayList(Arrays.asList(requestId.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
String instructorId = (String) iInstructors.next();
authorizerList.add(instructorId);
}
}
String requestSectionInfo = "";
// requested sections
if ("manual".equals(fromContext))
{
requestSectionInfo = addRequestedSectionIntoNotification(state, requestFields);
}
else if ("cmRequest".equals(fromContext))
{
requestSectionInfo = addRequestedCMSectionIntoNotification(state, requestFields);
}
String authorizerNotified = "";
String authorizerNotNotified = "";
if (!isFutureTerm) {
for (Iterator iInstructors = authorizerList.iterator(); iInstructors.hasNext();)
{
String instructorId = (String) iInstructors.next();
if (requireAuthorizer)
{
// 1. email to course site authorizer
boolean result = userNotificationProvider.notifyCourseRequestAuthorizer(instructorId, requestEmail, requestReplyToEmail, term != null? term.getTitle():"", requestSectionInfo, title, id, additional, productionSiteName);
if (!result)
{
// append authorizer who doesn't received an notification
authorizerNotNotified += instructorId + ", ";
}
else
{
// append authorizer who does received an notification
authorizerNotified += instructorId + ", ";
}
}
}
}
// 2. email to system support team
String supportEmailContent = userNotificationProvider.notifyCourseRequestSupport(requestEmail, productionSiteName, request, term != null?term.getTitle():"", requestListSize, requestSectionInfo,
officialAccountName, title, id, additional, requireAuthorizer, authorizerNotified, authorizerNotNotified);
// 3. email to site requeser
userNotificationProvider.notifyCourseRequestRequester(requestEmail, supportEmailContent, term != null?term.getTitle():"");
// revert the locale to system default
rb.setContextLocale(Locale.getDefault());
state.setAttribute(REQUEST_SENT, Boolean.valueOf(true));
} // if
// reset locale to user default
rb.setContextLocale(null);
} // sendSiteRequest
private String addRequestedSectionIntoNotification(SessionState state, List requestFields) {
StringBuffer buf = new StringBuffer();
// what are the required fields shown in the UI
List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector();
for (int i = 0; i < requiredFields.size(); i++) {
List requiredFieldList = (List) requestFields
.get(i);
for (int j = 0; j < requiredFieldList.size(); j++) {
SectionField requiredField = (SectionField) requiredFieldList
.get(j);
buf.append(requiredField.getLabelKey() + "\t"
+ requiredField.getValue() + "\n");
}
buf.append("\n");
}
return buf.toString();
}
private String addRequestedCMSectionIntoNotification(SessionState state, List cmRequestedSections) {
StringBuffer buf = new StringBuffer();
// what are the required fields shown in the UI
for (int i = 0; i < cmRequestedSections.size(); i++) {
SectionObject so = (SectionObject) cmRequestedSections.get(i);
buf.append(so.getTitle() + "(" + so.getEid()
+ ")" + so.getCategory() + "\n");
}
return buf.toString();
}
/**
* Notification sent when a course site is set up automatcally
*
*/
private void sendSiteNotification(SessionState state, Site site, List notifySites) {
boolean courseSite = SiteTypeUtil.isCourseSite(site.getType());
String term_name = "";
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term_name = ((AcademicSession) state
.getAttribute(STATE_TERM_SELECTED)).getEid();
}
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
User currentUser = UserDirectoryService.getCurrentUser();
if (requestEmail != null && currentUser != null) {
userNotificationProvider.notifySiteCreation(site, notifySites, courseSite, term_name, requestEmail);
} // if
// reset locale to user default
rb.setContextLocale(null);
} // sendSiteNotification
/**
* doCancel called when "eventSubmit_doCancel_create" is in the request
* parameters to c
*/
public void doCancel_create(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) {
state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE);
state.setAttribute(SiteHelper.SITE_CREATE_CANCELLED, Boolean.TRUE);
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX));
// remove state variables in tool editing
removeEditToolState(state);
} // doCancel_create
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters
* to c int index = Integer.valueOf(params.getString
* ("templateIndex")).intValue();
*/
public void doCancel(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.removeAttribute(STATE_MESSAGE);
String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX);
String backIndex = params.getString("back");
state.setAttribute(STATE_TEMPLATE_INDEX, backIndex);
if ("4".equals(currentIndex)) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_MESSAGE);
removeEditToolState(state);
} else if (getStateSite(state) != null && ("13".equals(currentIndex) || "14".equals(currentIndex)))
{
MathJaxEnabler.removeMathJaxAllowedAttributeFromState(state); // SAK-22384
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if ("15".equals(currentIndex)) {
params = data.getParameters();
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("cancelIndex"));
removeEditToolState(state);
}
// htripath: added '"45".equals(currentIndex)' for import from file
// cancel
else if ("45".equals(currentIndex)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if ("4".equals(currentIndex)) {
// from adding class
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} else if ("27".equals(currentIndex) || "28".equals(currentIndex) || "59".equals(currentIndex) || "60".equals(currentIndex)) {
// from import
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// worksite setup
if (getStateSite(state) == null) {
// in creating new site process
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// in editing site process
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
// site info
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
} else if ("26".equals(currentIndex)) {
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)
&& getStateSite(state) == null) {
// from creating site
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// from revising site
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
removeEditToolState(state);
} else if ("37".equals(currentIndex) || "44".equals(currentIndex) || "53".equals(currentIndex) || "36".equals(currentIndex)) {
// cancel back to edit class view
state.removeAttribute(STATE_TERM_SELECTED);
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
}
// if all fails to match
else if (isTemplateVisited(state, "12")) {
// go to site info list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else {
// go to WSetup list view
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX));
} // doCancel
/**
* doMenu_customize is called when "eventSubmit_doBack" is in the request
* parameters Pass parameter to actionForTemplate to request action for
* backward direction
*/
public void doMenu_customize(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}// doMenu_customize
/**
* doBack_to_list cancels an outstanding site edit, cleans state and returns
* to the site list
*
*/
public void doBack_to_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
if (site != null) {
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
h.put(site.getId(), state.getAttribute(STATE_PAGESIZE));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
// restore the page size for Worksite setup tool
if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) {
state.setAttribute(STATE_PAGESIZE, state
.getAttribute(STATE_PAGESIZE_SITESETUP));
state.removeAttribute(STATE_PAGESIZE_SITESETUP);
}
cleanState(state);
setupFormNamesAndConstants(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
// reset
resetVisitedTemplateListToIndex(state, "0");
} // doBack_to_list
/**
* reset to sublist with index as the last item
* @param state
* @param index
*/
private void resetVisitedTemplateListToIndex(SessionState state, String index) {
if (state.getAttribute(STATE_VISITED_TEMPLATES) != null)
{
List<String> l = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (l != null && l.indexOf(index) >=0 && l.indexOf(index) < l.size())
{
state.setAttribute(STATE_VISITED_TEMPLATES, l.subList(0, l.indexOf(index)+1));
}
}
}
/**
* toolId might be of form original tool id concatenated with number
* find whether there is an counterpart in the the multipleToolIdSet
* @param state
* @param toolId
* @return
*/
private String findOriginalToolId(SessionState state, String toolId) {
// treat home tool differently
if (toolId.equals(TOOL_ID_HOME) || SITE_INFO_TOOL_ID.equals(toolId))
{
return toolId;
}
else
{
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
String rv = null;
if (toolRegistrationList != null)
{
for (Iterator i=toolRegistrationList.iterator(); rv == null && i.hasNext();)
{
Tool tool = (Tool) i.next();
String tId = tool.getId();
rv = originalToolId(toolId, tId);
}
}
return rv;
}
}
// replace fake tool ids with real ones. Don't duplicate, since several fake tool ids may appear for the same real one
// it's far from clear that we need to be using fake tool ids at all. But I don't know the code well enough
// to get rid of the fakes completely.
private List<String> originalToolIds(List<String>toolIds, SessionState state) {
Set<String>found = new HashSet<String>();
List<String>rv = new ArrayList<String>();
for (String toolId: toolIds) {
String origToolId = findOriginalToolId(state, toolId);
if (!found.contains(origToolId)) {
rv.add(origToolId);
found.add(origToolId);
}
}
return rv;
}
private String originalToolId(String toolId, String toolRegistrationId) {
String rv = null;
if (toolId.equals(toolRegistrationId))
{
rv = toolRegistrationId;
}
else if (toolId.indexOf(toolRegistrationId) != -1 && isMultipleInstancesAllowed(toolRegistrationId))
{
// the multiple tool id format is of SITE_IDTOOL_IDx, where x is an intger >= 1
if (toolId.endsWith(toolRegistrationId))
{
// get the site id part out
String uuid = toolId.replaceFirst(toolRegistrationId, "");
if (uuid != null && uuid.length() == UUID_LENGTH)
rv = toolRegistrationId;
} else
{
String suffix = toolId.substring(toolId.indexOf(toolRegistrationId) + toolRegistrationId.length());
try
{
Integer.parseInt(suffix);
rv = toolRegistrationId;
}
catch (Exception e)
{
// not the right tool id
M_log.debug(this + ".findOriginalToolId not matching tool id = " + toolRegistrationId + " original tool id=" + toolId + e.getMessage(), e);
}
}
}
return rv;
}
/**
* Read from tool registration whether multiple registration is allowed for this tool
* @param toolId
* @return
*/
private boolean isMultipleInstancesAllowed(String toolId)
{
Tool tool = ToolManager.getTool(toolId);
if (tool != null)
{
Properties tProperties = tool.getRegisteredConfig();
return (tProperties.containsKey("allowMultipleInstances")
&& tProperties.getProperty("allowMultipleInstances").equalsIgnoreCase(Boolean.TRUE.toString()))?true:false;
}
return false;
}
private HashMap<String, String> getMultiToolConfiguration(String toolId, ToolConfiguration toolConfig)
{
HashMap<String, String> rv = new HashMap<String, String>();
// read attribute list from configuration file
ArrayList<String> attributes=new ArrayList<String>();
String attributesConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE + toolId);
if ( attributesConfig != null && attributesConfig.length() > 0)
{
// read attributes from config file
attributes = new ArrayList(Arrays.asList(attributesConfig.split(",")));
}
else
{
if (toolId.equals(NEWS_TOOL_ID))
{
// default setting for News tool
attributes.add(NEWS_TOOL_CHANNEL_CONFIG);
}
else if (toolId.equals(WEB_CONTENT_TOOL_ID))
{
// default setting for Web Content tool
attributes.add(WEB_CONTENT_TOOL_SOURCE_CONFIG);
}
}
// read the defaul attribute setting from configuration
ArrayList<String> defaultValues =new ArrayList<String>();
String defaultValueConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE_DEFAULT + toolId);
if ( defaultValueConfig != null && defaultValueConfig.length() > 0)
{
defaultValues = new ArrayList(Arrays.asList(defaultValueConfig.split(",")));
}
else
{
// otherwise, treat News tool and Web Content tool differently
if (toolId.equals(NEWS_TOOL_ID))
{
// default value
defaultValues.add(NEWS_TOOL_CHANNEL_CONFIG_VALUE);
}
else if (toolId.equals(WEB_CONTENT_TOOL_ID))
{
// default value
defaultValues.add(WEB_CONTENT_TOOL_SOURCE_CONFIG_VALUE);
}
}
if (attributes != null && attributes.size() > 0 && defaultValues != null && defaultValues.size() > 0 && attributes.size() == defaultValues.size())
{
for (int i = 0; i < attributes.size(); i++)
{
String attribute = attributes.get(i);
// check to see the current settings first
Properties config = toolConfig != null ? toolConfig.getConfig() : null;
if (config != null && config.containsKey(attribute))
{
rv.put(attribute, config.getProperty(attribute));
}
else
{
// set according to the default setting
rv.put(attribute, defaultValues.get(i));
}
}
}
return rv;
}
/**
* The triage function for saving modified features page
* @param data
*/
public void doAddRemoveFeatureConfirm_option(RunData data) {
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if ("revise".equals(option))
{
// save the modified features
doSave_revised_features(state, params);
}
else if ("back".equals(option))
{
// back a step
doBack(data);
}
else if ("cancel".equals(option))
{
// cancel out
doCancel(data);
}
}
/**
* doSave_revised_features
*/
public void doSave_revised_features(SessionState state, ParameterParser params) {
Site site = getStateSite(state);
saveFeatures(params, state, site);
// SAK-22384
if (MathJaxEnabler.prepareMathJaxToolSettingsForSave(site, state))
{
commitSite(site);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// clean state variables
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX));
// refresh the whole page
scheduleTopRefresh();
}
} // doSave_revised_features
/**
* doMenu_siteInfo_cancel_access
*/
public void doMenu_siteInfo_cancel_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // doMenu_siteInfo_cancel_access
/**
* doMenu_siteInfo_importSelection
*/
public void doMenu_siteInfo_importSelection(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "58");
}
} // doMenu_siteInfo_importSelection
/**
* doMenu_siteInfo_import
*/
public void doMenu_siteInfo_import(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "28");
}
} // doMenu_siteInfo_import
/**
* doMenu_siteInfo_import_user
*/
public void doMenu_siteInfo_import_user(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "61"); // import users
}
} // doMenu_siteInfo_import_user
public void doMenu_siteInfo_importMigrate(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "59");
}
} // doMenu_siteInfo_importMigrate
/**
* doMenu_siteInfo_editClass
*/
public void doMenu_siteInfo_editClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
} // doMenu_siteInfo_editClass
/**
* doMenu_siteInfo_addClass
*/
public void doMenu_siteInfo_addClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
String termEid = site.getProperties().getProperty(Site.PROP_SITE_TERM_EID);
if (termEid == null)
{
// no term eid stored, need to get term eid from the term title
String termTitle = site.getProperties().getProperty(Site.PROP_SITE_TERM);
List asList = cms.getAcademicSessions();
if (termTitle != null && asList != null)
{
boolean found = false;
for (int i = 0; i<asList.size() && !found; i++)
{
AcademicSession as = (AcademicSession) asList.get(i);
if (as.getTitle().equals(termTitle))
{
termEid = as.getEid();
site.getPropertiesEdit().addProperty(Site.PROP_SITE_TERM_EID, termEid);
try
{
SiteService.save(site);
}
catch (Exception e)
{
M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + site.getId(), e);
}
found=true;
}
}
}
}
if (termEid != null)
{
state.setAttribute(STATE_TERM_SELECTED, cms.getAcademicSession(termEid));
try
{
List sections = prepareCourseAndSectionListing(UserDirectoryService.getCurrentUser().getEid(), cms.getAcademicSession(termEid).getEid(), state);
isFutureTermSelected(state);
if (sections != null && sections.size() > 0)
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
}
catch (Exception e)
{
M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + termEid, e);
}
}
else
{
List currentTerms = cms.getCurrentAcademicSessions();
if (currentTerms != null && !currentTerms.isEmpty())
{
// if the term information is missing for the site, assign it to the first current term in list
state.setAttribute(STATE_TERM_SELECTED, currentTerms.get(0));
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
} // doMenu_siteInfo_addClass
/**
* doMenu_siteInfo_duplicate
*/
public void doMenu_siteInfo_duplicate(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "29");
}
} // doMenu_siteInfo_import
/**
* doMenu_edit_site_info
*
*/
public void doMenu_edit_site_info(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
sitePropertiesIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} // doMenu_edit_site_info
/**
* doMenu_edit_site_tools
*
*/
public void doMenu_edit_site_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// Clean up state on our first entry from a shortcut
String panel = data.getParameters().getString("panel");
if ( "Shortcut".equals(panel) ) cleanState(state);
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "4");
if (state.getAttribute(STATE_INITIALIZED) == null) {
state.setAttribute(STATE_OVERRIDE_TEMPLATE_INDEX, "4");
}
}
} // doMenu_edit_site_tools
/**
* doMenu_edit_site_access
*
*/
public void doMenu_edit_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
try {
Site site = getStateSite(state);
state.setAttribute(STATE_SITE_ACCESS_PUBLISH, Boolean.valueOf(site.isPublished()));
state.setAttribute(STATE_SITE_ACCESS_INCLUDE, Boolean.valueOf(site.isPubView()));
boolean joinable = site.isJoinable();
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(joinable));
String joinerRole = site.getJoinerRole();
if (joinerRole == null || joinerRole.length() == 0)
{
String[] joinerRoles = ServerConfigurationService.getStrings("siteinfo.default_joiner_role");
Set<Role> roles = site.getRoles();
if (roles != null && joinerRole != null && joinerRoles.length > 0)
{
// find the role match
for (Role r : roles)
{
for(int i = 0; i < joinerRoles.length; i++)
{
if (r.getId().equalsIgnoreCase(joinerRoles[i]))
{
joinerRole = r.getId();
break;
}
}
if (joinerRole != null)
{
break;
}
}
}
}
state.setAttribute(STATE_JOINERROLE, joinerRole);
// bjones86 - SAK-24423 - update state for joinable site settings
JoinableSiteSettings.updateStateFromSitePropertiesOnEditAccessOrNewSite( site.getProperties(), state );
}
catch (Exception e)
{
M_log.warn(this + " doMenu_edit_site_access problem of getting site" + e.getMessage());
}
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doMenu_edit_site_access
/**
* Back to worksite setup's list view
*
*/
public void doBack_to_site_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
// reset
resetVisitedTemplateListToIndex(state, "0");
} // doBack_to_site_list
/**
* doSave_site_info
*
*/
public void doSave_siteInfo(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site Site = getStateSite(state);
ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit();
String site_type = (String) state.getAttribute(STATE_SITE_TYPE);
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteTitleEditable(state, SiteTypeUtil.getTargetSiteType(site_type)))
{
Site.setTitle(siteInfo.title);
}
Site.setDescription(siteInfo.description);
Site.setShortDescription(siteInfo.short_description);
if (site_type != null) {
// set icon url for course
setAppearance(state, Site, siteInfo.iconUrl);
}
// site contact information
String contactName = siteInfo.site_contact_name;
if (contactName != null) {
siteProperties.addProperty(Site.PROP_SITE_CONTACT_NAME, contactName);
}
String contactEmail = siteInfo.site_contact_email;
if (contactEmail != null) {
siteProperties.addProperty(Site.PROP_SITE_CONTACT_EMAIL, contactEmail);
}
Collection<String> oldAliasIds = getSiteReferenceAliasIds(Site);
boolean updateSiteRefAliases = aliasesEditable(state, Site.getId());
if ( updateSiteRefAliases ) {
setSiteReferenceAliases(state, Site.getId());
}
/// site language information
String locale_string = (String) state.getAttribute("locale_string");
siteProperties.removeProperty(PROP_SITE_LANGUAGE);
siteProperties.addProperty(PROP_SITE_LANGUAGE, locale_string);
// SAK-22384 mathjax support
MathJaxEnabler.prepareMathJaxAllowedSettingsForSave(Site, state);
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
SiteService.save(Site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// back to site info view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// Need to refresh the entire page because, e.g. the current site's name
// may have changed. This is problematic, though, b/c the current
// top-level portal URL may reference a just-deleted alias. A temporary
// alias translation map is one option, but it is difficult to know when
// to clean up. So we send a redirect instead of just scheduling
// a reload.
//
// One problem with this is we have no good way to know what the
// top-level portal handler should actually be. We also don't have a
// particularly good way of knowing how the portal expects to receive
// page references. We can't just use SitePage.getUrl() because that
// method assumes that site reference roots are identical to portal
// handler URL fragments, which is not guaranteed. Hence the approach
// below which tries to guess at the right portal handler, but just
// punts on page reference roots, using SiteService.PAGE_SUBTYPE for
// that portion of the URL
//
// None of this helps other users who may try to reload an aliased site
// URL that no longer resolves.
if ( updateSiteRefAliases ) {
sendParentRedirect((HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE),
getDefaultSiteUrl(ToolManager.getCurrentPlacement().getContext()) + "/" +
SiteService.PAGE_SUBTYPE + "/" +
((ToolConfiguration) ToolManager.getCurrentPlacement()).getPageId());
} else {
scheduleTopRefresh();
}
}
} // doSave_siteInfo
/**
* Check to see whether the site's title is editable or not
* @param state
* @param site_type
* @return
*/
private boolean siteTitleEditable(SessionState state, String site_type) {
return site_type != null
&& ((state.getAttribute(TITLE_NOT_EDITABLE_SITE_TYPE) != null
&& !((List) state.getAttribute(TITLE_NOT_EDITABLE_SITE_TYPE)).contains(site_type)));
}
/**
* Tests if the alias editing feature has been enabled
* ({@link #aliasEditingEnabled(SessionState, String)}) and that
* current user has set/remove aliasing permissions for the given
* {@link Site} ({@link #aliasEditingPermissioned(SessionState, String)}).
*
* <p>(Method name and signature is an attempt to be consistent with
* {@link #siteTitleEditable(SessionState, String)}).</p>
*
* @param state not used
* @param siteId a site identifier (not a {@link Reference}); must not be <code>null</code>
* @return
*/
private boolean aliasesEditable(SessionState state, String siteId) {
return aliasEditingEnabled(state, siteId) &&
aliasEditingPermissioned(state, siteId);
}
/**
* Tests if alias editing has been enabled by configuration. This is
* independent of any permissioning considerations. Also note that this
* feature is configured separately from alias assignment during worksite
* creation. This feature applies exclusively to alias edits and deletes
* against existing sites.
*
* <p>(Method name and signature is an attempt to be consistent with
* {@link #siteTitleEditable(SessionState, String)}).</p>
*
* @see #aliasAssignmentForNewSitesEnabled(SessionState)
* @param state
* @param siteId
* @return
*/
private boolean aliasEditingEnabled(SessionState state, String siteId) {
return ServerConfigurationService.getBoolean("site-manage.enable.alias.edit", false);
}
/**
* Tests if alias assignment for new sites has been enabled by configuration.
* This is independent of any permissioning considerations.
*
* <p>(Method name and signature is an attempt to be consistent with
* {@link #siteTitleEditable(SessionState, String)}).</p>
*
* @param state
* @param siteId
* @return
*/
private boolean aliasAssignmentForNewSitesEnabled(SessionState state) {
return ServerConfigurationService.getBoolean("site-manage.enable.alias.new", false);
}
/**
* Tests if the current user has set and remove permissions for aliases
* of the given site. <p>(Method name and signature is an attempt to be
* consistent with {@link #siteTitleEditable(SessionState, String)}).</p>
*
* @param state
* @param siteId
* @return
*/
private boolean aliasEditingPermissioned(SessionState state, String siteId) {
String siteRef = SiteService.siteReference(siteId);
return AliasService.allowSetAlias("", siteRef) &&
AliasService.allowRemoveTargetAliases(siteRef);
}
/**
* init
*
*/
private void init(VelocityPortlet portlet, RunData data, SessionState state) {
state.setAttribute(STATE_ACTION, "SiteAction");
setupFormNamesAndConstants(state);
if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) {
state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable());
}
if (SITE_MODE_SITESETUP.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
// need to watch out for the config question.xml existence.
// read the file and put it to backup folder.
if (SiteSetupQuestionFileParser.isConfigurationXmlAvailable())
{
SiteSetupQuestionFileParser.updateConfig();
}
} else if (SITE_MODE_HELPER.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) {
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} else if (SITE_MODE_SITEINFO.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))){
String siteId = ToolManager.getCurrentPlacement().getContext();
getReviseSite(state, siteId);
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// update
h.put(siteId, Integer.valueOf(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
state.setAttribute(STATE_PAGESIZE, Integer.valueOf(200));
}
}
if (state.getAttribute(STATE_SITE_TYPES) == null) {
PortletConfig config = portlet.getPortletConfig();
// all site types (SITE_DEFAULT_LIST overrides tool config)
String t = StringUtils.trimToNull(SITE_DEFAULT_LIST);
if ( t == null )
t = StringUtils.trimToNull(config.getInitParameter("siteTypes"));
if (t != null) {
List types = new ArrayList(Arrays.asList(t.split(",")));
if (cms == null)
{
// if there is no CourseManagementService, disable the process of creating course site
List<String> courseTypes = SiteTypeUtil.getCourseSiteTypes();
types.remove(courseTypes);
}
state.setAttribute(STATE_SITE_TYPES, types);
} else {
t = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TYPES);
if (t != null) {
state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays
.asList(t.split(","))));
} else {
state.setAttribute(STATE_SITE_TYPES, new Vector());
}
}
}
// show UI for adding non-official participant(s) or not
// if nonOfficialAccount variable is set to be false inside sakai.properties file, do not show the UI section for adding them.
// the setting defaults to be true
if (state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT) == null)
{
state.setAttribute(ADD_NON_OFFICIAL_PARTICIPANT, ServerConfigurationService.getString("nonOfficialAccount", "true"));
}
if (state.getAttribute(STATE_VISITED_TEMPLATES) == null)
{
List<String> templates = new Vector<String>();
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) {
templates.add("0"); // the default page of WSetup tool
} else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) {
templates.add("12");// the default page of Site Info tool
}
state.setAttribute(STATE_VISITED_TEMPLATES, templates);
}
if (state.getAttribute(STATE_SITE_TITLE_MAX) == null) {
int siteTitleMaxLength = ServerConfigurationService.getInt("site.title.maxlength", 25);
state.setAttribute(STATE_SITE_TITLE_MAX, siteTitleMaxLength);
}
} // init
public void doNavigate_to_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = StringUtils.trimToNull(data.getParameters().getString(
"option"));
if (siteId != null) {
getReviseSite(state, siteId);
} else {
doBack_to_list(data);
}
} // doNavigate_to_site
/**
* Get site information for revise screen
*/
private void getReviseSite(SessionState state, String siteId) {
if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) {
state.setAttribute(STATE_SELECTED_USER_LIST, new Vector());
}
List sites = (List) state.getAttribute(STATE_SITES);
try {
Site site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
if (sites != null) {
int pos = -1;
for (int index = 0; index < sites.size() && pos == -1; index++) {
if (((Site) sites.get(index)).getId().equals(siteId)) {
pos = index;
}
}
// has any previous site in the list?
if (pos > 0) {
state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1));
} else {
state.removeAttribute(STATE_PREV_SITE);
}
// has any next site in the list?
if (pos < sites.size() - 1) {
state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1));
} else {
state.removeAttribute(STATE_NEXT_SITE);
}
}
String type = site.getType();
if (type == null) {
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
state.setAttribute(STATE_SITE_TYPE, type);
} catch (IdUnusedException e) {
M_log.warn(this + ".getReviseSite: " + e.toString() + " site id = " + siteId, e);
}
// one site has been selected
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // getReviseSite
/**
* when user clicks "join" for a joinable set
* @param data
*/
public void doJoinableSet(RunData data){
ParameterParser params = data.getParameters();
String groupRef = params.getString("joinable-group-ref");
Site currentSite;
try {
currentSite = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
if(currentSite != null){
Group siteGroup = currentSite.getGroup(groupRef);
//make sure its a joinable set:
String joinableSet = siteGroup.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET);
if(joinableSet != null && !"".equals(joinableSet.trim())){
//check that the max limit hasn't been reached:
int max = 0;
try{
max = Integer.parseInt(siteGroup.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET_MAX));
AuthzGroup group = authzGroupService.getAuthzGroup(groupRef);
int size = group.getMembers().size();
if(size < max){
//check that the user isn't already a member
String userId = UserDirectoryService.getCurrentUser().getId();
boolean found = false;
for(Member member : group.getMembers()){
if(member.getUserId().equals(userId)){
found = true;
break;
}
}
if(!found){
// add current user as the maintainer
Member member = currentSite.getMember(userId);
if(member != null){
siteGroup.addMember(userId, member.getRole().getId(), true, false);
SecurityAdvisor yesMan = new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference) {
return SecurityAdvice.ALLOWED;
}
};
try{
SecurityService.pushAdvisor(yesMan);
commitSite(currentSite);
}catch (Exception e) {
M_log.debug(e);
}finally{
SecurityService.popAdvisor();
}
}
}
}
}catch (Exception e) {
M_log.debug("Error adding user to group: " + groupRef + ", " + e.getMessage(), e);
}
}
}
} catch (IdUnusedException e) {
M_log.debug("Error adding user to group: " + groupRef + ", " + e.getMessage(), e);
}
}
/**
* when user clicks "join" for a joinable set
* @param data
*/
public void doUnjoinableSet(RunData data){
ParameterParser params = data.getParameters();
String groupRef = params.getString("group-ref");
Site currentSite;
try {
currentSite = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
if(currentSite != null){
Group siteGroup = currentSite.getGroup(groupRef);
//make sure its a joinable set:
String joinableSet = siteGroup.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET);
if(joinableSet != null && !"".equals(joinableSet.trim())){
try{
AuthzGroup group = authzGroupService.getAuthzGroup(groupRef);
//check that the user is already a member
String userId = UserDirectoryService.getCurrentUser().getId();
boolean found = false;
for(Member member : group.getMembers()){
if(member.getUserId().equals(userId)){
found = true;
break;
}
}
if(found){
// remove current user as the maintainer
Member member = currentSite.getMember(userId);
if(member != null){
siteGroup.removeMember(userId);
SecurityAdvisor yesMan = new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference) {
return SecurityAdvice.ALLOWED;
}
};
try{
SecurityService.pushAdvisor(yesMan);
commitSite(currentSite);
}catch (Exception e) {
M_log.debug(e);
}finally{
SecurityService.popAdvisor();
}
}
}
}catch (Exception e) {
M_log.debug("Error removing user to group: " + groupRef + ", " + e.getMessage(), e);
}
}
}
} catch (IdUnusedException e) {
M_log.debug("Error removing user to group: " + groupRef + ", " + e.getMessage(), e);
}
}
/**
* SAK 23029 - iterate through changed partiants to see how many would have maintain role if all roles, status and deletion changes went through
*
*/
private List<Participant> testProposedUpdates(List<Participant> participants, ParameterParser params, String maintainRole) {
List<Participant> maintainersAfterUpdates = new ArrayList<Participant>();
// create list of all partcipants that have been 'Charles Bronson-ed'
Set<String> removedParticipantIds = new HashSet();
Set<String> deactivatedParticipants = new HashSet();
if (params.getStrings("selectedUser") != null) {
List removals = new ArrayList(Arrays.asList(params.getStrings("selectedUser")));
for (int i = 0; i < removals.size(); i++) {
String rId = (String) removals.get(i);
removedParticipantIds.add(rId);
}
}
// create list of all participants that have been deactivated
for(Participant statusParticipant : participants ) {
String activeGrantId = statusParticipant.getUniqname();
String activeGrantField = "activeGrant" + activeGrantId;
if (params.getString(activeGrantField) != null) {
boolean activeStatus = params.getString(activeGrantField).equalsIgnoreCase("true") ? true : false;
if (activeStatus == false) {
deactivatedParticipants.add(activeGrantId);
}
}
}
// now add only those partcipants whose new/current role is maintainer, is (still) active, and not marked for deletion
for(Participant roleParticipant : participants ) {
String id = roleParticipant.getUniqname();
String roleId = "role" + id;
String newRole = params.getString(roleId);
if ((deactivatedParticipants.contains(id)==false) && roleParticipant.isActive() != false) { // skip any that are not already inactive or are not candidates for deactivation
if (removedParticipantIds.contains(id) == false) {
if (newRole != null){
if (newRole.equals(maintainRole)) {
maintainersAfterUpdates.add(roleParticipant);
}
} else {
// participant has no new role; was participant already maintainer?
if (roleParticipant.getRole().equals(maintainRole)) {
maintainersAfterUpdates.add(roleParticipant);
}
}
}
}
}
return maintainersAfterUpdates;
}
/**
* doUpdate_participant
*
*/
public void doUpdate_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
Site s = getStateSite(state);
String realmId = SiteService.siteReference(s.getId());
// list of updated users
List<String> userUpdated = new Vector<String>();
// list of all removed user
List<String> usersDeleted = new Vector<String>();
if (AuthzGroupService.allowUpdate(realmId)
|| SiteService.allowUpdateSiteMembership(s.getId())) {
try {
// init variables useful for actual edits and mainainersAfterProposedChanges check
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
String maintainRoleString = realmEdit.getMaintainRole();
List participants = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST));
// SAK 23029 Test proposed removals/updates; reject all where activeMainainer count would = 0 if all proposed changes were made
List<Participant> maintainersAfterProposedChanges = testProposedUpdates(participants, params, maintainRoleString);
if (maintainersAfterProposedChanges.size() == 0) {
addAlert(state,
rb.getFormattedMessage("sitegen.siteinfolist.lastmaintainuseractive", new Object[]{maintainRoleString} ));
return;
}
// SAK23029 - proposed changes do not leave site w/o maintainers; proceed with any allowed updates
// list of roles being added or removed
HashSet<String>roles = new HashSet<String>();
// List used for user auditing
List<String[]> userAuditList = new ArrayList<String[]>();
// remove all roles and then add back those that were checked
for (int i = 0; i < participants.size(); i++) {
String id = null;
// added participant
Participant participant = (Participant) participants.get(i);
id = participant.getUniqname();
if (id != null) {
// get the newly assigned role
String inputRoleField = "role" + id;
String roleId = params.getString(inputRoleField);
String oldRoleId = participant.getRole();
boolean roleChange = roleId != null && !roleId.equals(oldRoleId);
// get the grant active status
boolean activeGrant = true;
String activeGrantField = "activeGrant" + id;
if (params.getString(activeGrantField) != null) {
activeGrant = params
.getString(activeGrantField)
.equalsIgnoreCase("true") ? true
: false;
}
boolean activeGrantChange = roleId != null && (participant.isActive() && !activeGrant || !participant.isActive() && activeGrant);
// save any roles changed for permission check
if (roleChange) {
roles.add(roleId);
roles.add(oldRoleId);
}
// SAK-23257 - display an error message if the new role is in the restricted role list
String siteType = s.getType();
List<Role> allowedRoles = SiteParticipantHelper.getAllowedRoles( siteType, getRoles( state ) );
for( String roleName : roles )
{
Role r = realmEdit.getRole( roleName );
if( !allowedRoles.contains( r ) )
{
addAlert( state, rb.getFormattedMessage( "java.roleperm", new Object[] { roleName } ) );
return;
}
}
if (roleChange || activeGrantChange)
{
boolean fromProvider = !participant.isRemoveable();
if (fromProvider && !roleId.equals(participant.getRole())) {
fromProvider = false;
}
realmEdit.addMember(id, roleId, activeGrant,
fromProvider);
String currentUserId = (String) state.getAttribute(STATE_CM_CURRENT_USERID);
String[] userAuditString = {s.getId(),participant.getEid(),roleId,userAuditService.USER_AUDIT_ACTION_UPDATE,userAuditRegistration.getDatabaseSourceKey(),currentUserId};
userAuditList.add(userAuditString);
// construct the event string
String userUpdatedString = "uid=" + id;
if (roleChange)
{
userUpdatedString += ";oldRole=" + oldRoleId + ";newRole=" + roleId;
}
else
{
userUpdatedString += ";role=" + roleId;
}
if (activeGrantChange)
{
userUpdatedString += ";oldActive=" + participant.isActive() + ";newActive=" + activeGrant;
}
else
{
userUpdatedString += ";active=" + activeGrant;
}
userUpdatedString += ";provided=" + fromProvider;
// add to the list for all participants that have role changes
userUpdated.add(userUpdatedString);
}
}
}
// remove selected users
if (params.getStrings("selectedUser") != null) {
List removals = new ArrayList(Arrays.asList(params
.getStrings("selectedUser")));
state.setAttribute(STATE_SELECTED_USER_LIST, removals);
for (int i = 0; i < removals.size(); i++) {
String rId = (String) removals.get(i);
try {
User user = UserDirectoryService.getUser(rId);
// save role for permission check
if (user != null) {
String userId = user.getId();
Member userMember = realmEdit
.getMember(userId);
if (userMember != null) {
Role role = userMember.getRole();
if (role != null) {
roles.add(role.getId());
}
realmEdit.removeMember(userId);
usersDeleted.add("uid=" + userId);
String currentUserId = (String) state.getAttribute(STATE_CM_CURRENT_USERID);
String[] userAuditString = {s.getId(),user.getEid(),role.getId(),userAuditService.USER_AUDIT_ACTION_REMOVE,userAuditRegistration.getDatabaseSourceKey(),currentUserId};
userAuditList.add(userAuditString);
}
}
} catch (UserNotDefinedException e) {
M_log.warn(this + ".doUpdate_participant: IdUnusedException " + rId + ". ", e);
if (("admins".equals(showOrphanedMembers) && SecurityService.isSuperUser()) || ("maintainers".equals(showOrphanedMembers))) {
Member userMember = realmEdit.getMember(rId);
if (userMember != null) {
Role role = userMember.getRole();
if (role != null) {
roles.add(role.getId());
}
realmEdit.removeMember(rId);
}
}
}
}
}
// if user doesn't have update, don't let them add or remove any role with site.upd in it.
if (!AuthzGroupService.allowUpdate(realmId)) {
// see if any changed have site.upd
for (String rolename: roles) {
Role role = realmEdit.getRole(rolename);
if (role != null && role.isAllowed("site.upd")) {
addAlert(state, rb.getFormattedMessage("java.roleperm", new Object[]{rolename}));
return;
}
}
}
AuthzGroupService.save(realmEdit);
// do the audit logging - Doing this in one bulk call to the database will cause the actual audit stamp to be off by maybe 1 second at the most
// but seems to be a better solution than call this multiple time for every update
if (!userAuditList.isEmpty())
{
userAuditRegistration.addToUserAuditing(userAuditList);
}
// then update all related group realms for the role
doUpdate_related_group_participants(s, realmId);
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(
SiteService.SECURE_UPDATE_SITE_MEMBERSHIP,
realmEdit.getId(), false));
// check the configuration setting, whether logging membership
// change at individual level is allowed
if (ServerConfigurationService.getBoolean(
SiteHelper.WSETUP_TRACK_USER_MEMBERSHIP_CHANGE, false)) {
// event for each individual update
for (String userChangedRole : userUpdated) {
EventTrackingService
.post(EventTrackingService
.newEvent(
org.sakaiproject.site.api.SiteService.EVENT_USER_SITE_MEMBERSHIP_UPDATE,
userChangedRole, true));
}
// event for each individual remove
for (String userDeleted : usersDeleted) {
EventTrackingService
.post(EventTrackingService
.newEvent(
org.sakaiproject.site.api.SiteService.EVENT_USER_SITE_MEMBERSHIP_REMOVE,
userDeleted, true));
}
}
} catch (GroupNotDefinedException e) {
addAlert(state, rb.getString("java.problem2"));
M_log.warn(this + ".doUpdate_participant: IdUnusedException " + s.getTitle() + "(" + realmId + "). ", e);
} catch (AuthzPermissionException e) {
addAlert(state, rb.getString("java.changeroles"));
M_log.warn(this + ".doUpdate_participant: PermissionException " + s.getTitle() + "(" + realmId + "). ", e);
}
}
} // doUpdate_participant
/**
* update realted group realm setting according to parent site realm changes
* @param s
* @param realmId
*/
private void doUpdate_related_group_participants(Site s, String realmId) {
Collection groups = s.getGroups();
boolean trackIndividualChange = ServerConfigurationService.getBoolean(SiteHelper.WSETUP_TRACK_USER_MEMBERSHIP_CHANGE, false);
if (groups != null)
{
try
{
for (Iterator iGroups = groups.iterator(); iGroups.hasNext();)
{
Group g = (Group) iGroups.next();
if (g != null)
{
try
{
Set gMembers = g.getMembers();
for (Iterator iGMembers = gMembers.iterator(); iGMembers.hasNext();)
{
Member gMember = (Member) iGMembers.next();
String gMemberId = gMember.getUserId();
Member siteMember = s.getMember(gMemberId);
if ( siteMember == null)
{
// user has been removed from the site
g.removeMember(gMemberId);
}
else
{
// check for Site Info-managed groups: don't change roles for other groups (e.g. section-managed groups)
String gProp = g.getProperties().getProperty(g.GROUP_PROP_WSETUP_CREATED);
// if there is a difference between the role setting, remove the entry from group and add it back with correct role, all are marked "not provided"
Role groupRole = g.getUserRole(gMemberId);
Role siteRole = siteMember.getRole();
if (gProp != null && gProp.equals(Boolean.TRUE.toString()) &&
groupRole != null && siteRole != null && !groupRole.equals(siteRole))
{
if (g.getRole(siteRole.getId()) == null)
{
// in case there is no matching role as that in the site, create such role and add it to the user
g.addRole(siteRole.getId(), siteRole);
}
g.removeMember(gMemberId);
g.addMember(gMemberId, siteRole.getId(), siteMember.isActive(), false);
// track the group membership change at individual level
if (trackIndividualChange)
{
// an event for each individual member role change
EventTrackingService.post(EventTrackingService.newEvent(org.sakaiproject.site.api.SiteService.EVENT_USER_GROUP_MEMBERSHIP_UPDATE, "uid=" + gMemberId + ";groupId=" + g.getId() + ";oldRole=" + groupRole + ";newRole=" + siteRole + ";active=" + siteMember.isActive() + ";provided=false", true/*update event*/));
}
}
}
}
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_GROUP_MEMBERSHIP, g.getId(),true));
}
catch (Exception ee)
{
M_log.warn(this + ".doUpdate_related_group_participants: " + ee.getMessage() + g.getId(), ee);
}
}
}
// commit, save the site
SiteService.save(s);
}
catch (Exception e)
{
M_log.warn(this + ".doUpdate_related_group_participants: " + e.getMessage() + s.getId(), e);
}
}
}
/**
* doUpdate_site_access
*
*/
public void doUpdate_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site sEdit = getStateSite(state);
ParameterParser params = data.getParameters();
// get all form inputs
readInputAndUpdateStateVariable(state, params, "publishunpublish", STATE_SITE_ACCESS_PUBLISH, true);
readInputAndUpdateStateVariable(state, params, "include", STATE_SITE_ACCESS_INCLUDE, true);
readInputAndUpdateStateVariable(state, params, "joinable", STATE_JOINABLE, true);
readInputAndUpdateStateVariable(state, params, "joinerRole", STATE_JOINERROLE, false);
// bjones86 - SAK-24423 - get all joinable site settings from the form input
JoinableSiteSettings.getAllFormInputs( state, params );
boolean publishUnpublish = state.getAttribute(STATE_SITE_ACCESS_PUBLISH) != null ? ((Boolean) state.getAttribute(STATE_SITE_ACCESS_PUBLISH)).booleanValue() : false;
boolean include = state.getAttribute(STATE_SITE_ACCESS_INCLUDE) != null ? ((Boolean) state.getAttribute(STATE_SITE_ACCESS_INCLUDE)).booleanValue() : false;
if (sEdit != null) {
// editing existing site
// publish site or not
sEdit.setPublished(publishUnpublish);
// site public choice
List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
if (publicChangeableSiteTypes != null && sEdit.getType() != null && !publicChangeableSiteTypes.contains(sEdit.getType()))
{
// set pubview to true for those site types which pubview change is not allowed
sEdit.setPubView(true);
}
else
{
// set pubview according to UI selection
sEdit.setPubView(include);
}
doUpdate_site_access_joinable(data, state, params, sEdit);
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(sEdit);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// TODO: hard coding this frame id is fragile, portal dependent,
// and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
// bjones86 - SAK-24423 - remove joinable site settings from the state
JoinableSiteSettings.removeJoinableSiteSettingsFromState( state );
}
} else {
// adding new site
if (state.getAttribute(STATE_SITE_INFO) != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
siteInfo.published = publishUnpublish;
// site public choice
siteInfo.include = include;
// joinable site or not
boolean joinable = state.getAttribute(STATE_JOINABLE) != null ? ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue() : null;
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromStateOnSiteUpdate( state, siteInfo, joinable );
if (joinable) {
siteInfo.joinable = true;
String joinerRole = state.getAttribute(STATE_JOINERROLE) != null ? (String) state.getAttribute(STATE_JOINERROLE) : null;
if (joinerRole != null) {
siteInfo.joinerRole = joinerRole;
} else {
siteInfo.joinerRole = null;
addAlert(state, rb.getString("java.joinsite") + " ");
}
} else {
siteInfo.joinable = false;
siteInfo.joinerRole = null;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
//if creating a site from an archive, go to that template
//otherwise go to confirm page
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_CREATE_FROM_ARCHIVE) == Boolean.TRUE) {
state.setAttribute(STATE_TEMPLATE_INDEX, "62");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
}
}
}
} // doUpdate_site_access
private void readInputAndUpdateStateVariable(SessionState state, ParameterParser params, String paramName, String stateAttributeName, boolean isBoolean)
{
String paramValue = StringUtils.trimToNull(params.getString(paramName));
if (paramValue != null) {
if (isBoolean)
{
state.setAttribute(stateAttributeName, Boolean.valueOf(paramValue));
}
else
{
state.setAttribute(stateAttributeName, paramValue);
}
} else {
state.removeAttribute(stateAttributeName);
}
}
/**
* Apply requested changes to a site's joinability. Only relevant for
* site edits, not new site creation.
*
* <p>Not intended for direct execution from a Velocity-rendered form
* submit.</p>
*
* <p>Originally extracted from {@link #doUpdate_site_access(RunData)} to
* increase testability when adding special handling for an unspecified
* joinability parameter. The <code>sEdit</code> param is passed in
* to avoid repeated hits to the <code>SiteService</code> from
* {@link #getStateSite(SessionState)}. (It's called <code>sEdit</code> to
* reduce the scope of the refactoring diff just slightly.) <code>state</code>
* is passed in to avoid more proliferation of <code>RunData</code>
* downcasts.</p>
*
* @see #CONVERT_NULL_JOINABLE_TO_UNJOINABLE
* @param data request context -- must not be <code>null</code>
* @param state session state -- must not be <code>null</code>
* @param params request parameter facade -- must not be <code>null</code>
* @param sEdit site to be edited -- must not be <code>null</code>
*/
void doUpdate_site_access_joinable(RunData data,
SessionState state, ParameterParser params, Site sEdit) {
boolean joinable = state.getAttribute(STATE_JOINABLE) != null ? ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue() : null;
if (!sEdit.isPublished())
{
// reset joinable role if the site is not published
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
} else if (joinable) {
sEdit.setJoinable(true);
String joinerRole = state.getAttribute(STATE_JOINERROLE) != null ? (String) state.getAttribute(STATE_JOINERROLE) : null;
if (joinerRole != null) {
sEdit.setJoinerRole(joinerRole);
} else {
addAlert(state, rb.getString("java.joinsite") + " ");
}
// bjones86 - SAK-24423 - update site properties for joinable site settings
JoinableSiteSettings.updateSitePropertiesFromStateOnSiteUpdate( sEdit.getPropertiesEdit(), state );
} else if ( !joinable ||
(!joinable && ServerConfigurationService.getBoolean(CONVERT_NULL_JOINABLE_TO_UNJOINABLE, true))) {
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
} // else just leave joinability alone
}
/**
* /* Actions for vm templates under the "chef_site" root. This method is
* called by doContinue. Each template has a hidden field with the value of
* template-index that becomes the value of index for the switch statement
* here. Some cases not implemented.
*/
private void actionForTemplate(String direction, int index,
ParameterParser params, final SessionState state, RunData data) {
// Continue - make any permanent changes, Back - keep any data entered
// on the form
boolean forward = "continue".equals(direction) ? true : false;
SiteInfo siteInfo = new SiteInfo();
// SAK-16600 change to new template for tool editing
if (index==3) { index= 4;}
switch (index) {
case 0:
/*
* actionForTemplate chef_site-list.vm
*
*/
break;
case 1:
/*
* actionForTemplate chef_site-type.vm
*
*/
break;
case 4:
/*
* actionForTemplate chef_site-editFeatures.vm
* actionForTemplate chef_site-editToolGroupFeatures.vm
*
*/
if (forward) {
// editing existing site or creating a new one?
Site site = getStateSite(state);
getFeatures(params, state, site==null?"18":"15");
}
break;
case 8:
/*
* actionForTemplate chef_site-siteDeleteConfirm.vm
*
*/
break;
case 10:
/*
* actionForTemplate chef_site-newSiteConfirm.vm
*
*/
if (!forward) {
}
break;
case 12:
/*
* actionForTemplate chef_site_siteInfo-list.vm
*
*/
break;
case 13:
/*
* actionForTemplate chef_site_siteInfo-editInfo.vm
*
*/
if (forward) {
if (getStateSite(state) == null)
{
// alerts after clicking Continue but not Back
if (!forward) {
// removing previously selected template site
state.removeAttribute(STATE_TEMPLATE_SITE);
}
updateSiteAttributes(state);
}
updateSiteInfo(params, state);
}
break;
case 14:
/*
* actionForTemplate chef_site_siteInfo-editInfoConfirm.vm
*
*/
break;
case 15:
/*
* actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm
*
*/
break;
case 18:
/*
* actionForTemplate chef_siteInfo-editAccess.vm
*
*/
if (!forward) {
}
break;
case 24:
/*
* actionForTemplate
* chef_site-siteInfo-editAccess-globalAccess-confirm.vm
*
*/
break;
case 26:
/*
* actionForTemplate chef_site-modifyENW.vm
*
*/
updateSelectedToolList(state, params, true);
break;
case 27:
/*
* actionForTemplate chef_site-importSites.vm
*
*/
if (forward) {
Site existingSite = getStateSite(state);
if (existingSite != null) {
// revising a existing site's tool
if (select_import_tools(params, state)) {
String threadName = "SiteImportThread" + existingSite.getId();
boolean found = false;
//check all running threads for our named thread
//this isn't cluster safe, but this check it more targeted towards
//a single user re-importing multiple times during a slow import (which would be on the same server)
for(Thread t : Thread.getAllStackTraces().keySet()){
if(threadName.equals(t.getName())){
found = true;
break;
}
}
if(found){
//an existing thread is running for this site import, throw warning
addAlert(state, rb.getString("java.import.existing"));
}else{
final Hashtable importTools = (Hashtable) state
.getAttribute(STATE_IMPORT_SITE_TOOL);
final List selectedTools = originalToolIds((List<String>) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST), state);
final String userEmail = UserDirectoryService.getCurrentUser().getEmail();
final Session session = SessionManager.getCurrentSession();
final ToolSession toolSession = SessionManager.getCurrentToolSession();
Thread siteImportThread = new Thread(){
public void run() {
Site existingSite = getStateSite(state);
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_START, existingSite.getReference(), false));
SessionManager.setCurrentSession(session);
SessionManager.setCurrentToolSession(toolSession);
importToolIntoSite(selectedTools, importTools,
existingSite);
existingSite = getStateSite(state); // refresh site for
// WC and News
commitSite(existingSite);
userNotificationProvider.notifySiteImportCompleted(userEmail, existingSite.getId(), existingSite.getTitle());
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_END, existingSite.getReference(), false));
}
};
siteImportThread.setName(threadName);
siteImportThread.start();
state.setAttribute(IMPORT_QUEUED, rb.get("importQueued"));
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
} else {
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
} else {
// new site
select_import_tools(params, state);
}
} else {
// read form input about import tools
select_import_tools(params, state);
}
break;
case 60:
/*
* actionForTemplate chef_site-importSitesMigrate.vm
*
*/
if (forward) {
Site existingSite = getStateSite(state);
if (existingSite != null) {
// revising a existing site's tool
if (select_import_tools(params, state)) {
String threadName = "SiteImportThread" + existingSite.getId();
boolean found = false;
//check all running threads for our named thread
//this isn't cluster safe, but this check it more targeted towards
//a single user re-importing multiple times during a slow import (which would be on the same server)
for(Thread t : Thread.getAllStackTraces().keySet()){
if(threadName.equals(t.getName())){
found = true;
break;
}
}
if(found){
//an existing thread is running for this site import, throw warning
addAlert(state, rb.getString("java.import.existing"));
}else{
final Hashtable importTools = (Hashtable) state
.getAttribute(STATE_IMPORT_SITE_TOOL);
final List selectedTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
final String userEmail = UserDirectoryService.getCurrentUser().getEmail();
final Session session = SessionManager.getCurrentSession();
final ToolSession toolSession = SessionManager.getCurrentToolSession();
Thread siteImportThread = new Thread(){
public void run() {
Site existingSite = getStateSite(state);
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_START, existingSite.getReference(), false));
SessionManager.setCurrentSession(session);
SessionManager.setCurrentToolSession(toolSession);
// Remove all old contents before importing contents from new site
importToolIntoSiteMigrate(selectedTools, importTools,
existingSite);
userNotificationProvider.notifySiteImportCompleted(userEmail, existingSite.getId(), existingSite.getTitle());
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_END, existingSite.getReference(), false));
}
};
siteImportThread.setName(threadName);
siteImportThread.start();
state.setAttribute(IMPORT_QUEUED, rb.get("importQueued"));
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
} else {
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
} else {
// new site
select_import_tools(params, state);
}
} else {
// read form input about import tools
select_import_tools(params, state);
}
break;
case 28:
/*
* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
state.removeAttribute(STATE_IMPORT_SITES);
} else {
List importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
sites.put(s, new Vector());
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 58:
/*
* actionForTemplate chef_siteinfo-importSelection.vm
*
*/
break;
case 59:
/*
* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
state.removeAttribute(STATE_IMPORT_SITES);
} else {
List importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
sites.put(s, new Vector());
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 29:
/*
* actionForTemplate chef_siteinfo-duplicate.vm
*
*/
if (forward) {
if (state.getAttribute(SITE_DUPLICATED) == null) {
if (StringUtils.trimToNull(params.getString("title")) == null) {
addAlert(state, rb.getString("java.dupli") + " ");
} else {
String title = params.getString("title");
state.setAttribute(SITE_DUPLICATED_NAME, title);
String newSiteId = IdManager.createUuid();
try {
String oldSiteId = (String) state
.getAttribute(STATE_SITE_INSTANCE_ID);
// Retrieve the source site reference to be used in the EventTrackingService
// notification of the start/end of a site duplication.
String sourceSiteRef = null;
try {
Site sourceSite = SiteService.getSite(oldSiteId);
sourceSiteRef = sourceSite.getReference();
} catch (IdUnusedException e) {
M_log.warn(this + ".actionForTemplate; case29: invalid source siteId: "+oldSiteId);
return;
}
// SAK-20797
long oldSiteQuota = this.getSiteSpecificQuota(oldSiteId);
Site site = SiteService.addSite(newSiteId,
getStateSite(state));
// An event for starting the "duplicate site" action
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_DUPLICATE_START, sourceSiteRef, site.getId(), false, NotificationService.NOTI_OPTIONAL));
// get the new site icon url
if (site.getIconUrl() != null)
{
site.setIconUrl(transferSiteResource(oldSiteId, newSiteId, site.getIconUrl()));
}
// set title
site.setTitle(title);
// SAK-20797 alter quota if required
boolean duplicateQuota = params.getString("dupequota") != null ? params.getBoolean("dupequota") : false;
if (duplicateQuota==true) {
if (oldSiteQuota > 0) {
M_log.info("Saving quota");
try {
String collId = m_contentHostingService
.getSiteCollection(site.getId());
ContentCollectionEdit col = m_contentHostingService.editCollection(collId);
ResourcePropertiesEdit resourceProperties = col.getPropertiesEdit();
resourceProperties.addProperty(
ResourceProperties.PROP_COLLECTION_BODY_QUOTA,
new Long(oldSiteQuota)
.toString());
m_contentHostingService.commitCollection(col);
} catch (Exception ignore) {
M_log.warn("saveQuota: unable to duplicate site-specific quota for site : "
+ site.getId() + " : " + ignore);
}
}
}
try {
SiteService.save(site);
// import tool content
importToolContent(oldSiteId, site, false);
String siteType = site.getType();
if (SiteTypeUtil.isCourseSite(siteType)) {
// for course site, need to
// read in the input for
// term information
String termId = StringUtils.trimToNull(params
.getString("selectTerm"));
if (termId != null) {
AcademicSession term = cms.getAcademicSession(termId);
if (term != null) {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(Site.PROP_SITE_TERM, term.getTitle());
rp.addProperty(Site.PROP_SITE_TERM_EID, term.getEid());
} else {
M_log.warn("termId=" + termId + " not found");
}
}
}
// save again
SiteService.save(site);
String realm = SiteService.siteReference(site.getId());
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm);
if (SiteTypeUtil.isCourseSite(siteType))
{
// also remove the provider id attribute if any
realmEdit.setProviderGroupId(null);
}
// add current user as the maintainer
realmEdit.addMember(UserDirectoryService.getCurrentUser().getId(), site.getMaintainRole(), true, false);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: IdUnusedException, not found, or not an AuthzGroup object "+ realm, e);
addAlert(state, rb.getString("java.realm"));
} catch (AuthzPermissionException e) {
addAlert(state, this + rb.getString("java.notaccess"));
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.notaccess"), e);
}
} catch (IdUnusedException e) {
M_log.warn(this + " actionForTemplate chef_siteinfo-duplicate:: IdUnusedException when saving " + newSiteId);
} catch (PermissionException e) {
M_log.warn(this + " actionForTemplate chef_siteinfo-duplicate:: PermissionException when saving " + newSiteId);
}
// TODO: hard coding this frame id
// is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
// send site notification
sendSiteNotification(state, site, null);
state.setAttribute(SITE_DUPLICATED, Boolean.TRUE);
// An event for ending the "duplicate site" action
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_DUPLICATE_END, sourceSiteRef, site.getId(), false, NotificationService.NOTI_OPTIONAL));
} catch (IdInvalidException e) {
addAlert(state, rb.getString("java.siteinval"));
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.siteinval") + " site id = " + newSiteId, e);
} catch (IdUsedException e) {
addAlert(state, rb.getString("java.sitebeenused"));
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.sitebeenused") + " site id = " + newSiteId, e);
} catch (PermissionException e) {
addAlert(state, rb.getString("java.allowcreate"));
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.allowcreate") + " site id = " + newSiteId, e);
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// site duplication confirmed
state.removeAttribute(SITE_DUPLICATED);
state.removeAttribute(SITE_DUPLICATED_NAME);
// return to the list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
break;
case 33:
break;
case 36:
/*
* actionForTemplate chef_site-newSiteCourse.vm
*/
if (forward) {
List providerChosenList = new Vector();
List providerDescriptionChosenList = new Vector();
if (params.getStrings("providerCourseAdd") == null) {
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
if (params.getString("manualAdds") == null) {
addAlert(state, rb.getString("java.manual") + " ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// The list of courses selected from provider listing
if (params.getStrings("providerCourseAdd") != null) {
providerChosenList = new ArrayList(Arrays.asList(params
.getStrings("providerCourseAdd"))); // list of
// description choices
if (params.getStrings("providerCourseAddDescription") != null) {
providerDescriptionChosenList = new ArrayList(Arrays.asList(params
.getStrings("providerCourseAddDescription"))); // list of
state.setAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN,
providerDescriptionChosenList);
}
// course
// ids
String userId = (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED);
String currentUserId = (String) state
.getAttribute(STATE_CM_CURRENT_USERID);
if (userId == null
|| (userId != null && userId
.equals(currentUserId))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
} else {
// STATE_CM_AUTHORIZER_SECTIONS are SectionObject,
// so need to prepare it
// also in this page, u can pick either section from
// current user OR
// sections from another users but not both. -
// daisy's note 1 for now
// till we are ready to add more complexity
List sectionObjectList = prepareSectionObject(
providerChosenList, userId);
state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS,
sectionObjectList);
state
.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
// set special instruction & we will keep
// STATE_CM_AUTHORIZER_LIST
String additional = StringUtils.trimToEmpty(params
.getString("additional"));
state.setAttribute(FORM_ADDITIONAL, additional);
}
}
collectNewSiteInfo(state, params, providerChosenList);
String find_course = params.getString("find_course");
if (state.getAttribute(STATE_TEMPLATE_SITE) != null && (find_course == null || !"true".equals(find_course)))
{
// creating based on template
doFinish(data);
}
}
}
break;
case 38:
break;
case 39:
break;
case 42:
/*
* actionForTemplate chef_site-type-confirm.vm
*
*/
break;
case 43:
/*
* actionForTemplate chef_site-editClass.vm
*
*/
if (forward) {
if (params.getStrings("providerClassDeletes") == null
&& params.getStrings("manualClassDeletes") == null
&& params.getStrings("cmRequestedClassDeletes") == null
&& !"back".equals(direction)) {
addAlert(state, rb.getString("java.classes"));
}
if (params.getStrings("providerClassDeletes") != null) {
// build the deletions list
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
List providerCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("providerClassDeletes")));
for (ListIterator i = providerCourseDeleteList
.listIterator(); i.hasNext();) {
providerCourseList.remove((String) i.next());
}
//Track provider deletes, seems like the only place to do it. If a confirmation is ever added somewhere, don't do this.
trackRosterChanges(org.sakaiproject.site.api.SiteService.EVENT_SITE_ROSTER_REMOVE,providerCourseDeleteList);
state.setAttribute(SITE_PROVIDER_COURSE_LIST,
providerCourseList);
}
if (params.getStrings("manualClassDeletes") != null) {
// build the deletions list
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
List manualCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("manualClassDeletes")));
for (ListIterator i = manualCourseDeleteList.listIterator(); i
.hasNext();) {
manualCourseList.remove((String) i.next());
}
state.setAttribute(SITE_MANUAL_COURSE_LIST,
manualCourseList);
}
if (params.getStrings("cmRequestedClassDeletes") != null) {
// build the deletions list
List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<String> cmRequestedCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("cmRequestedClassDeletes")));
for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i
.hasNext();) {
String sectionId = (String) i.next();
try
{
SectionObject so = new SectionObject(cms.getSection(sectionId));
SectionObject soFound = null;
for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();)
{
SectionObject k = (SectionObject) j.next();
if (k.eid.equals(sectionId))
{
soFound = k;
}
}
if (soFound != null) cmRequestedCourseList.remove(soFound);
}
catch (IdNotFoundException e)
{
M_log.warn("actionForTemplate 43 editClass: Cannot find section " + sectionId);
}
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList);
}
updateCourseClasses(state, new Vector(), new Vector());
}
break;
case 44:
if (forward) {
AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
Site site = getStateSite(state);
ResourcePropertiesEdit pEdit = site.getPropertiesEdit();
// update the course site property and realm based on the selection
updateCourseSiteSections(state, site.getId(), pEdit, a);
try
{
SiteService.save(site);
}
catch (Exception e)
{
M_log.warn(this + ".actionForTemplate chef_siteinfo-addCourseConfirm: " + e.getMessage() + site.getId(), e);
}
removeAddClassContext(state);
}
break;
case 54:
if (forward) {
// store answers to site setup questions
if (getAnswersToSetupQuestions(params, state))
{
state.setAttribute(STATE_TEMPLATE_INDEX, state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE));
}
}
break;
case 61:
// import users
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
} else {
importSitesUsers(params, state);
}
}
break;
}
}// actionFor Template
/**
*
* @param action
* @param providers
*/
private void trackRosterChanges(String event, List <String> rosters) {
if (ServerConfigurationService.getBoolean(
SiteHelper.WSETUP_TRACK_ROSTER_CHANGE, false)) {
// event for each individual update
if (rosters != null) {
for (String roster : rosters) {
EventTrackingService.post(EventTrackingService.newEvent(event, "roster="+roster, true));
}
}
}
}
/**
* import not-provided users from selected sites
* @param params
*/
private void importSitesUsers(ParameterParser params, SessionState state) {
// the target site
Site site = getStateSite(state);
try {
// the target realm
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(site.getId()));
List importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
for (int i = 0; i < importSites.size(); i++) {
String fromSiteId = (String) importSites.get(i);
try {
Site fromSite = SiteService.getSite(fromSiteId);
// get realm information
String fromRealmId = SiteService.siteReference(fromSite.getId());
AuthzGroup fromRealm = AuthzGroupService.getAuthzGroup(fromRealmId);
// get all users in the from site
Set fromUsers = fromRealm.getUsers();
for (Iterator iFromUsers = fromUsers.iterator(); iFromUsers.hasNext();)
{
String fromUserId = (String) iFromUsers.next();
Member fromMember = fromRealm.getMember(fromUserId);
if (!fromMember.isProvided())
{
// add user
realm.addMember(fromUserId, fromMember.getRole().getId(), fromMember.isActive(), false);
}
}
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".importSitesUsers: GroupNotDefinedException, " + fromSiteId + " not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.cannotedit"));
} catch (IdUnusedException e) {
M_log.warn(this + ".importSitesUsers: IdUnusedException, " + fromSiteId + " not found, or not an AuthzGroup object", e);
}
}
// post event about the realm participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realm.getId(), false));
// save realm
AuthzGroupService.save(realm);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".importSitesUsers: IdUnusedException, " + site.getTitle() + "(" + site.getId() + ") not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.cannotedit"));
} catch (AuthzPermissionException e) {
M_log.warn(this + ".importSitesUsers: PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + site.getId() + "). ", e);
addAlert(state, rb.getString("java.notaccess"));
}
}
/**
* This is used to update exsiting site attributes with encoded site id in it. A new resource item is added to new site when needed
*
* @param oSiteId
* @param nSiteId
* @param siteAttribute
* @return the new migrated resource url
*/
private String transferSiteResource(String oSiteId, String nSiteId, String siteAttribute) {
String rv = "";
String accessUrl = ServerConfigurationService.getAccessUrl();
if (siteAttribute!= null && siteAttribute.indexOf(oSiteId) != -1 && accessUrl != null)
{
// stripe out the access url, get the relative form of "url"
Reference ref = EntityManager.newReference(siteAttribute.replaceAll(accessUrl, ""));
try
{
ContentResource resource = m_contentHostingService.getResource(ref.getId());
// the new resource
ContentResource nResource = null;
String nResourceId = resource.getId().replaceAll(oSiteId, nSiteId);
try
{
nResource = m_contentHostingService.getResource(nResourceId);
}
catch (Exception n2Exception)
{
// copy the resource then
try
{
nResourceId = m_contentHostingService.copy(resource.getId(), nResourceId);
nResource = m_contentHostingService.getResource(nResourceId);
}
catch (Exception n3Exception)
{
}
}
// get the new resource url
rv = nResource != null?nResource.getUrl(false):"";
}
catch (Exception refException)
{
M_log.warn(this + ":transferSiteResource: cannot find resource with ref=" + ref.getReference() + " " + refException.getMessage());
}
}
return rv;
}
/**
* copy tool content from old site
* @param oSiteId source (old) site id
* @param site destination site
* @param bypassSecurity use SecurityAdvisor if true
*/
private void importToolContent(String oSiteId, Site site, boolean bypassSecurity) {
String nSiteId = site.getId();
// import tool content
if (bypassSecurity)
{
// importing from template, bypass the permission checking:
// temporarily allow the user to read and write from assignments (asn.revise permission)
SecurityService.pushAdvisor(new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
});
}
List pageList = site.getPages();
Set<String> toolsCopied = new HashSet<String>();
Map transversalMap = new HashMap();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList
.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
if (!(pageToolList == null || pageToolList.size() == 0))
{
Tool tool = ((ToolConfiguration) pageToolList.get(0)).getTool();
String toolId = tool != null?tool.getId():"";
if (toolId.equalsIgnoreCase("sakai.resources")) {
// handle
// resource
// tool
// specially
Map<String,String> entityMap = transferCopyEntities(
toolId,
m_contentHostingService
.getSiteCollection(oSiteId),
m_contentHostingService
.getSiteCollection(nSiteId));
if(entityMap != null){
transversalMap.putAll(entityMap);
}
} else if (toolId.equalsIgnoreCase(SITE_INFORMATION_TOOL)) {
// handle Home tool specially, need to update the site infomration display url if needed
String newSiteInfoUrl = transferSiteResource(oSiteId, nSiteId, site.getInfoUrl());
site.setInfoUrl(newSiteInfoUrl);
}
else {
// other
// tools
// SAK-19686 - added if statement and toolsCopied.add
if (!toolsCopied.contains(toolId)) {
Map<String,String> entityMap = transferCopyEntities(toolId,
oSiteId, nSiteId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
toolsCopied.add(toolId);
}
}
}
}
//update entity references
toolsCopied = new HashSet<String>();
for (ListIterator i = pageList
.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
if (!(pageToolList == null || pageToolList.size() == 0))
{
Tool tool = ((ToolConfiguration) pageToolList.get(0)).getTool();
String toolId = tool != null?tool.getId():"";
updateEntityReferences(toolId, nSiteId, transversalMap, site);
}
}
}
if (bypassSecurity)
{
SecurityService.popAdvisor();
}
}
/**
* get user answers to setup questions
* @param params
* @param state
* @return
*/
protected boolean getAnswersToSetupQuestions(ParameterParser params, SessionState state)
{
boolean rv = true;
String answerString = null;
String answerId = null;
Set userAnswers = new HashSet();
SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE));
if (siteTypeQuestions != null)
{
List<SiteSetupQuestion> questions = siteTypeQuestions.getQuestions();
for (Iterator i = questions.iterator(); i.hasNext();)
{
SiteSetupQuestion question = (SiteSetupQuestion) i.next();
// get the selected answerId
answerId = params.get(question.getId());
if (question.isRequired() && answerId == null)
{
rv = false;
addAlert(state, rb.getString("sitesetupquestion.alert"));
}
else if (answerId != null)
{
SiteSetupQuestionAnswer answer = questionService.getSiteSetupQuestionAnswer(answerId);
if (answer != null)
{
if (answer.getIsFillInBlank())
{
// need to read the text input instead
answerString = params.get("fillInBlank_" + answerId);
}
SiteSetupUserAnswer uAnswer = questionService.newSiteSetupUserAnswer();
uAnswer.setAnswerId(answerId);
uAnswer.setAnswerString(answerString);
uAnswer.setQuestionId(question.getId());
uAnswer.setUserId(SessionManager.getCurrentSessionUserId());
//update the state variable
userAnswers.add(uAnswer);
}
}
}
state.setAttribute(STATE_SITE_SETUP_QUESTION_ANSWER, userAnswers);
}
return rv;
}
/**
* remove related state variable for adding class
*
* @param state
* SessionState object
*/
private void removeAddClassContext(SessionState state) {
// remove related state variables
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTIONS);
state.removeAttribute(FORM_SITEINFO_ALIASES);
state.removeAttribute(FORM_SITEINFO_URL_BASE);
sitePropertiesIntoState(state);
} // removeAddClassContext
private void updateCourseClasses(SessionState state, List notifyClasses,
List requestClasses) {
List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
Site site = getStateSite(state);
String id = site.getId();
String realmId = SiteService.siteReference(id);
if ((providerCourseSectionList == null)
|| (providerCourseSectionList.size() == 0)) {
// no section access so remove Provider Id
try {
AuthzGroup realmEdit1 = AuthzGroupService
.getAuthzGroup(realmId);
boolean hasNonProvidedMainroleUser = false;
String maintainRoleString = realmEdit1.getMaintainRole();
Set<String> maintainRoleUsers = realmEdit1.getUsersHasRole(maintainRoleString);
if (!maintainRoleUsers.isEmpty())
{
for(Iterator<String> users = maintainRoleUsers.iterator(); !hasNonProvidedMainroleUser && users.hasNext();)
{
String userId = users.next();
if (!realmEdit1.getMember(userId).isProvided())
hasNonProvidedMainroleUser = true;
}
}
if (!hasNonProvidedMainroleUser)
{
// if after the removal, there is no provider id, and there is no maintain role user anymore, show alert message and don't save the update
addAlert(state, rb.getString("sitegen.siteinfolist.nomaintainuser")
+ maintainRoleString + ".");
}
else
{
realmEdit1.setProviderGroupId(NULL_STRING);
AuthzGroupService.save(realmEdit1);
}
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.cannotedit"));
return;
} catch (AuthzPermissionException e) {
M_log.warn(this + ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ", e);
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((providerCourseSectionList != null)
&& (providerCourseSectionList.size() != 0)) {
// section access so rewrite Provider Id, don't need the current realm provider String
String externalRealm = buildExternalRealm(id, state,
providerCourseSectionList, null);
try {
AuthzGroup realmEdit2 = AuthzGroupService
.getAuthzGroup(realmId);
realmEdit2.setProviderGroupId(externalRealm);
AuthzGroupService.save(realmEdit2);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.cannotclasses"));
return;
} catch (AuthzPermissionException e) {
M_log.warn(this
+ ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ", e);
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
//reload the site object after changes group realms have been removed from the site.
site = getStateSite(state);
// the manual request course into properties
setSiteSectionProperty(manualCourseSectionList, site, PROP_SITE_REQUEST_COURSE);
// the cm request course into properties
setSiteSectionProperty(cmRequestedCourseList, site, STATE_CM_REQUESTED_SECTIONS);
// clean the related site groups
// if the group realm provider id is not listed for the site, remove the related group
for (Iterator iGroups = site.getGroups().iterator(); iGroups.hasNext();)
{
Group group = (Group) iGroups.next();
try
{
AuthzGroup gRealm = AuthzGroupService.getAuthzGroup(group.getReference());
String gProviderId = StringUtils.trimToNull(gRealm.getProviderGroupId());
if (gProviderId != null)
{
if (!listContainsString(manualCourseSectionList, gProviderId)
&& !listContainsString(cmRequestedCourseList, gProviderId)
&& !listContainsString(providerCourseSectionList, gProviderId))
{
// if none of those three lists contains the provider id, remove the group and realm
AuthzGroupService.removeAuthzGroup(group.getReference());
}
}
}
catch (Exception e)
{
M_log.warn(this + ".updateCourseClasses: cannot remove authzgroup : " + group.getReference(), e);
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(site);
} else {
}
if (requestClasses != null && requestClasses.size() > 0
&& state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
try {
// send out class request notifications
sendSiteRequest(state, "change",
((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(),
(List<SectionObject>) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS),
"manual");
} catch (Exception e) {
M_log.warn(this +".updateCourseClasses:" + e.toString(), e);
}
}
if (notifyClasses != null && notifyClasses.size() > 0) {
try {
// send out class access confirmation notifications
sendSiteNotification(state, getStateSite(state), notifyClasses);
} catch (Exception e) {
M_log.warn(this + ".updateCourseClasses:" + e.toString(), e);
}
}
} // updateCourseClasses
/**
* test whether
* @param list
* @param providerId
* @return
*/
boolean listContainsString(List list, String s)
{
boolean rv = false;
if (list != null && !list.isEmpty() && s != null && s.length() != 0)
{
for (Object o : list)
{
// deals with different object type
if (o instanceof SectionObject)
{
rv = ((SectionObject) o).getEid().equals(s);
}
else if (o instanceof String)
{
rv = ((String) o).equals(s);
}
// exit when find match
if (rv)
break;
}
}
return rv;
}
private void setSiteSectionProperty(List courseSectionList, Site site, String propertyName) {
if ((courseSectionList != null) && (courseSectionList.size() != 0)) {
// store the requested sections in one site property
StringBuffer sections = new StringBuffer();
for (int j = 0; j < courseSectionList.size();) {
sections = sections.append(courseSectionList.get(j));
if (courseSectionList.get(j) instanceof SectionObject)
{
SectionObject so = (SectionObject) courseSectionList.get(j);
sections = sections.append(so.getEid());
}
else if (courseSectionList.get(j) instanceof String)
{
sections = sections.append((String) courseSectionList.get(j));
}
j++;
if (j < courseSectionList.size()) {
sections = sections.append("+");
}
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(propertyName, sections.toString());
} else {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.removeProperty(propertyName);
}
}
/**
* Sets selected roles for multiple users
*
* @param params
* The ParameterParser object
* @param listName
* The state variable
*/
private void getSelectedRoles(SessionState state, ParameterParser params,
String listName) {
Hashtable pSelectedRoles = (Hashtable) state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
if (pSelectedRoles == null) {
pSelectedRoles = new Hashtable();
}
List userList = (List) state.getAttribute(listName);
for (int i = 0; i < userList.size(); i++) {
String userId = null;
if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) {
userId = ((Participant) userList.get(i)).getUniqname();
} else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) {
userId = (String) userList.get(i);
}
if (userId != null) {
String rId = StringUtils.trimToNull(params.getString("role"
+ userId));
if (rId == null) {
addAlert(state, rb.getString("java.rolefor") + " " + userId
+ ". ");
pSelectedRoles.remove(userId);
} else {
pSelectedRoles.put(userId, rId);
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles);
} // getSelectedRoles
/**
* dispatch function for changing participants roles
*/
public void doSiteinfo_edit_role(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("same_role_true")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params
.getString("role_to_all"));
} else if (option.equalsIgnoreCase("same_role_false")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) {
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
new Hashtable());
}
} else if (option.equalsIgnoreCase("continue")) {
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
doCancel(data);
}
} // doSiteinfo_edit_role
/**
* save changes to site global access
*/
public void doSiteinfo_save_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site s = getStateSite(state);
boolean joinable = ((Boolean) state.getAttribute("form_joinable"))
.booleanValue();
s.setJoinable(joinable);
if (joinable) {
// set the joiner role
String joinerRole = (String) state.getAttribute("form_joinerRole");
s.setJoinerRole(joinerRole);
// bjones86 - SAK-24423 - update site properties for joinable site settings
JoinableSiteSettings.updateSitePropertiesFromStateOnSiteInfoSaveGlobalAccess( s.getPropertiesEdit(), state );
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// release site edit
commitSite(s);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doSiteinfo_save_globalAccess
/**
* updateSiteAttributes
*
*/
private void updateSiteAttributes(SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
M_log
.warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null");
return;
}
Site site = getStateSite(state);
if (site != null) {
if (StringUtils.trimToNull(siteInfo.title) != null) {
site.setTitle(siteInfo.title);
}
if (siteInfo.description != null) {
site.setDescription(siteInfo.description);
}
site.setPublished(siteInfo.published);
setAppearance(state, site, siteInfo.iconUrl);
site.setJoinable(siteInfo.joinable);
if (StringUtils.trimToNull(siteInfo.joinerRole) != null) {
site.setJoinerRole(siteInfo.joinerRole);
}
// Make changes and then put changed site back in state
String id = site.getId();
// bjones86 - SAK-24423 - update site properties for joinable site settings
JoinableSiteSettings.updateSitePropertiesFromStateOnUpdateSiteAttributes( site, state );
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
if (SiteService.allowUpdateSite(id)) {
try {
SiteService.getSite(id);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
} catch (IdUnusedException e) {
M_log.warn(this + ".updateSiteAttributes: IdUnusedException "
+ siteInfo.getTitle() + "(" + id + ") not found", e);
}
}
// no permission
else {
addAlert(state, rb.getString("java.makechanges"));
M_log.warn(this + ".updateSiteAttributes: PermissionException "
+ siteInfo.getTitle() + "(" + id + ")");
}
}
} // updateSiteAttributes
/**
* %%% legacy properties, to be removed
*/
private void updateSiteInfo(ParameterParser params, SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE);
// title
boolean hasRosterAttached = params.getString("hasRosterAttached") != null ? Boolean.getBoolean(params.getString("hasRosterAttached")) : false;
if ((siteTitleEditable(state, siteInfo.site_type) || !hasRosterAttached) && params.getString("title") != null)
{
// site titel is editable and could not be null
String title = StringUtils.trimToNull(params.getString("title"));
siteInfo.title = title;
if (title == null) {
addAlert(state, rb.getString("java.specify") + " ");
}
// check for site title length
else if (title.length() > SiteConstants.SITE_GROUP_TITLE_LIMIT)
{
addAlert(state, rb.getFormattedMessage("site_group_title_length_limit", new Object[]{SiteConstants.SITE_GROUP_TITLE_LIMIT}));
}
}
if (params.getString("description") != null) {
StringBuilder alertMsg = new StringBuilder();
String description = params.getString("description");
siteInfo.description = FormattedText.processFormattedText(description, alertMsg);
}
if (params.getString("short_description") != null) {
siteInfo.short_description = params.getString("short_description");
}
String skin = params.getString("skin");
if (skin != null) {
// if there is a skin input for course site
skin = StringUtils.trimToNull(skin);
siteInfo.iconUrl = skin;
} else {
// if ther is a icon input for non-course site
String icon = StringUtils.trimToNull(params.getString("icon"));
if (icon != null) {
if (icon.endsWith(PROTOCOL_STRING)) {
addAlert(state, rb.getString("alert.protocol"));
}
siteInfo.iconUrl = icon;
} else {
siteInfo.iconUrl = "";
}
}
if (params.getString("additional") != null) {
siteInfo.additional = params.getString("additional");
}
if (params.getString("iconUrl") != null) {
siteInfo.iconUrl = params.getString("iconUrl");
} else if (params.getString("skin") != null) {
siteInfo.iconUrl = params.getString("skin");
}
if (params.getString("joinerRole") != null) {
siteInfo.joinerRole = params.getString("joinerRole");
}
if (params.getString("joinable") != null) {
boolean joinable = params.getBoolean("joinable");
siteInfo.joinable = joinable;
if (!joinable)
siteInfo.joinerRole = NULL_STRING;
}
if (params.getString("itemStatus") != null) {
siteInfo.published = Boolean
.valueOf(params.getString("itemStatus")).booleanValue();
}
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromParams( params, siteInfo );
// site contact information
String name = StringUtils.trimToEmpty(params.getString("siteContactName"));
if (name.length() == 0)
{
addAlert(state, rb.getString("alert.sitediinf.sitconnam"));
}
siteInfo.site_contact_name = name;
String email = StringUtils.trimToEmpty(params
.getString("siteContactEmail"));
if (email != null) {
if (!email.isEmpty() && !EmailValidator.getInstance().isValid(email)) {
// invalid email
addAlert(state, rb.getFormattedMessage("java.invalid.email", new Object[]{FormattedText.escapeHtml(email,false)}));
}
siteInfo.site_contact_email = email;
}
int aliasCount = params.getInt("alias_count", 0);
siteInfo.siteRefAliases.clear();
for ( int j = 0; j < aliasCount ; j++ ) {
String alias = StringUtils.trimToNull(params.getString("alias_" + j));
if ( alias == null ) {
continue;
}
// Kernel will force these to lower case anyway. Forcing
// to lower case whenever reading out of the form simplifies
// comparisons at save time, though, and provides consistent
// on-screen display.
alias = alias.toLowerCase();
// An invalid alias will set an alert, which theoretically
// disallows further progress in the workflow, but we
// still need to re-render the invalid form contents.
// Thus siteInfo.aliases contains all input aliases, even if
// invalid. (Same thing happens above for email.)
validateSiteAlias(alias, state);
siteInfo.siteRefAliases.add(alias);
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // updateSiteInfo
private boolean validateSiteAlias(String aliasId, SessionState state) {
if ( (aliasId = StringUtils.trimToNull(aliasId)) == null ) {
addAlert(state, rb.getFormattedMessage("java.alias.isinval", new Object[]{aliasId}));
return false;
}
boolean isSimpleResourceName = aliasId.equals(Validator.escapeResourceName(aliasId));
boolean isSimpleUrl = aliasId.equals(Validator.escapeUrl(aliasId));
if ( !(isSimpleResourceName) || !(isSimpleUrl) ) {
// The point of these site aliases is to have easy-to-recall,
// easy-to-guess URLs. So we take a very conservative approach
// here and disallow any aliases which would require special
// encoding or would simply be ignored when building a valid
// resource reference or outputting that reference as a URL.
addAlert(state, rb.getFormattedMessage("java.alias.isinval", new Object[]{aliasId}));
return false;
} else {
String currentSiteId = StringUtils.trimToNull((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
boolean editingSite = currentSiteId != null;
try {
String targetRef = AliasService.getTarget(aliasId);
if ( editingSite ) {
String siteRef = SiteService.siteReference(currentSiteId);
boolean targetsCurrentSite = siteRef.equals(targetRef);
if ( !(targetsCurrentSite) ) {
addAlert(state, rb.getFormattedMessage("java.alias.exists", new Object[]{aliasId}));
return false;
}
} else {
addAlert(state, rb.getFormattedMessage("java.alias.exists", new Object[]{aliasId}));
return false;
}
} catch (IdUnusedException e) {
// No conflicting aliases
}
return true;
}
}
/**
* getParticipantList
*
*/
private Collection getParticipantList(SessionState state) {
List members = new Vector();
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List providerCourseList = null;
providerCourseList = SiteParticipantHelper.getProviderCourseList(siteId);
if (providerCourseList != null && providerCourseList.size() > 0) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
Collection participants = SiteParticipantHelper.prepareParticipants(siteId, providerCourseList);
state.setAttribute(STATE_PARTICIPANT_LIST, participants);
return participants;
} // getParticipantList
/**
* getRoles
*
*/
private List getRoles(SessionState state) {
List roles = new Vector();
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
roles.addAll(realm.getRoles());
Collections.sort(roles);
} catch (GroupNotDefinedException e) {
M_log.warn( this + ".getRoles: IdUnusedException " + realmId, e);
}
return roles;
} // getRoles
/**
* getRoles
*
* bjones86 - SAK-23257 - added state and siteType parameters so list
* of joiner roles can respect the restricted role lists in sakai.properties.
*
*/
private List<Role> getJoinerRoles(String realmId, SessionState state, String siteType) {
List roles = new ArrayList();
/** related to SAK-18462, this is a list of permissions that the joinable roles shouldn't have ***/
String[] prohibitPermissionForJoinerRole = ServerConfigurationService.getStrings("siteinfo.prohibited_permission_for_joiner_role");
if (prohibitPermissionForJoinerRole == null) {
prohibitPermissionForJoinerRole = new String[]{"site.upd"};
}
if (realmId != null)
{
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
// get all roles that allows at least one permission in the list
Set<String> permissionAllowedRoleIds = new HashSet<String>();
for(String permission:prohibitPermissionForJoinerRole)
{
permissionAllowedRoleIds.addAll(realm.getRolesIsAllowed(permission));
}
// bjones86 - SAK-23257
List<Role> allowedRoles = null;
Set<String> restrictedRoles = null;
if (null == state.getAttribute(STATE_SITE_INSTANCE_ID)) {
restrictedRoles = SiteParticipantHelper.getRestrictedRoles(state.getAttribute(STATE_SITE_TYPE ).toString());
}
else {
allowedRoles = SiteParticipantHelper.getAllowedRoles(siteType, getRoles(state));
}
for(Role role:realm.getRoles())
{
if (permissionAllowedRoleIds == null
|| permissionAllowedRoleIds!= null && !permissionAllowedRoleIds.contains(role.getId()))
{
// bjones86 - SAK-23257
if (allowedRoles != null && allowedRoles.contains(role)) {
roles.add(role);
}
else if (restrictedRoles != null &&
(!restrictedRoles.contains(role.getId()) || !restrictedRoles.contains(role.getId().toLowerCase()))) {
roles.add(role);
}
}
}
Collections.sort(roles);
} catch (GroupNotDefinedException e) {
M_log.warn( this + ".getRoles: IdUnusedException " + realmId, e);
}
}
return roles;
} // getRolesWithoutPermission
private void addSynopticTool(SitePage page, String toolId,
String toolTitle, String layoutHint, int position) {
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
// Add synoptic announcements tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool(toolId);
tool.setTool(toolId, reg);
tool.setTitle(toolTitle);
tool.setLayoutHints(layoutHint);
// count how many synoptic tools in the second/right column
int totalSynopticTools = 0;
for (ToolConfiguration t : page.getTools())
{
if (t.getToolId() != null && SYNOPTIC_TOOL_ID_MAP.containsKey(t.getToolId()))
{
totalSynopticTools++;
}
}
// now move the newly added synoptic tool to proper position
for (int i=0; i< (totalSynopticTools-position-1);i++)
{
tool.moveUp();
}
}
private void saveFeatures(ParameterParser params, SessionState state, Site site) {
String siteType = checkNullSiteType(state, site.getType(), site.getId());
// get the list of Worksite Setup configured pages
List wSetupPageList = state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST)!=null?(List) state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST):new Vector();
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
WorksiteSetupPage wSetupHome = new WorksiteSetupPage();
List pageList = new Vector();
// declare some flags used in making decisions about Home, whether to
// add, remove, or do nothing
boolean hasHome = false;
String homePageId = null;
boolean homeInWSetupPageList = false;
List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
boolean hasEmail = false;
boolean hasSiteInfo = false;
// tools to be imported from other sites?
Hashtable importTools = null;
if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) {
importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);
}
// Home tool chosen?
if (chosenList.contains(TOOL_ID_HOME)) {
// add home tool later
hasHome = true;
}
// order the id list
chosenList = orderToolIds(state, siteType, chosenList, false);
// Special case - Worksite Setup Home comes from a hardcoded checkbox on
// the vm template rather than toolRegistrationList
// see if Home was chosen
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String choice = (String) j.next();
if ("sakai.mailbox".equals(choice)) {
hasEmail = true;
String alias = StringUtils.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
String channelReference = mailArchiveChannelReference(site.getId());
if (alias != null) {
if (!Validator.checkEmailLocal(alias)) {
addAlert(state, rb.getString("java.theemail"));
} else if (!AliasService.allowSetAlias(alias, channelReference )) {
addAlert(state, rb.getString("java.addalias"));
} else {
try {
// first, clear any alias set to this channel
AliasService.removeTargetAliases(channelReference); // check
// to
// see
// whether
// the
// alias
// has
// been
// used
try {
String target = AliasService.getTarget(alias);
boolean targetsThisSite = site.getReference().equals(target);
if (!(targetsThisSite)) {
addAlert(state, rb.getString("java.emailinuse") + " ");
}
} catch (IdUnusedException ee) {
try {
AliasService.setAlias(alias,
channelReference);
} catch (IdUsedException exception) {
} catch (IdInvalidException exception) {
} catch (PermissionException exception) {
}
}
} catch (PermissionException exception) {
}
}
}
}else if (choice.equals(TOOL_ID_SITEINFO)) {
hasSiteInfo = true;
}
}
// see if Home and/or Help in the wSetupPageList (can just check title
// here, because we checked patterns before adding to the list)
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
wSetupPage = (WorksiteSetupPage) i.next();
if (isHomePage(site.getPage(wSetupPage.getPageId()))) {
homeInWSetupPageList = true;
homePageId = wSetupPage.getPageId();
break;
}
}
if (hasHome) {
SitePage page = site.getPage(homePageId);
if (!homeInWSetupPageList) {
// if Home is chosen and Home is not in wSetupPageList, add Home
// to site and wSetupPageList
page = site.addPage();
page.setTitle(rb.getString("java.home"));
wSetupHome.pageId = page.getId();
wSetupHome.pageTitle = page.getTitle();
wSetupHome.toolId = TOOL_ID_HOME;
wSetupPageList.add(wSetupHome);
}
// the list tools on the home page
List<ToolConfiguration> toolList = page.getTools();
// get tool id set for Home page from configuration
List<String> homeToolIds = getHomeToolIds(state, !homeInWSetupPageList, page);
// count
int nonSynopticToolIndex=0, synopticToolIndex = 0;
for (String homeToolId: homeToolIds)
{
if (!SYNOPTIC_TOOL_ID_MAP.containsKey(homeToolId))
{
if (!pageHasToolId(toolList, homeToolId))
{
// not a synoptic tool and is not in Home page yet, just add it
Tool reg = ToolManager.getTool(homeToolId);
if (reg != null)
{
ToolConfiguration tool = page.addTool();
tool.setTool(homeToolId, reg);
tool.setTitle(reg.getTitle() != null?reg.getTitle():"");
tool.setLayoutHints("0," + nonSynopticToolIndex++);
}
}
}
else
{
// synoptic tool
List<String> parentToolList = (List<String>) SYNOPTIC_TOOL_ID_MAP.get(homeToolId);
List chosenListClone = new Vector();
// chosenlist may have things like bcf89cd4-fa3a-4dda-80bd-ed0b89981ce7sakai.chat
// get list of the actual tool names
List<String>chosenOrigToolList = new ArrayList<String>();
for (String chosenTool: (List<String>)chosenList)
chosenOrigToolList.add(findOriginalToolId(state, chosenTool));
chosenListClone.addAll(chosenOrigToolList);
boolean hasAnyParentToolId = chosenListClone.removeAll(parentToolList);
//first check whether the parent tool is available in site but its parent tool is no longer selected
if (pageHasToolId(toolList, homeToolId))
{
if (!hasAnyParentToolId && !SiteService.isUserSite(site.getId()))
{
for (ListIterator iToolList = toolList.listIterator(); iToolList.hasNext();)
{
ToolConfiguration tConf= (ToolConfiguration) iToolList.next();
// avoid NPE when the tool definition is missing
if (tConf.getTool() != null && homeToolId.equals(tConf.getTool().getId()))
{
page.removeTool((ToolConfiguration) tConf);
break;
}
}
}
else
{
synopticToolIndex++;
}
}
// then add those synoptic tools which wasn't there before
if (!pageHasToolId(toolList, homeToolId) && hasAnyParentToolId)
{
try
{
// use value from map to find an internationalized tool title
String toolTitleText = rb.getString(SYNOPTIC_TOOL_TITLE_MAP.get(homeToolId));
addSynopticTool(page, homeToolId, toolTitleText, synopticToolIndex + ",1", synopticToolIndex++);
} catch (Exception e) {
M_log.warn(this + ".saveFeatures addSynotpicTool: " + e.getMessage() + " site id = " + site.getId() + " tool = " + homeToolId, e);
}
}
}
}
if (page.getTools().size() == 1)
{
// only use one column layout
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
// mark this page as Home page inside its property
if (page.getProperties().getProperty(SitePage.IS_HOME_PAGE) == null)
{
page.getPropertiesEdit().addProperty(SitePage.IS_HOME_PAGE, Boolean.TRUE.toString());
}
} // add Home
// if Home is in wSetupPageList and not chosen, remove Home feature from
// wSetupPageList and site
if (!hasHome && homeInWSetupPageList) {
// remove Home from wSetupPageList
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
SitePage sitePage = site.getPage(comparePage.getPageId());
if (sitePage != null && isHomePage(sitePage)) {
// remove the Home page
site.removePage(sitePage);
wSetupPageList.remove(comparePage);
break;
}
}
}
// declare flags used in making decisions about whether to add, remove,
// or do nothing
boolean inChosenList;
boolean inWSetupPageList;
Set categories = new HashSet();
// UMICH 1035
categories.add(siteType);
categories.add(SiteTypeUtil.getTargetSiteType(siteType));
Set toolRegistrationSet = ToolManager.findTools(categories, null);
// first looking for any tool for removal
Vector removePageIds = new Vector();
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page id + tool id for multiple tool instances
if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
inChosenList = false;
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
if (pageToolId.equals(toolId)) {
inChosenList = true;
}
}
// exclude the Home page if there is any
if (!inChosenList && !(homePageId != null && wSetupPage.getPageId().equals(homePageId))) {
removePageIds.add(wSetupPage.getPageId());
}
}
for (int i = 0; i < removePageIds.size(); i++) {
// if the tool exists in the wSetupPageList, remove it from the site
String removeId = (String) removePageIds.get(i);
SitePage sitePage = site.getPage(removeId);
site.removePage(sitePage);
// and remove it from wSetupPageList
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
if (!wSetupPage.getPageId().equals(removeId)) {
wSetupPage = null;
}
}
if (wSetupPage != null) {
wSetupPageList.remove(wSetupPage);
}
}
// then looking for any tool to add
for (ListIterator j = orderToolIds(state, siteType, chosenList, false)
.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
boolean multiAllowed = isMultipleInstancesAllowed(findOriginalToolId(state, toolId));
// exclude Home tool
if (!toolId.equals(TOOL_ID_HOME))
{
// Is the tool in the wSetupPageList?
inWSetupPageList = false;
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page Id + toolId for multiple tool instances
if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
if (pageToolId.equals(toolId)) {
inWSetupPageList = true;
// but for tool of multiple instances, need to change the title
if (multiAllowed) {
SitePage pEdit = (SitePage) site
.getPage(wSetupPage.pageId);
pEdit.setTitle((String) multipleToolIdTitleMap.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) jTool
.next();
String tId = tool.getTool().getId();
if (isMultipleInstancesAllowed(findOriginalToolId(state, tId))) {
// set tool title
tool.setTitle((String) multipleToolIdTitleMap.get(toolId));
// save tool configuration
saveMultipleToolConfiguration(state, tool, toolId);
}
}
}
}
}
if (inWSetupPageList) {
// if the tool already in the list, do nothing so to save the
// option settings
} else {
// if in chosen list but not in wSetupPageList, add it to the
// site (one tool on a page)
Tool toolRegFound = null;
for (Iterator i = toolRegistrationSet.iterator(); i.hasNext();) {
Tool toolReg = (Tool) i.next();
String toolRegId = toolReg.getId();
if (toolId.equals(toolRegId)) {
toolRegFound = toolReg;
break;
}
else if (multiAllowed && toolId.startsWith(toolRegId))
{
try
{
// in case of adding multiple tools, tool id is of format ORIGINAL_TOOL_ID + INDEX_NUMBER
Integer.parseInt(toolId.replace(toolRegId, ""));
toolRegFound = toolReg;
break;
}
catch (Exception parseException)
{
// ignore parse exception
}
}
}
if (toolRegFound != null) {
// we know such a tool, so add it
WorksiteSetupPage addPage = new WorksiteSetupPage();
SitePage page = site.addPage();
addPage.pageId = page.getId();
if (multiAllowed) {
// set tool title
page.setTitle((String) multipleToolIdTitleMap.get(toolId));
page.setTitleCustom(true);
} else {
// other tools with default title
page.setTitle(toolRegFound.getTitle());
}
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
// if so specified in the tool's registration file,
// configure the tool's page to open in a new window.
if ("true".equals(toolRegFound.getRegisteredConfig().getProperty("popup"))) {
page.setPopup(true);
}
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
addPage.toolId = toolId;
wSetupPageList.add(addPage);
// set tool title
if (multiAllowed) {
// set tool title
tool.setTitle((String) multipleToolIdTitleMap.get(toolId));
// save tool configuration
saveMultipleToolConfiguration(state, tool, toolId);
} else {
tool.setTitle(toolRegFound.getTitle());
}
}
}
}
} // for
// commit
commitSite(site);
site = refreshSiteObject(site);
// check the status of external lti tools
// 1. any lti tool to remove?
HashMap<String, Map<String, Object>> ltiTools = state.getAttribute(STATE_LTITOOL_SELECTED_LIST) != null?(HashMap<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_SELECTED_LIST):null;
Map<String, Map<String, Object>> oldLtiTools = state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) != null? (Map<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) : null;;
if (oldLtiTools != null)
{
// get all the old enalbed lti tools
for(String oldLtiToolsId : oldLtiTools.keySet())
{
if (ltiTools == null || !ltiTools.containsKey(oldLtiToolsId))
{
// the tool is not selectd now. Remove it from site
Map<String, Object> oldLtiToolValues = oldLtiTools.get(oldLtiToolsId);
Long contentKey = Long.valueOf(oldLtiToolValues.get("contentKey").toString());
m_ltiService.deleteContent(contentKey);
// refresh the site object
site = refreshSiteObject(site);
}
}
}
// 2. any lti tool to add?
if (ltiTools != null)
{
// then looking for any lti tool to add
for (Map.Entry<String, Map<String, Object>> ltiTool : ltiTools.entrySet()) {
String ltiToolId = ltiTool.getKey();
if (!oldLtiTools.containsKey(ltiToolId))
{
Map<String, Object> toolValues = ltiTool.getValue();
Properties reqProperties = (Properties) toolValues.get("reqProperties");
if (reqProperties==null) {
reqProperties = new Properties();
}
Object retval = m_ltiService.insertToolContent(null, ltiToolId, reqProperties, site.getId());
if (retval instanceof String)
{
// error inserting tool content
addAlert(state, (String) retval);
break;
}
else
{
// success inserting tool content
String pageTitle = reqProperties.getProperty("pagetitle");
retval = m_ltiService.insertToolSiteLink(((Long) retval).toString(), pageTitle, site.getId());
if (retval instanceof String)
{
addAlert(state, ((String) retval).substring(2));
break;
}
}
}
// refresh the site object
site = refreshSiteObject(site);
}
} // if
// reorder Home and Site Info only if the site has not been customized order before
if (!site.isCustomPageOrdered())
{
// the steps for moving page within the list
int moves = 0;
if (hasHome) {
SitePage homePage = null;
// Order tools - move Home to the top - first find it
pageList = site.getPages();
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
if (isHomePage(page))
{
homePage = page;
break;
}
}
}
if (homePage != null)
{
moves = pageList.indexOf(homePage);
for (int n = 0; n < moves; n++) {
homePage.moveUp();
}
}
}
// if Site Info is newly added, more it to the last
if (hasSiteInfo) {
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = { TOOL_ID_SITEINFO };
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); siteInfoPage == null
&& i.hasNext();) {
SitePage page = (SitePage) i.next();
int s = page.getTools(toolIds).size();
if (s > 0) {
siteInfoPage = page;
break;
}
}
if (siteInfoPage != null)
{
// move home from it's index to the first position
moves = pageList.indexOf(siteInfoPage);
for (int n = moves; n < pageList.size(); n++) {
siteInfoPage.moveDown();
}
}
}
}
}
// if there is no email tool chosen
if (!hasEmail) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
// commit
commitSite(site);
site = refreshSiteObject(site);
// import
importToolIntoSite(chosenList, importTools, site);
} // saveFeatures
/**
* refresh site object
* @param site
* @return
*/
private Site refreshSiteObject(Site site) {
// refresh the site object
try
{
site = SiteService.getSite(site.getId());
}
catch (Exception e)
{
// error getting site after tool modification
M_log.warn(this + " - cannot get site " + site.getId() + " after inserting lti tools");
}
return site;
}
/**
* Save configuration values for multiple tool instances
*/
private void saveMultipleToolConfiguration(SessionState state, ToolConfiguration tool, String toolId) {
// get the configuration of multiple tool instance
HashMap<String, HashMap<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(HashMap<String, HashMap<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap<String, HashMap<String, String>>();
// set tool attributes
HashMap<String, String> attributes = multipleToolConfiguration.get(toolId);
if (attributes != null)
{
for(Map.Entry<String, String> attributeEntry : attributes.entrySet())
{
String attribute = attributeEntry.getKey();
String attributeValue = attributeEntry.getValue();
// if we have a value
if (attributeValue != null)
{
// if this value is not the same as the tool's registered, set it in the placement
if (!attributeValue.equals(tool.getTool().getRegisteredConfig().getProperty(attribute)))
{
tool.getPlacementConfig().setProperty(attribute, attributeValue);
}
// otherwise clear it
else
{
tool.getPlacementConfig().remove(attribute);
}
}
// if no value
else
{
tool.getPlacementConfig().remove(attribute);
}
}
}
}
/**
* Is the tool stealthed or hidden
* @param toolId
* @return
*/
private boolean notStealthOrHiddenTool(String toolId) {
Tool tool = ToolManager.getTool(toolId);
Set<Tool> tools = ToolManager.findTools(Collections.emptySet(), null);
boolean result = tool != null && tools.contains(tool);
return result;
}
/**
* Is the siteType listed in the tool properties list of categories?
* @param siteType
* @param tool
* @return
* SAK 23808
*/
private boolean isSiteTypeInToolCategory(String siteType, Tool tool) {
Set<Tool> tools = ToolManager.findTools(Collections.emptySet(), null);
Set<String> categories = tool.getCategories();
Iterator<String> iterator = categories.iterator();
while(iterator.hasNext()) {
String nextCat = iterator.next();
if(nextCat.equals(siteType)) {
return true;
}
}
return false;
}
/**
* getFeatures gets features for a new site
*
*/
private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) {
List idsSelected = new Vector();
List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
// to reset the state variable of the multiple tool instances
Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet();
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// related to LTI Tool selection
Map<String, Map<String, Object>> existingLtiIds = state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) != null? (Map<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST):null;
HashMap<String, Map<String, Object>> ltiTools = (HashMap<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_LIST);
HashMap<String, Map<String, Object>> ltiSelectedTools = new HashMap<String, Map<String, Object>> ();
boolean goToToolConfigPage = false;
boolean homeSelected = false;
// lti tool selection
boolean ltiToolSelected = false;
// Add new pages and tools, if any
if (params.getStrings("selectedTools") == null && params.getStrings("selectedLtiTools") == null) {
addAlert(state, rb.getString("atleastonetool"));
} else {
List l = new ArrayList(Arrays.asList(params
.getStrings("selectedTools"))); // toolId's of chosen tools
for (int i = 0; i < l.size(); i++) {
String toolId = (String) l.get(i);
if (toolId.equals(TOOL_ID_HOME)) {
homeSelected = true;
if (!idsSelected.contains(toolId))
idsSelected.add(toolId);
}
else if (toolId.startsWith(LTITOOL_ID_PREFIX))
{
String ltiToolId = toolId.substring(LTITOOL_ID_PREFIX.length());
// whether there is any lti tool been selected
if (existingLtiIds == null)
{
ltiToolSelected = true;
}
else
{
if (!existingLtiIds.keySet().contains(ltiToolId))
{
// there are some new lti tool(s) selected
ltiToolSelected = true;
}
}
// add tool entry to list
ltiSelectedTools.put(ltiToolId, ltiTools.get(ltiToolId));
}
else
{
String originId = findOriginalToolId(state, toolId);
if (isMultipleInstancesAllowed(originId))
{
// if user is adding either EmailArchive tool, News tool
// or Web Content tool, go to the Customize page for the
// tool
if (!existTools.contains(toolId)) {
goToToolConfigPage = true;
if (!multipleToolIdSet.contains(toolId))
multipleToolIdSet.add(toolId);
if (!multipleToolIdTitleMap.containsKey(toolId))
{
// reset tool title if there is a different title config setting
String titleConfig = ServerConfigurationService.getString(CONFIG_TOOL_TITLE + originId);
if (titleConfig != null && titleConfig.length() > 0 )
{
multipleToolIdTitleMap.put(toolId, titleConfig);
}
else
{
multipleToolIdTitleMap.put(toolId, ToolManager.getTool(originId).getTitle());
}
}
}
}
else if ("sakai.mailbox".equals(toolId)) {
// get the email alias when an Email Archive tool
// has been selected
String alias = getSiteAlias(mailArchiveChannelReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID)));
if (alias != null) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, alias);
}
// go to the config page
if (!existTools.contains(toolId))
{
goToToolConfigPage = true;
}
}
if (!idsSelected.contains(toolId))
idsSelected.add(toolId);
}
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.valueOf(
homeSelected));
if (!ltiSelectedTools.isEmpty())
{
state.setAttribute(STATE_LTITOOL_SELECTED_LIST, ltiSelectedTools);
}
else
{
state.removeAttribute(STATE_LTITOOL_SELECTED_LIST);
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's
// in case of import
String importString = params.getString("import");
if (importString != null
&& importString.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
List importSites = new Vector();
if (params.getStrings("importSites") != null) {
importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
}
if (importSites.size() == 0) {
addAlert(state, rb.getString("java.toimport") + " ");
} else {
Hashtable sites = new Hashtable();
for (int index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
if (!sites.containsKey(s)) {
sites.put(s, new Vector());
}
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
// of
// ToolRegistration
// toolId's
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_IMPORT) != null) {
// go to import tool page
state.setAttribute(STATE_TEMPLATE_INDEX, "27");
} else if (goToToolConfigPage || ltiToolSelected) {
state.setAttribute(STATE_MULTIPLE_TOOL_INSTANCE_SELECTED, Boolean.valueOf(goToToolConfigPage));
// go to the configuration page for multiple instances of tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else {
// go to next page
state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex);
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
}
} // getFeatures
// import tool content into site
private void importToolIntoSite(List toolIds, Hashtable importTools,
Site site) {
if (importTools != null) {
Map transversalMap = new HashMap();
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++) {
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = m_contentHostingService
.getSiteCollection(fromSiteId);
String toSiteCollectionId = m_contentHostingService
.getSiteCollection(toSiteId);
Map<String,String> entityMap = transferCopyEntities(toolId, fromSiteCollectionId,
toSiteCollectionId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
resourcesImported = true;
}
}
}
// import other tools then
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
if(SITE_INFO_TOOL_ID.equals(toolId)){
copySiteInformation(fromSiteId, site);
}else{
Map<String,String> entityMap = transferCopyEntities(toolId, fromSiteId, toSiteId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
resourcesImported = true;
}
}
}
}
//update entity references
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if(importTools.containsKey(toolId)){
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String toSiteId = site.getId();
updateEntityReferences(toolId, toSiteId, transversalMap, site);
}
}
}
}
} // importToolIntoSite
private void importToolIntoSiteMigrate(List toolIds, Hashtable importTools,
Site site) {
if (importTools != null) {
Map transversalMap = new HashMap();
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++) {
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = m_contentHostingService
.getSiteCollection(fromSiteId);
String toSiteCollectionId = m_contentHostingService
.getSiteCollection(toSiteId);
Map<String,String> entityMap = transferCopyEntitiesMigrate(toolId, fromSiteCollectionId,
toSiteCollectionId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
resourcesImported = true;
}
}
}
// import other tools then
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
if(SITE_INFO_TOOL_ID.equals(toolId)){
copySiteInformation(fromSiteId, site);
}else{
Map<String,String> entityMap = transferCopyEntitiesMigrate(toolId, fromSiteId, toSiteId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
}
}
}
}
//update entity references
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if(importTools.containsKey(toolId)){
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String toSiteId = site.getId();
updateEntityReferences(toolId, toSiteId, transversalMap, site);
}
}
}
}
} // importToolIntoSiteMigrate
private void copySiteInformation(String fromSiteId, Site toSite){
try {
Site fromSite = SiteService.getSite(fromSiteId);
//we must get the new site again b/c some tools (lesson builder) can make changes to the site structure (i.e. add pages).
Site editToSite = SiteService.getSite(toSite.getId());
editToSite.setDescription(fromSite.getDescription());
editToSite.setInfoUrl(fromSite.getInfoUrl());
commitSite(editToSite);
toSite = editToSite;
} catch (IdUnusedException e) {
}
}
public void saveSiteStatus(SessionState state, boolean published) {
Site site = getStateSite(state);
site.setPublished(published);
} // saveSiteStatus
public void commitSite(Site site, boolean published) {
site.setPublished(published);
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
} // commitSite
public void commitSite(Site site) {
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
}// commitSite
private String getSetupRequestEmailAddress() {
String from = ServerConfigurationService.getString("setup.request",
null);
if (from == null) {
from = "postmaster@".concat(ServerConfigurationService
.getServerName());
M_log.warn(this + " - no 'setup.request' in configuration, using: "+ from);
}
return from;
}
/**
* get the setup.request.replyTo setting. If missing, use setup.request setting.
* @return
*/
private String getSetupRequestReplyToEmailAddress() {
String rv = ServerConfigurationService.getString("setup.request.replyTo", null);
if (rv == null) {
rv = getSetupRequestEmailAddress();
}
return rv;
}
/**
* addNewSite is called when the site has enough information to create a new
* site
*
*/
private void addNewSite(ParameterParser params, SessionState state) {
if (getStateSite(state) != null) {
// There is a Site in state already, so use it rather than creating
// a new Site
return;
}
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
String id = StringUtils.trimToNull(siteInfo.getSiteId());
if (id == null) {
// get id
id = IdManager.createUuid();
siteInfo.site_id = id;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
Site site = null;
// if create based on template,
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
if (templateSite != null) {
site = SiteService.addSite(id, templateSite);
// set site type
site.setType(SiteTypeUtil.getTargetSiteType(templateSite.getType()));
} else {
site = SiteService.addSite(id, siteInfo.site_type);
}
// add current user as the maintainer
site.addMember(UserDirectoryService.getCurrentUser().getId(), site.getMaintainRole(), true, false);
String title = StringUtils.trimToNull(siteInfo.title);
String description = siteInfo.description;
setAppearance(state, site, siteInfo.iconUrl);
site.setDescription(description);
if (title != null) {
site.setTitle(title);
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
/// site language information
String locale_string = (String) state.getAttribute("locale_string");
rp.addProperty(PROP_SITE_LANGUAGE, locale_string);
site.setShortDescription(siteInfo.short_description);
site.setPubView(siteInfo.include);
site.setJoinable(siteInfo.joinable);
site.setJoinerRole(siteInfo.joinerRole);
site.setPublished(siteInfo.published);
// site contact information
rp.addProperty(Site.PROP_SITE_CONTACT_NAME,
siteInfo.site_contact_name);
rp.addProperty(Site.PROP_SITE_CONTACT_EMAIL,
siteInfo.site_contact_email);
// SAK-22790 add props from SiteInfo object
rp.addAll(siteInfo.getProperties());
// SAK-23491 add template_used property
if (templateSite != null) {
// if the site was created from template
rp.addProperty(TEMPLATE_USED, templateSite.getId());
}
// bjones86 - SAK-24423 - update site properties for joinable site settings
JoinableSiteSettings.updateSitePropertiesFromSiteInfoOnAddNewSite( siteInfo, rp );
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
// commit newly added site in order to enable related realm
commitSite(site);
} catch (IdUsedException e) {
addAlert(state, rb.getFormattedMessage("java.sitewithid.exists", new Object[]{id}));
M_log.warn(this + ".addNewSite: " + rb.getFormattedMessage("java.sitewithid.exists", new Object[]{id}), e);
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex"));
return;
} catch (IdInvalidException e) {
addAlert(state, rb.getFormattedMessage("java.sitewithid.notvalid", new Object[]{id}));
M_log.warn(this + ".addNewSite: " + rb.getFormattedMessage("java.sitewithid.notvalid", new Object[]{id}), e);
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex"));
return;
} catch (PermissionException e) {
addAlert(state, rb.getFormattedMessage("java.permission", new Object[]{id}));
M_log.warn(this + ".addNewSite: " + rb.getFormattedMessage("java.permission", new Object[]{id}), e);
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex"));
return;
}
}
} // addNewSite
/**
* created based on setTermListForContext - Denny
* @param context
* @param state
*/
private void setTemplateListForContext(Context context, SessionState state)
{
List<Site> templateSites = new ArrayList<Site>();
boolean allowedForTemplateSites = true;
// system wide setting for disable site creation based on template sites
if (ServerConfigurationService.getString("wsetup.enableSiteTemplate", "true").equalsIgnoreCase(Boolean.FALSE.toString()))
{
allowedForTemplateSites = false;
}
else
{
if (ServerConfigurationService.getStrings("wsetup.enableSiteTemplate.userType") != null) {
List<String> userTypes = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("wsetup.enableSiteTemplate.userType")));
if (userTypes != null && userTypes.size() > 0)
{
User u = UserDirectoryService.getCurrentUser();
if (!(u != null && (SecurityService.isSuperUser() || userTypes.contains(u.getType()))))
{
// be an admin type user or any type of users defined in the configuration
allowedForTemplateSites = false;
}
}
}
}
if (allowedForTemplateSites)
{
// We're searching for template sites and these are marked by a property
// called 'template' with a value of true
Map templateCriteria = new HashMap(1);
templateCriteria.put("template", "true");
templateSites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ANY, null, null, templateCriteria, SortType.TITLE_ASC, null);
}
// If no templates could be found, stick an empty list in the context
if(templateSites == null || templateSites.size() <= 0)
templateSites = new ArrayList();
//SAK25400 sort templates by type
context.put("templateSites",sortTemplateSitesByType(templateSites));
context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX));
} // setTemplateListForContext
/**
* %%% legacy properties, to be cleaned up
*
*/
private void sitePropertiesIntoState(SessionState state) {
try {
Site site = getStateSite(state);
SiteInfo siteInfo = new SiteInfo();
if (site != null)
{
ResourceProperties siteProperties = site.getProperties();
// set from site attributes
siteInfo.title = site.getTitle();
siteInfo.description = site.getDescription();
siteInfo.iconUrl = site.getIconUrl();
siteInfo.infoUrl = site.getInfoUrl();
siteInfo.joinable = site.isJoinable();
siteInfo.joinerRole = site.getJoinerRole();
siteInfo.published = site.isPublished();
siteInfo.include = site.isPubView();
siteInfo.short_description = site.getShortDescription();
siteInfo.site_type = site.getType();
// term information
String term = siteProperties.getProperty(Site.PROP_SITE_TERM);
if (term != null) {
siteInfo.term = term;
}
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromSiteProperties( siteProperties, siteInfo );
// site contact information
String contactName = siteProperties.getProperty(Site.PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(Site.PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
if (u != null)
{
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
}
if (contactName != null) {
siteInfo.site_contact_name = contactName;
}
if (contactEmail != null) {
siteInfo.site_contact_email = contactEmail;
}
state.setAttribute(FORM_SITEINFO_ALIASES, getSiteReferenceAliasIds(site));
}
siteInfo.additional = "";
state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type);
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute(FORM_SITEINFO_URL_BASE, getSiteBaseUrl());
} catch (Exception e) {
M_log.warn(this + ".sitePropertiesIntoState: " + e.getMessage(), e);
}
} // sitePropertiesIntoState
/**
* pageMatchesPattern returns tool id if a SitePage matches a WorkSite Setuppattern
* otherwise return null
* @param state
* @param page
* @return
*/
private List<String> pageMatchesPattern(SessionState state, SitePage page) {
List<String> rv = new Vector<String>();
List pageToolList = page.getTools();
// if no tools on the page, return false
if (pageToolList == null) {
return null;
}
// don't compare tool properties, which may be changed using Options
List toolList = new Vector();
int count = pageToolList.size();
// check Home tool first
if (isHomePage(page))
{
rv.add(TOOL_ID_HOME);
rv.add(TOOL_ID_HOME);
return rv;
}
// check whether the page has Site Info tool
boolean foundSiteInfoTool = false;
for (int i = 0; i < count; i++)
{
ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList.get(i);
if (toolConfiguration.getToolId().equals(TOOL_ID_SITEINFO))
{
foundSiteInfoTool = true;
break;
}
}
if (foundSiteInfoTool)
{
rv.add(TOOL_ID_SITEINFO);
rv.add(TOOL_ID_SITEINFO);
return rv;
}
// Other than Home, Site Info page, no other page is allowed to have more than one tool within. Otherwise, WSetup/Site Info tool won't handle it
if (count != 1)
{
return null;
}
// if the page layout doesn't match, return false
else if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return null;
}
else
{
// for the case where the page has one tool
ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList.get(0);
toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
if (pageToolList != null && pageToolList.size() != 0) {
// if tool attributes don't match, return false
String match = null;
for (ListIterator i = toolList.listIterator(); i.hasNext();) {
MyTool tool = (MyTool) i.next();
if (toolConfiguration.getTitle() != null) {
if (toolConfiguration.getTool() != null
&& originalToolId(toolConfiguration.getTool().getId(), tool.getId()) != null) {
match = tool.getId();
rv.add(match);
rv.add(toolConfiguration.getId());
}
}
}
// no tool registeration is found (tool is not editable within Site Info tool), set return value to be null
if (match == null)
{
rv = null;
}
}
}
return rv;
} // pageMatchesPattern
/**
* check whether the page tool list contains certain toolId
* @param pageToolList
* @param toolId
* @return
*/
private boolean pageHasToolId(List pageToolList, String toolId) {
for (Iterator iPageToolList = pageToolList.iterator(); iPageToolList.hasNext();)
{
ToolConfiguration toolConfiguration = (ToolConfiguration) iPageToolList.next();
Tool t = toolConfiguration.getTool();
if (t != null && toolId.equals(toolConfiguration.getTool().getId()))
{
return true;
}
}
return false;
}
/**
* siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list
* of pages and tools that match WorkSite Setup configurations into state
*/
private void siteToolsIntoState(SessionState state) {
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
Map<String, Map<String, String>> multipleToolIdAttributeMap = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null? (Map<String, Map<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap();
String wSetupTool = NULL_STRING;
String wSetupToolId = NULL_STRING;
List wSetupPageList = new Vector();
Site site = getStateSite(state, true);
List pageList = site.getPages();
// Put up tool lists filtered by category
String type = checkNullSiteType(state, site.getType(), site.getId());
if (type == null) {
M_log.warn(this + ": - unknown STATE_SITE_TYPE");
} else {
state.setAttribute(STATE_SITE_TYPE, type);
}
// set tool registration list
setToolRegistrationList(state, type);
multipleToolIdAttributeMap = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null? (Map<String, Map<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap();
// for the selected tools
boolean check_home = false;
Vector idSelected = new Vector();
HashMap<String, String> toolTitles = new HashMap<String, String>();
List toolRegList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// populate the tool title list
if (toolRegList != null)
{
for (Object t: toolRegList) {
toolTitles.put(((MyTool) t).getId(),((MyTool) t).getTitle());
}
}
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
// reset
wSetupTool = null;
wSetupToolId = null;
SitePage page = (SitePage) i.next();
// collect the pages consistent with Worksite Setup patterns
List<String> pmList = pageMatchesPattern(state, page);
if (pmList != null)
{
wSetupTool = pmList.get(0);
wSetupToolId = pmList.get(1);
}
if (wSetupTool != null) {
if (isHomePage(page))
{
check_home = true;
toolTitles.put("home", page.getTitle());
}
else
{
if (isMultipleInstancesAllowed(findOriginalToolId(state, wSetupTool)))
{
String mId = page.getId() + wSetupTool;
idSelected.add(mId);
toolTitles.put(mId, page.getTitle());
multipleToolIdTitleMap.put(mId, page.getTitle());
// get the configuration for multiple instance
HashMap<String, String> toolConfigurations = getMultiToolConfiguration(wSetupTool, page.getTool(wSetupToolId));
multipleToolIdAttributeMap.put(mId, toolConfigurations);
MyTool newTool = new MyTool();
String titleConfig = ServerConfigurationService.getString(CONFIG_TOOL_TITLE + mId);
if (titleConfig != null && titleConfig.length() > 0)
{
// check whether there is a different title setting
newTool.title = titleConfig;
}
else
{
// use the default
newTool.title = ToolManager.getTool(wSetupTool).getTitle();
}
newTool.id = mId;
newTool.selected = false;
boolean hasThisMultipleTool = false;
int j = 0;
for (; j < toolRegList.size() && !hasThisMultipleTool; j++) {
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals(wSetupTool)) {
hasThisMultipleTool = true;
newTool.description = t.getDescription();
}
}
if (hasThisMultipleTool) {
toolRegList.add(j - 1, newTool);
} else {
toolRegList.add(newTool);
}
}
else
{
idSelected.add(wSetupTool);
toolTitles.put(wSetupTool, page.getTitle());
}
}
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
wSetupPage.pageId = page.getId();
wSetupPage.pageTitle = page.getTitle();
wSetupPage.toolId = wSetupTool;
wSetupPageList.add(wSetupPage);
}
}
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolIdAttributeMap);
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.valueOf(check_home));
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
state.setAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST, toolTitles);
// of
// ToolRegistration
// toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST,idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home));
state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList);
} // siteToolsIntoState
/**
* adjust site type
* @param state
* @param site
* @return
*/
private String checkNullSiteType(SessionState state, String type, String siteId) {
if (type == null) {
if (siteId != null && SiteService.isUserSite(siteId)) {
type = "myworkspace";
} else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
// for those sites without type, use the tool set for default
// site type
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
return type;
}
/**
* reset the state variables used in edit tools mode
*
* @state The SessionState object
*/
private void removeEditToolState(SessionState state) {
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
state.removeAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION);
state.removeAttribute(STATE_TOOL_REGISTRATION_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
MathJaxEnabler.removeMathJaxToolsAttributeFromState(state); // SAK-22384
}
private List orderToolIds(SessionState state, String type, List<String> toolIdList, boolean synoptic) {
List rv = new Vector();
// look for null site type
if (type == null && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
if (type != null && toolIdList != null) {
List<String> orderedToolIds = ServerConfigurationService.getToolOrder(SiteTypeUtil.getTargetSiteType(type)); // UMICH-1035
for (String tool_id : orderedToolIds) {
for (String toolId : toolIdList) {
String rToolId = originalToolId(toolId, tool_id);
if (rToolId != null)
{
rv.add(toolId);
break;
}
else
{
List<String> parentToolList = (List<String>) SYNOPTIC_TOOL_ID_MAP.get(toolId);
if (parentToolList != null && parentToolList.contains(tool_id))
{
rv.add(toolId);
break;
}
}
}
}
}
// add those toolids without specified order
if (toolIdList != null)
{
for (String toolId : toolIdList) {
if (!rv.contains(toolId)) {
rv.add(toolId);
}
}
}
return rv;
} // orderToolIds
private void setupFormNamesAndConstants(SessionState state) {
TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear()
+ ", " + UserDirectoryService.getCurrentUser().getDisplayName()
+ ". All Rights Reserved. ";
state.setAttribute(STATE_MY_COPYRIGHT, mycopyright);
state.setAttribute(STATE_SITE_INSTANCE_ID, null);
state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString());
SiteInfo siteInfo = new SiteInfo();
Participant participant = new Participant();
participant.name = NULL_STRING;
participant.uniqname = NULL_STRING;
participant.active = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute("form_participantToAdd", participant);
state.setAttribute(FORM_ADDITIONAL, NULL_STRING);
// legacy
state.setAttribute(FORM_HONORIFIC, "0");
state.setAttribute(FORM_REUSE, "0");
state.setAttribute(FORM_RELATED_CLASS, "0");
state.setAttribute(FORM_RELATED_PROJECT, "0");
state.setAttribute(FORM_INSTITUTION, "0");
// sundry form variables
state.setAttribute(FORM_PHONE, "");
state.setAttribute(FORM_EMAIL, "");
state.setAttribute(FORM_SUBJECT, "");
state.setAttribute(FORM_DESCRIPTION, "");
state.setAttribute(FORM_TITLE, "");
state.setAttribute(FORM_NAME, "");
state.setAttribute(FORM_SHORT_DESCRIPTION, "");
} // setupFormNamesAndConstants
/**
* setupSkins
*
*/
private void setupIcons(SessionState state) {
List icons = new Vector();
String[] iconNames = {"*default*"};
String[] iconUrls = {""};
String[] iconSkins = {""};
// get icon information
if (ServerConfigurationService.getStrings("iconNames") != null) {
iconNames = ServerConfigurationService.getStrings("iconNames");
}
if (ServerConfigurationService.getStrings("iconUrls") != null) {
iconUrls = ServerConfigurationService.getStrings("iconUrls");
}
if (ServerConfigurationService.getStrings("iconSkins") != null) {
iconSkins = ServerConfigurationService.getStrings("iconSkins");
}
if ((iconNames != null) && (iconUrls != null) && (iconSkins != null)
&& (iconNames.length == iconUrls.length)
&& (iconNames.length == iconSkins.length)) {
for (int i = 0; i < iconNames.length; i++) {
MyIcon s = new MyIcon(StringUtils.trimToNull((String) iconNames[i]),
StringUtils.trimToNull((String) iconUrls[i]), StringUtils.trimToNull((String) iconSkins[i]));
icons.add(s);
}
}
state.setAttribute(STATE_ICONS, icons);
}
private void setAppearance(SessionState state, Site edit, String iconUrl) {
// set the icon
iconUrl = StringUtils.trimToNull(iconUrl);
//SAK-18721 convert spaces in URL to %20
iconUrl = StringUtils.replace(iconUrl, " ", "%20");
edit.setIconUrl(iconUrl);
// if this icon is in the config appearance list, find a skin to set
List icons = (List) state.getAttribute(STATE_ICONS);
for (Iterator i = icons.iterator(); i.hasNext();) {
Object icon = (Object) i.next();
if (icon instanceof MyIcon && StringUtils.equals(((MyIcon) icon).getUrl(), iconUrl)) {
edit.setSkin(((MyIcon) icon).getSkin());
return;
}
}
}
/**
* A dispatch funtion when selecting course features
*/
public void doAdd_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// to reset the state variable of the multiple tool instances
Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet();
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// editing existing site or creating a new one?
Site site = getStateSite(state);
// dispatch
if (option.startsWith("add_")) {
// this could be format of originalToolId plus number of multiplication
String addToolId = option.substring("add_".length(), option.length());
// find the original tool id
String originToolId = findOriginalToolId(state, addToolId);
if (originToolId != null)
{
Tool tool = ToolManager.getTool(originToolId);
if (tool != null)
{
insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId)));
updateSelectedToolList(state, params, false);
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
}
}else if (option.startsWith("remove_")) {
// this could be format of originalToolId plus number of multiplication
String removeToolId = option.substring("remove_".length(), option.length());
// find the original tool id
String originToolId = findOriginalToolId(state, removeToolId);
if (originToolId != null)
{
Tool tool = ToolManager.getTool(originToolId);
if (tool != null)
{
updateSelectedToolList(state, params, false);
removeTool(state, removeToolId, originToolId);
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
}
} else if (option.equalsIgnoreCase("import")) {
// import or not
updateSelectedToolList(state, params, false);
String importSites = params.getString("import");
if (importSites != null
&& importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
} else if (option.equalsIgnoreCase("continueENW")) {
// continue in multiple tools page
updateSelectedToolList(state, params, false);
doContinue(data);
} else if (option.equalsIgnoreCase("continue")) {
// continue
MathJaxEnabler.applyToolSettingsToState(state, site, params); // SAK-22384
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
// back
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
if (site == null)
{
// cancel
doCancel_create(data);
}
else
{
// cancel editing
doCancel(data);
}
}
} // doAdd_features
/**
* update the selected tool list
*
* @param params
* The ParameterParser object
* @param updateConfigVariables
* Need to update configuration variables
*/
private void updateSelectedToolList(SessionState state, ParameterParser params, boolean updateConfigVariables) {
if (params.getStrings("selectedTools") != null)
{
// read entries for multiple tool customization
List selectedTools = new ArrayList(Arrays.asList(params.getStrings("selectedTools")));
HashMap<String, String> toolTitles = state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST) != null ? (HashMap<String, String>) state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST) : new HashMap<String, String>();
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
HashMap<String, HashMap<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(HashMap<String, HashMap<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap<String, HashMap<String, String>>();
Vector<String> idSelected = (Vector<String>) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
boolean has_home = false;
String emailId = state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null?(String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS):null;
for (int i = 0; i < selectedTools.size(); i++)
{
String id = (String) selectedTools.get(i);
if (id.equalsIgnoreCase(TOOL_ID_HOME)) {
has_home = true;
} else if (id.equalsIgnoreCase("sakai.mailbox")) {
// read email id
emailId = StringUtils.trimToNull(params.getString("emailId"));
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId);
if ( updateConfigVariables ) {
// if Email archive tool is selected, check the email alias
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
String channelReference = mailArchiveChannelReference(siteId);
if (emailId == null) {
addAlert(state, rb.getString("java.emailarchive") + " ");
} else {
if (!Validator.checkEmailLocal(emailId)) {
addAlert(state, rb.getString("java.theemail"));
} else if (!AliasService.allowSetAlias(emailId, channelReference )) {
addAlert(state, rb.getString("java.addalias"));
} else {
// check to see whether the alias has been used by
// other sites
try {
String target = AliasService.getTarget(emailId);
if (target != null) {
if (siteId != null) {
if (!target.equals(channelReference)) {
// the email alias is not used by
// current site
addAlert(state, rb.getString("java.emailinuse") + " ");
}
} else {
addAlert(state, rb.getString("java.emailinuse") + " ");
}
}
} catch (IdUnusedException ee) {
}
}
}
}
}
else if (isMultipleInstancesAllowed(findOriginalToolId(state, id)) && (idSelected != null && !idSelected.contains(id) || idSelected == null))
{
// newly added mutliple instances
String title = StringUtils.trimToNull(params.getString("title_" + id));
if (title != null)
{
// truncate the title to maxlength as defined
if (title.length() > MAX_TOOL_TITLE_LENGTH)
{
title = title.substring(0, MAX_TOOL_TITLE_LENGTH);
}
// save the titles entered
multipleToolIdTitleMap.put(id, title);
}
toolTitles.put(id, title);
// get the attribute input
HashMap<String, String> attributes = multipleToolConfiguration.get(id);
if (attributes == null)
{
// if missing, get the default setting for original id
attributes = multipleToolConfiguration.get(findOriginalToolId(state, id));
}
if (attributes != null)
{
for(Iterator<String> e = attributes.keySet().iterator(); e.hasNext();)
{
String attribute = e.next();
String attributeInput = StringUtils.trimToNull(params.getString(attribute + "_" + id));
if (attributeInput != null)
{
// save the attribute input if valid, otherwise generate alert
if ( FormattedText.validateURL(attributeInput) )
attributes.put(attribute, attributeInput);
else
addAlert(state, rb.getString("java.invurl"));
}
}
multipleToolConfiguration.put(id, attributes);
}
}
}
// update the state objects
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration);
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.valueOf(has_home));
state.setAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST, toolTitles);
}
// read in the input for external tool list
updateSelectedExternalToolList(state, params);
} // updateSelectedToolList
/**
* read in the input for external tool list
* @param state
* @param params
*/
private void updateSelectedExternalToolList(SessionState state,
ParameterParser params) {
// update the lti tool list
if (state.getAttribute(STATE_LTITOOL_SELECTED_LIST) != null)
{
Properties reqProps = params.getProperties();
// remember the reqProps may contain multiple lti inputs, so we need to differentiate those inputs and store one tool specific input into the map
HashMap<String, Map<String, Object>> ltiTools = (HashMap<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_SELECTED_LIST);
for ( Map.Entry<String,Map<String, Object>> ltiToolEntry : ltiTools.entrySet())
{
String ltiToolId = ltiToolEntry.getKey();
Map<String, Object> ltiToolAttributes = ltiToolEntry.getValue();
String[] contentToolModel=m_ltiService.getContentModel(Long.valueOf(ltiToolId));
Properties reqForCurrentTool = new Properties();
// the input page contains attributes prefixed with lti tool id, need to look for those attribute inut values
for (int k=0; k< contentToolModel.length;k++)
{
// sample format of contentToolModel[k]:
// title:text:label=bl_content_title:required=true:maxlength=255
String contentToolModelAttribute = contentToolModel[k].substring(0, contentToolModel[k].indexOf(":"));
String k_contentToolModelAttribute = ltiToolId + "_" + contentToolModelAttribute;
if (reqProps.containsKey(k_contentToolModelAttribute))
{
reqForCurrentTool.put(contentToolModelAttribute, reqProps.get(k_contentToolModelAttribute));
}
}
// add the tool id field
reqForCurrentTool.put(LTIService.LTI_TOOL_ID, ltiToolId);
ltiToolAttributes.put("reqProperties", reqForCurrentTool);
// update the lti tool list
ltiTools.put(ltiToolId, ltiToolAttributes);
}
state.setAttribute(STATE_LTITOOL_SELECTED_LIST, ltiTools);
}
}
/**
* find the tool in the tool list and insert another tool instance to the list
* @param state
* @param toolId
* @param defaultTitle
* @param defaultDescription
* @param insertTimes
*/
private void insertTool(SessionState state, String toolId, String defaultTitle, String defaultDescription, int insertTimes) {
// the list of available tools
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
HashMap<String, String> toolTitles = state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST) != null ? (HashMap<String, String>) state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST) : new HashMap<String, String>();
List oTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// get the attributes of multiple tool instances
HashMap<String, HashMap<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(HashMap<String, HashMap<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap<String, HashMap<String, String>>();
int toolListedTimes = 0;
// get the proper insert index for the whole tool list
int index = 0;
int insertIndex = 0;
while (index < toolList.size()) {
MyTool tListed = (MyTool) toolList.get(index);
if (tListed.getId().indexOf(toolId) != -1 && !oTools.contains(tListed.getId())) {
toolListedTimes++;
// update the insert index
insertIndex = index+1;
}
index++;
}
// get the proper insert index for the selected tool list
List toolSelected = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
index = 0;
int insertSelectedToolIndex = 0;
while (index < toolSelected.size()) {
String selectedId = (String) toolSelected.get(index);
if (selectedId.indexOf(toolId) != -1 ) {
// update the insert index
insertSelectedToolIndex = index+1;
}
index++;
}
// insert multiple tools
for (int i = 0; i < insertTimes; i++) {
toolSelected.add(insertSelectedToolIndex, toolId + toolListedTimes);
// We need to insert a specific tool entry only if all the specific
// tool entries have been selected
String newToolId = toolId + toolListedTimes;
MyTool newTool = new MyTool();
String titleConfig = ServerConfigurationService.getString(CONFIG_TOOL_TITLE + toolId);
if (titleConfig != null && titleConfig.length() > 0)
{
// check whether there is a different title setting
defaultTitle = titleConfig;
}
newTool.title = defaultTitle;
newTool.id = newToolId;
newTool.description = defaultDescription;
toolList.add(insertIndex, newTool);
toolListedTimes++;
// add title
multipleToolIdTitleMap.put(newToolId, defaultTitle);
toolTitles.put(newToolId, defaultTitle);
// get the attribute input
HashMap<String, String> attributes = multipleToolConfiguration.get(newToolId);
if (attributes == null)
{
// if missing, get the default setting for original id
attributes = getMultiToolConfiguration(toolId, null);
multipleToolConfiguration.put(newToolId, attributes);
}
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST, toolTitles);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
} // insertTool
/**
* find the tool in the tool list and remove the tool instance
* @param state
* @param toolId
* @param originalToolId
*/
private void removeTool(SessionState state, String toolId, String originalToolId) {
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// get the attributes of multiple tool instances
HashMap<String, HashMap<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(HashMap<String, HashMap<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap<String, HashMap<String, String>>();
// the selected tool list
List toolSelected = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// remove the tool from related state variables
toolSelected.remove(toolId);
// remove the tool from the title map
multipleToolIdTitleMap.remove(toolId);
// remove the tool from the configuration map
boolean found = false;
for (ListIterator i = toolList.listIterator(); i.hasNext() && !found;)
{
MyTool tool = (MyTool) i.next();
if (tool.getId().equals(toolId))
{
toolList.remove(tool);
found = true;
}
}
multipleToolConfiguration.remove(toolId);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
} // removeTool
/**
*
* set selected participant role Hashtable
*/
private void setSelectedParticipantRoles(SessionState state) {
List selectedUserIds = (List) state
.getAttribute(STATE_SELECTED_USER_LIST);
List participantList = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST));
List selectedParticipantList = new Vector();
Hashtable selectedParticipantRoles = new Hashtable();
if (!selectedUserIds.isEmpty() && participantList != null) {
for (int i = 0; i < participantList.size(); i++) {
String id = "";
Object o = (Object) participantList.get(i);
if (o.getClass().equals(Participant.class)) {
// get participant roles
id = ((Participant) o).getUniqname();
selectedParticipantRoles.put(id, ((Participant) o)
.getRole());
}
if (selectedUserIds.contains(id)) {
selectedParticipantList.add(participantList.get(i));
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
selectedParticipantRoles);
state.setAttribute(STATE_SELECTED_PARTICIPANTS, selectedParticipantList);
} // setSelectedParticipantRol3es
public class MyIcon {
protected String m_name = null;
protected String m_url = null;
protected String m_skin = null;
public MyIcon(String name, String url, String skin) {
m_name = name;
m_url = url;
m_skin = skin;
}
public String getName() {
return m_name;
}
public String getUrl() {
return m_url;
}
public String getSkin() {
return m_skin;
}
}
// a utility class for working with ToolConfigurations and ToolRegistrations
// %%% convert featureList from IdAndText to Tool so getFeatures item.id =
// chosen-feature.id is a direct mapping of data
public class MyTool {
public String id = NULL_STRING;
public String title = NULL_STRING;
public String description = NULL_STRING;
public boolean selected = false;
public boolean multiple = false;
public String group = NULL_STRING;
public String moreInfo = NULL_STRING;
public HashMap<String,MyTool> multiples = new HashMap<String,MyTool>();
public boolean required = false;
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public boolean getSelected() {
return selected;
}
public boolean isRequired() {
return required;
}
public boolean hasMultiples() {
return multiple;
}
public String getGroup() {
return group;
}
public String getMoreInfo() {
return moreInfo;
}
// SAK-16600
public HashMap<String,MyTool> getMultiples(String toolId) {
if (multiples == null) {
return new HashMap<String,MyTool>();
} else {
return multiples;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyTool other = (MyTool) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
private SiteAction getOuterType() {
return SiteAction.this;
}
}
/*
* WorksiteSetupPage is a utility class for working with site pages
* configured by Worksite Setup
*
*/
public class WorksiteSetupPage {
public String pageId = NULL_STRING;
public String pageTitle = NULL_STRING;
public String toolId = NULL_STRING;
public String getPageId() {
return pageId;
}
public String getPageTitle() {
return pageTitle;
}
public String getToolId() {
return toolId;
}
} // WorksiteSetupPage
public class SiteInfo {
public String site_id = NULL_STRING; // getId of Resource
public String external_id = NULL_STRING; // if matches site_id
// connects site with U-M
// course information
public String site_type = "";
public String iconUrl = NULL_STRING;
public String infoUrl = NULL_STRING;
public boolean joinable = false;
public String joinerRole = NULL_STRING;
public String title = NULL_STRING; // the short name of the site
public Set<String> siteRefAliases = new HashSet<String>(); // the aliases for the site itself
public String short_description = NULL_STRING; // the short (20 char)
// description of the
// site
public String description = NULL_STRING; // the longer description of
// the site
public String additional = NULL_STRING; // additional information on
// crosslists, etc.
public boolean published = false;
public boolean include = true; // include the site in the Sites index;
// default is true.
public String site_contact_name = NULL_STRING; // site contact name
public String site_contact_email = NULL_STRING; // site contact email
public String term = NULL_STRING; // academic term
public ResourceProperties properties = new BaseResourcePropertiesEdit();
// bjones86 - SAK-24423 - joinable site settings
public String joinerGroup = NULL_STRING;
public String getJoinerGroup()
{
return joinerGroup;
}
public boolean joinExcludePublic = false;
public boolean getJoinExcludePublic()
{
return joinExcludePublic;
}
public boolean joinLimitByAccountType = false;
public boolean getJoinLimitByAccountType()
{
return joinLimitByAccountType;
}
public String joinLimitedAccountTypes = NULL_STRING;
public String getJoinLimitedAccountTypes()
{
return joinLimitedAccountTypes;
} // end joinable site settings
public String getSiteId() {
return site_id;
}
public String getSiteType() {
return site_type;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getIconUrl() {
return iconUrl;
}
public String getInfoUrll() {
return infoUrl;
}
public boolean getJoinable() {
return joinable;
}
public String getJoinerRole() {
return joinerRole;
}
public String getAdditional() {
return additional;
}
public boolean getPublished() {
return published;
}
public boolean getInclude() {
return include;
}
public String getSiteContactName() {
return site_contact_name;
}
public String getSiteContactEmail() {
return site_contact_email;
}
public String getFirstAlias() {
return siteRefAliases.isEmpty() ? NULL_STRING : siteRefAliases.iterator().next();
}
public void addProperty(String key, String value) {
properties.addProperty(key, value);
}
public ResourceProperties getProperties() {
return properties;
}
public Set<String> getSiteRefAliases() {
return siteRefAliases;
}
public void setSiteRefAliases(Set<String> siteRefAliases) {
this.siteRefAliases = siteRefAliases;
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
} // SiteInfo
// customized type tool related
/**
* doFinish_site_type_tools is called when creation of a customized type site is
* confirmed
*/
public void doFinish_site_type_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// set up for the coming template
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue"));
int index = Integer.valueOf(params.getString("templateIndex"))
.intValue();
actionForTemplate("continue", index, params, state, data);
// add the pre-configured site type tools to a new site
addSiteTypeFeatures(state);
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
}// doFinish_site-type_tools
/**
* addSiteTypeToolsFeatures adds features to a new customized type site
*
*/
private void addSiteTypeFeatures(SessionState state) {
Site edit = null;
Site template = null;
String type = (String) state.getAttribute(STATE_SITE_TYPE);
HashMap<String, String> templates = siteTypeProvider.getTemplateForSiteTypes();
// get the template site id for this site type
if (templates != null && templates.containsKey(type))
{
String templateId = templates.get(type);
// get a unique id
String id = IdManager.createUuid();
// get the site template
try {
template = SiteService.getSite(templateId);
} catch (Exception e) {
M_log.warn(this + ".addSiteTypeFeatures:" + e.getMessage() + templateId, e);
}
if (template != null) {
// create a new site based on the template
try {
edit = SiteService.addSite(id, template);
// set site type
edit.setType(SiteTypeUtil.getTargetSiteType(template.getType()));
} catch (Exception e) {
M_log.warn(this + ".addSiteTypeFeatures:" + " add/edit site id=" + id, e);
}
// set the tab, etc.
if (edit != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
edit.setShortDescription(siteInfo.short_description);
edit.setTitle(siteInfo.title);
edit.setPublished(true);
edit.setPubView(false);
// SAK-23491 add template_used property
edit.getPropertiesEdit().addProperty(TEMPLATE_USED, templateId);
try {
SiteService.save(edit);
} catch (Exception e) {
M_log.warn(this + ".addSiteTypeFeatures:" + " commitEdit site id=" + id, e);
}
// now that the site and realm exist, we can set the email alias
// set the site alias as:
User currentUser = UserDirectoryService.getCurrentUser();
List<String> pList = new ArrayList<String>();
pList.add(currentUser != null ? currentUser.getEid():"");
String alias = siteTypeProvider.getSiteAlias(type, pList);
String channelReference = mailArchiveChannelReference(id);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
addAlert(state, rb.getFormattedMessage("java.alias.exists", new Object[]{alias}));
M_log.warn(this + ".addSiteTypeFeatures:" + rb.getFormattedMessage("java.alias.exists", new Object[]{alias}), ee);
} catch (IdInvalidException ee) {
addAlert(state, rb.getFormattedMessage("java.alias.isinval", new Object[]{alias}));
M_log.warn(this + ".addSiteTypeFeatures:" + rb.getFormattedMessage("java.alias.isinval", new Object[]{alias}), ee);
} catch (PermissionException ee) {
addAlert(state, rb.getString("java.addalias"));
M_log.warn(this + ".addSiteTypeFeatures:" + SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. ", ee);
}
}
}
}
} // addSiteTypeFeatures
/**
* handle with add site options
*
*/
public void doAdd_site_option(RunData data) {
String option = data.getParameters().getString("option");
if ("finish".equals(option)) {
doFinish(data);
} else if ("cancel".equals(option)) {
doCancel_create(data);
} else if ("back".equals(option)) {
doBack(data);
}
} // doAdd_site_option
/**
* handle with duplicate site options
*
*/
public void doDuplicate_site_option(RunData data) {
String option = data.getParameters().getString("option");
if ("duplicate".equals(option)) {
doContinue(data);
} else if ("cancel".equals(option)) {
doCancel(data);
} else if ("finish".equals(option)) {
doContinue(data);
}
} // doDuplicate_site_option
/**
* Get the mail archive channel reference for the main container placement
* for this site.
*
* @param siteId
* The site id.
* @return The mail archive channel reference for this site.
*/
protected String mailArchiveChannelReference(String siteId) {
Object m = ComponentManager
.get("org.sakaiproject.mailarchive.api.MailArchiveService");
if (m != null) {
return "/mailarchive"+Entity.SEPARATOR+"channel"+Entity.SEPARATOR+siteId+Entity.SEPARATOR+SiteService.MAIN_CONTAINER;
} else {
return "";
}
}
/**
* Transfer a copy of all entites from another context for any entity
* producer that claims this tool id.
*
* @param toolId
* The tool id.
* @param fromContext
* The context to import from.
* @param toContext
* The context to import into.
*/
protected Map transferCopyEntities(String toolId, String fromContext,
String toContext) {
// TODO: used to offer to resources first - why? still needed? -ggolden
Map transversalMap = new HashMap();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
if(ep instanceof EntityTransferrerRefMigrator){
EntityTransferrerRefMigrator etMp = (EntityTransferrerRefMigrator) ep;
Map<String,String> entityMap = etMp.transferCopyEntitiesRefMigrator(fromContext, toContext,
new Vector());
if(entityMap != null){
transversalMap.putAll(entityMap);
}
}else{
et.transferCopyEntities(fromContext, toContext, new Vector());
}
}
} catch (Throwable t) {
M_log.warn(this + ".transferCopyEntities: Error encountered while asking EntityTransfer to transferCopyEntities from: "
+ fromContext + " to: " + toContext, t);
}
}
}
return transversalMap;
}
private void updateSiteInfoToolEntityReferences(Map transversalMap, Site newSite){
if(transversalMap != null && transversalMap.size() > 0 && newSite != null){
Set<Entry<String, String>> entrySet = (Set<Entry<String, String>>) transversalMap.entrySet();
String msgBody = newSite.getDescription();
if(msgBody != null && !"".equals(msgBody)){
boolean updated = false;
Iterator<Entry<String, String>> entryItr = entrySet.iterator();
while(entryItr.hasNext()) {
Entry<String, String> entry = (Entry<String, String>) entryItr.next();
String fromContextRef = entry.getKey();
if(msgBody.contains(fromContextRef)){
msgBody = msgBody.replace(fromContextRef, entry.getValue());
updated = true;
}
}
if(updated){
//update the site b/c some tools (Lessonbuilder) updates the site structure (add/remove pages) and we don't want to
//over write this
try {
newSite = SiteService.getSite(newSite.getId());
newSite.setDescription(msgBody);
SiteService.save(newSite);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
}
}
}
}
protected void updateEntityReferences(String toolId, String toContext, Map transversalMap, Site newSite) {
if (toolId.equalsIgnoreCase(SITE_INFORMATION_TOOL)) {
updateSiteInfoToolEntityReferences(transversalMap, newSite);
}else{
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrerRefMigrator && ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
EntityTransferrerRefMigrator etRM = (EntityTransferrerRefMigrator) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
etRM.updateEntityReferences(toContext, transversalMap);
}
} catch (Throwable t) {
M_log.warn(
"Error encountered while asking EntityTransfer to updateEntityReferences at site: "
+ toContext, t);
}
}
}
}
}
protected Map transferCopyEntitiesMigrate(String toolId, String fromContext,
String toContext) {
Map transversalMap = new HashMap();
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
if(ep instanceof EntityTransferrerRefMigrator){
EntityTransferrerRefMigrator etRM = (EntityTransferrerRefMigrator) ep;
Map<String,String> entityMap = etRM.transferCopyEntitiesRefMigrator(fromContext, toContext,
new Vector(), true);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
}else{
et.transferCopyEntities(fromContext, toContext,
new Vector(), true);
}
}
} catch (Throwable t) {
M_log.warn(
"Error encountered while asking EntityTransfer to transferCopyEntities from: "
+ fromContext + " to: " + toContext, t);
}
}
}
return transversalMap;
}
/**
* @return Get a list of all tools that support the import (transfer copy)
* option
*/
protected Set importTools() {
HashSet rv = new HashSet();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
EntityTransferrer et = (EntityTransferrer) ep;
String[] tools = et.myToolIds();
if (tools != null) {
for (int t = 0; t < tools.length; t++) {
rv.add(tools[t]);
}
}
}
}
if (ServerConfigurationService.getBoolean("site-manage.importoption.siteinfo", false)){
rv.add(SITE_INFO_TOOL_ID);
}
return rv;
}
/**
* @param state
* @return Get a list of all tools that should be included as options for
* import
*/
protected List getToolsAvailableForImport(SessionState state, List<String> toolIdList) {
// The Web Content and News tools do not follow the standard rules for
// import
// Even if the current site does not contain the tool, News and WC will
// be
// an option if the imported site contains it
boolean displayWebContent = false;
boolean displayNews = false;
Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES))
.keySet();
Iterator sitesIter = importSites.iterator();
while (sitesIter.hasNext()) {
Site site = (Site) sitesIter.next();
// web content is a little tricky because worksite setup has the same tool id. you
// can differentiate b/c worksite setup has a property with the key "special"
Collection iframeTools = new ArrayList<Tool>();
iframeTools = site.getTools(new String[] {WEB_CONTENT_TOOL_ID});
if (iframeTools != null && iframeTools.size() > 0) {
for (Iterator i = iframeTools.iterator(); i.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) i.next();
if (!tool.getPlacementConfig().containsKey("special")) {
displayWebContent = true;
}
}
}
if (site.getToolForCommonId(NEWS_TOOL_ID) != null)
displayNews = true;
}
if (displayWebContent && !toolIdList.contains(WEB_CONTENT_TOOL_ID))
toolIdList.add(WEB_CONTENT_TOOL_ID);
if (displayNews && !toolIdList.contains(NEWS_TOOL_ID))
toolIdList.add(NEWS_TOOL_ID);
if (ServerConfigurationService.getBoolean("site-manage.importoption.siteinfo", false)){
toolIdList.add(SITE_INFO_TOOL_ID);
}
return toolIdList;
} // getToolsAvailableForImport
// bjones86 - SAK-23256 - added userFilteringIfEnabled parameter
private List<AcademicSession> setTermListForContext(Context context, SessionState state,
boolean upcomingOnly, boolean useFilteringIfEnabled) {
List<AcademicSession> terms;
if (upcomingOnly) {
terms = cms != null?cms.getCurrentAcademicSessions():null;
} else { // get all
terms = cms != null?cms.getAcademicSessions():null;
}
if (terms != null && terms.size() > 0) {
// bjones86 - SAK-23256
if( useFilteringIfEnabled )
{
if( !SecurityService.isSuperUser() )
{
if( ServerConfigurationService.getBoolean( SAK_PROP_FILTER_TERMS, false ) )
{
terms = filterTermDropDowns();
}
}
}
context.put("termList", sortAcademicSessions(terms));
}
return terms;
} // setTermListForContext
private void setSelectedTermForContext(Context context, SessionState state,
String stateAttribute) {
if (state.getAttribute(stateAttribute) != null) {
context.put("selectedTerm", state.getAttribute(stateAttribute));
}
} // setSelectedTermForContext
/**
* Removes any academic sessions that the user is not currently enrolled in
*
* @author bjones86 - SAK-23256
*
* @return the filtered list of academic sessions
*/
public List<AcademicSession> filterTermDropDowns()
{
List<AcademicSession> academicSessions = new ArrayList<AcademicSession>();
User user = UserDirectoryService.getCurrentUser();
if( cms != null && user != null)
{
Map<String, String> sectionRoles = cms.findSectionRoles( user.getEid() );
if( sectionRoles != null )
{
// Iterate through all the sections and add their corresponding academic sessions to our return value
Set<String> sectionEids = sectionRoles.keySet();
Iterator<String> itr = sectionEids.iterator();
while( itr.hasNext() )
{
String sectionEid = itr.next();
Section section = cms.getSection( sectionEid );
if( section != null )
{
CourseOffering courseOffering = cms.getCourseOffering( section.getCourseOfferingEid() );
if( courseOffering != null )
{
academicSessions.add( courseOffering.getAcademicSession() );
}
}
}
}
}
// Remove duplicates
for( int i = 0; i < academicSessions.size(); i++ )
{
for( int j = i + 1; j < academicSessions.size(); j++ )
{
if( academicSessions.get( i ).getEid().equals( academicSessions.get( j ).getEid() ) )
{
academicSessions.remove( academicSessions.get( j ) );
j--; //stay on this index (ie. j will get incremented back)
}
}
}
return academicSessions;
}
/**
* rewrote for 2.4
*
* @param userId
* @param academicSessionEid
* @param courseOfferingHash
* @param sectionHash
*/
private void prepareCourseAndSectionMap(String userId,
String academicSessionEid, HashMap courseOfferingHash,
HashMap sectionHash) {
// looking for list of courseOffering and sections that should be
// included in
// the selection list. The course offering must be offered
// 1. in the specific academic Session
// 2. that the specified user has right to attach its section to a
// course site
// map = (section.eid, sakai rolename)
if (groupProvider == null)
{
M_log.warn("Group provider not found");
return;
}
Map map = groupProvider.getGroupRolesForUser(userId);
if (map == null)
return;
Set keys = map.keySet();
Set roleSet = getRolesAllowedToAttachSection();
for (Iterator i = keys.iterator(); i.hasNext();) {
String sectionEid = (String) i.next();
String role = (String) map.get(sectionEid);
if (includeRole(role, roleSet)) {
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
// now consider those user with affiliated sections
List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid);
if (affiliatedSectionEids != null)
{
for (int k = 0; k < affiliatedSectionEids.size(); k++) {
String sectionEid = (String) affiliatedSectionEids.get(k);
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
} // prepareCourseAndSectionMap
private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) {
try {
section = cms.getSection(sectionEid);
} catch (IdNotFoundException e) {
M_log.warn("getCourseOfferingAndSectionMap: cannot find section " + sectionEid);
}
if (section != null) {
String courseOfferingEid = section.getCourseOfferingEid();
CourseOffering courseOffering = cms
.getCourseOffering(courseOfferingEid);
String sessionEid = courseOffering.getAcademicSession()
.getEid();
if (academicSessionEid.equals(sessionEid)) {
// a long way to the conclusion that yes, this course
// offering
// should be included in the selected list. Sigh...
// -daisyf
ArrayList sectionList = (ArrayList) sectionHash
.get(courseOffering.getEid());
if (sectionList == null) {
sectionList = new ArrayList();
}
sectionList.add(new SectionObject(section));
sectionHash.put(courseOffering.getEid(), sectionList);
courseOfferingHash.put(courseOffering.getEid(),
courseOffering);
}
}
}
/**
* for 2.4
*
* @param role
* @return
*/
private boolean includeRole(String role, Set roleSet) {
boolean includeRole = false;
for (Iterator i = roleSet.iterator(); i.hasNext();) {
String r = (String) i.next();
if (r.equals(role)) {
includeRole = true;
break;
}
}
return includeRole;
} // includeRole
protected Set getRolesAllowedToAttachSection() {
// Use !site.template.[site_type]
String azgId = "!site.template.course";
AuthzGroup azgTemplate;
try {
azgTemplate = AuthzGroupService.getAuthzGroup(azgId);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".getRolesAllowedToAttachSection: Could not find authz group " + azgId, e);
return new HashSet();
}
Set roles = azgTemplate.getRolesIsAllowed("site.upd");
roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd"));
return roles;
} // getRolesAllowedToAttachSection
/**
* Here, we will preapre two HashMap: 1. courseOfferingHash stores
* courseOfferingId and CourseOffering 2. sectionHash stores
* courseOfferingId and a list of its Section We sorted the CourseOffering
* by its eid & title and went through them one at a time to construct the
* CourseObject that is used for the displayed in velocity. Each
* CourseObject will contains a list of CourseOfferingObject(again used for
* vm display). Usually, a CourseObject would only contain one
* CourseOfferingObject. A CourseObject containing multiple
* CourseOfferingObject implies that this is a cross-listing situation.
*
* @param userId
* @param academicSessionEid
* @return
*/
private List prepareCourseAndSectionListing(String userId,
String academicSessionEid, SessionState state) {
// courseOfferingHash = (courseOfferingEid, vourseOffering)
// sectionHash = (courseOfferingEid, list of sections)
HashMap courseOfferingHash = new HashMap();
HashMap sectionHash = new HashMap();
prepareCourseAndSectionMap(userId, academicSessionEid,
courseOfferingHash, sectionHash);
// courseOfferingHash & sectionHash should now be filled with stuffs
// put section list in state for later use
state.setAttribute(STATE_PROVIDER_SECTION_LIST,
getSectionList(sectionHash));
ArrayList offeringList = new ArrayList();
Set keys = courseOfferingHash.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
CourseOffering o = (CourseOffering) courseOfferingHash
.get((String) i.next());
offeringList.add(o);
}
Collection offeringListSorted = sortCourseOfferings(offeringList);
ArrayList resultedList = new ArrayList();
// use this to keep track of courseOffering that we have dealt with
// already
// this is important 'cos cross-listed offering is dealt with together
// with its
// equivalents
ArrayList dealtWith = new ArrayList();
for (Iterator j = offeringListSorted.iterator(); j.hasNext();) {
CourseOffering o = (CourseOffering) j.next();
if (!dealtWith.contains(o.getEid())) {
// 1. construct list of CourseOfferingObject for CourseObject
ArrayList l = new ArrayList();
CourseOfferingObject coo = new CourseOfferingObject(o,
(ArrayList) sectionHash.get(o.getEid()));
l.add(coo);
// 2. check if course offering is cross-listed
Set set = cms.getEquivalentCourseOfferings(o.getEid());
if (set != null)
{
for (Iterator k = set.iterator(); k.hasNext();) {
CourseOffering eo = (CourseOffering) k.next();
if (courseOfferingHash.containsKey(eo.getEid())) {
// => cross-listed, then list them together
CourseOfferingObject coo_equivalent = new CourseOfferingObject(
eo, (ArrayList) sectionHash.get(eo.getEid()));
l.add(coo_equivalent);
dealtWith.add(eo.getEid());
}
}
}
CourseObject co = new CourseObject(o, l);
dealtWith.add(o.getEid());
resultedList.add(co);
}
}
return resultedList;
} // prepareCourseAndSectionListing
/* SAK-25400 template site types duplicated in list
* Sort template sites by type
**/
private Collection sortTemplateSitesByType(Collection<Site> templates) {
String[] sortKey = {"type"};
String[] sortOrder = {"asc"};
return sortCmObject(templates, sortKey, sortOrder);
}
/**
* Helper method for sortCmObject
* by order from sakai properties if specified or
* by default of eid, title
* using velocity SortTool
*
* @param offerings
* @return
*/
private Collection sortCourseOfferings(Collection<CourseOffering> offerings) {
// Get the keys from sakai.properties
String[] keys = ServerConfigurationService.getStrings(SORT_KEY_COURSE_OFFERING);
String[] orders = ServerConfigurationService.getStrings(SORT_ORDER_COURSE_OFFERING);
return sortCmObject(offerings, keys, orders);
} // sortCourseOffering
/**
* Helper method for sortCmObject
* by order from sakai properties if specified or
* by default of eid, title
* using velocity SortTool
*
* @param courses
* @return
*/
private Collection sortCourseSets(Collection<CourseSet> courses) {
// Get the keys from sakai.properties
String[] keys = ServerConfigurationService.getStrings(SORT_KEY_COURSE_SET);
String[] orders = ServerConfigurationService.getStrings(SORT_ORDER_COURSE_SET);
return sortCmObject(courses, keys, orders);
} // sortCourseOffering
/**
* Helper method for sortCmObject
* by order from sakai properties if specified or
* by default of eid, title
* using velocity SortTool
*
* @param sections
* @return
*/
private Collection sortSections(Collection<Section> sections) {
// Get the keys from sakai.properties
String[] keys = ServerConfigurationService.getStrings(SORT_KEY_SECTION);
String[] orders = ServerConfigurationService.getStrings(SORT_ORDER_SECTION);
return sortCmObject(sections, keys, orders);
} // sortCourseOffering
/**
* Helper method for sortCmObject
* by order from sakai properties if specified or
* by default of eid, title
* using velocity SortTool
*
* @param sessions
* @return
*/
private Collection sortAcademicSessions(Collection<AcademicSession> sessions) {
// Get the keys from sakai.properties
String[] keys = ServerConfigurationService.getStrings(SORT_KEY_SESSION);
String[] orders = ServerConfigurationService.getStrings(SORT_ORDER_SESSION);
return sortCmObject(sessions, keys, orders);
} // sortCourseOffering
/**
* Custom sort CM collections using properties provided object has getter & setter for
* properties in keys and orders
* defaults to eid & title if none specified
*
* @param collection a collection to be sorted
* @param keys properties to sort on
* @param orders properties on how to sort (asc, dsc)
* @return Collection the sorted collection
*/
private Collection sortCmObject(Collection collection, String[] keys, String[] orders) {
if (collection != null && !collection.isEmpty()) {
// Add them to a list for the SortTool (they must have the form
// "<key:order>" in this implementation)
List propsList = new ArrayList();
if (keys == null || orders == null || keys.length == 0 || orders.length == 0) {
// No keys are specified, so use the default sort order
propsList.add("eid");
propsList.add("title");
} else {
// Populate propsList
for (int i = 0; i < Math.min(keys.length, orders.length); i++) {
String key = keys[i];
String order = orders[i];
propsList.add(key + ":" + order);
}
}
// Sort the collection and return
SortTool sort = new SortTool();
return sort.sort(collection, propsList);
}
return Collections.emptyList();
} // sortCmObject
/**
* Custom sort CM collections provided object has getter & setter for
* eid & title
*
* @param collection a collection to be sorted
* @return Collection the sorted collection
*/
private Collection sortCmObject(Collection collection) {
return sortCmObject(collection, null, null);
}
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class SectionObject {
public Section section;
public String eid;
public String title;
public String category;
public String categoryDescription;
public boolean isLecture;
public boolean attached;
public List<String> authorizer;
public String description;
public SectionObject(Section section) {
this.section = section;
this.eid = section.getEid();
this.title = section.getTitle();
this.category = section.getCategory();
List<String> authorizers = new ArrayList<String>();
if (section.getEnrollmentSet() != null){
Set<String> instructorset = section.getEnrollmentSet().getOfficialInstructors();
if (instructorset != null) {
for (String instructor:instructorset) {
authorizers.add(instructor);
}
}
}
this.authorizer = authorizers;
this.categoryDescription = cms
.getSectionCategoryDescription(section.getCategory());
if ("01.lct".equals(section.getCategory())) {
this.isLecture = true;
} else {
this.isLecture = false;
}
Set set = authzGroupService.getAuthzGroupIds(section.getEid());
if (set != null && !set.isEmpty()) {
this.attached = true;
} else {
this.attached = false;
}
this.description = section.getDescription();
}
public Section getSection() {
return section;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public String getCategory() {
return category;
}
public String getCategoryDescription() {
return categoryDescription;
}
public boolean getIsLecture() {
return isLecture;
}
public boolean getAttached() {
return attached;
}
public String getDescription() {
return description;
}
public List<String> getAuthorizer() {
return authorizer;
}
public String getAuthorizerString() {
StringBuffer rv = new StringBuffer();
if (authorizer != null && !authorizer.isEmpty())
{
for (int count = 0; count < authorizer.size(); count++)
{
// concatenate all authorizers into a String
if (count > 0)
{
rv.append(", ");
}
rv.append(authorizer.get(count));
}
}
return rv.toString();
}
public void setAuthorizer(List<String> authorizer) {
this.authorizer = authorizer;
}
} // SectionObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseObject {
public String eid;
public String title;
public List courseOfferingObjects;
public CourseObject(CourseOffering offering, List courseOfferingObjects) {
this.eid = offering.getEid();
this.title = offering.getTitle();
this.courseOfferingObjects = courseOfferingObjects;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getCourseOfferingObjects() {
return courseOfferingObjects;
}
} // CourseObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseOfferingObject {
public String eid;
public String title;
public List sections;
public CourseOfferingObject(CourseOffering offering,
List unsortedSections) {
List propsList = new ArrayList();
propsList.add("category");
propsList.add("eid");
SortTool sort = new SortTool();
this.sections = new ArrayList();
if (unsortedSections != null) {
this.sections = (List) sort.sort(unsortedSections, propsList);
}
this.eid = offering.getEid();
this.title = offering.getTitle();
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getSections() {
return sections;
}
} // CourseOfferingObject constructor
/**
* get campus user directory for dispaly in chef_newSiteCourse.vm
*
* @return
*/
private String getCampusDirectory() {
return ServerConfigurationService.getString(
"site-manage.campusUserDirectory", null);
} // getCampusDirectory
private void removeAnyFlagedSection(SessionState state,
ParameterParser params) {
List all = new ArrayList();
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerCourseList != null && providerCourseList.size() > 0) {
all.addAll(providerCourseList);
}
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
if (manualCourseList != null && manualCourseList.size() > 0) {
all.addAll(manualCourseList);
}
for (int i = 0; i < all.size(); i++) {
String eid = (String) all.get(i);
String field = "removeSection" + eid;
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
// eid is in either providerCourseList or manualCourseList
// either way, just remove it
if (providerCourseList != null)
providerCourseList.remove(eid);
if (manualCourseList != null)
manualCourseList.remove(eid);
}
}
// if list is empty, set to null. This is important 'cos null is
// the indication that the list is empty in the code. See case 2 on line
// 1081
if (manualCourseList != null && manualCourseList.size() == 0)
manualCourseList = null;
if (providerCourseList != null && providerCourseList.size() == 0)
providerCourseList = null;
removeAnyFlaggedSectionFromState(state, params, STATE_CM_REQUESTED_SECTIONS);
removeAnyFlaggedSectionFromState(state, params, STATE_CM_SELECTED_SECTIONS);
removeAnyFlaggedSectionFromState(state, params, STATE_CM_AUTHORIZER_SECTIONS);
// remove manually requested sections
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector();
List removeRequiredFieldList = null;
for (int i = 0; i < requiredFields.size(); i++) {
String sectionTitle = "";
List requiredFieldList = (List) requiredFields.get(i);
for (int j = 0; j < requiredFieldList.size(); j++) {
SectionField requiredField = (SectionField) requiredFieldList.get(j);
sectionTitle = sectionTitle.concat(requiredField.getValue() + " ");
}
String field = "removeSection" + sectionTitle.trim();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
removeRequiredFieldList = requiredFieldList;
break;
}
}
if (removeRequiredFieldList != null)
{
requiredFields.remove(removeRequiredFieldList);
if (number > 1)
{
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, requiredFields);
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf(number -1));
}
else
{
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
}
}
}
}
private void removeAnyFlaggedSectionFromState(SessionState state, ParameterParser params, String state_variable)
{
List<SectionObject> rv = (List<SectionObject>) state.getAttribute(state_variable);
if (rv != null) {
for (int i = 0; i < rv.size(); i++) {
SectionObject so = (SectionObject) rv.get(i);
String field = "removeSection" + so.getEid();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
rv.remove(so);
}
}
if (rv.size() == 0)
state.removeAttribute(state_variable);
else
state.setAttribute(state_variable, rv);
}
}
private void collectNewSiteInfo(SessionState state,
ParameterParser params, List providerChosenList) {
if (state.getAttribute(STATE_MESSAGE) == null) {
SiteInfo siteInfo = state.getAttribute(STATE_SITE_INFO) != null? (SiteInfo) state.getAttribute(STATE_SITE_INFO): new SiteInfo();
// site title is the title of the 1st section selected -
// daisyf's note
if (providerChosenList != null && providerChosenList.size() >= 1) {
String title = prepareTitle((List) state
.getAttribute(STATE_PROVIDER_SECTION_LIST),
providerChosenList);
siteInfo.title = title;
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN) != null)
{
List<String> providerDescriptionChosenList = (List<String>) state.getAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
if (providerDescriptionChosenList != null)
{
for (String providerSectionId : providerDescriptionChosenList)
{
try
{
Section s = cms.getSection(providerSectionId);
if (s != null)
{
String sDescription = StringUtils.trimToNull(s.getDescription());
if (sDescription != null && !siteInfo.description.contains(sDescription))
{
siteInfo.description = siteInfo.description.concat(sDescription);
}
}
}
catch (IdNotFoundException e)
{
M_log.warn("collectNewSiteInfo: cannot find section " + providerSectionId);
}
}
}
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (params.getString("manualAdds") != null
&& ("true").equals(params.getString("manualAdds"))) {
// if creating a new site
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf(
1));
} else if (params.getString("find_course") != null
&& ("true").equals(params.getString("find_course"))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
prepFindPage(state);
} else {
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
if (getStateSite(state) != null) {
// if revising a site, go to the confirmation
// page of adding classes
//state.setAttribute(STATE_TEMPLATE_INDEX, "37");
} else {
// if creating a site, go the the site
// information entry page
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
}
}
}
/**
* By default, courseManagement is implemented
*
* @return
*/
private boolean courseManagementIsImplemented() {
boolean returnValue = true;
String isImplemented = ServerConfigurationService.getString(
"site-manage.courseManagementSystemImplemented", "true");
if (("false").equals(isImplemented))
returnValue = false;
return returnValue;
}
private List getCMSections(String offeringEid) {
if (offeringEid == null || offeringEid.trim().length() == 0)
return null;
if (cms != null) {
try
{
Set sections = cms.getSections(offeringEid);
if (sections != null)
{
Collection c = sortSections(new ArrayList(sections));
return (List) c;
}
}
catch (IdNotFoundException e)
{
M_log.warn("getCMSections: Cannot find sections for " + offeringEid);
}
}
return new ArrayList(0);
}
private List getCMCourseOfferings(String subjectEid, String termID) {
if (subjectEid == null || subjectEid.trim().length() == 0
|| termID == null || termID.trim().length() == 0)
return null;
if (cms != null) {
Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// ,
// termID);
ArrayList returnList = new ArrayList();
if (offerings != null)
{
Iterator coIt = offerings.iterator();
while (coIt.hasNext()) {
CourseOffering co = (CourseOffering) coIt.next();
AcademicSession as = co.getAcademicSession();
if (as != null && as.getEid().equals(termID))
returnList.add(co);
}
}
Collection c = sortCourseOfferings(returnList);
return (List) c;
}
return new ArrayList(0);
}
private List<String> getCMLevelLabels(SessionState state) {
List<String> rv = new Vector<String>();
// get CourseSet
Set courseSets = getCourseSet(state);
String currentLevel = "";
if (courseSets != null)
{
// Hieriarchy of CourseSet, CourseOffering and Section are multiple levels in CourseManagementService
List<SectionField> sectionFields = sectionFieldProvider.getRequiredFields();
for (SectionField field : sectionFields)
{
rv.add(field.getLabelKey());
}
}
return rv;
}
/**
* a recursive function to add courseset categories
* @param rv
* @param courseSets
*/
private List<String> addCategories(List<String> rv, Set courseSets) {
if (courseSets != null)
{
for (Iterator i = courseSets.iterator(); i.hasNext();)
{
// get the CourseSet object level
CourseSet cs = (CourseSet) i.next();
String level = cs.getCategory();
if (!rv.contains(level))
{
rv.add(level);
}
try
{
// recursively add child categories
rv = addCategories(rv, cms.getChildCourseSets(cs.getEid()));
}
catch (IdNotFoundException e)
{
// current CourseSet not found
}
}
}
return rv;
}
private void prepFindPage(SessionState state) {
// check the configuration setting for choosing next screen
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean(SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue())
{
// go to the course/section selection page
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
// get cm levels
final List cmLevels = getCMLevelLabels(state), selections = (List) state.getAttribute(STATE_CM_LEVEL_SELECTIONS);
int lvlSz = 0;
if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) {
// TODO: no cm levels configured, redirect to manual add
return;
}
if (selections != null && selections.size() >= lvlSz) {
// multiple selections for the section level
List<SectionObject> soList = new Vector<SectionObject>();
for (int k = cmLevels.size() -1; k < selections.size(); k++)
{
String string = (String) selections.get(k);
if (string != null && string.length() > 0)
{
try
{
Section sect = cms.getSection(string);
if (sect != null)
{
SectionObject so = new SectionObject(sect);
soList.add(so);
}
}
catch (IdNotFoundException e)
{
M_log.warn("prepFindPage: Cannot find section " + string);
}
}
}
state.setAttribute(STATE_CM_SELECTED_SECTION, soList);
} else
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.setAttribute(STATE_CM_LEVELS, cmLevels);
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
}
else
{
// skip the course/section selection page, go directly into the manually create course page
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
private void addRequestedSection(SessionState state) {
List<SectionObject> soList = (List<SectionObject>) state
.getAttribute(STATE_CM_SELECTED_SECTION);
String uniqueName = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (soList == null || soList.isEmpty())
return;
String s = ServerConfigurationService.getString("officialAccountName");
if (uniqueName == null)
{
addAlert(state, rb.getFormattedMessage("java.author", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
return;
}
if (getStateSite(state) == null)
{
// creating new site
List<SectionObject> requestedSections = (List<SectionObject>) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
for (SectionObject so : soList)
{
so.setAuthorizer(new ArrayList(Arrays.asList(uniqueName.split(","))));
if (requestedSections == null) {
requestedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!requestedSections.contains(so))
requestedSections.add(so);
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
// if the title has not yet been set and there is just
// one section, set the title to that section's EID
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo == null) {
siteInfo = new SiteInfo();
}
if (siteInfo.title == null || siteInfo.title.trim().length() == 0) {
if (requestedSections.size() >= 1) {
siteInfo.title = requestedSections.get(0).getTitle();
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
}
}
else
{
// editing site
for (SectionObject so : soList)
{
so.setAuthorizer(new ArrayList(Arrays.asList(uniqueName.split(","))));
List<SectionObject> cmSelectedSections = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmSelectedSections == null) {
cmSelectedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!cmSelectedSections.contains(so))
cmSelectedSections.add(so);
state.setAttribute(STATE_CM_SELECTED_SECTIONS, cmSelectedSections);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
}
}
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
}
public void doFind_course(RunData data) {
final SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
final ParameterParser params = data.getParameters();
final String option = params.get("option");
if (option != null && option.length() > 0)
{
if ("continue".equals(option))
{
String uniqname = StringUtils.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue())
{
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null)
{
addAlert(state, rb.getFormattedMessage("java.author", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
}
else
{
// check instructors
List instructors = new ArrayList(Arrays.asList(uniqname.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
String instructorId = (String) iInstructors.next();
try
{
UserDirectoryService.getUserByEid(instructorId);
}
catch (UserNotDefinedException e)
{
addAlert(state, rb.getFormattedMessage("java.validAuthor", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
M_log.warn(this + ".doFind_course:" + rb.getFormattedMessage("java.validAuthor", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
addRequestedSection(state);
}
}
}
else
{
addRequestedSection(state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
if (getStateSite(state) == null) {
if (state.getAttribute(STATE_TEMPLATE_SITE) != null)
{
// if creating site using template, stop here and generate the new site
// create site based on template
doFinish(data);
}
else
{
// else follow the normal flow
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
doContinue(data);
return;
} else if ("back".equals(option)) {
doBack(data);
return;
} else if ("cancel".equals(option)) {
if (getStateSite(state) == null)
{
doCancel_create(data);// cancel from new site creation
}
else
{
doCancel(data);// cancel from site info editing
}
return;
} else if ("add".equals(option)) {
// get the uniqname input
String uniqname = StringUtils.trimToNull(params.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
addRequestedSection(state);
return;
} else if ("manual".equals(option)) {
// TODO: send to case 37
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf(
1));
return;
} else if ("remove".equals(option))
removeAnyFlagedSection(state, params);
}
final List selections = new ArrayList(3);
int cmLevel = getCMLevelLabels(state).size();
String cmLevelChanged = params.get("cmLevelChanged");
if ("true".equals(cmLevelChanged)) {
// when cm level changes, set the focus to the new level
String cmChangedLevel = params.get("cmChangedLevel");
cmLevel = cmChangedLevel != null ? Integer.valueOf(cmChangedLevel).intValue() + 1:cmLevel;
}
for (int i = 0; i < cmLevel; i++) {
String[] val = params.getStrings("idField_" + i);
if (val == null || val.length == 0) {
break;
}
if (val.length == 1)
{
selections.add(val[0]);
}
else
{
for (int k=0; k<val.length;k++)
{
selections.add(val[k]);
}
}
}
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
prepFindPage(state);
}
/**
* return the title of the 1st section in the chosen list that has an
* enrollment set. No discrimination on section category
*
* @param sectionList
* @param chosenList
* @return
*/
private String prepareTitle(List sectionList, List chosenList) {
String title = null;
HashMap map = new HashMap();
for (Iterator i = sectionList.iterator(); i.hasNext();) {
SectionObject o = (SectionObject) i.next();
map.put(o.getEid(), o.getSection());
}
for (int j = 0; j < chosenList.size(); j++) {
String eid = (String) chosenList.get(j);
Section s = (Section) map.get(eid);
// we will always has a title regardless but we prefer it to be the
// 1st section on the chosen list that has an enrollment set
if (j == 0) {
title = s.getTitle();
}
if (s.getEnrollmentSet() != null) {
title = s.getTitle();
break;
}
}
return title;
} // prepareTitle
/**
* return an ArrayList of SectionObject
*
* @param sectionHash
* contains an ArrayList collection of SectionObject
* @return
*/
private ArrayList getSectionList(HashMap sectionHash) {
ArrayList list = new ArrayList();
// values is an ArrayList of section
Collection c = sectionHash.values();
for (Iterator i = c.iterator(); i.hasNext();) {
ArrayList l = (ArrayList) i.next();
list.addAll(l);
}
return list;
}
private String getAuthorizers(SessionState state, String attributeName) {
String authorizers = "";
ArrayList list = (ArrayList) state
.getAttribute(attributeName);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
if (i == 0) {
authorizers = (String) list.get(i);
} else {
authorizers = authorizers + ", " + list.get(i);
}
}
}
return authorizers;
}
private List prepareSectionObject(List sectionList, String userId) {
ArrayList list = new ArrayList();
if (sectionList != null) {
for (int i = 0; i < sectionList.size(); i++) {
String sectionEid = (String) sectionList.get(i);
try
{
Section s = cms.getSection(sectionEid);
if (s != null)
{
SectionObject so = new SectionObject(s);
so.setAuthorizer(new ArrayList(Arrays.asList(userId.split(","))));
list.add(so);
}
}
catch (IdNotFoundException e)
{
M_log.warn("prepareSectionObject: Cannot find section " + sectionEid);
}
}
}
return list;
}
/**
* change collection object to list object
* @param c
* @return
*/
private List collectionToList(Collection c)
{
List rv = new Vector();
if (c!=null)
{
for (Iterator i = c.iterator(); i.hasNext();)
{
rv.add(i.next());
}
}
return rv;
}
protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
throws ToolException
{
ToolSession toolSession = SessionManager.getCurrentToolSession();
SessionState state = getState(req);
if (SITE_MODE_HELPER_DONE.equals(state.getAttribute(STATE_SITE_MODE)))
{
String url = (String) SessionManager.getCurrentToolSession().getAttribute(Tool.HELPER_DONE_URL);
SessionManager.getCurrentToolSession().removeAttribute(Tool.HELPER_DONE_URL);
// TODO: Implement cleanup.
cleanState(state);
// Helper cleanup.
cleanStateHelper(state);
if (M_log.isDebugEnabled())
{
M_log.debug("Sending redirect to: "+ url);
}
try
{
res.sendRedirect(url);
}
catch (IOException e)
{
M_log.warn("Problem sending redirect to: "+ url, e);
}
return;
}
else
{
super.toolModeDispatch(methodBase, methodExt, req, res);
}
}
private void cleanStateHelper(SessionState state) {
state.removeAttribute(STATE_SITE_MODE);
state.removeAttribute(STATE_TEMPLATE_INDEX);
state.removeAttribute(STATE_INITIALIZED);
}
private String getSiteBaseUrl() {
return ServerConfigurationService.getPortalUrl() + "/" +
ServerConfigurationService.getString("portal.handler.default", "site") +
"/";
}
private String getDefaultSiteUrl(String siteId) {
return prefixString(getSiteBaseUrl(), siteId);
}
private Collection<String> getSiteReferenceAliasIds(Site forSite) {
return prefixSiteAliasIds(null, forSite);
}
private Collection<String> getSiteUrlsForSite(Site site) {
return prefixSiteAliasIds(getSiteBaseUrl(), site);
}
private Collection<String> getSiteUrlsForAliasIds(Collection<String> aliasIds) {
return prefixSiteAliasIds(getSiteBaseUrl(), aliasIds);
}
private String getSiteUrlForAliasId(String aliasId) {
return prefixString(getSiteBaseUrl(), aliasId);
}
private Collection<String> prefixSiteAliasIds(String prefix, Site site) {
return prefixSiteAliasIds(prefix, AliasService.getAliases(site.getReference()));
}
private Collection<String> prefixSiteAliasIds(String prefix, Collection<? extends Object> aliases) {
List<String> siteAliases = new ArrayList<String>();
for (Object alias : aliases) {
String aliasId = null;
if ( alias instanceof Alias ) {
aliasId = ((Alias)alias).getId();
} else {
aliasId = alias.toString();
}
siteAliases.add(prefixString(prefix,aliasId));
}
return siteAliases;
}
private String prefixString(String prefix, String aliasId) {
return (prefix == null ? "" : prefix) + aliasId;
}
private List<String> toIdList(List<? extends Entity> entities) {
List<String> ids = new ArrayList<String>(entities.size());
for ( Entity entity : entities ) {
ids.add(entity.getId());
}
return ids;
}
/**
* whether this tool title is of Home tool title
* @param toolTitle
* @return
*/
private boolean isHomePage(SitePage page)
{
if (page.getProperties().getProperty(SitePage.IS_HOME_PAGE) != null)
{
// check based on the page property first
return true;
}
else
{
// if above fails, check based on the page title
String pageTitle = page.getTitle();
return TOOL_ID_HOME.equalsIgnoreCase(pageTitle) || rb.getString("java.home").equalsIgnoreCase(pageTitle);
}
}
public boolean displaySiteAlias() {
if (ServerConfigurationService.getBoolean("wsetup.disable.siteAlias", false)) {
return false;
}
return true;
}
private void putPrintParticipantLinkIntoContext(Context context, RunData data, Site site) {
// the status servlet reqest url
String url = Web.serverUrl(data.getRequest()) + "/sakai-site-manage-tool/tool/printparticipant/" + site.getId();
context.put("printParticipantUrl", url);
}
/**
* dispatch function for site type vm
* @param data
*/
public void doSite_type_option(RunData data)
{
ParameterParser params = data.getParameters();
String option = StringUtils.trimToNull(params.getString("option"));
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (option != null)
{
if ("cancel".equals(option))
{
doCancel_create(data);
}
else if ("siteType".equals(option))
{
doSite_type(data);
}
else if ("createOnTemplate".equals(option))
{
doSite_copyFromTemplate(data);
}
else if ("createCourseOnTemplate".equals(option))
{
doSite_copyFromCourseTemplate(data);
}
else if ("createCourseOnTemplate".equals(option))
{
doSite_copyFromCourseTemplate(data);
}
else if ("createFromArchive".equals(option))
{
state.setAttribute(STATE_CREATE_FROM_ARCHIVE, Boolean.TRUE);
//continue with normal workflow
doSite_type(data);
}
}
}
/**
* create site from template
* @param params
* @param state
*/
private void doSite_copyFromTemplate(RunData data)
{
ParameterParser params = data.getParameters();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read template information
readCreateSiteTemplateInformation(params, state);
// create site
doFinish(data);
}
/**
* create course site from template, next step would be select roster
* @param params
* @param state
*/
private void doSite_copyFromCourseTemplate(RunData data)
{
ParameterParser params = data.getParameters();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read template information
readCreateSiteTemplateInformation(params, state);
// redirect for site roster selection
redirectCourseCreation(params, state, "selectTermTemplate");
}
/**
* read the user input for creating site based on template
* @param params
* @param state
*/
private void readCreateSiteTemplateInformation(ParameterParser params, SessionState state)
{
// get the template site id
String templateSiteId = params.getString("templateSiteId");
try {
Site templateSite = SiteService.getSite(templateSiteId);
state.setAttribute(STATE_TEMPLATE_SITE, templateSite);
state.setAttribute(STATE_SITE_TYPE, templateSite.getType());
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = templateSite.getType();
siteInfo.title = StringUtils.trimToNull(params.getString("siteTitleField"));
siteInfo.term = StringUtils.trimToNull(params.getString("selectTermTemplate"));
siteInfo.iconUrl = templateSite.getIconUrl();
// description is site-specific. Shouldn't come from template
// siteInfo.description = templateSite.getDescription();
siteInfo.short_description = templateSite.getShortDescription();
siteInfo.joinable = templateSite.isJoinable();
siteInfo.joinerRole = templateSite.getJoinerRole();
state.setAttribute(STATE_SITE_INFO, siteInfo);
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromParams( params, siteInfo );
// whether to copy users or site content over?
if (params.getBoolean("copyUsers")) state.setAttribute(STATE_TEMPLATE_SITE_COPY_USERS, Boolean.TRUE); else state.removeAttribute(STATE_TEMPLATE_SITE_COPY_USERS);
if (params.getBoolean("copyContent")) state.setAttribute(STATE_TEMPLATE_SITE_COPY_CONTENT, Boolean.TRUE); else state.removeAttribute(STATE_TEMPLATE_SITE_COPY_CONTENT);
if (params.getBoolean("publishSite")) state.setAttribute(STATE_TEMPLATE_PUBLISH, Boolean.TRUE); else state.removeAttribute(STATE_TEMPLATE_PUBLISH);
}
catch(Exception e){
M_log.warn(this + "readCreateSiteTemplateInformation: problem of getting template site: " + templateSiteId);
}
}
/**
* redirect course creation process after the term selection step
* @param params
* @param state
* @param termFieldName
*/
private void redirectCourseCreation(ParameterParser params, SessionState state, String termFieldName) {
User user = UserDirectoryService.getCurrentUser();
String currentUserId = user.getEid();
String userId = params.getString("userId");
if (userId == null || "".equals(userId)) {
userId = currentUserId;
} else {
// implies we are trying to pick sections owned by other
// users. Currently "select section by user" page only
// take one user per sitte request - daisy's note 1
ArrayList<String> list = new ArrayList();
list.add(userId);
state.setAttribute(STATE_CM_AUTHORIZER_LIST, list);
}
state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId);
String academicSessionEid = params.getString(termFieldName);
// check whether the academicsession might be null
if (academicSessionEid != null)
{
AcademicSession t = cms.getAcademicSession(academicSessionEid);
state.setAttribute(STATE_TERM_SELECTED, t);
if (t != null) {
List sections = prepareCourseAndSectionListing(userId, t
.getEid(), state);
isFutureTermSelected(state);
if (sections != null && sections.size() > 0) {
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean(SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue() && courseManagementIsImplemented())
{
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
} else { // not course type
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
}
public void doEdit_site_info(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String locale_string = params.getString("locales");
state.setAttribute("locale_string",locale_string);
String option = params.getString("option");
if ("removeSection".equals(option))
{
// remove section
removeAnyFlagedSection(state, params);
}
else if ("continue".equals(option))
{
// continue with site information edit
MathJaxEnabler.applyAllowedSettingsToState(state, params); // SAK-22384
doContinue(data);
}
else if ("back".equals(option))
{
// go back to previous pages
doBack(data);
}
else if ("cancel".equals(option))
{
// cancel
doCancel(data);
}
}
/**
* *
*
* @return Locale based on its string representation (language_region)
*/
private Locale getLocaleFromString(String localeString)
{
org.sakaiproject.component.api.ServerConfigurationService scs = (org.sakaiproject.component.api.ServerConfigurationService) ComponentManager.get(org.sakaiproject.component.api.ServerConfigurationService.class);
return scs.getLocaleFromString(localeString);
}
/**
* @return Returns the prefLocales
*/
public List<Locale> getPrefLocales()
{
// Initialize list of supported locales, if necessary
if (prefLocales.size() == 0) {
org.sakaiproject.component.api.ServerConfigurationService scs = (org.sakaiproject.component.api.ServerConfigurationService) ComponentManager.get(org.sakaiproject.component.api.ServerConfigurationService.class);
Locale[] localeArray = scs.getSakaiLocales();
// Add to prefLocales list
for (int i = 0; i < localeArray.length; i++) {
prefLocales.add(localeArray[i]);
}
}
return prefLocales;
}
// SAK-20797
/**
* return quota on site specified by siteId
* @param siteId
* @return value of site-specific quota or 0 if not found
*/
private long getSiteSpecificQuota(String siteId) {
long quota = 0;
try {
Site site = SiteService.getSite(siteId);
if (site != null) {
quota = getSiteSpecificQuota(site);
}
} catch (IdUnusedException e) {
M_log.warn("Quota calculation could not find the site " + siteId
+ "for site specific quota calculation",
M_log.isDebugEnabled() ? e : null);
}
return quota;
}
// SAK-20797
/**
* return quota set on this specific site
* @param collection
* @return value of site-specific quota or 0 if not found
*/
private long getSiteSpecificQuota(Site site) {
long quota = 0;
try
{
String collId = m_contentHostingService
.getSiteCollection(site.getId());
ContentCollection site_collection = m_contentHostingService.getCollection(collId);
long siteSpecific = site_collection.getProperties().getLongProperty(
ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
quota = siteSpecific;
}
catch (Exception ignore)
{
M_log.warn("getQuota: reading quota property for site : " + site.getId() + " : " + ignore);
quota = 0;
}
return quota;
}
// SAK-20797
/**
* return file size in bytes as formatted string
* @param quota
* @return formatted string (i.e. 2048 as 2 KB)
*/
private String formatSize(long quota) {
String size = "";
NumberFormat formatter = NumberFormat.getInstance(rb.getLocale());
formatter.setMaximumFractionDigits(1);
if (quota > 700000000L) {
String[] args = { formatter.format(1.0 * quota
/ (1024L * 1024L * 1024L)) };
size = rb.getFormattedMessage("size.gb", args);
} else if (quota > 700000L) {
String[] args = { formatter.format(1.0 * quota / (1024L * 1024L)) };
size = rb.getFormattedMessage("size.mb", args);
} else if (quota > 700L) {
String[] args = { formatter.format(1.0 * quota / 1024L) };
size = rb.getFormattedMessage("size.kb", args);
} else {
String[] args = { formatter.format(quota) };
size = rb.getFormattedMessage("size.bytes", args);
}
return size;
}
public class JoinableGroup{
private String reference;
private String title;
private String joinableSet;
private int size;
private int max;
private String members;
private boolean preview;
public JoinableGroup(String reference, String title, String joinableSet, int size, int max, String members, boolean preview){
this.reference = reference;
this.title = title;
this.joinableSet = joinableSet;
this.size = size;
this.max = max;
this.members = members;
this.preview = preview;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getJoinableSet() {
return joinableSet;
}
public void setJoinableSet(String joinableSet) {
this.joinableSet = joinableSet;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public String getMembers() {
return members;
}
public void setMembers(String members) {
this.members = members;
}
public boolean isPreview() {
return preview;
}
public void setPreview(boolean preview) {
this.preview = preview;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
}
/**
* Handles uploading an archive file as part of the site creation workflow
* @param data
*/
public void doUploadArchive(RunData data)
{
ParameterParser params = data.getParameters();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
//get params
FileItem fi = data.getParameters().getFileItem ("importFile");
//get uploaded file into a location we can process
String archiveUnzipBase = ServerConfigurationService.getString("archive.storage.path", FileUtils.getTempDirectoryPath());
//convert inputstream into actual file so we can unzip it
String zipFilePath = archiveUnzipBase + File.separator + fi.getFileName();
//rudimentary check that the file is a zip file
if(!StringUtils.endsWith(fi.getFileName(), ".zip")){
addAlert(state, rb.getString("archive.createsite.failedupload"));
return;
}
File tempZipFile = new File(zipFilePath);
if(tempZipFile.exists()) {
tempZipFile.delete();
}
try {
//copy contents into this file
IOUtils.copyLarge(fi.getInputStream(), new FileOutputStream(tempZipFile));
//set path into state so we can process it later
state.setAttribute(STATE_UPLOADED_ARCHIVE_PATH, tempZipFile.getAbsolutePath());
state.setAttribute(STATE_UPLOADED_ARCHIVE_NAME, tempZipFile.getName());
} catch (Exception e) {
M_log.error(e.getMessage(), e); //general catch all for the various exceptions that occur above. all are failures.
addAlert(state, rb.getString("archive.createsite.failedupload"));
}
//go to confirm screen
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
}
/**
* Handles merging an uploaded archive into the newly created site
* This is done after the site has been created in the site creation workflow
*
* @param siteId
* @param state
*/
private void doMergeArchiveIntoNewSite(String siteId, SessionState state) {
String currentUserId = userDirectoryService.getCurrentUser().getId();
try {
String archivePath = (String)state.getAttribute(STATE_UPLOADED_ARCHIVE_PATH);
//merge the zip into our new site
//we ignore the return because its not very useful. See ArchiveService for more details
archiveService.mergeFromZip(archivePath, siteId, currentUserId);
} catch (Exception e) {
M_log.error(e.getMessage(), e); //general catch all for the various exceptions that occur above. all are failures.
addAlert(state, rb.getString("archive.createsite.failedmerge"));
}
}
}
| site-manage/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.site.tool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.EmailValidator;
import org.apache.velocity.tools.generic.SortTool;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.api.privacy.PrivacyManager;
import org.sakaiproject.archive.api.ImportMetadata;
import org.sakaiproject.archive.cover.ArchiveService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityAdvisor.SecurityAdvice;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.coursemanagement.api.AcademicSession;
import org.sakaiproject.coursemanagement.api.CourseOffering;
import org.sakaiproject.coursemanagement.api.CourseSet;
import org.sakaiproject.coursemanagement.api.Section;
import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.EntityTransferrerRefMigrator;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.ImportException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.importer.api.ImportDataSource;
import org.sakaiproject.importer.api.ImportService;
import org.sakaiproject.importer.api.ResetOnCloseInputStream;
import org.sakaiproject.importer.api.SakaiArchive;
import org.sakaiproject.importer.api.ResetOnCloseInputStream;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.lti.api.LTIService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.SiteService.SortType;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.site.util.Participant;
import org.sakaiproject.site.util.SiteComparator;
import org.sakaiproject.site.util.SiteConstants;
import org.sakaiproject.site.util.SiteParticipantHelper;
import org.sakaiproject.site.util.SiteSetupQuestionFileParser;
import org.sakaiproject.site.util.SiteTextEditUtil;
import org.sakaiproject.site.util.SiteTypeUtil;
import org.sakaiproject.site.util.ToolComparator;
import org.sakaiproject.sitemanage.api.SectionField;
import org.sakaiproject.sitemanage.api.SiteHelper;
import org.sakaiproject.sitemanage.api.model.SiteSetupQuestion;
import org.sakaiproject.sitemanage.api.model.SiteSetupQuestionAnswer;
import org.sakaiproject.sitemanage.api.model.SiteSetupUserAnswer;
import org.sakaiproject.sitemanage.api.model.SiteTypeQuestions;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolException;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.userauditservice.api.UserAuditRegistration;
import org.sakaiproject.userauditservice.api.UserAuditService;
import org.sakaiproject.util.*;
// for basiclti integration
/**
* <p>
* SiteAction controls the interface for worksite setup.
* </p>
*/
public class SiteAction extends PagedResourceActionII {
// SAK-23491 add template_used property
private static final String TEMPLATE_USED = "template_used";
/** Our log (commons). */
private static Log M_log = LogFactory.getLog(SiteAction.class);
private LTIService m_ltiService = (LTIService) ComponentManager.get("org.sakaiproject.lti.api.LTIService");
private ContentHostingService m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
private ImportService importService = org.sakaiproject.importer.cover.ImportService
.getInstance();
private static String showOrphanedMembers = ServerConfigurationService.getString("site.setup.showOrphanedMembers", "admins");
/** portlet configuration parameter values* */
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric");
private static ResourceLoader cfgRb = new ResourceLoader("multipletools");
private Locale comparator_locale = rb.getLocale();
private org.sakaiproject.user.api.UserDirectoryService userDirectoryService = (org.sakaiproject.user.api.UserDirectoryService) ComponentManager.get(
org.sakaiproject.user.api.UserDirectoryService.class );
private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager
.get(org.sakaiproject.coursemanagement.api.CourseManagementService.class);
private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager
.get(org.sakaiproject.authz.api.GroupProvider.class);
private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager
.get(org.sakaiproject.authz.api.AuthzGroupService.class);
private org.sakaiproject.archive.api.ArchiveService archiveService = (org.sakaiproject.archive.api.ArchiveService) ComponentManager
.get(org.sakaiproject.archive.api.ArchiveService.class);
private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class);
private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class);
private org.sakaiproject.sitemanage.api.SiteTypeProvider siteTypeProvider = (org.sakaiproject.sitemanage.api.SiteTypeProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.SiteTypeProvider.class);
private static org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService questionService = (org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService) ComponentManager
.get(org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService.class);
private static org.sakaiproject.sitemanage.api.UserNotificationProvider userNotificationProvider = (org.sakaiproject.sitemanage.api.UserNotificationProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.UserNotificationProvider.class);
private static final String SITE_MODE_SITESETUP = "sitesetup";
private static final String SITE_MODE_SITEINFO = "siteinfo";
private static final String SITE_MODE_HELPER = "helper";
private static final String SITE_MODE_HELPER_DONE = "helper.done";
private static final String STATE_SITE_MODE = "site_mode";
private static final String TERM_OPTION_ALL = "-1";
protected final static String[] TEMPLATE = {
"-list",// 0
"-type",
"",// combined with 13
"",// chef_site-editFeatures.vm deleted. Functions are combined with chef_site-editToolGroupFeatures.vm
"-editToolGroupFeatures",
"",// moved to participant helper
"",
"",
"-siteDeleteConfirm",
"",
"-newSiteConfirm",// 10
"",
"-siteInfo-list",// 12
"-siteInfo-editInfo",
"-siteInfo-editInfoConfirm",
"-addRemoveFeatureConfirm",// 15
"",
"",
"-siteInfo-editAccess",
"",
"",// 20
"",
"",
"",
"",
"",// 25
"-modifyENW",
"-importSites",
"-siteInfo-import",
"-siteInfo-duplicate",
"",// 30
"",// 31
"",// 32
"",// 33
"",// 34
"",// 35
"-newSiteCourse",// 36
"-newSiteCourseManual",// 37
"",// 38
"",// 39
"",// 40
"",// 41
"-type-confirm",// 42
"-siteInfo-editClass",// 43
"-siteInfo-addCourseConfirm",// 44
"-siteInfo-importMtrlMaster", // 45 -- htripath for import
// material from a file
"-siteInfo-importMtrlCopy", // 46
"-siteInfo-importMtrlCopyConfirm",
"-siteInfo-importMtrlCopyConfirmMsg", // 48
"",//"-siteInfo-group", // 49 moved to the group helper
"",//"-siteInfo-groupedit", // 50 moved to the group helper
"",//"-siteInfo-groupDeleteConfirm", // 51, moved to the group helper
"",
"-findCourse", // 53
"-questions", // 54
"",// 55
"",// 56
"",// 57
"-siteInfo-importSelection", //58
"-siteInfo-importMigrate", //59
"-importSitesMigrate", //60
"-siteInfo-importUser",
"-uploadArchive"
};
/** Name of state attribute for Site instance id */
private static final String STATE_SITE_INSTANCE_ID = "site.instance.id";
/** Name of state attribute for Site Information */
private static final String STATE_SITE_INFO = "site.info";
private static final String STATE_SITE_TYPE = "site-type";
/** Name of state attribute for possible site types */
private static final String STATE_SITE_TYPES = "site_types";
private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type";
private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types";
private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types";
private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types";
private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types";
private final static String PROP_SITE_LANGUAGE = "locale_string";
/**
* Name of the state attribute holding the site list column list is sorted
* by
*/
private static final String SORTED_BY = "site.sorted.by";
/** Name of the state attribute holding the site list column to sort by */
private static final String SORTED_ASC = "site.sort.asc";
/** State attribute for list of sites to be deleted. */
private static final String STATE_SITE_REMOVALS = "site.removals";
/** Name of the state attribute holding the site list View selected */
private static final String STATE_VIEW_SELECTED = "site.view.selected";
private static final String STATE_TERM_VIEW_SELECTED = "site.termview.selected";
/*******************
* SAK-16600
*
* Refactor methods to update these values in state/context
*/
/** Names of lists related to tools groups */
private static final String STATE_TOOL_GROUP_LIST = "toolsByGroup";
/** Names of lists related to tools groups */
private static final String STATE_TOOL_GROUP_MULTIPLES = "toolGroupMultiples";
/** Names of lists related to tools */
private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList";
private static final String STATE_TOOL_REGISTRATION_TITLE_LIST = "toolRegistrationTitleList";
private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome";
private static final String STATE_EXTRA_SELECTED_TOOL_LIST = "extraSelectedToolList";
private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected";
private static final String UNGROUPED_TOOL_TITLE = "systoolgroups.ungrouped";
private static final String LTI_TOOL_TITLE = "systoolgroups.lti";
//********************
private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress";
private static final String STATE_PROJECT_TOOL_LIST = "projectToolList";
private final static String STATE_MULTIPLE_TOOL_ID_SET = "multipleToolIdSet";
private final static String STATE_MULTIPLE_TOOL_ID_TITLE_MAP = "multipleToolIdTitleMap";
private final static String STATE_MULTIPLE_TOOL_CONFIGURATION = "multipleToolConfiguration";
private final static String SITE_DEFAULT_LIST = ServerConfigurationService
.getString("site.types");
private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname";
private static final String STATE_SITE_ADD_COURSE = "canAddCourse";
private static final String STATE_SITE_ADD_PORTFOLIO = "canAddPortfolio";
private static final String STATE_PORTFOLIO_SITE_TYPE = "portfolio";
private static final String STATE_SITE_ADD_PROJECT = "canAddProject";
private static final String STATE_PROJECT_SITE_TYPE = "project";
private static final String STATE_SITE_IMPORT_ARCHIVE = "canImportArchive";
// SAK-23468
private static final String STATE_NEW_SITE_STATUS_ISPUBLISHED = "newSiteStatusIsPublished";
private static final String STATE_NEW_SITE_STATUS_TITLE = "newSiteStatusTitle";
private static final String STATE_NEW_SITE_STATUS_ID = "newSiteStatusID";
// %%% get rid of the IdAndText tool lists and just use ToolConfiguration or
// ToolRegistration lists
// %%% same for CourseItems
// Names for other state attributes that are lists
private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the
// list
// of
// site
// pages
// consistent
// with
// Worksite
// Setup
// page
// patterns
/**
* The name of the state form field containing additional information for a
* course request
*/
private static final String FORM_ADDITIONAL = "form.additional";
/** %%% in transition from putting all form variables in state */
private final static String FORM_TITLE = "form_title";
private final static String FORM_SITE_URL_BASE = "form_site_url_base";
private final static String FORM_SITE_ALIAS = "form_site_alias";
private final static String FORM_DESCRIPTION = "form_description";
private final static String FORM_HONORIFIC = "form_honorific";
private final static String FORM_INSTITUTION = "form_institution";
private final static String FORM_SUBJECT = "form_subject";
private final static String FORM_PHONE = "form_phone";
private final static String FORM_EMAIL = "form_email";
private final static String FORM_REUSE = "form_reuse";
private final static String FORM_RELATED_CLASS = "form_related_class";
private final static String FORM_RELATED_PROJECT = "form_related_project";
private final static String FORM_NAME = "form_name";
private final static String FORM_SHORT_DESCRIPTION = "form_short_description";
private final static String FORM_ICON_URL = "iconUrl";
private final static String FORM_SITEINFO_URL_BASE = "form_site_url_base";
private final static String FORM_SITEINFO_ALIASES = "form_site_aliases";
private final static String FORM_WILL_NOTIFY = "form_will_notify";
/** Context action */
private static final String CONTEXT_ACTION = "SiteAction";
/** The name of the Attribute for display template index */
private static final String STATE_TEMPLATE_INDEX = "site.templateIndex";
/** The name of the Attribute for display template index */
private static final String STATE_OVERRIDE_TEMPLATE_INDEX = "site.overrideTemplateIndex";
/** The name of the Attribute to indicate we are operating in shortcut mode */
private static final String STATE_IN_SHORTCUT = "site.currentlyInShortcut";
/** State attribute for state initialization. */
private static final String STATE_INITIALIZED = "site.initialized";
/** State attributes for using templates in site creation. */
private static final String STATE_TEMPLATE_SITE = "site.templateSite";
private static final String STATE_TEMPLATE_SITE_COPY_USERS = "site.templateSiteCopyUsers";
private static final String STATE_TEMPLATE_SITE_COPY_CONTENT = "site.templateSiteCopyContent";
private static final String STATE_TEMPLATE_PUBLISH = "site.templateSitePublish";
/** The action for menu */
private static final String STATE_ACTION = "site.action";
/** The user copyright string */
private static final String STATE_MY_COPYRIGHT = "resources.mycopyright";
/** The copyright character */
private static final String COPYRIGHT_SYMBOL = "copyright (c)";
/** The null/empty string */
private static final String NULL_STRING = "";
/** The state attribute alerting user of a sent course request */
private static final String REQUEST_SENT = "site.request.sent";
/** The state attributes in the make public vm */
private static final String STATE_JOINABLE = "state_joinable";
private static final String STATE_JOINERROLE = "state_joinerRole";
private static final String STATE_SITE_ACCESS_PUBLISH = "state_site_access_publish";
private static final String STATE_SITE_ACCESS_INCLUDE = "state_site_access_include";
/** the list of selected user */
private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list";
private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles";
private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants";
private static final String STATE_PARTICIPANT_LIST = "state_participant_list";
private static final String STATE_ADD_PARTICIPANTS = "state_add_participants";
/** for changing participant roles */
private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole";
private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role";
/** for remove user */
private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list";
private static final String STATE_IMPORT = "state_import";
private static final String STATE_IMPORT_SITES = "state_import_sites";
private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool";
/** for navigating between sites in site list */
private static final String STATE_SITES = "state_sites";
private static final String STATE_PREV_SITE = "state_prev_site";
private static final String STATE_NEXT_SITE = "state_next_site";
/** for course information */
private final static String STATE_TERM_COURSE_LIST = "state_term_course_list";
private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash";
private final static String STATE_TERM_SELECTED = "state_term_selected";
private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected";
private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected";
private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider";
private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen";
private final static String STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN = "state_add_class_provider_description_chosen";
private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual";
private final static String STATE_AUTO_ADD = "state_auto_add";
private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number";
private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields";
public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections";
public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list";
public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list";
private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates";
private final static String STATE_ICONS = "icons";
public static final String SITE_DUPLICATED = "site_duplicated";
public static final String SITE_DUPLICATED_NAME = "site_duplicated_named";
// types of site whose title can not be editable
public static final String TITLE_NOT_EDITABLE_SITE_TYPE = "title_not_editable_site_type";
// maximum length of a site title
private static final String STATE_SITE_TITLE_MAX = "site_title_max_length";
// types of site where site view roster permission is editable
public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type";
// htripath : for import material from file - classic import
private static final String ALL_ZIP_IMPORT_SITES = "allzipImports";
private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports";
private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports";
private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName";
private static final String SESSION_CONTEXT_ID = "sessionContextId";
// page size for worksite setup tool
private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup";
// page size for site info tool
private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo";
private static final String IMPORT_DATA_SOURCE = "import_data_source";
// Special tool id for Home page
private static final String SITE_INFORMATION_TOOL="sakai.iframe.site";
private static final String STATE_CM_LEVELS = "site.cm.levels";
private static final String STATE_CM_LEVEL_OPTS = "site.cm.level_opts";
private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections";
private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection";
private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested";
private static final String STATE_CM_SELECTED_SECTIONS = "site.cm.selectedSections";
private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list";
private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId";
private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list";
private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections";
private String cmSubjectCategory;
private boolean warnedNoSubjectCategory = false;
// the string marks the protocol part in url
private static final String PROTOCOL_STRING = "://";
/**
* {@link org.sakaiproject.component.api.ServerConfigurationService} property.
* If <code>false</code>, ensures that a site's joinability settings are not affected should
* that site be <em>edited</em> after its type has been enumerated by a
* "wsetup.disable.joinable" property. Code should cause this prop value to
* default to <code>true</code> to preserve backward compatibility. Property
* naming tries to match mini-convention established by "wsetup.disable.joinable"
* (which has no corresponding constant).
*
* <p>Has no effect on the site creation process -- only site editing</p>
*
* @see #doUpdate_site_access_joinable(RunData, SessionState, ParameterParser, Site)
*/
public static final String CONVERT_NULL_JOINABLE_TO_UNJOINABLE = "wsetup.convert.null.joinable.to.unjoinable";
private static final String SITE_TEMPLATE_PREFIX = "template";
private static final String STATE_TYPE_SELECTED = "state_type_selected";
// the template index after exist the question mode
private static final String STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE = "state_site_setup_question_next_template";
// SAK-12912, the answers to site setup questions
private static final String STATE_SITE_SETUP_QUESTION_ANSWER = "state_site_setup_question_answer";
// SAK-13389, the non-official participant
private static final String ADD_NON_OFFICIAL_PARTICIPANT = "add_non_official_participant";
// the list of visited templates
private static final String STATE_VISITED_TEMPLATES = "state_visited_templates";
private String STATE_GROUP_HELPER_ID = "state_group_helper_id";
// used in the configuration file to specify which tool attributes are configurable through WSetup tool, and what are the default value for them.
private String CONFIG_TOOL_ATTRIBUTE = "wsetup.config.tool.attribute_";
private String CONFIG_TOOL_ATTRIBUTE_DEFAULT = "wsetup.config.tool.attribute.default_";
// used in the configuration file to specify the default tool title
private String CONFIG_TOOL_TITLE = "wsetup.config.tool.title_";
// home tool id
private static final String TOOL_ID_HOME = "home";
// Site Info tool id
private static final String TOOL_ID_SITEINFO = "sakai.siteinfo";
// synoptic tool ids
private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar";
private static final String TOOL_ID_SYNOPTIC_ANNOUNCEMENT = "sakai.synoptic.announcement";
private static final String TOOL_ID_SYNOPTIC_CHAT = "sakai.synoptic.chat";
private static final String TOOL_ID_SYNOPTIC_MESSAGECENTER = "sakai.synoptic.messagecenter";
private static final String TOOL_ID_SYNOPTIC_DISCUSSION = "sakai.synoptic.discussion";
private static final String IMPORT_QUEUED = "import.queued";
// map of synoptic tool and the related tool ids
private final static Map<String, List<String>> SYNOPTIC_TOOL_ID_MAP;
static
{
SYNOPTIC_TOOL_ID_MAP = new HashMap<String, List<String>>();
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SUMMARY_CALENDAR, new ArrayList(Arrays.asList("sakai.schedule")));
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SYNOPTIC_ANNOUNCEMENT, new ArrayList(Arrays.asList("sakai.announcements")));
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SYNOPTIC_CHAT, new ArrayList(Arrays.asList("sakai.chat")));
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SYNOPTIC_MESSAGECENTER, new ArrayList(Arrays.asList("sakai.messages", "sakai.forums", "sakai.messagecenter")));
SYNOPTIC_TOOL_ID_MAP.put(TOOL_ID_SYNOPTIC_DISCUSSION, new ArrayList(Arrays.asList("sakai.discussion")));
}
// map of synoptic tool and message bundle properties, used to lookup an internationalized tool title
private final static Map<String, String> SYNOPTIC_TOOL_TITLE_MAP;
static
{
SYNOPTIC_TOOL_TITLE_MAP = new HashMap<String, String>();
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SUMMARY_CALENDAR, "java.reccal");
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SYNOPTIC_ANNOUNCEMENT, "java.recann");
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SYNOPTIC_CHAT, "java.recent");
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SYNOPTIC_MESSAGECENTER, "java.recmsg");
SYNOPTIC_TOOL_TITLE_MAP.put(TOOL_ID_SYNOPTIC_DISCUSSION, "java.recdisc");
}
/** the web content tool id **/
private final static String WEB_CONTENT_TOOL_ID = "sakai.iframe";
private final static String SITE_INFO_TOOL_ID = "sakai.iframe.site";
private final static String WEB_CONTENT_TOOL_SOURCE_CONFIG = "source";
private final static String WEB_CONTENT_TOOL_SOURCE_CONFIG_VALUE = "http://";
/** the news tool **/
private final static String NEWS_TOOL_ID = "sakai.news";
private final static String NEWS_TOOL_CHANNEL_CONFIG = "channel-url";
private final static String NEWS_TOOL_CHANNEL_CONFIG_VALUE = "http://sakaiproject.org/feed";
private final static int UUID_LENGTH = 36;
/** the course set definition from CourseManagementService **/
private final static String STATE_COURSE_SET = "state_course_set";
// the maximum tool title length enforced in UI
private final static int MAX_TOOL_TITLE_LENGTH = 20;
private final static String SORT_KEY_SESSION = "worksitesetup.sort.key.session";
private final static String SORT_ORDER_SESSION = "worksitesetup.sort.order.session";
private final static String SORT_KEY_COURSE_SET = "worksitesetup.sort.key.courseSet";
private final static String SORT_ORDER_COURSE_SET = "worksitesetup.sort.order.courseSet";
private final static String SORT_KEY_COURSE_OFFERING = "worksitesetup.sort.key.courseOffering";
private final static String SORT_ORDER_COURSE_OFFERING = "worksitesetup.sort.order.courseOffering";
private final static String SORT_KEY_SECTION = "worksitesetup.sort.key.section";
private final static String SORT_ORDER_SECTION = "worksitesetup.sort.order.section";
// bjones86 - SAK-23255
private final static String CONTEXT_IS_ADMIN = "isAdmin";
private final static String CONTEXT_SKIP_MANUAL_COURSE_CREATION = "skipManualCourseCreation";
private final static String CONTEXT_SKIP_COURSE_SECTION_SELECTION = "skipCourseSectionSelection";
private final static String CONTEXT_FILTER_TERMS = "filterTerms";
private final static String SAK_PROP_SKIP_MANUAL_COURSE_CREATION = "wsetup.skipManualCourseCreation";
private final static String SAK_PROP_SKIP_COURSE_SECTION_SELECTION = "wsetup.skipCourseSectionSelection";
private List prefLocales = new ArrayList();
private static final String VM_ALLOWED_ROLES_DROP_DOWN = "allowedRoles";
// bjones86 - SAK-23256
private static final String SAK_PROP_FILTER_TERMS = "worksitesetup.filtertermdropdowns";
private static final String CONTEXT_HAS_TERMS = "hasTerms";
// state variable for whether any multiple instance tool has been selected
private String STATE_MULTIPLE_TOOL_INSTANCE_SELECTED = "state_multiple_tool_instance_selected";
// state variable for lti tools
private String STATE_LTITOOL_LIST = "state_ltitool_list";
// state variable for selected lti tools in site
private String STATE_LTITOOL_EXISTING_SELECTED_LIST = "state_ltitool_existing_selected_list";
// state variable for selected lti tools during tool modification
private String STATE_LTITOOL_SELECTED_LIST = "state_ltitool_selected_list";
// special prefix String for basiclti tool ids
private String LTITOOL_ID_PREFIX = "lti_";
private String m_filePath;
private String moreInfoPath;
private String libraryPath;
private static final String STATE_CREATE_FROM_ARCHIVE = "createFromArchive";
private static final String STATE_UPLOADED_ARCHIVE_PATH = "uploadedArchivePath";
private static final String STATE_UPLOADED_ARCHIVE_NAME = "uploadedArchiveNAme";
private static UserAuditRegistration userAuditRegistration = (UserAuditRegistration) ComponentManager.get("org.sakaiproject.userauditservice.api.UserAuditRegistration.sitemanage");
private static UserAuditService userAuditService = (UserAuditService) ComponentManager.get(UserAuditService.class);
private PrivacyManager privacyManager = (PrivacyManager) ComponentManager.get(PrivacyManager.class);
/**
* what are the tool ids within Home page?
* If this is for a newly added Home tool, get the tool ids from template site or system set default
* Else if this is an existing Home tool, get the tool ids from the page
* @param state
* @param newHomeTool
* @param homePage
* @return
*/
private List<String> getHomeToolIds(SessionState state, boolean newHomeTool, SitePage homePage)
{
List<String> rv = new Vector<String>();
// if this is a new Home tool page to be added, get the tool ids from definition (template site first, and then configurations)
Site site = getStateSite(state);
String siteType = site != null? site.getType() : "";
// First: get the tool ids from configuration files
// initially by "wsetup.home.toolids" + site type, and if missing, use "wsetup.home.toolids"
if (ServerConfigurationService.getStrings("wsetup.home.toolids." + siteType) != null) {
rv = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("wsetup.home.toolids." + siteType)));
} else if (ServerConfigurationService.getStrings("wsetup.home.toolids") != null) {
rv = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("wsetup.home.toolids")));
}
// Second: if tool list is empty, get it from the template site settings
if (rv.isEmpty())
{
// template site
Site templateSite = null;
String templateSiteId = "";
if (SiteService.isUserSite(site.getId()))
{
// myworkspace type site: get user type first, and then get the template site
try
{
User user = UserDirectoryService.getUser(SiteService.getSiteUserId(site.getId()));
templateSiteId = SiteService.USER_SITE_TEMPLATE + "." + user.getType();
templateSite = SiteService.getSite(templateSiteId);
}
catch (Throwable t)
{
M_log.debug(this + ": getHomeToolIds cannot find site " + templateSiteId + t.getMessage());
// use the fall-back, user template site
try
{
templateSiteId = SiteService.USER_SITE_TEMPLATE;
templateSite = SiteService.getSite(templateSiteId);
}
catch (Throwable tt)
{
M_log.debug(this + ": getHomeToolIds cannot find site " + templateSiteId + tt.getMessage());
}
}
}
else
{
// not myworkspace site
// first: see whether it is during site creation process and using a template site
templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
if (templateSite == null)
{
// second: if no template is chosen by user, then use template based on site type
templateSiteId = SiteService.SITE_TEMPLATE + "." + siteType;
try
{
templateSite = SiteService.getSite(templateSiteId);
}
catch (Throwable t)
{
M_log.debug(this + ": getHomeToolIds cannot find site " + templateSiteId + t.getMessage());
// thrid: if cannot find template site with the site type, use the default template
templateSiteId = SiteService.SITE_TEMPLATE;
try
{
templateSite = SiteService.getSite(templateSiteId);
}
catch (Throwable tt)
{
M_log.debug(this + ": getHomeToolIds cannot find site " + templateSiteId + tt.getMessage());
}
}
}
}
if (templateSite != null)
{
// get Home page and embedded tool ids
for (SitePage page: (List<SitePage>)templateSite.getPages())
{
String title = page.getTitle();
if (isHomePage(page))
{
// found home page, add all tool ids to return value
for(ToolConfiguration tConfiguration : (List<ToolConfiguration>) page.getTools())
{
String toolId = tConfiguration.getToolId();
if (ToolManager.getTool(toolId) != null)
rv.add(toolId);
}
break;
}
}
}
}
// Third: if the tool id list is still empty because we cannot find any template site yet, use the default settings
if (rv.isEmpty())
{
if (siteType.equalsIgnoreCase("myworkspace"))
{
// first try with MOTD tool
if (ToolManager.getTool("sakai.motd") != null)
rv.add("sakai.motd");
if (rv.isEmpty())
{
// then try with the myworkspace information tool
if (ToolManager.getTool("sakai.iframe.myworkspace") != null)
rv.add("sakai.iframe.myworkspace");
}
}
else
{
// try the site information tool
if (ToolManager.getTool("sakai.iframe.site") != null)
rv.add("sakai.iframe.site");
}
// synoptical tools
if (ToolManager.getTool(TOOL_ID_SUMMARY_CALENDAR) != null)
{
rv.add(TOOL_ID_SUMMARY_CALENDAR);
}
if (ToolManager.getTool(TOOL_ID_SYNOPTIC_ANNOUNCEMENT) != null)
{
rv.add(TOOL_ID_SYNOPTIC_ANNOUNCEMENT);
}
if (ToolManager.getTool(TOOL_ID_SYNOPTIC_CHAT) != null)
{
rv.add(TOOL_ID_SYNOPTIC_CHAT);
}
if (ToolManager.getTool(TOOL_ID_SYNOPTIC_MESSAGECENTER) != null)
{
rv.add(TOOL_ID_SYNOPTIC_MESSAGECENTER);
}
}
// Fourth: if this is an existing Home tool page, get any extra tool ids in the page already back to the list
if (!newHomeTool)
{
// found home page, add all tool ids to return value
for(ToolConfiguration tConfiguration : (List<ToolConfiguration>) homePage.getTools())
{
String hToolId = tConfiguration.getToolId();
if (!rv.contains(hToolId))
{
rv.add(hToolId);
}
}
}
return rv;
}
/*
* Configure directory for moreInfo content
*/
private String setMoreInfoPath(ServletContext ctx) {
String rpath = ctx.getRealPath("");
String ctxPath = ctx.getServletContextName();
String rserve = StringUtils.remove(rpath,ctxPath);
return rserve;
}
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet,
JetspeedRunData rundata) {
ServletContext ctx = rundata.getRequest().getSession().getServletContext();
String serverContextPath = ServerConfigurationService.getString("config.sitemanage.moreInfoDir", "library/image/");
libraryPath = File.separator + serverContextPath;
moreInfoPath = setMoreInfoPath(ctx) + serverContextPath;
// Cleanout if the helper has been asked to start afresh.
if (state.getAttribute(SiteHelper.SITE_CREATE_START) != null) {
cleanState(state);
cleanStateHelper(state);
// Removed from possible previous invokations.
state.removeAttribute(SiteHelper.SITE_CREATE_START);
state.removeAttribute(SiteHelper.SITE_CREATE_CANCELLED);
state.removeAttribute(SiteHelper.SITE_CREATE_SITE_ID);
}
super.initState(state, portlet, rundata);
// store current userId in state
User user = UserDirectoryService.getCurrentUser();
String userId = user.getEid();
state.setAttribute(STATE_CM_CURRENT_USERID, userId);
PortletConfig config = portlet.getPortletConfig();
// types of sites that can either be public or private
String changeableTypes = StringUtils.trimToNull(config
.getInitParameter("publicChangeableSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) {
if (changeableTypes != null) {
state
.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new ArrayList(Arrays.asList(changeableTypes
.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new Vector());
}
}
// type of sites that are always public
String publicTypes = StringUtils.trimToNull(config
.getInitParameter("publicSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) {
if (publicTypes != null) {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList(
Arrays.asList(publicTypes.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector());
}
}
// types of sites that are always private
String privateTypes = StringUtils.trimToNull(config
.getInitParameter("privateSiteTypes"));
if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) {
if (privateTypes != null) {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList(
Arrays.asList(privateTypes.split(","))));
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// default site type
String defaultType = StringUtils.trimToNull(config
.getInitParameter("defaultSiteType"));
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) {
if (defaultType != null) {
state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType);
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// certain type(s) of site cannot get its "joinable" option set
if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) {
if (ServerConfigurationService
.getStrings("wsetup.disable.joinable") != null) {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new ArrayList(Arrays.asList(ServerConfigurationService
.getStrings("wsetup.disable.joinable"))));
} else {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new Vector());
}
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) {
state.setAttribute(STATE_TOP_PAGE_MESSAGE, Integer.valueOf(0));
}
// skins if any
if (state.getAttribute(STATE_ICONS) == null) {
setupIcons(state);
}
if (ServerConfigurationService.getStrings("site.type.titleNotEditable") != null) {
state.setAttribute(TITLE_NOT_EDITABLE_SITE_TYPE, new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("site.type.titleNotEditable"))));
} else {
state.setAttribute(TITLE_NOT_EDITABLE_SITE_TYPE, new ArrayList(Arrays
.asList(new String[]{ServerConfigurationService
.getString("courseSiteType", "course")})));
}
if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) {
List siteTypes = new Vector();
if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) {
siteTypes = new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("editViewRosterSiteType")));
}
state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes);
}
if (state.getAttribute(STATE_SITE_MODE) == null) {
// get site tool mode from tool registry
String site_mode = config.getInitParameter(STATE_SITE_MODE);
// When in helper mode we don't have
if (site_mode == null) {
site_mode = SITE_MODE_HELPER;
}
state.setAttribute(STATE_SITE_MODE, site_mode);
}
} // initState
/**
* cleanState removes the current site instance and it's properties from
* state
*/
private void cleanState(SessionState state) {
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.removeAttribute(STATE_SITE_INFO);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
// remove the state attributes related to multi-tool selection
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
state.removeAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION);
state.removeAttribute(STATE_TOOL_REGISTRATION_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST);
// remove those state attributes related to course site creation
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.removeAttribute(STATE_TERM_COURSE_HASH);
state.removeAttribute(STATE_TERM_SELECTED);
state.removeAttribute(STATE_INSTRUCTOR_SELECTED);
state.removeAttribute(STATE_FUTURE_TERM_SELECTED);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_PROVIDER_SECTION_LIST);
state.removeAttribute(STATE_CM_LEVELS);
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_CURRENT_USERID);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL); // don't we need to clean this
// too? -daisyf
state.removeAttribute(STATE_TEMPLATE_SITE);
state.removeAttribute(STATE_TYPE_SELECTED);
state.removeAttribute(STATE_SITE_SETUP_QUESTION_ANSWER);
state.removeAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE);
// lti tools
state.removeAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST);
state.removeAttribute(STATE_LTITOOL_SELECTED_LIST);
// bjones86 - SAK-24423 - remove joinable site settings from the state
JoinableSiteSettings.removeJoinableSiteSettingsFromState( state );
} // cleanState
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context) {
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = ToolManager.getCurrentPlacement().getContext();
String siteRef = SiteService.siteReference(contextString);
// if it is in Worksite setup tool, pass the selected site's reference
if (state.getAttribute(STATE_SITE_MODE) != null
&& ((String) state.getAttribute(STATE_SITE_MODE))
.equals(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
Site s = getStateSite(state);
if (s != null) {
siteRef = s.getReference();
}
}
}
// setup for editing the permissions of the site for this tool, using
// the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb
.getString("setperfor")
+ " " + SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "site.");
} // doPermissions
/**
* Build the context for shortcut display
*/
public String buildShortcutPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
return buildMainPanelContext(portlet, context, data, state, true);
}
/**
* Build the context for normal display
*/
public String buildMainPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
return buildMainPanelContext(portlet, context, data, state, false);
}
/**
* Build the context for normal/shortcut display and detect switches
*/
public String buildMainPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state,
boolean inShortcut) {
rb = new ResourceLoader("sitesetupgeneric");
context.put("tlang", rb);
context.put("clang", cfgRb);
// TODO: what is all this doing? if we are in helper mode, we are
// already setup and don't get called here now -ggolden
/*
* String helperMode = (String)
* state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode !=
* null) { Site site = getStateSite(state); if (site != null) { if
* (site.getType() != null && ((List)
* state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) {
* context.put("editViewRoster", Boolean.TRUE); } else {
* context.put("editViewRoster", Boolean.FALSE); } } else {
* context.put("editViewRoster", Boolean.FALSE); } // for new, don't
* show site.del in Permission page context.put("hiddenLock",
* "site.del");
*
* String template = PermissionsAction.buildHelperContext(portlet,
* context, data, state); if (template == null) { addAlert(state,
* rb.getString("theisa")); } else { return template; } }
*/
String template = null;
context.put("action", CONTEXT_ACTION);
// updatePortlet(state, portlet, data);
if (state.getAttribute(STATE_INITIALIZED) == null) {
init(portlet, data, state);
String overRideTemplate = (String) state.getAttribute(STATE_OVERRIDE_TEMPLATE_INDEX);
if ( overRideTemplate != null ) {
state.removeAttribute(STATE_OVERRIDE_TEMPLATE_INDEX);
state.setAttribute(STATE_TEMPLATE_INDEX, overRideTemplate);
}
}
// Track when we come into Main panel most recently from Shortcut Panel
// Reset the state and template if we *just* came into Main from Shortcut
if ( inShortcut ) {
state.setAttribute(STATE_IN_SHORTCUT, "true");
} else {
String fromShortcut = (String) state.getAttribute(STATE_IN_SHORTCUT);
if ( "true".equals(fromShortcut) ) {
cleanState(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
state.removeAttribute(STATE_IN_SHORTCUT);
}
String indexString = (String) state.getAttribute(STATE_TEMPLATE_INDEX);
// update the visited template list with the current template index
addIntoStateVisitedTemplates(state, indexString);
template = buildContextForTemplate(getPrevVisitedTemplate(state), Integer.valueOf(indexString), portlet, context, data, state);
return template;
} // buildMainPanelContext
/**
* add index into the visited template indices list
* @param state
* @param index
*/
private void addIntoStateVisitedTemplates(SessionState state, String index) {
List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (templateIndices == null)
{
templateIndices = new Vector<String>();
}
if (templateIndices.size() == 0 || !templateIndices.contains(index))
{
// this is to prevent from page refreshing accidentally updates the list
templateIndices.add(index);
state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices);
}
}
/**
* remove the last index
* @param state
*/
private void removeLastIndexInStateVisitedTemplates(SessionState state) {
List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (templateIndices!=null && templateIndices.size() > 0)
{
// this is to prevent from page refreshing accidentally updates the list
templateIndices.remove(templateIndices.size()-1);
state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices);
}
}
private String getPrevVisitedTemplate(SessionState state) {
List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (templateIndices != null && templateIndices.size() >1 )
{
return templateIndices.get(templateIndices.size()-2);
}
else
{
return null;
}
}
/**
* whether template indexed has been visited
* @param state
* @param templateIndex
* @return
*/
private boolean isTemplateVisited(SessionState state, String templateIndex)
{
boolean rv = false;
List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (templateIndices != null && templateIndices.size() >0 )
{
rv = templateIndices.contains(templateIndex);
}
return rv;
}
/**
* Build the context for each template using template_index parameter passed
* in a form hidden field. Each case is associated with a template. (Not all
* templates implemented). See String[] TEMPLATES.
*
* @param index
* is the number contained in the template's template_index
*/
private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
String alert=(String)state.getAttribute(STATE_MESSAGE);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
context.put("siteTextEdit", new SiteTextEditUtil());
// the last visited template index
if (preIndex != null)
context.put("backIndex", preIndex);
// SAK-16600 adjust index for toolGroup mode
if (index==3)
index = 4;
context.put("templateIndex", String.valueOf(index));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// all site types
context.put("courseSiteTypeStrings", SiteService.getSiteTypeStrings("course"));
context.put("portfolioSiteTypeStrings", SiteService.getSiteTypeStrings("portfolio"));
context.put("projectSiteTypeStrings", SiteService.getSiteTypeStrings("project"));
//can the user create course sites?
context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite());
// can the user create portfolio sites?
context.put("portfolioSiteType", STATE_PORTFOLIO_SITE_TYPE);
context.put(STATE_SITE_ADD_PORTFOLIO, SiteService.allowAddPortfolioSite());
// can the user create project sites?
context.put("projectSiteType", STATE_PROJECT_SITE_TYPE);
context.put(STATE_SITE_ADD_PROJECT, SiteService.allowAddProjectSite());
// can the user user create sites from archives?
context.put(STATE_SITE_IMPORT_ARCHIVE, SiteService.allowImportArchiveSite());
Site site = getStateSite(state);
List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
switch (index) {
case 0:
/*
* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
// make sure auto-updates are enabled
Hashtable views = new Hashtable();
// Allow a user to see their deleted sites.
if (ServerConfigurationService.getBoolean("site.soft.deletion", false)) {
views.put(SiteConstants.SITE_TYPE_DELETED, rb.getString("java.sites.deleted"));
if (SiteConstants.SITE_TYPE_DELETED.equals((String) state.getAttribute(STATE_VIEW_SELECTED))) {
context.put("canSeeSoftlyDeletedSites", true);
}
}
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
context.put("menu", bar);
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
// If we're in the restore view
context.put("showRestore", SiteConstants.SITE_TYPE_DELETED.equals((String) state.getAttribute(STATE_VIEW_SELECTED)));
if (SecurityService.isSuperUser()) {
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
}
views.put(SiteConstants.SITE_TYPE_ALL, rb.getString("java.allmy"));
views.put(SiteConstants.SITE_TYPE_MYWORKSPACE, rb.getFormattedMessage("java.sites", new Object[]{rb.getString("java.my")}));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type, rb.getFormattedMessage("java.sites", new Object[]{type}));
}
List<String> moreTypes = siteTypeProvider.getTypesForSiteList();
if (!moreTypes.isEmpty())
{
for(String mType : moreTypes)
{
views.put(mType, rb.getFormattedMessage("java.sites", new Object[]{mType}));
}
}
// Allow SuperUser to see all deleted sites.
if (ServerConfigurationService.getBoolean("site.soft.deletion", false)) {
views.put(SiteConstants.SITE_TYPE_DELETED, rb.getString("java.sites.deleted"));
}
// default view
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, SiteConstants.SITE_TYPE_ALL);
}
// sort the keys in the views lookup
List<String> viewKeys = Collections.list(views.keys());
Collections.sort(viewKeys);
context.put("viewKeys", viewKeys);
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
//term filter:
Hashtable termViews = new Hashtable();
termViews.put(TERM_OPTION_ALL, rb.getString("list.allTerms"));
// bjones86 - SAK-23256
List<AcademicSession> aSessions = setTermListForContext( context, state, false, false );
if(aSessions != null){
for(AcademicSession s : aSessions){
termViews.put(s.getTitle(), s.getTitle());
}
}
// default term view
if (state.getAttribute(STATE_TERM_VIEW_SELECTED) == null) {
state.setAttribute(STATE_TERM_VIEW_SELECTED, TERM_OPTION_ALL);
}else {
context.put("viewTermSelected", (String) state
.getAttribute(STATE_TERM_VIEW_SELECTED));
}
// sort the keys in the termViews lookup
List<String> termViewKeys = Collections.list(termViews.keys());
Collections.sort(termViewKeys);
context.put("termViewKeys", termViewKeys);
context.put("termViews", termViews);
if(termViews.size() == 1){
//this means the terms are empty, only the default option exist
context.put("hideTermFilter", true);
}else{
context.put("hideTermFilter", false);
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List<Site> allSites = prepPage(state);
state.setAttribute(STATE_SITES, allSites);
context.put("sites", allSites);
context.put("totalPageNumber", Integer.valueOf(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on
// each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
context.put("sortby_softlydeleted", SortType.SOFTLY_DELETED_ASC.toString());
// default to be no paging
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
//SAK-22438 if user can add one of these site types then they can see the link to add a new site
boolean allowAddSite = false;
if(SiteService.allowAddCourseSite()) {
allowAddSite = true;
} else if (SiteService.allowAddPortfolioSite()) {
allowAddSite = true;
} else if (SiteService.allowAddProjectSite()) {
allowAddSite = true;
}
context.put("allowAddSite",allowAddSite);
//SAK-23468 put create variables into context
addSiteCreationValuesIntoContext(context,state);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
/*
* buildContextForTemplate chef_site-type.vm
*
*/
List types = (List) state.getAttribute(STATE_SITE_TYPES);
List<String> mTypes = siteTypeProvider.getTypesForSiteCreation();
if (mTypes != null && !mTypes.isEmpty())
{
types.addAll(mTypes);
}
context.put("siteTypes", types);
context.put("templateControls", ServerConfigurationService.getString("templateControls", ""));
// put selected/default site type into context
String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED);
context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0));
// bjones86 - SAK-23256
Boolean hasTerms = Boolean.FALSE;
List<AcademicSession> termList = setTermListForContext( context, state, true, true ); // true => only
if( termList != null && termList.size() > 0 )
{
hasTerms = Boolean.TRUE;
}
context.put( CONTEXT_HAS_TERMS, hasTerms );
// upcoming terms
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
// template site
setTemplateListForContext(context, state);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 4:
/*
* buildContextForTemplate chef_site-editToolGroups.vm
*
*/
state.removeAttribute(STATE_TOOL_GROUP_LIST);
String type = (String) state.getAttribute(STATE_SITE_TYPE);
setTypeIntoContext(context, type);
Map<String,List> groupTools = getTools(state, type, site);
state.setAttribute(STATE_TOOL_GROUP_LIST, groupTools);
// information related to LTI tools
buildLTIToolContextForTemplate(context, state, site, true);
if (SecurityService.isSuperUser()) {
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
}
// save all lists to context
pageOrderToolTitleIntoContext(context, state, type, (site == null), site==null?null:site.getProperties().getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES));
Boolean checkToolGroupHome = (Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED);
context.put("check_home", checkToolGroupHome);
context.put("ltitool_id_prefix", LTITOOL_ID_PREFIX);
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
if (site != null)
{
MathJaxEnabler.addMathJaxSettingsToEditToolsContext(context, site, state); // SAK-22384
context.put("SiteTitle", site.getTitle());
context.put("existSite", Boolean.TRUE);
context.put("backIndex", "12"); // back to site info list page
}
else
{
context.put("existSite", Boolean.FALSE);
context.put("backIndex", "13"); // back to new site information page
}
context.put("homeToolId", TOOL_ID_HOME);
context.put("toolsByGroup", (LinkedHashMap<String,List>) state.getAttribute(STATE_TOOL_GROUP_LIST));
context.put("toolGroupMultiples", getToolGroupMultiples(state, (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST)));
return (String) getContext(data).get("template") + TEMPLATE[4];
case 8:
/*
* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
// Are we attempting to softly delete a site.
boolean softlyDeleting = ServerConfigurationService.getBoolean("site.soft.deletion", false);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
if (SiteService.allowRemoveSite(id)) {
try {
// check whether site exists
Site removeSite = SiteService.getSite(id);
//check site isn't already softly deleted
if(softlyDeleting && removeSite.isSoftlyDeleted()) {
softlyDeleting = false;
}
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id + e.getMessage());
addAlert(state, rb.getFormattedMessage("java.couldntlocate", new Object[]{id}));
}
} else {
addAlert(state, rb.getFormattedMessage("java.couldntdel", new Object[]{site_title}));
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
//check if soft deletes are activated
context.put("softDelete", softlyDeleting);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 10:
/*
* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (SiteTypeUtil.isCourseSite(siteType)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE);
context.put("isProjectSite", Boolean.FALSE);
putSelectedProviderCourseIntoContext(context, state);
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", Integer.valueOf(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
else if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("manualAddNumber", Integer.valueOf(((List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS)).size()));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtils.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (SiteTypeUtil.isProjectSite(siteType)) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtils.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("siteUrls", getSiteUrlsForAliasIds(siteInfo.siteRefAliases));
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
/// site language information
String locale_string_selected = (String) state.getAttribute("locale_string");
if(locale_string_selected == "" || locale_string_selected == null)
context.put("locale_string_selected", "");
else
{
Locale locale_selected = getLocaleFromString(locale_string_selected);
context.put("locale_string_selected", locale_selected);
}
// put tool selection into context
toolSelectionIntoContext(context, state, siteType, null, null/*site.getProperties().getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES)*/);
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", Boolean.valueOf(siteInfo.include));
context.put("published", Boolean.valueOf(siteInfo.published));
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
// bjones86 - SAK-24423 - add joinable site settings to context
JoinableSiteSettings.addJoinableSiteSettingsToNewSiteConfirmContext( context, siteInfo );
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("fromArchive", state.getAttribute(STATE_UPLOADED_ARCHIVE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 12:
/*
* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
// put the link for downloading participant
putPrintParticipantLinkIntoContext(context, data, site);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
if (site.getProviderGroupId() != null) {
M_log.debug("site has provider");
context.put("hasProviderSet", Boolean.TRUE);
} else {
M_log.debug("site has no provider");
context.put("hasProviderSet", Boolean.FALSE);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (StringUtils.equals(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteFriendlyUrls", getSiteUrlsForSite(site));
context.put("siteDefaultUrl", getDefaultSiteUrl(siteId));
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteId", site.getId());
if (unJoinableSiteTypes != null && !unJoinableSiteTypes.contains(siteType))
{
context.put("siteJoinable", Boolean.valueOf(site.isJoinable()));
}
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (allowUpdateSite)
{
// Site modified by information
User siteModifiedBy = site.getModifiedBy();
Time siteModifiedTime = site.getModifiedTime();
if (siteModifiedBy != null) {
context.put("siteModifiedBy", siteModifiedBy.getSortName());
}
if (siteModifiedTime != null) {
context.put("siteModifiedTime", siteModifiedTime.toStringLocalFull());
}
// top menu bar
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
// if the page order helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
// in particular, need to check site types for showing the tool or not
if (isPageOrderAllowed(siteType, siteProperties.getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES)))
{
b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
}
}
}
if (allowUpdateSiteMembership)
{
// show add participant menu
if (!isMyWorkspace) {
// if the add participant helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-manage-participant-helper")) {
b.add(new MenuEntry(rb.getString("java.addp"),
"doParticipantHelper"));
}
// show the Edit Class Roster menu
if (ServerConfigurationService.getBoolean("site.setup.allow.editRoster", true) && siteType != null && SiteTypeUtil.isCourseSite(siteType)) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
}
}
if (allowUpdateGroupMembership) {
// show Manage Groups menu
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
// if the manage group helper is available, not
// stealthed and not hidden, show the link
// read the helper name from configuration variable: wsetup.group.helper.name
// the default value is: "sakai-site-manage-group-section-role-helper"
// the older version of group helper which is not section/role aware is named:"sakai-site-manage-group-helper"
String groupHelper = ServerConfigurationService.getString("wsetup.group.helper.name", "sakai-site-manage-group-section-role-helper");
if (setHelper("wsetup.groupHelper", groupHelper, state, STATE_GROUP_HELPER_ID)) {
b.add(new MenuEntry(rb.getString("java.group"),
"doManageGroupHelper"));
}
}
}
if (allowUpdateSite)
{
// show add parent sites menu
if (!isMyWorkspace) {
if (notStealthOrHiddenTool("sakai-site-manage-link-helper")) {
b.add(new MenuEntry(rb.getString("java.link"),
"doLinkHelper"));
}
if (notStealthOrHiddenTool("sakai.basiclti.admin.helper")) {
b.add(new MenuEntry(rb.getString("java.external"),
"doExternalHelper"));
}
}
}
if (allowUpdateSite)
{
if (!isMyWorkspace) {
List<String> providedSiteTypes = siteTypeProvider.getTypes();
boolean isProvidedType = false;
if (siteType != null
&& providedSiteTypes.contains(siteType)) {
isProvidedType = true;
}
if (!isProvidedType) {
// hide site access for provided site types
// type of sites
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
// hide site duplicate and import
if (SiteService.allowAddSite(null) && ServerConfigurationService.getBoolean("site.setup.allowDuplicateSite", true))
{
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
}
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
// import link should be visible even if only one
// site
if (updatableSites.size() > 0) {
//a configuration param for showing/hiding Import From Site with Clean Up
String importFromSite = ServerConfigurationService.getString("clean.import.site",Boolean.TRUE.toString());
if (importFromSite.equalsIgnoreCase("true")) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_importSelection"));
}
else {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
}
// a configuration param for
// showing/hiding import
// from file choice
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
// htripath: June
// 4th added as per
// Kris and changed
// desc of above
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
}
if (allowUpdateSite)
{
// show add parent sites menu
if (!isMyWorkspace) {
boolean eventLog = "true".equals(ServerConfigurationService.getString("user_audit_log_display", "true"));
if (notStealthOrHiddenTool("sakai.useraudit") && eventLog) {
b.add(new MenuEntry(rb.getString("java.userAuditEventLog"),
"doUserAuditEventLog"));
}
}
}
if (b.size() > 0)
{
// add the menus to vm
context.put("menu", b);
}
if(state.getAttribute(IMPORT_QUEUED) != null){
context.put("importQueued", true);
state.removeAttribute(IMPORT_QUEUED);
if(UserDirectoryService.getCurrentUser().getEmail() == null || "".equals(UserDirectoryService.getCurrentUser().getEmail())){
context.put("importQueuedNoEmail", true);
}
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
// allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
// set participant list
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
Collection participantsCollection = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME);
sortedBy = SiteConstants.SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
context.put("participantListSize", Integer.valueOf(participantsCollection.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties.getProperty(Site.PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(Site.PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (SiteTypeUtil.isCourseSite(siteType)) {
context.put("isCourseSite", Boolean.TRUE);
coursesIntoContext(state, context, site);
context.put("term", siteProperties
.getProperty(Site.PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
Collection<Group> groups = null;
if (ServerConfigurationService.getBoolean("wsetup.group.support.summary", true))
{
if ((allowUpdateSite || allowUpdateGroupMembership)
&& (!isMyWorkspace && ServerConfigurationService.getBoolean("wsetup.group.support", true)))
{
// show all site groups
groups = site.getGroups();
}
else
{
// show groups that the current user is member of
groups = site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId());
}
}
if (groups != null)
{
// filter out only those groups that are manageable by site-info
Collection<Group> filteredGroups = new ArrayList<Group>();
Collection<Group> filteredSections = new ArrayList<Group>();
Collection<String> viewMembershipGroups = new ArrayList<String>();
Collection<String> unjoinableGroups = new ArrayList<String>();
for (Group g : groups)
{
Object gProp = g.getProperties().getProperty(g.GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString()))
{
filteredGroups.add(g);
}
else
{
filteredSections.add(g);
}
Object vProp = g.getProperties().getProperty(g.GROUP_PROP_VIEW_MEMBERS);
if (vProp != null && vProp.equals(Boolean.TRUE.toString())){
viewMembershipGroups.add(g.getId());
}
Object joinableProp = g.getProperties().getProperty(g.GROUP_PROP_JOINABLE_SET);
Object unjoinableProp = g.getProperties().getProperty(g.GROUP_PROP_JOINABLE_UNJOINABLE);
if (joinableProp != null && !"".equals(joinableProp.toString())
&& unjoinableProp != null && unjoinableProp.equals(Boolean.TRUE.toString())
&& g.getMember(UserDirectoryService.getCurrentUser().getId()) != null){
unjoinableGroups.add(g.getId());
}
}
context.put("groups", filteredGroups);
context.put("sections", filteredSections);
context.put("viewMembershipGroups", viewMembershipGroups);
context.put("unjoinableGroups", unjoinableGroups);
}
//joinable groups:
Collection<JoinableGroup> joinableGroups = new ArrayList<JoinableGroup>();
if(site.getGroups() != null){
//find a list of joinable-sets this user is already a member of
//in order to not display those groups as options
Set<String> joinableSetsMember = new HashSet<String>();
for(Group group : site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId())){
String joinableSet = group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET);
if(joinableSet != null && !"".equals(joinableSet.trim())){
joinableSetsMember.add(joinableSet);
}
}
for(Group group : site.getGroups()){
String joinableSet = group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET);
if(joinableSet != null && !"".equals(joinableSet.trim()) && !joinableSetsMember.contains(joinableSet)){
String reference = group.getReference();
String title = group.getTitle();
int max = 0;
try{
max = Integer.parseInt(group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET_MAX));
}catch (Exception e) {
}
boolean preview = Boolean.valueOf(group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET_PREVIEW));
String groupMembers = "";
int size = 0;
try
{
AuthzGroup g = authzGroupService.getAuthzGroup(group.getReference());
Collection<Member> gMembers = g != null ? g.getMembers():new Vector<Member>();
size = gMembers.size();
if (size > 0)
{
Set<String> hiddenUsers = new HashSet<String>();
boolean viewHidden = viewHidden = SecurityService.unlock("roster.viewHidden", site.getReference()) || SecurityService.unlock("roster.viewHidden", g.getReference());
if(!SiteService.allowViewRoster(siteId) && !viewHidden){
//find hidden users in this group:
//add hidden users to set so we can filter them out
Set<String> memberIds = new HashSet<String>();
for(Member member : gMembers){
memberIds.add(member.getUserId());
}
hiddenUsers = privacyManager.findHidden(site.getReference(), memberIds);
}
for (Iterator<Member> gItr=gMembers.iterator(); gItr.hasNext();){
Member p = (Member) gItr.next();
// exclude those user with provided roles and rosters
String userId = p.getUserId();
if(!hiddenUsers.contains(userId)){
try
{
User u = UserDirectoryService.getUser(userId);
if(!"".equals(groupMembers)){
groupMembers += ", ";
}
groupMembers += u.getDisplayName();
}
catch (Exception e)
{
M_log.debug(this + "joinablegroups: cannot find user with id " + userId);
// need to remove the group member
size--;
}
}
}
}
}
catch (GroupNotDefinedException e)
{
M_log.debug(this + "joinablegroups: cannot find group " + group.getReference());
}
joinableGroups.add(new JoinableGroup(reference, title, joinableSet, size, max, groupMembers, preview));
}
}
if(joinableGroups.size() > 0){
context.put("joinableGroups", joinableGroups);
}
}
} catch (Exception e) {
M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e);
}
roles = getRoles(state);
context.put("roles", roles);
// SAK-23257 - add the allowed roles to the context for UI rendering
context.put( VM_ALLOWED_ROLES_DROP_DOWN, SiteParticipantHelper.getAllowedRoles( site.getType(), roles ) );
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
// UVa add realm object to context so we can provide last modified time
realmId = SiteService.siteReference(site.getId());
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
context.put("realmModifiedTime",realm.getModifiedTime().toStringLocalFullZ());
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException " + realmId);
}
// SAK-22384 mathjax support
MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
/*
* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
if (site != null) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("continue", "14");
ResourcePropertiesEdit props = site.getPropertiesEdit();
String locale_string = StringUtils.trimToEmpty(props.getProperty(PROP_SITE_LANGUAGE));
context.put("locale_string",locale_string);
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("continue", "4");
// get the system default as locale string
context.put("locale_string", "");
}
boolean displaySiteAlias = displaySiteAlias();
context.put("displaySiteAlias", Boolean.valueOf(displaySiteAlias));
if (displaySiteAlias)
{
context.put(FORM_SITE_URL_BASE, getSiteBaseUrl());
context.put(FORM_SITE_ALIAS, siteInfo.getFirstAlias());
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("type", siteType);
context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, siteType)));
context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX));
if (SiteTypeUtil.isCourseSite(siteType)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
boolean hasRosterAttached = putSelectedProviderCourseIntoContext(context, state);
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
if (!hasRosterAttached && cmRequestedList.size() > 0)
{
hasRosterAttached = true;
}
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
if (!hasRosterAttached && cmAuthorizerSectionList.size() > 0)
{
hasRosterAttached = true;
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", Integer.valueOf(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (!hasRosterAttached)
{
hasRosterAttached = true;
}
} else {
if (site != null)
if (!hasRosterAttached)
{
hasRosterAttached = coursesIntoContext(state, context, site);
}
else
{
coursesIntoContext(state, context, site);
}
if (courseManagementIsImplemented()) {
} else {
context.put("templateIndex", "37");
}
}
context.put("hasRosterAttached", Boolean.valueOf(hasRosterAttached));
if (StringUtils.trimToNull(siteInfo.term) == null) {
if (site != null)
{
// existing site
siteInfo.term = site.getProperties().getProperty(Site.PROP_SITE_TERM);
}
else
{
// creating new site
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
siteInfo.term = t != null?t.getEid() : "";
}
}
context.put("selectedTerm", siteInfo.term != null? siteInfo.term:"");
} else {
context.put("isCourseSite", Boolean.FALSE);
if (SiteTypeUtil.isProjectSite(siteType)) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtils.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
}
// about skin and icon selection
skinIconSelection(context, state, SiteTypeUtil.isCourseSite(siteType), site, siteInfo);
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider.getRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("title", siteInfo.title);
context.put(FORM_SITE_URL_BASE, getSiteBaseUrl());
context.put(FORM_SITE_ALIAS, siteInfo.getFirstAlias());
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
context.put("site_aliases", state.getAttribute(FORM_SITEINFO_ALIASES));
context.put("site_url_base", state.getAttribute(FORM_SITEINFO_URL_BASE));
context.put("site_aliases_editable", aliasesEditable(state, site == null ? null:site.getReference()));
context.put("site_alias_assignable", aliasAssignmentForNewSitesEnabled(state));
// available languages in sakai.properties
List locales = getPrefLocales();
context.put("locales",locales);
// SAK-22384 mathjax support
MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
/*
* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("displaySiteAlias", Boolean.valueOf(displaySiteAlias()));
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (SiteTypeUtil.isCourseSite(siteType)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", siteInfo.term);
} else {
context.put("isCourseSite", Boolean.FALSE);
}
// about skin and icon selection
skinIconSelection(context, state, SiteTypeUtil.isCourseSite(siteType), site, siteInfo);
context.put("oTitle", site.getTitle());
context.put("title", siteInfo.title);
// get updated language
String new_locale_string = (String) state.getAttribute("locale_string");
if(new_locale_string == "" || new_locale_string == null)
context.put("new_locale", "");
else
{
Locale new_locale = getLocaleFromString(new_locale_string);
context.put("new_locale", new_locale);
}
// get site language saved
ResourcePropertiesEdit props = site.getPropertiesEdit();
String oLocale_string = props.getProperty(PROP_SITE_LANGUAGE);
if(oLocale_string == "" || oLocale_string == null)
context.put("oLocale", "");
else
{
Locale oLocale = getLocaleFromString(oLocale_string);
context.put("oLocale", oLocale);
}
context.put("description", siteInfo.description);
context.put("oDescription", site.getDescription());
context.put("short_description", siteInfo.short_description);
context.put("oShort_description", site.getShortDescription());
context.put("skin", siteInfo.iconUrl);
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", siteInfo.iconUrl);
context.put("include", siteInfo.include);
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", siteInfo.site_contact_name);
context.put("oName", siteProperties.getProperty(Site.PROP_SITE_CONTACT_NAME));
context.put("email", siteInfo.site_contact_email);
context.put("oEmail", siteProperties.getProperty(Site.PROP_SITE_CONTACT_EMAIL));
context.put("siteUrls", getSiteUrlsForAliasIds(siteInfo.siteRefAliases));
context.put("oSiteUrls", getSiteUrlsForSite(site));
// SAK-22384 mathjax support
MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
/*
* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
String overridePageOrderSiteTypes = site.getProperties().getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES);
// put tool selection into context
toolSelectionIntoContext(context, state, site_type, site.getId(), overridePageOrderSiteTypes);
MathJaxEnabler.addMathJaxSettingsToEditToolsConfirmationContext(context, site, state, STATE_TOOL_REGISTRATION_TITLE_LIST); // SAK-22384
return (String) getContext(data).get("template") + TEMPLATE[15];
case 18:
/*
* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
if (site != null) {
// editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("published", state.getAttribute(STATE_SITE_ACCESS_PUBLISH));
context.put("include", state.getAttribute(STATE_SITE_ACCESS_INCLUDE));
context.put("shoppingPeriodInstructorEditable", ServerConfigurationService.getBoolean("delegatedaccess.shopping.instructorEditable", false));
context.put("viewDelegatedAccessUsers", ServerConfigurationService.getBoolean("delegatedaccess.siteaccess.instructorViewable", false));
// bjones86 - SAK-24423 - add joinable site settings to context
JoinableSiteSettings.addJoinableSiteSettingsToEditAccessContextWhenSiteIsNotNull( context, state, site, !unJoinableSiteTypes.contains( siteType ) );
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// bjones86 - SAK-23257
context.put("roles", getJoinerRoles(site.getReference(), state, site.getType()));
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// bjones86 - SAK-24423 - add joinable site settings to context
JoinableSiteSettings.addJoinableSiteSettingsToEditAccessContextWhenSiteIsNull( context, siteInfo, true );
// the template site, if using one
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
// use the type's template, if defined
String realmTemplate = "!site.template";
// if create based on template, use the roles from the template
if (templateSite != null) {
realmTemplate = SiteService.siteReference(templateSite.getId());
} else if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate);
// bjones86 - SAK-23257
context.put("roles", getJoinerRoles(r.getId(), state, null));
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template");
// bjones86 - SAK-23257
context.put("roles", getJoinerRoles(rr.getId(), state, null));
} catch (GroupNotDefinedException ee) {
}
}
// new site, go to confirmation page
context.put("continue", "10");
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
setTypeIntoContext(context, siteType);
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 26:
/*
* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("continue", "15");
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
// all info related to multiple tools
multipleToolIntoContext(context, state);
// put the lti tool selection into context
if (state.getAttribute(STATE_LTITOOL_SELECTED_LIST) != null)
{
HashMap<String, Map<String, Object>> currentLtiTools = (HashMap<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_SELECTED_LIST);
for (Map.Entry<String, Map<String, Object>> entry : currentLtiTools.entrySet() ) {
Map<String, Object> toolMap = entry.getValue();
String toolId = entry.getKey();
// get the proper html for tool input
String ltiToolId = toolMap.get("id").toString();
String[] contentToolModel=m_ltiService.getContentModel(Long.valueOf(ltiToolId));
// attach the ltiToolId to each model attribute, so that we could have the tool configuration page for multiple tools
for(int k=0; k<contentToolModel.length;k++)
{
contentToolModel[k] = ltiToolId + "_" + contentToolModel[k];
}
Map<String, Object> ltiTool = m_ltiService.getTool(Long.valueOf(ltiToolId));
String formInput=m_ltiService.formInput(ltiTool, contentToolModel);
toolMap.put("formInput", formInput);
currentLtiTools.put(ltiToolId, toolMap);
}
context.put("ltiTools", currentLtiTools);
context.put("ltiService", m_ltiService);
context.put("oldLtiTools", state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST));
}
context.put("toolManager", ToolManager.getInstance());
AcademicSession thisAcademicSession = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
String emailId = null;
boolean prePopulateEmail = ServerConfigurationService.getBoolean("wsetup.mailarchive.prepopulate.email",true);
if(prePopulateEmail == true && state.getAttribute(STATE_TOOL_EMAIL_ADDRESS)==null){
if(thisAcademicSession!=null){
String siteTitle1 = siteInfo.title.replaceAll("[(].*[)]", "");
siteTitle1 = siteTitle1.trim();
siteTitle1 = siteTitle1.replaceAll(" ", "-");
emailId = siteTitle1;
}else{
emailId = StringUtils.deleteWhitespace(siteInfo.title);
}
}else{
emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (emailId != null) {
context.put("emailId", emailId);
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("homeToolId", TOOL_ID_HOME);
context.put("maxToolTitleLength", MAX_TOOL_TITLE_LENGTH);
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
/*
* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
// define the tools available for import. defaults to those tools in the "to" site
List<String> importableTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("step", "2");
context.put("currentSite", site);
// if the site exists, there may be other tools available for import
importableTools = getToolsAvailableForImport(state, importableTools);
} else {
// new site, go to edit access page
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put("existingSite", Boolean.valueOf(existingSite));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
originalToolIds((List<String>) importableTools, state), false));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
context.put("hideImportedContent", ServerConfigurationService.getBoolean("content.import.hidden", false));
if(ServerConfigurationService.getBoolean("site-manage.importoption.siteinfo", false)){
try{
String siteInfoToolTitle = ToolManager.getTool(SITE_INFO_TOOL_ID).getTitle();
context.put("siteInfoToolTitle", siteInfoToolTitle);
}catch(Exception e){
}
}
return (String) getContext(data).get("template") + TEMPLATE[27];
case 60:
/*
* buildContextForTemplate chef_site-importSitesMigrate.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("step", "2");
context.put("currentSite", site);
} else {
// new site, go to edit access page
context.put("back", "4");
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
// get the tool id list
List<String> toolIdList = new Vector<String>();
if (existingSite)
{
// list all site tools which are displayed on its own page
List<SitePage> sitePages = site.getPages();
if (sitePages != null)
{
for (SitePage page: sitePages)
{
List<ToolConfiguration> pageToolsList = page.getTools(0);
// we only handle one tool per page case
if ( page.getLayout() == SitePage.LAYOUT_SINGLE_COL && pageToolsList.size() == 1)
{
toolIdList.add(pageToolsList.get(0).getToolId());
}
}
}
}
else
{
// during site creation
toolIdList = (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdList);
// order it
SortedIterator iToolIdList = new SortedIterator(getToolsAvailableForImport(state, toolIdList).iterator(),new ToolComparator());
Hashtable<String, String> toolTitleTable = new Hashtable<String, String>();
for(;iToolIdList.hasNext();)
{
String toolId = (String) iToolIdList.next();
try
{
String toolTitle = ToolManager.getTool(toolId).getTitle();
toolTitleTable.put(toolId, toolTitle);
}
catch (Exception e)
{
Log.info("chef", this + " buildContexForTemplate case 60: cannot get tool title for " + toolId + e.getMessage());
}
}
context.put("selectedTools", toolTitleTable); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[60];
case 28:
/*
* buildContextForTemplate chef_siteinfo-import.vm
*
*/
putImportSitesInfoIntoContext(context, site, state, false);
return (String) getContext(data).get("template") + TEMPLATE[28];
case 58:
/*
* buildContextForTemplate chef_siteinfo-importSelection.vm
*
*/
putImportSitesInfoIntoContext(context, site, state, false);
return (String) getContext(data).get("template") + TEMPLATE[58];
case 59:
/*
* buildContextForTemplate chef_siteinfo-importMigrate.vm
*
*/
putImportSitesInfoIntoContext(context, site, state, false);
return (String) getContext(data).get("template") + TEMPLATE[59];
case 29:
/*
* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && SiteTypeUtil.isCourseSite(sType)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
Site.PROP_SITE_TERM));
// bjones86 - SAK-23256
setTermListForContext( context, state, true, false ); // true upcoming only
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
// SAK-20797 - display checkboxes only if sitespecific value exists
long quota = getSiteSpecificQuota(site);
if (quota > 0) {
context.put("hasSiteSpecificQuota", true);
context.put("quotaSize", formatSize(quota*1024));
}
else {
context.put("hasSiteSpecificQuota", false);
}
context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX));
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
// SAK-9824
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
coursesIntoContext(state, context, site);
// bjones86 - SAK-23256
List<AcademicSession> terms = setTermListForContext( context, state, true, false ); // true -> upcoming only
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
if (terms != null && terms.size() > 0)
{
boolean foundTerm = false;
for(AcademicSession testTerm : terms)
{
if (t != null && testTerm.getEid().equals(t.getEid()))
{
foundTerm = true;
break;
}
}
if (!foundTerm)
{
// if the term is no longer listed in the term list, choose the first term in the list instead
t = terms.get(0);
}
}
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (providerCourseList == null || !providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
} else {
// need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS
// contains sections that doens't belongs to current user and
// STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does -
// v2.4 daisyf
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
putSelectedProviderCourseIntoContext(context, state);
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
//authorizerList is a list of SectionObject
/*
String userId = null;
if (authorizerList != null) {
userId = (String) authorizerList.get(0);
}
List list2 = prepareSectionObject(
authorizerSectionList, userId);
*/
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state, STATE_CM_AUTHORIZER_LIST));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
// added for 2.4 -daisyf
context.put("campusDirectory", getCampusDirectory());
context.put("userId", state.getAttribute(STATE_INSTRUCTOR_SELECTED) != null ? (String) state.getAttribute(STATE_INSTRUCTOR_SELECTED) : UserDirectoryService.getCurrentUser().getId());
/*
* for measuring how long it takes to load sections java.util.Date
* date = new java.util.Date(); M_log.debug("***2. finish at:
* "+date); M_log.debug("***3. userId:"+(String) state
* .getAttribute(STATE_INSTRUCTOR_SELECTED));
*/
context.put("basedOnTemplate", state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE:Boolean.FALSE);
// bjones86 - SAK-21706
context.put( CONTEXT_SKIP_COURSE_SECTION_SELECTION,
ServerConfigurationService.getBoolean( SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE ) );
context.put( CONTEXT_SKIP_MANUAL_COURSE_CREATION,
ServerConfigurationService.getBoolean( SAK_PROP_SKIP_MANUAL_COURSE_CREATION, Boolean.FALSE ) );
context.put("siteType", state.getAttribute(STATE_TYPE_SELECTED));
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName", ""));
if (state.getAttribute(STATE_SITE_QUEST_UNIQNAME) == null)
{
context.put("value_uniqname", getAuthorizers(state, STATE_SITE_QUEST_UNIQNAME));
}
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", Integer.valueOf(number));
}
context.put("currentNumber", Integer.valueOf(number));
context.put("listSize", number>0?Integer.valueOf(number - 1):0);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0)
{
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
putSelectedProviderCourseIntoContext(context, state);
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("cmRequestedSections", l);
}
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (site == null) {
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
}
}
isFutureTermSelected(state);
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
context.put("basedOnTemplate", state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE:Boolean.FALSE);
context.put("requireAuthorizer", ServerConfigurationService.getString("wsetup.requireAuthorizer", "true").equals("true")?Boolean.TRUE:Boolean.FALSE);
// bjones86 - SAK-21706/SAK-23255
context.put( CONTEXT_IS_ADMIN, SecurityService.isSuperUser() );
context.put( CONTEXT_SKIP_COURSE_SECTION_SELECTION, ServerConfigurationService.getBoolean( SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE ) );
context.put( CONTEXT_FILTER_TERMS, ServerConfigurationService.getBoolean( SAK_PROP_FILTER_TERMS, Boolean.FALSE ) );
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
/*
* buildContextForTemplate chef_site-type-confirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%%
// use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", Boolean.valueOf(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
/*
* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
/*
* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
putSelectedProviderCourseIntoContext(context, state);
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null)
{
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null)
{
context.put("cmRequestedSections", state.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", Integer.valueOf(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
// htripath - import materials from classic
case 45:
/*
* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
// zip file
// context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
// case 49, 50, 51 have been implemented in helper mode
case 53: {
/*
* build context for chef_site-findCourse.vm
*/
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
if (cmLevels == null)
{
cmLevels = getCMLevelLabels(state);
}
List<SectionObject> selectedSect = (List<SectionObject>) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", Boolean.valueOf(true));
}
int cmLevelSize = 0;
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
// TODO: redirect to manual entry: case #37
} else {
cmLevelSize = cmLevels.size();
Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS);
int numSelections = 0;
if (selections != null)
{
numSelections = selections.size();
}
if (numSelections != 0)
{
// execution will fall through these statements based on number of selections already made
if (numSelections == cmLevelSize - 1)
{
levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1));
}
else if (numSelections == cmLevelSize - 2)
{
levelOpts[numSelections] = getCMCourseOfferings(getSelectionString(selections, numSelections), t.getEid());
}
else if (numSelections < cmLevelSize)
{
levelOpts[numSelections] = sortCourseSets(cms.findCourseSets(getSelectionString(selections, numSelections)));
}
}
// always set the top level
Set<CourseSet> courseSets = filterCourseSetList(getCourseSet(state));
levelOpts[0] = sortCourseSets(courseSets);
// clean further element inside the array
for (int i = numSelections + 1; i<cmLevelSize; i++)
{
levelOpts[i] = null;
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
context.put("cmBaseCourseSetLevel", Integer.valueOf((levelOpts.length-3) >= 0 ? (levelOpts.length-3) : 0)); // staring from that selection level, the lookup will be for CourseSet, CourseOffering, and Section
context.put("maxSelectionDepth", Integer.valueOf(levelOpts.length-1));
state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts);
}
putSelectedProviderCourseIntoContext(context, state);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", Integer.valueOf(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("cmRequestedSections", requestedSections);
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_TERM_COURSE_LIST) != null)
{
context.put("backIndex", "36");
}
else
{
context.put("backIndex", "1");
}
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "36");
}
context.put("authzGroupService", AuthzGroupService.getInstance());
if (selectedSect !=null && !selectedSect.isEmpty() && state.getAttribute(STATE_SITE_QUEST_UNIQNAME) == null){
context.put("value_uniqname", selectedSect.get(0).getAuthorizerString());
}
context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
context.put("basedOnTemplate", state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE:Boolean.FALSE);
// bjones86 - SAK-21706/SAK-23255
context.put( CONTEXT_IS_ADMIN, SecurityService.isSuperUser() );
context.put( CONTEXT_SKIP_MANUAL_COURSE_CREATION, ServerConfigurationService.getBoolean( SAK_PROP_SKIP_MANUAL_COURSE_CREATION, Boolean.FALSE ) );
context.put( CONTEXT_FILTER_TERMS, ServerConfigurationService.getBoolean( SAK_PROP_FILTER_TERMS, Boolean.FALSE ) );
return (String) getContext(data).get("template") + TEMPLATE[53];
}
case 54:
/*
* build context for chef_site-questions.vm
*/
SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE));
if (siteTypeQuestions != null)
{
context.put("questionSet", siteTypeQuestions);
context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER));
}
context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE));
return (String) getContext(data).get("template") + TEMPLATE[54];
case 61:
/*
* build context for chef_site-importUser.vm
*/
context.put("toIndex", "12");
// only show those sites with same site type
putImportSitesInfoIntoContext(context, site, state, true);
return (String) getContext(data).get("template") + TEMPLATE[61];
case 62:
/*
* build context for chef_site-uploadArchive.vm
*/
//back to access, continue to confirm
context.put("back", "18");
//now go to uploadArchive template
return (String) getContext(data).get("template") + TEMPLATE[62];
}
// should never be reached
return (String) getContext(data).get("template") + TEMPLATE[0];
}
private void toolSelectionIntoContext(Context context, SessionState state, String siteType, String siteId, String overridePageOrderSiteTypes) {
List toolRegistrationList;
List toolRegistrationSelectedList;
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
toolRegistrationList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList);
if (toolRegistrationSelectedList != null && toolRegistrationList != null)
{
// see if any tool is added outside of Site Info tool, which means the tool is outside of the allowed tool set for this site type
context.put("extraSelectedToolList", state.getAttribute(STATE_EXTRA_SELECTED_TOOL_LIST));
}
// put tool title into context if PageOrderHelper is enabled
pageOrderToolTitleIntoContext(context, state, siteType, false, overridePageOrderSiteTypes);
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, checkNullSiteType(state, siteType, siteId), toolRegistrationSelectedList, false));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
// all info related to multiple tools
multipleToolIntoContext(context, state);
context.put("homeToolId", TOOL_ID_HOME);
// put the lti tools information into context
context.put("ltiTools", state.getAttribute(STATE_LTITOOL_SELECTED_LIST));
context.put("oldLtiTools", state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST));
context.put("ltitool_id_prefix", LTITOOL_ID_PREFIX);
}
/**
* prepare lti tool information in context and state variables
* @param context
* @param state
* @param site
* @param updateToolRegistration
*/
private void buildLTIToolContextForTemplate(Context context,
SessionState state, Site site, boolean updateToolRegistration) {
List<Map<String, Object>> tools;
// get the list of available external lti tools
tools = m_ltiService.getTools(null,null,0,0);
if (tools != null && !tools.isEmpty())
{
HashMap<String, Map<String, Object>> ltiTools = new HashMap<String, Map<String, Object>>();
// get invoke count for all lti tools
List<Map<String,Object>> contents = m_ltiService.getContents(null,null,0,0);
HashMap<String, Map<String, Object>> linkedLtiContents = new HashMap<String, Map<String, Object>>();
for ( Map<String,Object> content : contents ) {
String ltiToolId = content.get(m_ltiService.LTI_TOOL_ID).toString();
String siteId = StringUtils.trimToNull((String) content.get(m_ltiService.LTI_SITE_ID));
if (siteId != null)
{
// whether the tool is already enabled in site
String pstr = (String) content.get(LTIService.LTI_PLACEMENT);
if (StringUtils.trimToNull(pstr) != null && site != null)
{
// the lti tool is enabled in the site
ToolConfiguration toolConfig = SiteService.findTool(pstr);
if (toolConfig != null && toolConfig.getSiteId().equals(siteId))
{
Map<String, Object> m = new HashMap<String, Object>();
Map<String, Object> ltiToolValues = m_ltiService.getTool(Long.valueOf(ltiToolId));
if ( ltiToolValues != null )
{
m.put("toolTitle", ltiToolValues.get(LTIService.LTI_TITLE));
m.put("pageTitle", ltiToolValues.get(LTIService.LTI_PAGETITLE));
m.put(LTIService.LTI_TITLE, (String) content.get(LTIService.LTI_TITLE));
m.put("contentKey", content.get(LTIService.LTI_ID));
linkedLtiContents.put(ltiToolId, m);
}
}
}
}
}
for (Map<String, Object> toolMap : tools ) {
String ltiToolId = toolMap.get("id").toString();
String siteId = StringUtils.trimToNull((String) toolMap.get(m_ltiService.LTI_SITE_ID));
toolMap.put("selected", linkedLtiContents.containsKey(ltiToolId));
if (siteId == null)
{
// only show the system-range lti tools
ltiTools.put(ltiToolId, toolMap);
}
else
{
// show the site-range lti tools only if
// 1. this is in Site Info editing existing site,
// and 2. the lti tool site_id equals to current site
if (site != null && siteId.equals(site.getId()))
{
ltiTools.put(ltiToolId, toolMap);
}
}
}
state.setAttribute(STATE_LTITOOL_LIST, ltiTools);
state.setAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST, linkedLtiContents);
context.put("ltiTools", ltiTools);
context.put("selectedLtiTools",linkedLtiContents);
if (updateToolRegistration)
{
// put the selected lti tool ids into state attribute
List<String> idSelected = state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST) != null? (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST):new ArrayList<String>();
for(String ltiId :linkedLtiContents.keySet())
{
// attach the prefix
idSelected.add(LTITOOL_ID_PREFIX+ltiId);
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected);
}
}
}
private String getSelectionString(List selections, int numSelections) {
StringBuffer eidBuffer = new StringBuffer();
for (int i = 0; i < numSelections;i++)
{
eidBuffer.append(selections.get(i)).append(",");
}
String eid = eidBuffer.toString();
// trim off last ","
if (eid.endsWith(","))
eid = eid.substring(0, eid.lastIndexOf(","));
return eid;
}
/**
* get CourseSet from CourseManagementService and update state attribute
* @param state
* @return
*/
private Set getCourseSet(SessionState state) {
Set courseSet = null;
if (state.getAttribute(STATE_COURSE_SET) != null)
{
courseSet = (Set) state.getAttribute(STATE_COURSE_SET);
}
else
{
courseSet = cms.getCourseSets();
state.setAttribute(STATE_COURSE_SET, courseSet);
}
return courseSet;
}
/**
* put customized page title into context during an editing process for an existing site and the PageOrder tool is enabled for this site
* @param context
* @param state
* @param siteType
* @param newSite
*/
private void pageOrderToolTitleIntoContext(Context context, SessionState state, String siteType, boolean newSite, String overrideSitePageOrderSetting) {
// check if this is an existing site and PageOrder is enabled for the site. If so, show tool title
if (!newSite && notStealthOrHiddenTool("sakai-site-pageorder-helper") && isPageOrderAllowed(siteType, overrideSitePageOrderSetting))
{
// the actual page titles
context.put(STATE_TOOL_REGISTRATION_TITLE_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST));
context.put("allowPageOrderHelper", Boolean.TRUE);
}
else
{
context.put("allowPageOrderHelper", Boolean.FALSE);
}
}
/**
* Depending on institutional setting, all or part of the CourseSet list will be shown in the dropdown list in find course page
* for example, sakai.properties could have following setting:
* sitemanage.cm.courseset.categories.count=1
* sitemanage.cm.courseset.categories.1=Department
* Hence, only CourseSet object with category of "Department" will be shown
* @param courseSets
* @return
*/
private Set<CourseSet> filterCourseSetList(Set<CourseSet> courseSets) {
if (ServerConfigurationService.getStrings("sitemanage.cm.courseset.categories") != null) {
List<String> showCourseSetTypes = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("sitemanage.cm.courseset.categories")));
Set<CourseSet> rv = new HashSet<CourseSet>();
for(CourseSet courseSet:courseSets)
{
if (showCourseSetTypes.contains(courseSet.getCategory()))
{
rv.add(courseSet);
}
}
courseSets = rv;
}
return courseSets;
}
/**
* put all info necessary for importing site into context
* @param context
* @param site
*/
private void putImportSitesInfoIntoContext(Context context, Site site, SessionState state, boolean ownTypeOnly) {
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
ownTypeOnly?site.getType():null, null, null, SortType.TITLE_ASC, null));
}
/**
* get the titles of list of selected provider courses into context
* @param context
* @param state
* @return true if there is selected provider course, false otherwise
*/
private boolean putSelectedProviderCourseIntoContext(Context context, SessionState state) {
boolean rv = false;
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List<String> providerSectionList = (List<String>) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", providerSectionList);
context.put("selectedProviderCourseDescription", state.getAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN));
if (providerSectionList != null && providerSectionList.size() > 0)
{
// roster attached
rv = true;
}
HashMap<String, String> providerSectionListTitles = new HashMap<String, String>();
if (providerSectionList != null)
{
for (String providerSectionId : providerSectionList)
{
try
{
Section s = cms.getSection(providerSectionId);
if (s != null)
{
providerSectionListTitles.put(s.getEid(), s.getTitle());
}
}
catch (IdNotFoundException e)
{
providerSectionListTitles.put(providerSectionId, providerSectionId);
M_log.warn("putSelectedProviderCourseIntoContext Cannot find section " + providerSectionId);
}
}
context.put("size", Integer.valueOf(providerSectionList.size() - 1));
}
context.put("selectedProviderCourseTitles", providerSectionListTitles);
}
return rv;
}
/**
* whether the PageOrderHelper is allowed to be shown in this site type
* @param siteType
* @param overrideSitePageOrderSetting
* @return
*/
private boolean isPageOrderAllowed(String siteType, String overrideSitePageOrderSetting) {
if (overrideSitePageOrderSetting != null && Boolean.valueOf(overrideSitePageOrderSetting))
{
// site-specific setting, show PageOrder tool
return true;
}
else
{
// read the setting from sakai properties
boolean rv = true;
String hidePageOrderSiteTypes = ServerConfigurationService.getString(SiteConstants.SAKAI_PROPERTY_HIDE_PAGEORDER_SITE_TYPES, "");
if ( hidePageOrderSiteTypes.length() != 0)
{
if (new ArrayList<String>(Arrays.asList(StringUtils.split(hidePageOrderSiteTypes, ","))).contains(siteType))
{
rv = false;
}
}
return rv;
}
}
/*
* SAK-16600 TooGroupMultiples come from toolregistrationselectedlist
* @param state current session
* @param list list of all tools
* @return set of tools that are multiples
*/
private Map getToolGroupMultiples(SessionState state, List list) {
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
Map<String,List> toolGroupMultiples = new HashMap<String, List>();
if ( list != null )
{
for(Iterator iter = list.iterator(); iter.hasNext();)
{
String toolId = ((MyTool)iter.next()).getId();
String originId = findOriginalToolId(state, toolId);
// is this tool in the list of multipeToolIds?
if (multipleToolIdSet.contains(originId)) {
// is this the original tool or a multiple having uniqueId+originalToolId?
if (!originId.equals(toolId)) {
if (!toolGroupMultiples.containsKey(originId)) {
toolGroupMultiples.put(originId, new ArrayList());
}
List tools = toolGroupMultiples.get(originId);
MyTool tool = new MyTool();
tool.id = toolId;
tool.title = (String) multipleToolIdTitleMap.get(toolId);
// tool comes from toolRegistrationSelectList so selected should be true
tool.selected = true;
// is a toolMultiple ever *required*?
tools.add(tool);
// update the tools list for this tool id
toolGroupMultiples.put(originId, tools);
}
}
}
}
return toolGroupMultiples;
}
private void multipleToolIntoContext(Context context, SessionState state) {
// titles for multiple tool instances
context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET ));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context.put(STATE_MULTIPLE_TOOL_CONFIGURATION, state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION));
context.put(STATE_MULTIPLE_TOOL_INSTANCE_SELECTED, state.getAttribute(STATE_MULTIPLE_TOOL_INSTANCE_SELECTED));
}
// SAK-23468 If this is after an add site, the
private void addSiteCreationValuesIntoContext(Context context, SessionState state) {
String siteID = (String) state.getAttribute(STATE_NEW_SITE_STATUS_ID);
if (siteID != null) { // make sure this message is only seen immediately after a new site is created.
context.put(STATE_NEW_SITE_STATUS_ISPUBLISHED, state.getAttribute(STATE_NEW_SITE_STATUS_ISPUBLISHED));
String siteTitle = (String) state.getAttribute(STATE_NEW_SITE_STATUS_TITLE);
context.put(STATE_NEW_SITE_STATUS_TITLE, siteTitle);
context.put(STATE_NEW_SITE_STATUS_ID, siteID);
// remove the values from state so the values are gone on the next call to chef_site-list
//clearNewSiteStateParameters(state);
}
}
// SAK-23468
private void setNewSiteStateParameters(Site site, SessionState state){
if (site != null) {
state.setAttribute(STATE_NEW_SITE_STATUS_ISPUBLISHED, Boolean.valueOf(site.isPublished()));
state.setAttribute(STATE_NEW_SITE_STATUS_ID, site.getId());
state.setAttribute(STATE_NEW_SITE_STATUS_TITLE, site.getTitle());
}
}
// SAK-23468
private void clearNewSiteStateParameters(SessionState state) {
state.removeAttribute(STATE_NEW_SITE_STATUS_ISPUBLISHED);
state.removeAttribute(STATE_NEW_SITE_STATUS_ID);
state.removeAttribute(STATE_NEW_SITE_STATUS_TITLE);
}
/**
* show site skin and icon selections or not
* @param state
* @param site
* @param siteInfo
*/
private void skinIconSelection(Context context, SessionState state, boolean isCourseSite, Site site, SiteInfo siteInfo) {
// 1. the skin list
// For course site, display skin list based on "disable.course.site.skin.selection" value set with sakai.properties file. The setting defaults to be false.
boolean disableCourseSkinChoice = ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true");
// For non-course site, display skin list based on "disable.noncourse.site.skin.selection" value set with sakai.properties file. The setting defaults to be true.
boolean disableNonCourseSkinChoice = ServerConfigurationService.getString("disable.noncourse.site.skin.selection", "true").equals("true");
if ((isCourseSite && !disableCourseSkinChoice) || (!isCourseSite && !disableNonCourseSkinChoice))
{
context.put("allowSkinChoice", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
}
else
{
context.put("allowSkinChoice", Boolean.FALSE);
}
if (siteInfo != null && StringUtils.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
} else if (site != null && site.getIconUrl() != null)
{
context.put("selectedIcon", site.getIconUrl());
}
}
/**
*
*/
public void doPageOrderHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// // sites other then the current site)
//
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-pageorder-helper");
}
/**
* Launch the participant Helper Tool -- for adding participant
*
* @see case 12
*
*/
public void doParticipantHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-manage-participant-helper");
}
/**
* Launch the Manage Group helper Tool -- for adding, editing and deleting groups
*
*/
public void doManageGroupHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), (String) state.getAttribute(STATE_GROUP_HELPER_ID));//"sakai-site-manage-group-helper");
}
/**
* Launch the Link Helper Tool -- for setting/clearing parent site
*
* @see case 12 // TODO
*
*/
public void doLinkHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-manage-link-helper");
}
/**
* Launch the External Tools Helper -- For managing external tools
*/
public void doExternalHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai.basiclti.admin.helper");
}
public void doUserAuditEventLog(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai.useraudit");
}
public boolean setHelper(String helperName, String defaultHelperId, SessionState state, String stateHelperString)
{
String helperId = ServerConfigurationService.getString(helperName, defaultHelperId);
// if the state variable regarding the helper is not set yet, set it with the configured helper id
if (state.getAttribute(stateHelperString) == null)
{
state.setAttribute(stateHelperString, helperId);
}
if (notStealthOrHiddenTool(helperId)) {
return true;
}
return false;
}
// htripath: import materials from classic
/**
* Master import -- for import materials from a file
*
* @see case 45
*
*/
public void doAttachmentsMtrlFrmFile(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// state.setAttribute(FILE_UPLOAD_MAX_SIZE,
// ServerConfigurationService.getString("content.upload.max", "1"));
state.setAttribute(STATE_TEMPLATE_INDEX, "45");
} // doImportMtrlFrmFile
/**
* Handle File Upload request
*
* @see case 46
* @throws Exception
*/
public void doUpload_Mtrl_Frm_File(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List allzipList = new Vector();
List finalzipList = new Vector();
List directcopyList = new Vector();
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = data.getParameters().getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString(
"content.upload.max", "1");
long max_bytes = 1024 * 1024;
try {
max_bytes = Long.parseLong(max_file_size_mb) * 1024 * 1024;
} catch (Exception e) {
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
M_log.warn(this + ".doUpload_Mtrl_Frm_File: wrong setting of content.upload.max = " + max_file_size_mb, e);
}
if (fileFromUpload == null) {
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getFormattedMessage("importFile.size", new Object[]{max_file_size_mb}));
} else if (fileFromUpload.getFileName() == null
|| fileFromUpload.getFileName().length() == 0) {
addAlert(state, rb.getString("importFile.choosefile"));
} else {
//Need some other kind of input stream?
ResetOnCloseInputStream fileInput = null;
long fileSize=0;
try {
// Write to temp file, this should probably be in the velocity util?
File tempFile = null;
tempFile = File.createTempFile("importFile", ".tmp");
// Delete temp file when program exits.
tempFile.deleteOnExit();
InputStream fileInputStream = fileFromUpload.getInputStream();
FileOutputStream outBuf = new FileOutputStream(tempFile);
byte[] bytes = new byte[102400];
int read = 0;
while ((read = fileInputStream.read(bytes)) != -1) {
outBuf.write(bytes, 0, read);
}
fileInputStream.close();
outBuf.flush();
outBuf.close();
fileSize = tempFile.length();
fileInput = new ResetOnCloseInputStream(tempFile);
}
catch (FileNotFoundException fnfe) {
M_log.warn("FileNotFoundException creating temp import file",fnfe);
}
catch (IOException ioe) {
M_log.warn("IOException creating temp import file",ioe);
}
if (fileSize >= max_bytes) {
addAlert(state, rb.getFormattedMessage("importFile.size", new Object[]{max_file_size_mb}));
}
else if (fileSize > 0) {
if (fileInput != null && importService.isValidArchive(fileInput)) {
ImportDataSource importDataSource = importService
.parseFromFile(fileInput);
Log.info("chef", "Getting import items from manifest.");
List lst = importDataSource.getItemCategories();
if (lst != null && lst.size() > 0) {
Iterator iter = lst.iterator();
while (iter.hasNext()) {
ImportMetadata importdata = (ImportMetadata) iter
.next();
// Log.info("chef","Preparing import
// item '" + importdata.getId() + "'");
if ((!importdata.isMandatory())
&& (importdata.getFileName()
.endsWith(".xml"))) {
allzipList.add(importdata);
} else {
directcopyList.add(importdata);
}
}
}
// set Attributes
state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList);
state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList);
state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName);
state.setAttribute(IMPORT_DATA_SOURCE, importDataSource);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} else { // uploaded file is not a valid archive
addAlert(state, rb.getString("importFile.invalidfile"));
}
}
}
} // doImportMtrlFrmFile
/**
* Handle addition to list request
*
* @param data
*/
public void doAdd_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("addImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
fnlList.add(removeItems(value, zipList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Helper class for Add and remove
*
* @param value
* @param items
* @return
*/
public ImportMetadata removeItems(String value, List items) {
ImportMetadata result = null;
for (int i = 0; i < items.size(); i++) {
ImportMetadata item = (ImportMetadata) items.get(i);
if (value.equals(item.getId())) {
result = (ImportMetadata) items.remove(i);
break;
}
}
return result;
}
/**
* Handle the request for remove
*
* @param data
*/
public void doRemove_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("removeImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
zipList.add(removeItems(value, fnlList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Handle the request for copy
*
* @param data
*/
public void doCopyMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "47");
} // doCopy_MtrlSite
/**
* Handle the request for Save
*
* @param data
* @throws ImportException
*/
public void doSaveMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES);
ImportDataSource importDataSource = (ImportDataSource) state
.getAttribute(IMPORT_DATA_SOURCE);
// combine the selected import items with the mandatory import items
fnlList.addAll(directList);
Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size()
+ " top level items");
Log.info("chef", "doSaveMtrlSite() the importDataSource is "
+ importDataSource.getClass().getName());
if (importDataSource instanceof SakaiArchive) {
Log.info("chef",
"doSaveMtrlSite() our data source is a Sakai format");
((SakaiArchive) importDataSource).buildSourceFolder(fnlList);
Log.info("chef", "doSaveMtrlSite() source folder is "
+ ((SakaiArchive) importDataSource).getSourceFolder());
ArchiveService.merge(((SakaiArchive) importDataSource)
.getSourceFolder(), siteId, null);
} else {
importService.doImportItems(importDataSource
.getItemsForCategories(fnlList), siteId);
}
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.removeAttribute(IMPORT_DATA_SOURCE);
state.setAttribute(STATE_TEMPLATE_INDEX, "48");
} // doSave_MtrlSite
public void doSaveMtrlSiteMsg(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
// htripath-end
/**
* Handle the site search request.
*/
public void doSite_search(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the search form field into the state object
String search = StringUtils.trimToNull(data.getParameters().getString(
FORM_SEARCH));
// set the flag to go to the prev page on the next list
if (search == null) {
state.removeAttribute(STATE_SEARCH);
} else {
state.setAttribute(STATE_SEARCH, search);
}
} // doSite_search
/**
* Handle a Search Clear request.
*/
public void doSite_search_clear(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// clear the search
state.removeAttribute(STATE_SEARCH);
} // doSite_search_clear
/**
*
* @param state
* @param context
* @param site
* @return true if there is any roster attached, false otherwise
*/
private boolean coursesIntoContext(SessionState state, Context context,
Site site) {
boolean rv = false;
List providerCourseList = SiteParticipantHelper.getProviderCourseList((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
if (providerCourseList != null && providerCourseList.size() > 0) {
rv = true;
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
Hashtable<String, String> sectionTitles = new Hashtable<String, String>();
for(int i = 0; i < providerCourseList.size(); i++)
{
String sectionId = (String) providerCourseList.get(i);
try
{
Section s = cms.getSection(sectionId);
if (s != null)
{
sectionTitles.put(sectionId, s.getTitle());
}
}
catch (IdNotFoundException e)
{
sectionTitles.put(sectionId, sectionId);
M_log.warn("coursesIntoContext: Cannot find section " + sectionId);
}
}
context.put("providerCourseTitles", sectionTitles);
context.put("providerCourseList", providerCourseList);
}
// put manual requested courses into context
boolean rv2 = courseListFromStringIntoContext(state, context, site, STATE_CM_REQUESTED_SECTIONS, STATE_CM_REQUESTED_SECTIONS, "cmRequestedCourseList");
// put manual requested courses into context
boolean rv3 = courseListFromStringIntoContext(state, context, site, PROP_SITE_REQUEST_COURSE, SITE_MANUAL_COURSE_LIST, "manualCourseList");
return (rv || rv2 || rv3);
}
/**
*
* @param state
* @param context
* @param site
* @param site_prop_name
* @param state_attribute_string
* @param context_string
* @return true if there is any roster attached; false otherwise
*/
private boolean courseListFromStringIntoContext(SessionState state, Context context, Site site, String site_prop_name, String state_attribute_string, String context_string) {
boolean rv = false;
String courseListString = StringUtils.trimToNull(site != null?site.getProperties().getProperty(site_prop_name):null);
if (courseListString != null) {
rv = true;
List courseList = new Vector();
if (courseListString.indexOf("+") != -1) {
courseList = new ArrayList(Arrays.asList(groupProvider.unpackId(courseListString)));
} else {
courseList.add(courseListString);
}
if (state_attribute_string.equals(STATE_CM_REQUESTED_SECTIONS))
{
// need to construct the list of SectionObjects
List<SectionObject> soList = new Vector();
for (int i=0; i<courseList.size();i++)
{
String courseEid = (String) courseList.get(i);
try
{
Section s = cms.getSection(courseEid);
if (s!=null)
{
soList.add(new SectionObject(s));
}
}
catch (IdNotFoundException e)
{
M_log.warn("courseListFromStringIntoContext: cannot find section " + courseEid);
}
}
if (soList.size() > 0)
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, soList);
}
else
{
// the list is of String objects
state.setAttribute(state_attribute_string, courseList);
}
}
context.put(context_string, state.getAttribute(state_attribute_string));
return rv;
}
/**
* buildInstructorSectionsList Build the CourseListItem list for this
* Instructor for the requested Term
*
*/
private void buildInstructorSectionsList(SessionState state,
ParameterParser params, Context context) {
// Site information
// The sections of the specified term having this person as Instructor
context.put("providerCourseSectionList", state
.getAttribute("providerCourseSectionList"));
context.put("manualCourseSectionList", state
.getAttribute("manualCourseSectionList"));
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
// bjones86 - SAK-23256
setTermListForContext( context, state, true, false ); //-> future terms only
context.put(STATE_TERM_COURSE_LIST, state
.getAttribute(STATE_TERM_COURSE_LIST));
context.put("tlang", rb);
} // buildInstructorSectionsList
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state) {
int size = 0;
String search = "";
String userId = SessionManager.getCurrentSessionUserId();
String term = (String) state.getAttribute(STATE_TERM_VIEW_SELECTED);
Map<String,String> termProp = null;
if(term != null && !"".equals(term) && !TERM_OPTION_ALL.equals(term)){
termProp = new HashMap<String,String>();
termProp.put(Site.PROP_SITE_TERM, term);
}
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
search = StringUtils.trimToNull((String) state
.getAttribute(STATE_SEARCH));
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(SiteConstants.SITE_TYPE_ALL)) {
// search for non-user sites, using
// the criteria
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, termProp);
} else if (view.equals(SiteConstants.SITE_TYPE_MYWORKSPACE)) {
// search for a specific user site
// for the particular user id in the
// criteria - exact match only
try {
SiteService.getSite(SiteService
.getUserSiteId(search));
size++;
} catch (IdUnusedException e) {
}
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_DELETED)) {
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY_DELETED,
null, search, null);
} else {
// search for specific type of sites
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
view, search, termProp);
}
}
} else {
Site userWorkspaceSite = null;
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn(this + "sizeResources, template index = 0: Cannot find user "
+ SessionManager.getCurrentSessionUserId()
+ "'s My Workspace site.", e);
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(SiteConstants.SITE_TYPE_ALL)) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
size++;
}
} else {
size++;
}
}
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null);
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_DELETED)) {
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.DELETED,
null,search, null);
} else if (view.equals(SiteConstants.SITE_TYPE_MYWORKSPACE)) {
// get the current user MyWorkspace site
try {
SiteService.getSite(SiteService
.getUserSiteId(userId));
size++;
} catch (IdUnusedException e) {
}
} else {
// search for specific type of sites
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, termProp);
}
}
}
}
// for SiteInfo list page
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
Collection l = (Collection) state.getAttribute(STATE_PARTICIPANT_LIST);
size = (l != null) ? l.size() : 0;
}
return size;
} // sizeResources
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last) {
String search = StringUtils.trimToNull((String) state
.getAttribute(STATE_SEARCH));
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
// get sort type
SortType sortType = null;
String sortBy = (String) state.getAttribute(SORTED_BY);
boolean sortAsc = (Boolean.valueOf((String) state
.getAttribute(SORTED_ASC))).booleanValue();
if (sortBy.equals(SortType.TITLE_ASC.toString())) {
sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC;
} else if (sortBy.equals(SortType.TYPE_ASC.toString())) {
sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC;
} else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_BY_ASC
: SortType.CREATED_BY_DESC;
} else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_ON_ASC
: SortType.CREATED_ON_DESC;
} else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) {
sortType = sortAsc ? SortType.PUBLISHED_ASC
: SortType.PUBLISHED_DESC;
} else if (sortBy.equals(SortType.SOFTLY_DELETED_ASC.toString())) {
sortType = sortAsc ? SortType.SOFTLY_DELETED_ASC
: SortType.SOFTLY_DELETED_DESC;
}
String term = (String) state.getAttribute(STATE_TERM_VIEW_SELECTED);
Map<String,String> termProp = null;
if(term != null && !"".equals(term) && !TERM_OPTION_ALL.equals(term)){
termProp = new HashMap<String,String>();
termProp.put(Site.PROP_SITE_TERM, term);
}
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(SiteConstants.SITE_TYPE_ALL)) {
// search for non-user sites, using the
// criteria
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, termProp, sortType,
new PagingPosition(first, last));
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_MYWORKSPACE)) {
// search for a specific user site for
// the particular user id in the
// criteria - exact match only
List rv = new Vector();
try {
Site userSite = SiteService.getSite(SiteService
.getUserSiteId(search));
rv.add(userSite);
} catch (IdUnusedException e) {
}
return rv;
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_DELETED)) {
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY_DELETED,
null,
search, null, sortType,
new PagingPosition(first, last));
} else {
// search for a specific site
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY,
view, search, termProp, sortType,
new PagingPosition(first, last));
}
}
} else {
List rv = new Vector();
Site userWorkspaceSite = null;
String userId = SessionManager.getCurrentSessionUserId();
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn(this + "readResourcesPage template index = 0 :Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.", e);
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(SiteConstants.SITE_TYPE_ALL)) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
rv.add(userWorkspaceSite);
}
} else {
rv.add(userWorkspaceSite);
}
}
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, termProp, sortType,
new PagingPosition(first, last)));
}
else if (view.equals(SiteConstants.SITE_TYPE_MYWORKSPACE)) {
// get the current user MyWorkspace site
try {
rv.add(SiteService.getSite(SiteService.getUserSiteId(userId)));
} catch (IdUnusedException e) {
}
} else if (view.equalsIgnoreCase(SiteConstants.SITE_TYPE_DELETED)) {
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.DELETED,
null,
search, null, sortType,
new PagingPosition(first, last));
} else {
rv.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, termProp, sortType,
new PagingPosition(first, last)));
}
}
return rv;
}
}
// if in Site Info list view
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)): new Vector();
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
Iterator sortedParticipants = null;
if (sortedBy != null) {
sortedParticipants = new SortedIterator(participants
.iterator(), new SiteComparator(sortedBy,sortedAsc,comparator_locale));
participants.clear();
while (sortedParticipants.hasNext()) {
participants.add(sortedParticipants.next());
}
}
PagingPosition page = new PagingPosition(first, last);
page.validate(participants.size());
participants = participants.subList(page.getFirst() - 1, page.getLast());
return participants;
}
return null;
} // readResourcesPage
/**
* get the selected tool ids from import sites
*/
private boolean select_import_tools(ParameterParser params,
SessionState state) {
// has the user selected any tool for importing?
boolean anyToolSelected = false;
Hashtable importTools = new Hashtable();
// the tools for current site
List selectedTools = originalToolIds((List<String>) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST), state); // String
// toolId's
if (selectedTools != null)
{
for (int i = 0; i < selectedTools.size(); i++) {
// any tools chosen from import sites?
String toolId = (String) selectedTools.get(i);
if (params.getStrings(toolId) != null) {
importTools.put(toolId, new ArrayList(Arrays.asList(params
.getStrings(toolId))));
if (!anyToolSelected) {
anyToolSelected = true;
}
}
}
}
state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools);
return anyToolSelected;
} // select_import_tools
/**
* Is it from the ENW edit page?
*
* @return ture if the process went through the ENW page; false, otherwise
*/
private boolean fromENWModifyView(SessionState state) {
boolean fromENW = false;
List oTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
List toolList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (toolList != null)
{
for (int i = 0; i < toolList.size() && !fromENW; i++) {
String toolId = (String) toolList.get(i);
if ("sakai.mailbox".equals(toolId)
|| isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
if (oTools == null) {
// if during site creation proces
fromENW = true;
} else if (!oTools.contains(toolId)) {
// if user is adding either EmailArchive tool, News tool or
// Web Content tool, go to the Customize page for the tool
fromENW = true;
}
}
}
}
return fromENW;
}
/**
* doNew_site is called when the Site list tool bar New... button is clicked
*
*/
public void doNew_site(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// start clean
cleanState(state);
if (state.getAttribute(STATE_INITIALIZED) == null) {
state.setAttribute(STATE_OVERRIDE_TEMPLATE_INDEX, "1");
} else {
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
}
}
} // doNew_site
/**
* doMenu_site_delete is called when the Site list tool bar Delete button is
* clicked
*
*/
public void doMenu_site_delete(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] removals = (String[]) params.getStrings("selectedMembers");
state.setAttribute(STATE_SITE_REMOVALS, removals);
// present confirm delete template
state.setAttribute(STATE_TEMPLATE_INDEX, "8");
} // doMenu_site_delete
/**
* Restore a softly deleted site
*
*/
public void doMenu_site_restore(RunData data) {
SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] toRestore = (String[]) params.getStrings("selectedMembers");
for (String siteId: toRestore) {
try {
Site s = SiteService.getSite(siteId);
//check if softly deleted
if(!s.isSoftlyDeleted()){
M_log.warn("Tried to restore site that has not been marked for deletion: " + siteId);
continue;
}
//reverse it
s.setSoftlyDeleted(false);
SiteService.save(s);
} catch (IdUnusedException e) {
M_log.warn("Error restoring site:" + siteId + ":" + e.getClass() + ":" + e.getMessage());
addAlert(state, rb.getString("softly.deleted.invalidsite"));
} catch (PermissionException e) {
M_log.warn("Error restoring site:" + siteId + ":" + e.getClass() + ":" + e.getMessage());
addAlert(state, rb.getString("softly.deleted.restore.nopermission"));
}
}
} // doSite_restore
public void doSite_delete_confirmed(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
M_log
.warn("SiteAction.doSite_delete_confirmed selectedMembers null");
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the
// site list
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked sites
if (!chosenList.isEmpty()) {
for (ListIterator i = chosenList.listIterator(); i.hasNext();) {
String id = (String) i.next();
String site_title = NULL_STRING;
if (SiteService.allowRemoveSite(id)) {
try {
Site site = SiteService.getSite(id);
site_title = site.getTitle();
//now delete the site
SiteService.removeSite(site);
M_log.debug("Removed site: " + site.getId());
} catch (IdUnusedException e) {
M_log.warn(this +".doSite_delete_confirmed - IdUnusedException " + id, e);
addAlert(state, rb.getFormattedMessage("java.couldnt", new Object[]{site_title,id}));
} catch (PermissionException e) {
M_log.warn(this + ".doSite_delete_confirmed - PermissionException, site " + site_title + "(" + id + ").", e);
addAlert(state, rb.getFormattedMessage("java.dontperm", new Object[]{site_title}));
}
} else {
M_log.warn(this + ".doSite_delete_confirmed - allowRemoveSite failed for site "+ id);
addAlert(state, rb.getFormattedMessage("java.dontperm", new Object[]{site_title}));
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site
// list
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
} // doSite_delete_confirmed
/**
* get the Site object based on SessionState attribute values
*
* @return Site object related to current state; null if no such Site object
* could be found
*/
protected Site getStateSite(SessionState state) {
return getStateSite(state, false);
} // getStateSite
/**
* get the Site object based on SessionState attribute values
*
* @param autoContext - If true, we fall back to a context if it exists
* @return Site object related to current state; null if no such Site object
* could be found
*/
protected Site getStateSite(SessionState state, boolean autoContext) {
Site site = null;
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
try {
site = SiteService.getSite((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
} catch (Exception ignore) {
}
}
if ( site == null && autoContext ) {
String siteId = ToolManager.getCurrentPlacement().getContext();
try {
site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, siteId);
} catch (Exception ignore) {
}
}
return site;
} // getStateSite
/**
* do called when "eventSubmit_do" is in the request parameters to c is
* called from site list menu entry Revise... to get a locked site as
* editable and to go to the correct template to begin DB version of writes
* changes to disk at site commit whereas XML version writes at server
* shutdown
*/
public void doGet_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// check form filled out correctly
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked
// sites
String siteId = "";
if (!chosenList.isEmpty()) {
if (chosenList.size() != 1) {
addAlert(state, rb.getString("java.please"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
siteId = (String) chosenList.get(0);
getReviseSite(state, siteId);
state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
// reset the paging info
resetPaging(state);
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_PAGESIZE_SITESETUP, state
.getAttribute(STATE_PAGESIZE));
}
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// when first entered Site Info, set the participant list size to
// 200 as default
state.setAttribute(STATE_PAGESIZE, Integer.valueOf(200));
// update
h.put(siteId, Integer.valueOf(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
} else {
// restore the page size in site info tool
state.setAttribute(STATE_PAGESIZE, h.get(siteId));
}
} // doGet_site
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_reuse(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// create a new Site object based on selected Site object and put in
// state
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_reuse
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_revise(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// get site as Site object, check SiteCreationStatus and SiteType of
// site, put in state, and set STATE_TEMPLATE_INDEX correctly
// set mode to state_mode_site_type
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_revise
/**
* doView_sites is called when "eventSubmit_doView_sites" is in the request
* parameters
*/
public void doView_sites(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_VIEW_SELECTED, params.getString("view"));
state.setAttribute(STATE_TERM_VIEW_SELECTED, params.getString("termview"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
resetPaging(state);
} // doView_sites
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doView(RunData data) throws Exception {
// called from chef_site-list.vm with a select option to build query of
// sites
//
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doView
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doSite_type(RunData data) {
/*
* for measuring how long it takes to load sections java.util.Date date =
* new java.util.Date(); M_log.debug("***1. start preparing
* section:"+date);
*/
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("templateIndex"))
.intValue();
actionForTemplate("continue", index, params, state, data);
List<String> pSiteTypes = siteTypeProvider.getTypesForSiteCreation();
String type = StringUtils.trimToNull(params.getString("itemType"));
if (type == null) {
addAlert(state, rb.getString("java.select") + " ");
} else {
state.setAttribute(STATE_TYPE_SELECTED, type);
setNewSiteType(state, type);
if (SiteTypeUtil.isCourseSite(type)) { // UMICH-1035
// redirect
redirectCourseCreation(params, state, "selectTerm");
} else if (SiteTypeUtil.isProjectSite(type)) { // UMICH-1035
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
} else if (pSiteTypes != null && pSiteTypes.contains(SiteTypeUtil.getTargetSiteType(type))) { // UMICH-1035
// if of customized type site use pre-defined site info and exclude
// from public listing
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
User currentUser = UserDirectoryService.getCurrentUser();
List<String> idList = new ArrayList<String>();
idList.add(currentUser.getEid());
List<String> nameList = new ArrayList<String>();
nameList.add(currentUser.getDisplayName());
siteInfo.title = siteTypeProvider.getSiteTitle(type, idList);
siteInfo.description = siteTypeProvider.getSiteDescription(type, nameList);
siteInfo.short_description = siteTypeProvider.getSiteShortDescription(type, idList);
siteInfo.include = false;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// skip directly to confirm creation of site
state.setAttribute(STATE_TEMPLATE_INDEX, "42");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
// get the user selected template
getSelectedTemplate(state, params, type);
}
redirectToQuestionVM(state, type);
} // doSite_type
/**
* see whether user selected any template
* @param state
* @param params
* @param type
*/
private void getSelectedTemplate(SessionState state,
ParameterParser params, String type) {
String templateSiteId = params.getString("selectTemplate" + type);
if (templateSiteId != null)
{
Site templateSite = null;
try
{
templateSite = SiteService.getSite(templateSiteId);
// save the template site in state
state.setAttribute(STATE_TEMPLATE_SITE, templateSite);
// the new site type is based on the template site
setNewSiteType(state, templateSite.getType());
}catch (Exception e) {
// should never happened, as the list of templates are generated
// from existing sites
M_log.warn(this + ".doSite_type" + e.getClass().getName(), e);
state.removeAttribute(STATE_TEMPLATE_SITE);
}
// grab site info from template
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
// copy information from template site
siteInfo.description = templateSite.getDescription();
siteInfo.short_description = templateSite.getShortDescription();
siteInfo.iconUrl = templateSite.getIconUrl();
siteInfo.infoUrl = templateSite.getInfoUrl();
siteInfo.joinable = templateSite.isJoinable();
siteInfo.joinerRole = templateSite.getJoinerRole();
//siteInfo.include = false;
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromSitePropertiesOnSelectTemplate( templateSite.getProperties(), siteInfo );
List<String> toolIdsSelected = new Vector<String>();
List pageList = templateSite.getPages();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
if (pageToolList != null && pageToolList.size() > 0)
{
Tool tConfig = ((ToolConfiguration) pageToolList.get(0)).getTool();
if (tConfig != null)
{
toolIdsSelected.add(tConfig.getId());
}
}
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdsSelected);
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
else
{
// no template selected
state.removeAttribute(STATE_TEMPLATE_SITE);
}
}
/**
* Depend on the setup question setting, redirect the site setup flow
* @param state
* @param type
*/
private void redirectToQuestionVM(SessionState state, String type) {
// SAK-12912: check whether there is any setup question defined
SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions(type);
if (siteTypeQuestions != null)
{
List questionList = siteTypeQuestions.getQuestions();
if (questionList != null && !questionList.isEmpty())
{
// there is at least one question defined for this type
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE, state.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, "54");
}
}
}
}
/**
* Determine whether the selected term is considered of "future term"
* @param state
* @param t
*/
private void isFutureTermSelected(SessionState state) {
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
int weeks = 0;
Calendar c = (Calendar) Calendar.getInstance().clone();
try {
weeks = Integer
.parseInt(ServerConfigurationService
.getString(
"roster.available.weeks.before.term.start",
"0"));
c.add(Calendar.DATE, weeks * 7);
} catch (Exception ignore) {
}
if (t != null && t.getStartDate() != null && c.getTimeInMillis() < t.getStartDate().getTime()) {
// if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.TRUE);
} else {
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.FALSE);
}
}
public void doChange_user(RunData data) {
doSite_type(data);
} // doChange_user
/**
*
*/
private void removeSection(SessionState state, ParameterParser params)
{
// v2.4 - added by daisyf
// RemoveSection - remove any selected course from a list of
// provider courses
// check if any section need to be removed
removeAnyFlagedSection(state, params);
List providerChosenList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
collectNewSiteInfo(state, params, providerChosenList);
}
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doManual_add_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) {
readCourseSectionInfo(state, params);
String uniqname = StringUtils.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
// update site information
SiteInfo siteInfo = state.getAttribute(STATE_SITE_INFO) != null? (SiteInfo) state.getAttribute(STATE_SITE_INFO):new SiteInfo();
if (params.getString("additional") != null) {
siteInfo.additional = params.getString("additional");
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (option.equalsIgnoreCase("add")) {
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null) {
addAlert(state, rb.getFormattedMessage("java.author", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
} else {
// in case of multiple instructors
List instructors = new ArrayList(Arrays.asList(uniqname.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
String eid = StringUtils.trimToEmpty((String) iInstructors.next());
try {
UserDirectoryService.getUserByEid(eid);
} catch (UserNotDefinedException e) {
addAlert(state, rb.getFormattedMessage("java.validAuthor", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
M_log.warn(this + ".doManual_add_course: cannot find user with eid=" + eid, e);
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_TEMPLATE_SITE) != null)
{
// create site based on template
doFinish(data);
}
else
{
if (getStateSite(state) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
}
}
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
} else if (option.equalsIgnoreCase("removeSection"))
{
// remove selected section
removeAnyFlagedSection(state, params);
}
} // doManual_add_course
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doSite_information(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("continue"))
{
doContinue(data);
// if create based on template, skip the feature selection
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
if (templateSite != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
} else if (option.equalsIgnoreCase("removeSection"))
{
// remove selected section
removeSection(state, params);
}
} // doSite_information
/**
* read the input information of subject, course and section in the manual
* site creation page
*/
private void readCourseSectionInfo(SessionState state,
ParameterParser params) {
String option = params.getString("option");
int oldNumber = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
oldNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
// read the user input
int validInputSites = 0;
boolean validInput = true;
List multiCourseInputs = new Vector();
for (int i = 0; i < oldNumber; i++) {
List requiredFields = sectionFieldProvider.getRequiredFields();
List aCourseInputs = new Vector();
int emptyInputNum = 0;
// iterate through all required fields
for (int k = 0; k < requiredFields.size(); k++) {
SectionField sectionField = (SectionField) requiredFields
.get(k);
String fieldLabel = sectionField.getLabelKey();
String fieldInput = StringUtils.trimToEmpty(params
.getString(fieldLabel + i));
sectionField.setValue(fieldInput);
aCourseInputs.add(sectionField);
if (fieldInput.length() == 0) {
// is this an empty String input?
emptyInputNum++;
}
}
// is any input invalid?
if (emptyInputNum == 0) {
// valid if all the inputs are not empty
multiCourseInputs.add(validInputSites++, aCourseInputs);
} else if (emptyInputNum == requiredFields.size()) {
// ignore if all inputs are empty
if (option.equalsIgnoreCase("change"))
{
multiCourseInputs.add(validInputSites++, aCourseInputs);
}
} else {
// input invalid
validInput = false;
}
}
// how many more course/section to include in the site?
if (option.equalsIgnoreCase("change")) {
if (params.getString("number") != null) {
int newNumber = Integer.parseInt(params.getString("number"));
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf(oldNumber + newNumber));
List requiredFields = sectionFieldProvider.getRequiredFields();
for (int j = 0; j < newNumber; j++) {
// add a new course input
List aCourseInputs = new Vector();
// iterate through all required fields
for (int m = 0; m < requiredFields.size(); m++) {
aCourseInputs = sectionFieldProvider.getRequiredFields();
}
multiCourseInputs.add(aCourseInputs);
}
}
}
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs);
if (!option.equalsIgnoreCase("change")) {
if (!validInput || validInputSites == 0) {
// not valid input
addAlert(state, rb.getString("java.miss"));
}
// valid input, adjust the add course number
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf( validInputSites>1?validInputSites:1));
}
// set state attributes
state.setAttribute(FORM_ADDITIONAL, StringUtils.trimToEmpty(params
.getString("additional")));
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
if (siteInfo.title == null || siteInfo.title.length() == 0)
{
// if SiteInfo doesn't have title, construct the title
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
if ((providerCourseList == null || providerCourseList.size() == 0)
&& multiCourseInputs.size() > 0) {
String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(),
(List) multiCourseInputs.get(0));
// default title
String title = sectionFieldProvider.getSectionTitle(t.getEid(), (List) multiCourseInputs.get(0));
try {
Section s = cms.getSection(sectionEid);
title = s != null?s.getTitle():title;
} catch (IdNotFoundException e) {
M_log.warn("readCourseSectionInfo: Cannot find section " + sectionEid);
}
siteInfo.title = title;
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
}
} // readCourseSectionInfo
/**
*
* @param state
* @param type
*/
private void setNewSiteType(SessionState state, String type) {
state.setAttribute(STATE_SITE_TYPE, type);
// start out with fresh site information
SiteInfo siteInfo = new SiteInfo();
siteInfo.site_type = type;
siteInfo.published = true;
User u = UserDirectoryService.getCurrentUser();
if (u != null)
{
siteInfo.site_contact_name=u.getDisplayName();
siteInfo.site_contact_email=u.getEmail();
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
// set tool registration list
if (!"copy".equals(type))
{
setToolRegistrationList(state, type);
}
}
/** SAK16600 insert current site type into context
* @param context current context
* @param type current type
* @return courseSiteType type of 'course'
*/
private void setTypeIntoContext(Context context, String type) {
if (type != null && SiteTypeUtil.isCourseSite(type)) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (type != null && SiteTypeUtil.isProjectSite(type)) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
/**
* Set the state variables for tool registration list basd on current site type, save to STATE_TOOL_GROUP_LIST. This list should include
* all tool types - normal, home, multiples and blti. Note that if the toolOrder.xml is in the original format, this list will consist of
* all tools in a single group
* @param state
* @param is type
* @param site
*/
private Map<String,List> getTools(SessionState state, String type, Site site) {
boolean checkhome = state.getAttribute(STATE_TOOL_HOME_SELECTED) != null ?((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED)).booleanValue():true;
boolean isNewToolOrderType = ServerConfigurationService.getBoolean("config.sitemanage.useToolGroup", false);
Map<String,List> toolGroup = new LinkedHashMap<String,List>();
MyTool newTool = null;
File moreInfoDir = new File(moreInfoPath);
List toolList;
// if this is legacy format toolOrder.xml file, get all tools by siteType
if (isNewToolOrderType == false) {
String defaultGroupName = rb.getString("tool.group.default");
toolGroup.put(defaultGroupName, getOrderedToolList(state, defaultGroupName, type, checkhome));
} else {
// get all the groups that are available for this site type
List groups = ServerConfigurationService.getCategoryGroups(SiteTypeUtil.getTargetSiteType(type));
for(Iterator<String> itr = groups.iterator(); itr.hasNext();) {
String groupId = itr.next();
String groupName = getGroupName(groupId);
toolList = getGroupedToolList(groupId, groupName, type, checkhome, moreInfoDir);
if (toolList.size() > 0) {
toolGroup.put(groupName, toolList);
}
}
// add ungroups tools to end of toolGroup list
String ungroupedName = getGroupName(UNGROUPED_TOOL_TITLE);
List ungroupedList = getUngroupedTools(ungroupedName, toolGroup, state, moreInfoDir, site);
if (ungroupedList.size() > 0) {
toolGroup.put(ungroupedName, ungroupedList );
}
}
// add external tools to end of toolGroup list
String externaltoolgroupname = getGroupName(LTI_TOOL_TITLE);
List externalTools = getLtiToolGroup(externaltoolgroupname, moreInfoDir, site);
if (externalTools.size() > 0 )
toolGroup.put(externaltoolgroupname, externalTools);
// Home page should be auto-selected
if (checkhome==true) {
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(true));
}
// refresh selectedList
List<String> selectedTools = new ArrayList<String>();
for(Iterator itr = toolGroup.keySet().iterator(); itr.hasNext(); ) {
String key = (String) itr.next();
List toolGroupSelectedList =(List) toolGroup.get(key);
for (Iterator listItr = toolGroupSelectedList.iterator(); listItr.hasNext();) {
MyTool tool = (MyTool) listItr.next();
if (tool.selected) {
selectedTools.add(tool.id);
}
}
}
return toolGroup;
}
/**
* Get ordered, ungrouped list of tools
* @param groupName - name of default group to add all tools
* @param type - site type
* @param checkhome
*/
private List getOrderedToolList(SessionState state, String groupName, String type, boolean checkhome) {
MyTool newTool = null;
List toolsInOrderedList = new ArrayList();
// see setToolRegistrationList()
List toolList = (List)state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// mark the required tools
List requiredTools = ServerConfigurationService.getToolsRequired(SiteTypeUtil.getTargetSiteType(type));
// add Home tool only once
boolean hasHomeTool = false;
for (Iterator itr = toolList.iterator(); itr.hasNext(); )
{
MyTool tr = (MyTool)itr.next();
String toolId = tr.getId();
if (TOOL_ID_HOME.equals(tr.getId()))
{
hasHomeTool = true;
}
if (tr != null) {
newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
newTool.group = groupName;
if (requiredTools != null && requiredTools.contains(toolId))
newTool.required = true;
toolsInOrderedList.add(newTool);
}
}
if (!hasHomeTool)
{
// add Home tool to the front of the tool list
newTool = new MyTool();
newTool.id = TOOL_ID_HOME;
newTool.selected = checkhome;
newTool.required = false;
newTool.multiple = false;
toolsInOrderedList.add(0, newTool);
}
return toolsInOrderedList;
}
// SAK-23811
private List getGroupedToolList(String groupId, String groupName, String type, boolean checkhome, File moreInfoDir ) {
List toolsInGroup = new ArrayList();
MyTool newTool = null;
List toolList = ServerConfigurationService.getToolGroup(groupId);
// empty list
if (toolList != null) {
for(Iterator<String> iter = toolList.iterator(); iter.hasNext();) {
String id = iter.next();
String relativeWebPath = null;
if (id.equals(TOOL_ID_HOME)) { // SAK-23208
newTool = new MyTool();
newTool.id = id;
newTool.title = rb.getString("java.home");
newTool.description = rb.getString("java.home");
newTool.selected = checkhome;
newTool.required = ServerConfigurationService.toolGroupIsRequired(groupId,TOOL_ID_HOME);
newTool.multiple = false;
} else {
Tool tr = ToolManager.getTool(id);
if (tr != null)
{
String toolId = tr.getId();
if (isSiteTypeInToolCategory(SiteTypeUtil.getTargetSiteType(type), tr) && notStealthOrHiddenTool(toolId) ) // SAK 23808
{
newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = toolId;
newTool.description = tr.getDescription();
newTool.group = groupName;
newTool.moreInfo = getMoreInfoUrl(moreInfoDir, toolId);
newTool.required = ServerConfigurationService.toolGroupIsRequired(groupId,toolId);
newTool.selected = ServerConfigurationService.toolGroupIsSelected(groupId,toolId);
// does tool allow multiples and if so are they already defined?
newTool.multiple = isMultipleInstancesAllowed(toolId); // SAK-16600 - this flag will allow action for template#3 to massage list into new format
}
}
}
if (newTool != null) {
toolsInGroup.add(newTool);
newTool = null;
}
}
}
M_log.debug(groupName + ": loaded " + new Integer(toolsInGroup.size()).toString() + " tools");
return toolsInGroup;
}
/*
* Given groupId, return localized name from tools.properties
*/
private String getGroupName(String groupId) {
// undefined group will return standard '[missing key]' error string
return ToolManager.getLocalizedToolProperty(groupId,"title");
}
/*
* Using moreInfoDir, if toolId is found in the dir return path otherwise return null
*/
private String getMoreInfoImg(File infoDir, String toolId) {
String moreInfoUrl = null;
try {
Collection<File> files = FileUtils.listFiles(infoDir, new WildcardFileFilter(toolId+"*"), null);
if (files.isEmpty()==false) {
File mFile = files.iterator().next();
moreInfoUrl = libraryPath + mFile.getName(); // toolId;
}
} catch (Exception e) {
M_log.info("unable to read moreinfo: " + e.getMessage() );
}
return moreInfoUrl;
}
/*
* Using moreInfoDir, if toolId is found in the dir return path otherwise return null
*/
private String getMoreInfoUrl(File infoDir, String toolId) {
String moreInfoUrl = null;
try {
Collection<File> files = FileUtils.listFiles(infoDir, new WildcardFileFilter(toolId+"*"), null);
if (files.isEmpty()==false) {
File mFile = files.iterator().next();
moreInfoUrl = libraryPath + mFile.getName(); // toolId;
}
} catch (Exception e) {
M_log.info("unable to read moreinfo" + e.getMessage());
}
return moreInfoUrl;
}
/* SAK-16600 given list, return only those tools tha are BLTI
* NOTE - this method is not yet used
* @param selToolList list where tool.selected = true
* @return list of tools that are selected and blti
*/
private List<String> getToolGroupLtiTools(List<String> selToolList) {
List<String> onlyLtiTools = new ArrayList<String>();
List<Map<String, Object>> allTools = m_ltiService.getTools(null, null,0, 0);
if (allTools != null && !allTools.isEmpty()) {
for (Map<String, Object> tool : allTools) {
Set keySet = tool.keySet();
Integer ltiId = (Integer) tool.get("id");
if (ltiId != null) {
String toolId = ltiId.toString();
if (selToolList.contains(toolId)) {
onlyLtiTools.add(toolId);
}
}
}
}
return onlyLtiTools;
}
/* SAK-16600 return selected list with blti tools removed
* NOTE this method is not yet used
* @param selToolList list where tool.selected = true
* @return list of tools that are selected and not blti
*/
private List<String> removeLtiTools(List<String> selToolList) {
List<String> noLtiList = new ArrayList<String>();
noLtiList.addAll(selToolList);
List<String> ltiList = new ArrayList<String>();
List<Map<String, Object>> allTools = m_ltiService.getTools(null, null,0, 0);
if (allTools != null && !allTools.isEmpty()) {
for (Map<String, Object> tool : allTools) {
Set keySet = tool.keySet();
Integer ltiId = (Integer) tool.get("id");
if (ltiId != null) {
String toolId = ltiId.toString();
if (!ltiList.contains(toolId)) {
ltiList.add(toolId);
}
}
}
}
boolean result = noLtiList.removeAll(ltiList);
return noLtiList;
}
private List selectedLTITools(Site site) {
List selectedLTI = new ArrayList();
if (site !=null) {
String siteId = site.getId();
List<Map<String,Object>> contents = m_ltiService.getContents(null,null,0,0);
HashMap<String, Map<String, Object>> linkedLtiContents = new HashMap<String, Map<String, Object>>();
for ( Map<String,Object> content : contents ) {
String ltiToolId = content.get(m_ltiService.LTI_TOOL_ID).toString();
String ltiSiteId = StringUtils.trimToNull((String) content.get(m_ltiService.LTI_SITE_ID));
if ((ltiSiteId!=null) && ltiSiteId.equals(siteId)) {
selectedLTI.add(ltiToolId);
}
}
}
return selectedLTI;
}
// SAK-16600 find selected flag for ltiTool
// MAR25 create list of all selected ltitools
private boolean isLtiToolInSite(Long toolId, String siteId) {
if (siteId==null) return false;
Map<String,Object> toolProps= m_ltiService.getContent(toolId, siteId); // getTool(toolId);
if (toolProps==null){
return false;
} else {
String toolSite = StringUtils.trimToNull((String) toolProps.get(m_ltiService.LTI_SITE_ID));
return siteId.equals(toolSite);
}
}
/* SAK 16600 if toolGroup mode is active; and toolGroups don't use all available tools, put remaining tools into
* 'ungrouped' group having name 'GroupName'
* @param moreInfoDir file pointer to directory of MoreInfo content
* @param site current site
* @return list of MyTool items
*/
private List getUngroupedTools(String ungroupedName, Map<String,List> toolsByGroup, SessionState state, File moreInforDir, Site site) {
// Get all tools for site
List ungroupedToolsOld = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// copy the list of tools to avoid ConcurrentModificationException
List<MyTool> ungroupedTools = new Vector<MyTool>();
if ( ungroupedToolsOld != null )
ungroupedTools.addAll(ungroupedToolsOld);
// get all the tool groups that are available for this site
for (Iterator<String> toolgroupitr = toolsByGroup.keySet().iterator(); toolgroupitr.hasNext();) {
String groupName = toolgroupitr.next();
List toolList = toolsByGroup.get(groupName);
for (Iterator toollistitr = toolList.iterator(); toollistitr.hasNext();) {
MyTool ungroupedTool = (MyTool) toollistitr.next();
if (ungroupedTools.contains(ungroupedTool)) {
// remove all tools that are in a toolGroup list
ungroupedTools.remove(ungroupedTool);
}
}
}
// remove all toolMultiples
Map toolMultiples = getToolGroupMultiples(state, ungroupedTools);
if (toolMultiples != null) {
for(Iterator tmiter = toolMultiples.keySet().iterator(); tmiter.hasNext();) {
String toolId = (String) tmiter.next();
List multiToolList = (List) toolMultiples.get(toolId);
for (Iterator toollistitr = multiToolList.iterator(); toollistitr.hasNext();) {
MyTool multitoolId = (MyTool) toollistitr.next();
if (ungroupedTools.contains(multitoolId)){
ungroupedTools.remove(multitoolId);
}
}
}
}
// assign group name to all remaining tools
for (Iterator listitr = ungroupedTools.iterator(); listitr.hasNext(); ) {
MyTool tool = (MyTool) listitr.next();
tool.group = ungroupedName;
}
return ungroupedTools;
}
/* SAK 16600 Create list of ltitools to add to toolgroups; set selected for those
// tools already added to a sites with properties read to add to toolsByGroup list
* @param groupName name of the current group
* @param moreInfoDir file pointer to directory of MoreInfo content
* @param site current site
* @return list of MyTool items
*/
private List getLtiToolGroup(String groupName, File moreInfoDir, Site site) {
List ltiSelectedTools = selectedLTITools(site);
List ltiTools = new ArrayList();
List<Map<String, Object>> allTools = m_ltiService.getTools(null, null,
0, 0);
if (allTools != null && !allTools.isEmpty()) {
for (Map<String, Object> tool : allTools) {
Set keySet = tool.keySet();
String toolIdString = tool.get(m_ltiService.LTI_ID).toString();
try
{
// in Oracle, the lti tool id is returned as BigDecimal, which cannot be casted into Integer directly
Integer ltiId = Integer.valueOf(toolIdString);
if (ltiId != null) {
String ltiToolId = ltiId.toString();
if (ltiToolId != null) {
String relativeWebPath = null;
MyTool newTool = new MyTool();
newTool.title = tool.get("title").toString();
newTool.id = LTITOOL_ID_PREFIX + ltiToolId;
newTool.description = (String) tool.get("description");
newTool.group = groupName;
relativeWebPath = getMoreInfoUrl(moreInfoDir, ltiToolId);
if (relativeWebPath != null) {
newTool.moreInfo = relativeWebPath;
}
// SAK16600 should this be a property or specified in toolOrder.xml?
newTool.required = false;
newTool.selected = ltiSelectedTools.contains(ltiToolId);
ltiTools.add(newTool);
}
}
}
catch (NumberFormatException e)
{
M_log.error(this + " Cannot cast tool id String " + toolIdString + " into integer value.");
}
}
}
return ltiTools;
}
/**
* Set the state variables for tool registration list basd on site type
* @param state
* @param type
*/
private void setToolRegistrationList(SessionState state, String type) {
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
// get the tool id set which allows for multiple instances
Set multipleToolIdSet = new HashSet();
HashMap multipleToolConfiguration = new HashMap<String, HashMap<String, String>>();
// get registered tools list
Set categories = new HashSet();
categories.add(type);
categories.add(SiteTypeUtil.getTargetSiteType(type)); // UMICH-1035
Set toolRegistrations = ToolManager.findTools(categories, null);
if ((toolRegistrations == null || toolRegistrations.size() == 0)
&& state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
// use default site type and try getting tools again
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
categories.clear();
categories.add(SiteTypeUtil.getTargetSiteType(type)); //UMICH-1035
toolRegistrations = ToolManager.findTools(categories, null);
}
List tools = new Vector();
SortedIterator i = new SortedIterator(toolRegistrations.iterator(),
new ToolComparator());
for (; i.hasNext();) {
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
String originalToolId = findOriginalToolId(state, tr.getId());
if (isMultipleInstancesAllowed(originalToolId))
{
// of a tool which allows multiple instances
multipleToolIdSet.add(tr.getId());
// get the configuration for multiple instance
HashMap<String, String> toolConfigurations = getMultiToolConfiguration(originalToolId, null);
multipleToolConfiguration.put(tr.getId(), toolConfigurations);
}
tools.add(newTool);
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration);
}
/**
* Set the field on which to sort the list of students
*
*/
public void doSort_roster(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the field on which to sort the student list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort_roster
/**
* Set the field on which to sort the list of sites
*
*/
public void doSort_sites(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// call this method at the start of a sort for proper paging
resetPaging(state);
// get the field on which to sort the site list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
state.setAttribute(SORTED_BY, criterion);
} // doSort_sites
/**
* doContinue is called when "eventSubmit_doContinue" is in the request
* parameters
*/
public void doContinue(RunData data) {
// Put current form data in state and continue to the next template,
// make any permanent changes
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("templateIndex"))
.intValue();
// Let actionForTemplate know to make any permanent changes before
// continuing to the next template
String direction = "continue";
String option = params.getString("option");
actionForTemplate(direction, index, params, state, data);
if (state.getAttribute(STATE_MESSAGE) == null) {
if (index == 36 && ("add").equals(option)) {
// this is the Add extra Roster(s) case after a site is created
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
} else if (params.getString("continue") != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
}
}
}// doContinue
/**
* handle with continue add new course site options
*
*/
public void doContinue_new_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = data.getParameters().getString("option");
if ("continue".equals(option)) {
doContinue(data);
} else if ("cancel".equals(option)) {
doCancel_create(data);
} else if ("back".equals(option)) {
doBack(data);
} else if ("cancel".equals(option)) {
doCancel_create(data);
} else if ("norosters".equals(option)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
else if (option.equalsIgnoreCase("change_user")) { // SAK-22915
doChange_user(data);
}
else if (option.equalsIgnoreCase("change")) {
// change term
String termId = params.getString("selectTerm");
AcademicSession t = cms.getAcademicSession(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
isFutureTermSelected(state);
} else if (option.equalsIgnoreCase("cancel_edit")) {
// cancel
doCancel(data);
} else if (option.equalsIgnoreCase("add")) {
isFutureTermSelected(state);
// continue
doContinue(data);
}
} // doContinue_new_course
/**
* doBack is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward
* direction
*/
public void doBack(RunData data) {
// Put current form data in state and return to the previous template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int currentIndex = Integer.parseInt((String) state
.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
// Let actionForTemplate know not to make any permanent changes before
// continuing to the next template
String direction = "back";
actionForTemplate(direction, currentIndex, params, state, data);
// remove the last template index from the list
removeLastIndexInStateVisitedTemplates(state);
}// doBack
/**
* doFinish is called when a site has enough information to be saved as an
* unpublished site
*/
public void doFinish(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
addNewSite(params, state);
Site site = getStateSite(state);
// SAK-23468 Add new site params to state
setNewSiteStateParameters(site, state);
// Since the option to input aliases is presented to users prior to
// the new site actually being created, it doesn't really make sense
// to check permissions on the newly created site when we assign
// aliases, hence the advisor here.
//
// Set site aliases before dealing with tools b/c site aliases
// are more general and can, for example, serve the same purpose
// as mail channel aliases but the reverse is not true.
if ( aliasAssignmentForNewSitesEnabled(state) ) {
SecurityService.pushAdvisor(new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
if ( AliasService.SECURE_ADD_ALIAS.equals(function) ||
AliasService.SECURE_UPDATE_ALIAS.equals(function) ) {
return SecurityAdvice.ALLOWED;
}
return SecurityAdvice.PASS;
}
});
try {
setSiteReferenceAliases(state, site.getId()); // sets aliases for the site entity itself
} finally {
SecurityService.popAdvisor();
}
}
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
if (templateSite == null)
{
// normal site creation: add the features.
saveFeatures(params, state, site);
try {
site = SiteService.getSite(site.getId());
} catch (Exception ee) {
M_log.error(this + "doFinish: unable to reload site " + site.getId() + " after copying tools");
}
}
else
{
// creating based on template
if (state.getAttribute(STATE_TEMPLATE_SITE_COPY_CONTENT) != null)
{
// create based on template: skip add features, and copying all the contents from the tools in template site
importToolContent(templateSite.getId(), site, true);
try {
site = SiteService.getSite(site.getId());
} catch (Exception ee) {
M_log.error(this + "doFinish: unable to reload site " + site.getId() + " after importing tools");
}
}
// copy members
if(state.getAttribute(STATE_TEMPLATE_SITE_COPY_USERS) != null)
{
try
{
AuthzGroup templateGroup = authzGroupService.getAuthzGroup(templateSite.getReference());
AuthzGroup newGroup = authzGroupService.getAuthzGroup(site.getReference());
for(Iterator mi = templateGroup.getMembers().iterator();mi.hasNext();) {
Member member = (Member) mi.next();
if (newGroup.getMember(member.getUserId()) == null)
{
// only add those user who is not in the new site yet
newGroup.addMember(member.getUserId(), member.getRole().getId(), member.isActive(), member.isProvided());
}
}
authzGroupService.save(newGroup);
}
catch (Exception copyUserException)
{
M_log.warn(this + "doFinish: copy user exception template site =" + templateSite.getReference() + " new site =" + site.getReference() + " " + copyUserException.getMessage());
}
}
else
{
// if not bringing user over, remove the provider information
try
{
AuthzGroup newGroup = authzGroupService.getAuthzGroup(site.getReference());
newGroup.setProviderGroupId(null);
authzGroupService.save(newGroup);
// make sure current user stays in the site
newGroup = authzGroupService.getAuthzGroup(site.getReference());
String currentUserId = UserDirectoryService.getCurrentUser().getId();
if (newGroup.getUserRole(currentUserId) == null)
{
// add advisor
SecurityService.pushAdvisor(new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
});
newGroup.addMember(currentUserId, newGroup.getMaintainRole(), true, false);
authzGroupService.save(newGroup);
// remove advisor
SecurityService.popAdvisor();
}
}
catch (Exception removeProviderException)
{
M_log.warn(this + "doFinish: remove provider id " + " new site =" + site.getReference() + " " + removeProviderException.getMessage());
}
try {
site = SiteService.getSite(site.getId());
} catch (Exception ee) {
M_log.error(this + "doFinish: unable to reload site " + site.getId() + " after updating roster.");
}
}
// We don't want the new site to automatically be a template
site.getPropertiesEdit().removeProperty("template");
// publish the site or not based on the template choice
site.setPublished(state.getAttribute(STATE_TEMPLATE_PUBLISH) != null?true:false);
userNotificationProvider.notifyTemplateUse(templateSite, UserDirectoryService.getCurrentUser(), site);
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
// for course sites
String siteType = site.getType();
if (SiteTypeUtil.isCourseSite(siteType)) {
AcademicSession term = null;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
rp.addProperty(Site.PROP_SITE_TERM, term.getTitle());
rp.addProperty(Site.PROP_SITE_TERM_EID, term.getEid());
}
// update the site and related realm based on the rosters chosen or requested
updateCourseSiteSections(state, site.getId(), rp, term);
}
else
{
// for non course type site, send notification email
sendSiteNotification(state, getStateSite(state), null);
}
// commit site
commitSite(site);
//merge uploaded archive if required
if(state.getAttribute(STATE_CREATE_FROM_ARCHIVE) == Boolean.TRUE) {
doMergeArchiveIntoNewSite(site.getId(), state);
}
if (templateSite == null)
{
// save user answers
saveSiteSetupQuestionUserAnswers(state, site.getId());
}
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
// clean state variables
cleanState(state);
if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) {
state.setAttribute(SiteHelper.SITE_CREATE_SITE_ID, site.getId());
state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE);
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
}// doFinish
/**
* get one alias for site, if it exists
* @param reference
* @return
*/
private String getSiteAlias(String reference)
{
String alias = null;
if (reference != null)
{
// get the email alias when an Email Archive tool has been selected
List aliases = AliasService.getAliases(reference, 1, 1);
if (aliases.size() > 0) {
alias = ((Alias) aliases.get(0)).getId();
}
}
return alias;
}
/**
* Processes site entity aliases associated with the {@link SiteInfo}
* object currently cached in the session. Checked exceptions during
* processing of any given alias results in an alert and a log message,
* but all aliases will be processed. This behavior is an attempt to be
* consistent with established, heads-down style request processing
* behaviors, e.g. in {@link #doFinish(RunData)}.
*
* <p>Processing should work for both site creation and modification.</p>
*
* <p>Implements no permission checking of its own, so insufficient permissions
* will result in an alert being cached in the current session. Thus it
* is typically appropriate for the caller to check permissions first,
* especially because insufficient permissions may result in a
* misleading {@link SiteInfo) state. Specifically, the alias collection
* is likely empty, which is consistent with handling of other read-only
* fields in that object, but which would cause this method to attempt
* to delete all aliases for the current site.</p>
*
* <p>Exits quietly if no {@link SiteInfo} object has been cached under
* the {@link #STATE_SITE_INFO} key.</p>
*
* @param state
* @param siteId
*/
private void setSiteReferenceAliases(SessionState state, String siteId) {
SiteInfo siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
if ( siteInfo == null ) {
return;
}
String siteReference = SiteService.siteReference(siteId);
List<String> existingAliasIds = toIdList(AliasService.getAliases(siteReference));
Set<String> proposedAliasIds = siteInfo.siteRefAliases;
Set<String> aliasIdsToDelete = new HashSet<String>(existingAliasIds);
aliasIdsToDelete.removeAll(proposedAliasIds);
Set<String> aliasIdsToAdd = new HashSet<String>(proposedAliasIds);
aliasIdsToAdd.removeAll(existingAliasIds);
for ( String aliasId : aliasIdsToDelete ) {
try {
AliasService.removeAlias(aliasId);
} catch ( PermissionException e ) {
addAlert(state, rb.getFormattedMessage("java.delalias", new Object[]{aliasId}));
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getFormattedMessage("java.delalias", new Object[]{aliasId}), e);
} catch ( IdUnusedException e ) {
// no problem
} catch ( InUseException e ) {
addAlert(state, rb.getFormattedMessage("java.delalias", new Object[]{aliasId}) + rb.getFormattedMessage("java.alias.locked", new Object[]{aliasId}));
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getFormattedMessage("java.delalias", new Object[]{aliasId}) + rb.getFormattedMessage("java.alias.locked", new Object[]{aliasId}), e);
}
}
for ( String aliasId : aliasIdsToAdd ) {
try {
AliasService.setAlias(aliasId, siteReference);
} catch ( PermissionException e ) {
addAlert(state, rb.getString("java.addalias") + " ");
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getString("java.addalias"), e);
} catch ( IdInvalidException e ) {
addAlert(state, rb.getFormattedMessage("java.alias.isinval", new Object[]{aliasId}));
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getFormattedMessage("java.alias.isinval", new Object[]{aliasId}), e);
} catch ( IdUsedException e ) {
addAlert(state, rb.getFormattedMessage("java.alias.exists", new Object[]{aliasId}));
M_log.warn(this + ".setSiteReferenceAliases: " + rb.getFormattedMessage("java.alias.exists", new Object[]{aliasId}), e);
}
}
}
/**
* save user answers
* @param state
* @param siteId
*/
private void saveSiteSetupQuestionUserAnswers(SessionState state,
String siteId) {
// update the database with user answers to SiteSetup questions
if (state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER) != null)
{
Set<SiteSetupUserAnswer> userAnswers = (Set<SiteSetupUserAnswer>) state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER);
for(Iterator<SiteSetupUserAnswer> aIterator = userAnswers.iterator(); aIterator.hasNext();)
{
SiteSetupUserAnswer userAnswer = aIterator.next();
userAnswer.setSiteId(siteId);
// save to db
questionService.saveSiteSetupUserAnswer(userAnswer);
}
}
}
/**
* Update course site and related realm based on the roster chosen or requested
* @param state
* @param siteId
* @param rp
* @param term
*/
private void updateCourseSiteSections(SessionState state, String siteId, ResourcePropertiesEdit rp, AcademicSession term) {
// whether this is in the process of editing a site?
boolean editingSite = ((String)state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITEINFO)?true:false;
List providerCourseList = state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) == null ? new ArrayList() : (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
int manualAddNumber = 0;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
manualAddNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
}
List<SectionObject> cmRequestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
String realm = SiteService.siteReference(siteId);
if ((providerCourseList != null)
&& (providerCourseList.size() != 0)) {
try {
AuthzGroup realmEdit = AuthzGroupService
.getAuthzGroup(realm);
String providerRealm = buildExternalRealm(siteId, state,
providerCourseList, StringUtils.trimToNull(realmEdit.getProviderGroupId()));
realmEdit.setProviderGroupId(providerRealm);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".updateCourseSiteSections: IdUnusedException, not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.realm"));
}
catch (AuthzPermissionException e)
{
M_log.warn(this + rb.getString("java.notaccess"));
addAlert(state, rb.getString("java.notaccess"));
}
sendSiteNotification(state, getStateSite(state), providerCourseList);
//Track add changes
trackRosterChanges(org.sakaiproject.site.api.SiteService.EVENT_SITE_ROSTER_ADD,providerCourseList);
}
if (manualAddNumber != 0) {
// set the manual sections to the site property
String manualSections = rp.getProperty(PROP_SITE_REQUEST_COURSE) != null?rp.getProperty(PROP_SITE_REQUEST_COURSE)+"+":"";
// manualCourseInputs is a list of a list of SectionField
List manualCourseInputs = (List) state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < manualAddNumber; j++) {
manualSections = manualSections.concat(
sectionFieldProvider.getSectionEid(
term.getEid(),
(List) manualCourseInputs.get(j)))
.concat("+");
}
// trim the trailing plus sign
manualSections = trimTrailingString(manualSections, "+");
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
// send request
sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs, "manual");
}
if (cmRequestedSections != null
&& cmRequestedSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) {
// set the cmRequest sections to the site property
String cmRequestedSectionString = "";
if (!editingSite)
{
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < cmRequestedSections.size(); j++) {
cmRequestedSectionString = cmRequestedSectionString.concat(( cmRequestedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+");
sendSiteRequest(state, "new", cmRequestedSections.size(), cmRequestedSections, "cmRequest");
}
else
{
cmRequestedSectionString = rp.getProperty(STATE_CM_REQUESTED_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_REQUESTED_SECTIONS):"";
// get the selected cm section
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null )
{
List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmRequestedSectionString.length() != 0)
{
cmRequestedSectionString = cmRequestedSectionString.concat("+");
}
for (int j = 0; j < cmSelectedSections.size(); j++) {
cmRequestedSectionString = cmRequestedSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+");
sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest");
}
}
// update site property
if (cmRequestedSectionString.length() > 0)
{
rp.addProperty(STATE_CM_REQUESTED_SECTIONS, cmRequestedSectionString);
}
else
{
rp.removeProperty(STATE_CM_REQUESTED_SECTIONS);
}
}
if (cmAuthorizerSections != null
&& cmAuthorizerSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) {
// set the cmAuthorizer sections to the site property
String cmAuthorizerSectionString = "";
if (!editingSite)
{
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < cmAuthorizerSections.size(); j++) {
cmAuthorizerSectionString = cmAuthorizerSectionString.concat(( cmAuthorizerSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmAuthorizerSectionString = trimTrailingString(cmAuthorizerSectionString, "+");
sendSiteRequest(state, "new", cmAuthorizerSections.size(), cmAuthorizerSections, "cmRequest");
}
else
{
cmAuthorizerSectionString = rp.getProperty(STATE_CM_AUTHORIZER_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_AUTHORIZER_SECTIONS):"";
// get the selected cm section
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null )
{
List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmAuthorizerSectionString.length() != 0)
{
cmAuthorizerSectionString = cmAuthorizerSectionString.concat("+");
}
for (int j = 0; j < cmSelectedSections.size(); j++) {
cmAuthorizerSectionString = cmAuthorizerSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmAuthorizerSectionString = trimTrailingString(cmAuthorizerSectionString, "+");
sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest");
}
}
// update site property
if (cmAuthorizerSectionString.length() > 0)
{
rp.addProperty(STATE_CM_AUTHORIZER_SECTIONS, cmAuthorizerSectionString);
}
else
{
rp.removeProperty(STATE_CM_AUTHORIZER_SECTIONS);
}
}
}
/**
* Trim the trailing occurance of specified string
* @param cmRequestedSectionString
* @param trailingString
* @return
*/
private String trimTrailingString(String cmRequestedSectionString, String trailingString) {
if (cmRequestedSectionString.endsWith(trailingString)) {
cmRequestedSectionString = cmRequestedSectionString.substring(0, cmRequestedSectionString.lastIndexOf(trailingString));
}
return cmRequestedSectionString;
}
/**
* buildExternalRealm creates a site/realm id in one of three formats, for a
* single section, for multiple sections of the same course, or for a
* cross-listing having multiple courses
*
* @param sectionList
* is a Vector of CourseListItem
* @param id
* The site id
*/
private String buildExternalRealm(String id, SessionState state,
List<String> providerIdList, String existingProviderIdString) {
String realm = SiteService.siteReference(id);
if (!AuthzGroupService.allowUpdate(realm)) {
addAlert(state, rb.getString("java.rosters"));
return null;
}
List<String> allProviderIdList = new Vector<String>();
// see if we need to keep existing provider settings
if (existingProviderIdString != null)
{
allProviderIdList.addAll(Arrays.asList(groupProvider.unpackId(existingProviderIdString)));
}
// update the list with newly added providers
allProviderIdList.addAll(providerIdList);
if (allProviderIdList == null || allProviderIdList.size() == 0)
return null;
String[] providers = new String[allProviderIdList.size()];
providers = (String[]) allProviderIdList.toArray(providers);
String providerId = groupProvider.packId(providers);
return providerId;
} // buildExternalRealm
/**
* Notification sent when a course site needs to be set up by Support
*
*/
private void sendSiteRequest(SessionState state, String request,
int requestListSize, List requestFields, String fromContext) {
User cUser = UserDirectoryService.getCurrentUser();
String sendEmailToRequestee = null;
StringBuilder buf = new StringBuilder();
boolean requireAuthorizer = ServerConfigurationService.getString("wsetup.requireAuthorizer", "true").equals("true")?true:false;
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
// get the request replyTo email from configuration
String requestReplyToEmail = getSetupRequestReplyToEmailAddress();
if (requestEmail != null) {
String officialAccountName = ServerConfigurationService
.getString("officialAccountName", "");
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
AcademicSession term = null;
boolean termExist = false;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
termExist = true;
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
}
String productionSiteName = ServerConfigurationService
.getServerName();
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String content = NULL_STRING;
String sessionUserName = cUser.getDisplayName();
String additional = NULL_STRING;
if ("new".equals(request)) {
additional = siteInfo.getAdditional();
} else {
additional = (String) state.getAttribute(FORM_ADDITIONAL);
}
boolean isFutureTerm = false;
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
isFutureTerm = true;
}
// there is no offical instructor for future term sites
String requestId = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
// SAK-18976:Site Requests Generated by entering instructor's User ID fail to add term properties and fail to send site request approval email
List<String> authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
if (authorizerList == null) {
authorizerList = new ArrayList();
}
if (requestId != null) {
// in case of multiple instructors
List instructors = new ArrayList(Arrays.asList(requestId.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
String instructorId = (String) iInstructors.next();
authorizerList.add(instructorId);
}
}
String requestSectionInfo = "";
// requested sections
if ("manual".equals(fromContext))
{
requestSectionInfo = addRequestedSectionIntoNotification(state, requestFields);
}
else if ("cmRequest".equals(fromContext))
{
requestSectionInfo = addRequestedCMSectionIntoNotification(state, requestFields);
}
String authorizerNotified = "";
String authorizerNotNotified = "";
if (!isFutureTerm) {
for (Iterator iInstructors = authorizerList.iterator(); iInstructors.hasNext();)
{
String instructorId = (String) iInstructors.next();
if (requireAuthorizer)
{
// 1. email to course site authorizer
boolean result = userNotificationProvider.notifyCourseRequestAuthorizer(instructorId, requestEmail, requestReplyToEmail, term != null? term.getTitle():"", requestSectionInfo, title, id, additional, productionSiteName);
if (!result)
{
// append authorizer who doesn't received an notification
authorizerNotNotified += instructorId + ", ";
}
else
{
// append authorizer who does received an notification
authorizerNotified += instructorId + ", ";
}
}
}
}
// 2. email to system support team
String supportEmailContent = userNotificationProvider.notifyCourseRequestSupport(requestEmail, productionSiteName, request, term != null?term.getTitle():"", requestListSize, requestSectionInfo,
officialAccountName, title, id, additional, requireAuthorizer, authorizerNotified, authorizerNotNotified);
// 3. email to site requeser
userNotificationProvider.notifyCourseRequestRequester(requestEmail, supportEmailContent, term != null?term.getTitle():"");
// revert the locale to system default
rb.setContextLocale(Locale.getDefault());
state.setAttribute(REQUEST_SENT, Boolean.valueOf(true));
} // if
// reset locale to user default
rb.setContextLocale(null);
} // sendSiteRequest
private String addRequestedSectionIntoNotification(SessionState state, List requestFields) {
StringBuffer buf = new StringBuffer();
// what are the required fields shown in the UI
List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector();
for (int i = 0; i < requiredFields.size(); i++) {
List requiredFieldList = (List) requestFields
.get(i);
for (int j = 0; j < requiredFieldList.size(); j++) {
SectionField requiredField = (SectionField) requiredFieldList
.get(j);
buf.append(requiredField.getLabelKey() + "\t"
+ requiredField.getValue() + "\n");
}
buf.append("\n");
}
return buf.toString();
}
private String addRequestedCMSectionIntoNotification(SessionState state, List cmRequestedSections) {
StringBuffer buf = new StringBuffer();
// what are the required fields shown in the UI
for (int i = 0; i < cmRequestedSections.size(); i++) {
SectionObject so = (SectionObject) cmRequestedSections.get(i);
buf.append(so.getTitle() + "(" + so.getEid()
+ ")" + so.getCategory() + "\n");
}
return buf.toString();
}
/**
* Notification sent when a course site is set up automatcally
*
*/
private void sendSiteNotification(SessionState state, Site site, List notifySites) {
boolean courseSite = SiteTypeUtil.isCourseSite(site.getType());
String term_name = "";
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term_name = ((AcademicSession) state
.getAttribute(STATE_TERM_SELECTED)).getEid();
}
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
User currentUser = UserDirectoryService.getCurrentUser();
if (requestEmail != null && currentUser != null) {
userNotificationProvider.notifySiteCreation(site, notifySites, courseSite, term_name, requestEmail);
} // if
// reset locale to user default
rb.setContextLocale(null);
} // sendSiteNotification
/**
* doCancel called when "eventSubmit_doCancel_create" is in the request
* parameters to c
*/
public void doCancel_create(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) {
state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE);
state.setAttribute(SiteHelper.SITE_CREATE_CANCELLED, Boolean.TRUE);
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX));
// remove state variables in tool editing
removeEditToolState(state);
} // doCancel_create
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters
* to c int index = Integer.valueOf(params.getString
* ("templateIndex")).intValue();
*/
public void doCancel(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.removeAttribute(STATE_MESSAGE);
String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX);
String backIndex = params.getString("back");
state.setAttribute(STATE_TEMPLATE_INDEX, backIndex);
if ("4".equals(currentIndex)) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_MESSAGE);
removeEditToolState(state);
} else if (getStateSite(state) != null && ("13".equals(currentIndex) || "14".equals(currentIndex)))
{
MathJaxEnabler.removeMathJaxAllowedAttributeFromState(state); // SAK-22384
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if ("15".equals(currentIndex)) {
params = data.getParameters();
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("cancelIndex"));
removeEditToolState(state);
}
// htripath: added '"45".equals(currentIndex)' for import from file
// cancel
else if ("45".equals(currentIndex)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if ("4".equals(currentIndex)) {
// from adding class
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} else if ("27".equals(currentIndex) || "28".equals(currentIndex) || "59".equals(currentIndex) || "60".equals(currentIndex)) {
// from import
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// worksite setup
if (getStateSite(state) == null) {
// in creating new site process
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// in editing site process
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
// site info
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
} else if ("26".equals(currentIndex)) {
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)
&& getStateSite(state) == null) {
// from creating site
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// from revising site
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
removeEditToolState(state);
} else if ("37".equals(currentIndex) || "44".equals(currentIndex) || "53".equals(currentIndex) || "36".equals(currentIndex)) {
// cancel back to edit class view
state.removeAttribute(STATE_TERM_SELECTED);
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
}
// if all fails to match
else if (isTemplateVisited(state, "12")) {
// go to site info list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else {
// go to WSetup list view
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX));
} // doCancel
/**
* doMenu_customize is called when "eventSubmit_doBack" is in the request
* parameters Pass parameter to actionForTemplate to request action for
* backward direction
*/
public void doMenu_customize(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}// doMenu_customize
/**
* doBack_to_list cancels an outstanding site edit, cleans state and returns
* to the site list
*
*/
public void doBack_to_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
if (site != null) {
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
h.put(site.getId(), state.getAttribute(STATE_PAGESIZE));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
// restore the page size for Worksite setup tool
if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) {
state.setAttribute(STATE_PAGESIZE, state
.getAttribute(STATE_PAGESIZE_SITESETUP));
state.removeAttribute(STATE_PAGESIZE_SITESETUP);
}
cleanState(state);
setupFormNamesAndConstants(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
// reset
resetVisitedTemplateListToIndex(state, "0");
} // doBack_to_list
/**
* reset to sublist with index as the last item
* @param state
* @param index
*/
private void resetVisitedTemplateListToIndex(SessionState state, String index) {
if (state.getAttribute(STATE_VISITED_TEMPLATES) != null)
{
List<String> l = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES);
if (l != null && l.indexOf(index) >=0 && l.indexOf(index) < l.size())
{
state.setAttribute(STATE_VISITED_TEMPLATES, l.subList(0, l.indexOf(index)+1));
}
}
}
/**
* toolId might be of form original tool id concatenated with number
* find whether there is an counterpart in the the multipleToolIdSet
* @param state
* @param toolId
* @return
*/
private String findOriginalToolId(SessionState state, String toolId) {
// treat home tool differently
if (toolId.equals(TOOL_ID_HOME) || SITE_INFO_TOOL_ID.equals(toolId))
{
return toolId;
}
else
{
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
String rv = null;
if (toolRegistrationList != null)
{
for (Iterator i=toolRegistrationList.iterator(); rv == null && i.hasNext();)
{
Tool tool = (Tool) i.next();
String tId = tool.getId();
rv = originalToolId(toolId, tId);
}
}
return rv;
}
}
// replace fake tool ids with real ones. Don't duplicate, since several fake tool ids may appear for the same real one
// it's far from clear that we need to be using fake tool ids at all. But I don't know the code well enough
// to get rid of the fakes completely.
private List<String> originalToolIds(List<String>toolIds, SessionState state) {
Set<String>found = new HashSet<String>();
List<String>rv = new ArrayList<String>();
for (String toolId: toolIds) {
String origToolId = findOriginalToolId(state, toolId);
if (!found.contains(origToolId)) {
rv.add(origToolId);
found.add(origToolId);
}
}
return rv;
}
private String originalToolId(String toolId, String toolRegistrationId) {
String rv = null;
if (toolId.equals(toolRegistrationId))
{
rv = toolRegistrationId;
}
else if (toolId.indexOf(toolRegistrationId) != -1 && isMultipleInstancesAllowed(toolRegistrationId))
{
// the multiple tool id format is of SITE_IDTOOL_IDx, where x is an intger >= 1
if (toolId.endsWith(toolRegistrationId))
{
// get the site id part out
String uuid = toolId.replaceFirst(toolRegistrationId, "");
if (uuid != null && uuid.length() == UUID_LENGTH)
rv = toolRegistrationId;
} else
{
String suffix = toolId.substring(toolId.indexOf(toolRegistrationId) + toolRegistrationId.length());
try
{
Integer.parseInt(suffix);
rv = toolRegistrationId;
}
catch (Exception e)
{
// not the right tool id
M_log.debug(this + ".findOriginalToolId not matching tool id = " + toolRegistrationId + " original tool id=" + toolId + e.getMessage(), e);
}
}
}
return rv;
}
/**
* Read from tool registration whether multiple registration is allowed for this tool
* @param toolId
* @return
*/
private boolean isMultipleInstancesAllowed(String toolId)
{
Tool tool = ToolManager.getTool(toolId);
if (tool != null)
{
Properties tProperties = tool.getRegisteredConfig();
return (tProperties.containsKey("allowMultipleInstances")
&& tProperties.getProperty("allowMultipleInstances").equalsIgnoreCase(Boolean.TRUE.toString()))?true:false;
}
return false;
}
private HashMap<String, String> getMultiToolConfiguration(String toolId, ToolConfiguration toolConfig)
{
HashMap<String, String> rv = new HashMap<String, String>();
// read attribute list from configuration file
ArrayList<String> attributes=new ArrayList<String>();
String attributesConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE + toolId);
if ( attributesConfig != null && attributesConfig.length() > 0)
{
// read attributes from config file
attributes = new ArrayList(Arrays.asList(attributesConfig.split(",")));
}
else
{
if (toolId.equals(NEWS_TOOL_ID))
{
// default setting for News tool
attributes.add(NEWS_TOOL_CHANNEL_CONFIG);
}
else if (toolId.equals(WEB_CONTENT_TOOL_ID))
{
// default setting for Web Content tool
attributes.add(WEB_CONTENT_TOOL_SOURCE_CONFIG);
}
}
// read the defaul attribute setting from configuration
ArrayList<String> defaultValues =new ArrayList<String>();
String defaultValueConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE_DEFAULT + toolId);
if ( defaultValueConfig != null && defaultValueConfig.length() > 0)
{
defaultValues = new ArrayList(Arrays.asList(defaultValueConfig.split(",")));
}
else
{
// otherwise, treat News tool and Web Content tool differently
if (toolId.equals(NEWS_TOOL_ID))
{
// default value
defaultValues.add(NEWS_TOOL_CHANNEL_CONFIG_VALUE);
}
else if (toolId.equals(WEB_CONTENT_TOOL_ID))
{
// default value
defaultValues.add(WEB_CONTENT_TOOL_SOURCE_CONFIG_VALUE);
}
}
if (attributes != null && attributes.size() > 0 && defaultValues != null && defaultValues.size() > 0 && attributes.size() == defaultValues.size())
{
for (int i = 0; i < attributes.size(); i++)
{
String attribute = attributes.get(i);
// check to see the current settings first
Properties config = toolConfig != null ? toolConfig.getConfig() : null;
if (config != null && config.containsKey(attribute))
{
rv.put(attribute, config.getProperty(attribute));
}
else
{
// set according to the default setting
rv.put(attribute, defaultValues.get(i));
}
}
}
return rv;
}
/**
* The triage function for saving modified features page
* @param data
*/
public void doAddRemoveFeatureConfirm_option(RunData data) {
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if ("revise".equals(option))
{
// save the modified features
doSave_revised_features(state, params);
}
else if ("back".equals(option))
{
// back a step
doBack(data);
}
else if ("cancel".equals(option))
{
// cancel out
doCancel(data);
}
}
/**
* doSave_revised_features
*/
public void doSave_revised_features(SessionState state, ParameterParser params) {
Site site = getStateSite(state);
saveFeatures(params, state, site);
// SAK-22384
if (MathJaxEnabler.prepareMathJaxToolSettingsForSave(site, state))
{
commitSite(site);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// clean state variables
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX));
// refresh the whole page
scheduleTopRefresh();
}
} // doSave_revised_features
/**
* doMenu_siteInfo_cancel_access
*/
public void doMenu_siteInfo_cancel_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // doMenu_siteInfo_cancel_access
/**
* doMenu_siteInfo_importSelection
*/
public void doMenu_siteInfo_importSelection(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "58");
}
} // doMenu_siteInfo_importSelection
/**
* doMenu_siteInfo_import
*/
public void doMenu_siteInfo_import(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "28");
}
} // doMenu_siteInfo_import
/**
* doMenu_siteInfo_import_user
*/
public void doMenu_siteInfo_import_user(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "61"); // import users
}
} // doMenu_siteInfo_import_user
public void doMenu_siteInfo_importMigrate(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "59");
}
} // doMenu_siteInfo_importMigrate
/**
* doMenu_siteInfo_editClass
*/
public void doMenu_siteInfo_editClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
} // doMenu_siteInfo_editClass
/**
* doMenu_siteInfo_addClass
*/
public void doMenu_siteInfo_addClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
String termEid = site.getProperties().getProperty(Site.PROP_SITE_TERM_EID);
if (termEid == null)
{
// no term eid stored, need to get term eid from the term title
String termTitle = site.getProperties().getProperty(Site.PROP_SITE_TERM);
List asList = cms.getAcademicSessions();
if (termTitle != null && asList != null)
{
boolean found = false;
for (int i = 0; i<asList.size() && !found; i++)
{
AcademicSession as = (AcademicSession) asList.get(i);
if (as.getTitle().equals(termTitle))
{
termEid = as.getEid();
site.getPropertiesEdit().addProperty(Site.PROP_SITE_TERM_EID, termEid);
try
{
SiteService.save(site);
}
catch (Exception e)
{
M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + site.getId(), e);
}
found=true;
}
}
}
}
if (termEid != null)
{
state.setAttribute(STATE_TERM_SELECTED, cms.getAcademicSession(termEid));
try
{
List sections = prepareCourseAndSectionListing(UserDirectoryService.getCurrentUser().getEid(), cms.getAcademicSession(termEid).getEid(), state);
isFutureTermSelected(state);
if (sections != null && sections.size() > 0)
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
}
catch (Exception e)
{
M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + termEid, e);
}
}
else
{
List currentTerms = cms.getCurrentAcademicSessions();
if (currentTerms != null && !currentTerms.isEmpty())
{
// if the term information is missing for the site, assign it to the first current term in list
state.setAttribute(STATE_TERM_SELECTED, currentTerms.get(0));
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
} // doMenu_siteInfo_addClass
/**
* doMenu_siteInfo_duplicate
*/
public void doMenu_siteInfo_duplicate(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "29");
}
} // doMenu_siteInfo_import
/**
* doMenu_edit_site_info
*
*/
public void doMenu_edit_site_info(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
sitePropertiesIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} // doMenu_edit_site_info
/**
* doMenu_edit_site_tools
*
*/
public void doMenu_edit_site_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// Clean up state on our first entry from a shortcut
String panel = data.getParameters().getString("panel");
if ( "Shortcut".equals(panel) ) cleanState(state);
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "4");
if (state.getAttribute(STATE_INITIALIZED) == null) {
state.setAttribute(STATE_OVERRIDE_TEMPLATE_INDEX, "4");
}
}
} // doMenu_edit_site_tools
/**
* doMenu_edit_site_access
*
*/
public void doMenu_edit_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
try {
Site site = getStateSite(state);
state.setAttribute(STATE_SITE_ACCESS_PUBLISH, Boolean.valueOf(site.isPublished()));
state.setAttribute(STATE_SITE_ACCESS_INCLUDE, Boolean.valueOf(site.isPubView()));
boolean joinable = site.isJoinable();
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(joinable));
String joinerRole = site.getJoinerRole();
if (joinerRole == null || joinerRole.length() == 0)
{
String[] joinerRoles = ServerConfigurationService.getStrings("siteinfo.default_joiner_role");
Set<Role> roles = site.getRoles();
if (roles != null && joinerRole != null && joinerRoles.length > 0)
{
// find the role match
for (Role r : roles)
{
for(int i = 0; i < joinerRoles.length; i++)
{
if (r.getId().equalsIgnoreCase(joinerRoles[i]))
{
joinerRole = r.getId();
break;
}
}
if (joinerRole != null)
{
break;
}
}
}
}
state.setAttribute(STATE_JOINERROLE, joinerRole);
// bjones86 - SAK-24423 - update state for joinable site settings
JoinableSiteSettings.updateStateFromSitePropertiesOnEditAccessOrNewSite( site.getProperties(), state );
}
catch (Exception e)
{
M_log.warn(this + " doMenu_edit_site_access problem of getting site" + e.getMessage());
}
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doMenu_edit_site_access
/**
* Back to worksite setup's list view
*
*/
public void doBack_to_site_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
// reset
resetVisitedTemplateListToIndex(state, "0");
} // doBack_to_site_list
/**
* doSave_site_info
*
*/
public void doSave_siteInfo(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site Site = getStateSite(state);
ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit();
String site_type = (String) state.getAttribute(STATE_SITE_TYPE);
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteTitleEditable(state, SiteTypeUtil.getTargetSiteType(site_type)))
{
Site.setTitle(siteInfo.title);
}
Site.setDescription(siteInfo.description);
Site.setShortDescription(siteInfo.short_description);
if (site_type != null) {
// set icon url for course
setAppearance(state, Site, siteInfo.iconUrl);
}
// site contact information
String contactName = siteInfo.site_contact_name;
if (contactName != null) {
siteProperties.addProperty(Site.PROP_SITE_CONTACT_NAME, contactName);
}
String contactEmail = siteInfo.site_contact_email;
if (contactEmail != null) {
siteProperties.addProperty(Site.PROP_SITE_CONTACT_EMAIL, contactEmail);
}
Collection<String> oldAliasIds = getSiteReferenceAliasIds(Site);
boolean updateSiteRefAliases = aliasesEditable(state, Site.getId());
if ( updateSiteRefAliases ) {
setSiteReferenceAliases(state, Site.getId());
}
/// site language information
String locale_string = (String) state.getAttribute("locale_string");
siteProperties.removeProperty(PROP_SITE_LANGUAGE);
siteProperties.addProperty(PROP_SITE_LANGUAGE, locale_string);
// SAK-22384 mathjax support
MathJaxEnabler.prepareMathJaxAllowedSettingsForSave(Site, state);
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
SiteService.save(Site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// back to site info view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// Need to refresh the entire page because, e.g. the current site's name
// may have changed. This is problematic, though, b/c the current
// top-level portal URL may reference a just-deleted alias. A temporary
// alias translation map is one option, but it is difficult to know when
// to clean up. So we send a redirect instead of just scheduling
// a reload.
//
// One problem with this is we have no good way to know what the
// top-level portal handler should actually be. We also don't have a
// particularly good way of knowing how the portal expects to receive
// page references. We can't just use SitePage.getUrl() because that
// method assumes that site reference roots are identical to portal
// handler URL fragments, which is not guaranteed. Hence the approach
// below which tries to guess at the right portal handler, but just
// punts on page reference roots, using SiteService.PAGE_SUBTYPE for
// that portion of the URL
//
// None of this helps other users who may try to reload an aliased site
// URL that no longer resolves.
if ( updateSiteRefAliases ) {
sendParentRedirect((HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE),
getDefaultSiteUrl(ToolManager.getCurrentPlacement().getContext()) + "/" +
SiteService.PAGE_SUBTYPE + "/" +
((ToolConfiguration) ToolManager.getCurrentPlacement()).getPageId());
} else {
scheduleTopRefresh();
}
}
} // doSave_siteInfo
/**
* Check to see whether the site's title is editable or not
* @param state
* @param site_type
* @return
*/
private boolean siteTitleEditable(SessionState state, String site_type) {
return site_type != null
&& ((state.getAttribute(TITLE_NOT_EDITABLE_SITE_TYPE) != null
&& !((List) state.getAttribute(TITLE_NOT_EDITABLE_SITE_TYPE)).contains(site_type)));
}
/**
* Tests if the alias editing feature has been enabled
* ({@link #aliasEditingEnabled(SessionState, String)}) and that
* current user has set/remove aliasing permissions for the given
* {@link Site} ({@link #aliasEditingPermissioned(SessionState, String)}).
*
* <p>(Method name and signature is an attempt to be consistent with
* {@link #siteTitleEditable(SessionState, String)}).</p>
*
* @param state not used
* @param siteId a site identifier (not a {@link Reference}); must not be <code>null</code>
* @return
*/
private boolean aliasesEditable(SessionState state, String siteId) {
return aliasEditingEnabled(state, siteId) &&
aliasEditingPermissioned(state, siteId);
}
/**
* Tests if alias editing has been enabled by configuration. This is
* independent of any permissioning considerations. Also note that this
* feature is configured separately from alias assignment during worksite
* creation. This feature applies exclusively to alias edits and deletes
* against existing sites.
*
* <p>(Method name and signature is an attempt to be consistent with
* {@link #siteTitleEditable(SessionState, String)}).</p>
*
* @see #aliasAssignmentForNewSitesEnabled(SessionState)
* @param state
* @param siteId
* @return
*/
private boolean aliasEditingEnabled(SessionState state, String siteId) {
return ServerConfigurationService.getBoolean("site-manage.enable.alias.edit", false);
}
/**
* Tests if alias assignment for new sites has been enabled by configuration.
* This is independent of any permissioning considerations.
*
* <p>(Method name and signature is an attempt to be consistent with
* {@link #siteTitleEditable(SessionState, String)}).</p>
*
* @param state
* @param siteId
* @return
*/
private boolean aliasAssignmentForNewSitesEnabled(SessionState state) {
return ServerConfigurationService.getBoolean("site-manage.enable.alias.new", false);
}
/**
* Tests if the current user has set and remove permissions for aliases
* of the given site. <p>(Method name and signature is an attempt to be
* consistent with {@link #siteTitleEditable(SessionState, String)}).</p>
*
* @param state
* @param siteId
* @return
*/
private boolean aliasEditingPermissioned(SessionState state, String siteId) {
String siteRef = SiteService.siteReference(siteId);
return AliasService.allowSetAlias("", siteRef) &&
AliasService.allowRemoveTargetAliases(siteRef);
}
/**
* init
*
*/
private void init(VelocityPortlet portlet, RunData data, SessionState state) {
state.setAttribute(STATE_ACTION, "SiteAction");
setupFormNamesAndConstants(state);
if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) {
state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable());
}
if (SITE_MODE_SITESETUP.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
// need to watch out for the config question.xml existence.
// read the file and put it to backup folder.
if (SiteSetupQuestionFileParser.isConfigurationXmlAvailable())
{
SiteSetupQuestionFileParser.updateConfig();
}
} else if (SITE_MODE_HELPER.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) {
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} else if (SITE_MODE_SITEINFO.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))){
String siteId = ToolManager.getCurrentPlacement().getContext();
getReviseSite(state, siteId);
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// update
h.put(siteId, Integer.valueOf(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
state.setAttribute(STATE_PAGESIZE, Integer.valueOf(200));
}
}
if (state.getAttribute(STATE_SITE_TYPES) == null) {
PortletConfig config = portlet.getPortletConfig();
// all site types (SITE_DEFAULT_LIST overrides tool config)
String t = StringUtils.trimToNull(SITE_DEFAULT_LIST);
if ( t == null )
t = StringUtils.trimToNull(config.getInitParameter("siteTypes"));
if (t != null) {
List types = new ArrayList(Arrays.asList(t.split(",")));
if (cms == null)
{
// if there is no CourseManagementService, disable the process of creating course site
List<String> courseTypes = SiteTypeUtil.getCourseSiteTypes();
types.remove(courseTypes);
}
state.setAttribute(STATE_SITE_TYPES, types);
} else {
t = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TYPES);
if (t != null) {
state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays
.asList(t.split(","))));
} else {
state.setAttribute(STATE_SITE_TYPES, new Vector());
}
}
}
// show UI for adding non-official participant(s) or not
// if nonOfficialAccount variable is set to be false inside sakai.properties file, do not show the UI section for adding them.
// the setting defaults to be true
if (state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT) == null)
{
state.setAttribute(ADD_NON_OFFICIAL_PARTICIPANT, ServerConfigurationService.getString("nonOfficialAccount", "true"));
}
if (state.getAttribute(STATE_VISITED_TEMPLATES) == null)
{
List<String> templates = new Vector<String>();
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) {
templates.add("0"); // the default page of WSetup tool
} else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) {
templates.add("12");// the default page of Site Info tool
}
state.setAttribute(STATE_VISITED_TEMPLATES, templates);
}
if (state.getAttribute(STATE_SITE_TITLE_MAX) == null) {
int siteTitleMaxLength = ServerConfigurationService.getInt("site.title.maxlength", 25);
state.setAttribute(STATE_SITE_TITLE_MAX, siteTitleMaxLength);
}
} // init
public void doNavigate_to_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = StringUtils.trimToNull(data.getParameters().getString(
"option"));
if (siteId != null) {
getReviseSite(state, siteId);
} else {
doBack_to_list(data);
}
} // doNavigate_to_site
/**
* Get site information for revise screen
*/
private void getReviseSite(SessionState state, String siteId) {
if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) {
state.setAttribute(STATE_SELECTED_USER_LIST, new Vector());
}
List sites = (List) state.getAttribute(STATE_SITES);
try {
Site site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
if (sites != null) {
int pos = -1;
for (int index = 0; index < sites.size() && pos == -1; index++) {
if (((Site) sites.get(index)).getId().equals(siteId)) {
pos = index;
}
}
// has any previous site in the list?
if (pos > 0) {
state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1));
} else {
state.removeAttribute(STATE_PREV_SITE);
}
// has any next site in the list?
if (pos < sites.size() - 1) {
state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1));
} else {
state.removeAttribute(STATE_NEXT_SITE);
}
}
String type = site.getType();
if (type == null) {
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
state.setAttribute(STATE_SITE_TYPE, type);
} catch (IdUnusedException e) {
M_log.warn(this + ".getReviseSite: " + e.toString() + " site id = " + siteId, e);
}
// one site has been selected
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // getReviseSite
/**
* when user clicks "join" for a joinable set
* @param data
*/
public void doJoinableSet(RunData data){
ParameterParser params = data.getParameters();
String groupRef = params.getString("joinable-group-ref");
Site currentSite;
try {
currentSite = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
if(currentSite != null){
Group siteGroup = currentSite.getGroup(groupRef);
//make sure its a joinable set:
String joinableSet = siteGroup.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET);
if(joinableSet != null && !"".equals(joinableSet.trim())){
//check that the max limit hasn't been reached:
int max = 0;
try{
max = Integer.parseInt(siteGroup.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET_MAX));
AuthzGroup group = authzGroupService.getAuthzGroup(groupRef);
int size = group.getMembers().size();
if(size < max){
//check that the user isn't already a member
String userId = UserDirectoryService.getCurrentUser().getId();
boolean found = false;
for(Member member : group.getMembers()){
if(member.getUserId().equals(userId)){
found = true;
break;
}
}
if(!found){
// add current user as the maintainer
Member member = currentSite.getMember(userId);
if(member != null){
siteGroup.addMember(userId, member.getRole().getId(), true, false);
SecurityAdvisor yesMan = new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference) {
return SecurityAdvice.ALLOWED;
}
};
try{
SecurityService.pushAdvisor(yesMan);
commitSite(currentSite);
}catch (Exception e) {
M_log.debug(e);
}finally{
SecurityService.popAdvisor();
}
}
}
}
}catch (Exception e) {
M_log.debug("Error adding user to group: " + groupRef + ", " + e.getMessage(), e);
}
}
}
} catch (IdUnusedException e) {
M_log.debug("Error adding user to group: " + groupRef + ", " + e.getMessage(), e);
}
}
/**
* when user clicks "join" for a joinable set
* @param data
*/
public void doUnjoinableSet(RunData data){
ParameterParser params = data.getParameters();
String groupRef = params.getString("group-ref");
Site currentSite;
try {
currentSite = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
if(currentSite != null){
Group siteGroup = currentSite.getGroup(groupRef);
//make sure its a joinable set:
String joinableSet = siteGroup.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET);
if(joinableSet != null && !"".equals(joinableSet.trim())){
try{
AuthzGroup group = authzGroupService.getAuthzGroup(groupRef);
//check that the user is already a member
String userId = UserDirectoryService.getCurrentUser().getId();
boolean found = false;
for(Member member : group.getMembers()){
if(member.getUserId().equals(userId)){
found = true;
break;
}
}
if(found){
// remove current user as the maintainer
Member member = currentSite.getMember(userId);
if(member != null){
siteGroup.removeMember(userId);
SecurityAdvisor yesMan = new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference) {
return SecurityAdvice.ALLOWED;
}
};
try{
SecurityService.pushAdvisor(yesMan);
commitSite(currentSite);
}catch (Exception e) {
M_log.debug(e);
}finally{
SecurityService.popAdvisor();
}
}
}
}catch (Exception e) {
M_log.debug("Error removing user to group: " + groupRef + ", " + e.getMessage(), e);
}
}
}
} catch (IdUnusedException e) {
M_log.debug("Error removing user to group: " + groupRef + ", " + e.getMessage(), e);
}
}
/**
* SAK 23029 - iterate through changed partiants to see how many would have maintain role if all roles, status and deletion changes went through
*
*/
private List<Participant> testProposedUpdates(List<Participant> participants, ParameterParser params, String maintainRole) {
List<Participant> maintainersAfterUpdates = new ArrayList<Participant>();
// create list of all partcipants that have been 'Charles Bronson-ed'
Set<String> removedParticipantIds = new HashSet();
Set<String> deactivatedParticipants = new HashSet();
if (params.getStrings("selectedUser") != null) {
List removals = new ArrayList(Arrays.asList(params.getStrings("selectedUser")));
for (int i = 0; i < removals.size(); i++) {
String rId = (String) removals.get(i);
removedParticipantIds.add(rId);
}
}
// create list of all participants that have been deactivated
for(Participant statusParticipant : participants ) {
String activeGrantId = statusParticipant.getUniqname();
String activeGrantField = "activeGrant" + activeGrantId;
if (params.getString(activeGrantField) != null) {
boolean activeStatus = params.getString(activeGrantField).equalsIgnoreCase("true") ? true : false;
if (activeStatus == false) {
deactivatedParticipants.add(activeGrantId);
}
}
}
// now add only those partcipants whose new/current role is maintainer, is (still) active, and not marked for deletion
for(Participant roleParticipant : participants ) {
String id = roleParticipant.getUniqname();
String roleId = "role" + id;
String newRole = params.getString(roleId);
if ((deactivatedParticipants.contains(id)==false) && roleParticipant.isActive() != false) { // skip any that are not already inactive or are not candidates for deactivation
if (removedParticipantIds.contains(id) == false) {
if (newRole != null){
if (newRole.equals(maintainRole)) {
maintainersAfterUpdates.add(roleParticipant);
}
} else {
// participant has no new role; was participant already maintainer?
if (roleParticipant.getRole().equals(maintainRole)) {
maintainersAfterUpdates.add(roleParticipant);
}
}
}
}
}
return maintainersAfterUpdates;
}
/**
* doUpdate_participant
*
*/
public void doUpdate_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
Site s = getStateSite(state);
String realmId = SiteService.siteReference(s.getId());
// list of updated users
List<String> userUpdated = new Vector<String>();
// list of all removed user
List<String> usersDeleted = new Vector<String>();
if (AuthzGroupService.allowUpdate(realmId)
|| SiteService.allowUpdateSiteMembership(s.getId())) {
try {
// init variables useful for actual edits and mainainersAfterProposedChanges check
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
String maintainRoleString = realmEdit.getMaintainRole();
List participants = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST));
// SAK 23029 Test proposed removals/updates; reject all where activeMainainer count would = 0 if all proposed changes were made
List<Participant> maintainersAfterProposedChanges = testProposedUpdates(participants, params, maintainRoleString);
if (maintainersAfterProposedChanges.size() == 0) {
addAlert(state,
rb.getFormattedMessage("sitegen.siteinfolist.lastmaintainuseractive", new Object[]{maintainRoleString} ));
return;
}
// SAK23029 - proposed changes do not leave site w/o maintainers; proceed with any allowed updates
// list of roles being added or removed
HashSet<String>roles = new HashSet<String>();
// List used for user auditing
List<String[]> userAuditList = new ArrayList<String[]>();
// remove all roles and then add back those that were checked
for (int i = 0; i < participants.size(); i++) {
String id = null;
// added participant
Participant participant = (Participant) participants.get(i);
id = participant.getUniqname();
if (id != null) {
// get the newly assigned role
String inputRoleField = "role" + id;
String roleId = params.getString(inputRoleField);
String oldRoleId = participant.getRole();
boolean roleChange = roleId != null && !roleId.equals(oldRoleId);
// get the grant active status
boolean activeGrant = true;
String activeGrantField = "activeGrant" + id;
if (params.getString(activeGrantField) != null) {
activeGrant = params
.getString(activeGrantField)
.equalsIgnoreCase("true") ? true
: false;
}
boolean activeGrantChange = roleId != null && (participant.isActive() && !activeGrant || !participant.isActive() && activeGrant);
// save any roles changed for permission check
if (roleChange) {
roles.add(roleId);
roles.add(oldRoleId);
}
// SAK-23257 - display an error message if the new role is in the restricted role list
String siteType = s.getType();
List<Role> allowedRoles = SiteParticipantHelper.getAllowedRoles( siteType, getRoles( state ) );
for( String roleName : roles )
{
Role r = realmEdit.getRole( roleName );
if( !allowedRoles.contains( r ) )
{
addAlert( state, rb.getFormattedMessage( "java.roleperm", new Object[] { roleName } ) );
return;
}
}
if (roleChange || activeGrantChange)
{
boolean fromProvider = !participant.isRemoveable();
if (fromProvider && !roleId.equals(participant.getRole())) {
fromProvider = false;
}
realmEdit.addMember(id, roleId, activeGrant,
fromProvider);
String currentUserId = (String) state.getAttribute(STATE_CM_CURRENT_USERID);
String[] userAuditString = {s.getId(),participant.getEid(),roleId,userAuditService.USER_AUDIT_ACTION_UPDATE,userAuditRegistration.getDatabaseSourceKey(),currentUserId};
userAuditList.add(userAuditString);
// construct the event string
String userUpdatedString = "uid=" + id;
if (roleChange)
{
userUpdatedString += ";oldRole=" + oldRoleId + ";newRole=" + roleId;
}
else
{
userUpdatedString += ";role=" + roleId;
}
if (activeGrantChange)
{
userUpdatedString += ";oldActive=" + participant.isActive() + ";newActive=" + activeGrant;
}
else
{
userUpdatedString += ";active=" + activeGrant;
}
userUpdatedString += ";provided=" + fromProvider;
// add to the list for all participants that have role changes
userUpdated.add(userUpdatedString);
}
}
}
// remove selected users
if (params.getStrings("selectedUser") != null) {
List removals = new ArrayList(Arrays.asList(params
.getStrings("selectedUser")));
state.setAttribute(STATE_SELECTED_USER_LIST, removals);
for (int i = 0; i < removals.size(); i++) {
String rId = (String) removals.get(i);
try {
User user = UserDirectoryService.getUser(rId);
// save role for permission check
if (user != null) {
String userId = user.getId();
Member userMember = realmEdit
.getMember(userId);
if (userMember != null) {
Role role = userMember.getRole();
if (role != null) {
roles.add(role.getId());
}
realmEdit.removeMember(userId);
usersDeleted.add("uid=" + userId);
String currentUserId = (String) state.getAttribute(STATE_CM_CURRENT_USERID);
String[] userAuditString = {s.getId(),user.getEid(),role.getId(),userAuditService.USER_AUDIT_ACTION_REMOVE,userAuditRegistration.getDatabaseSourceKey(),currentUserId};
userAuditList.add(userAuditString);
}
}
} catch (UserNotDefinedException e) {
M_log.warn(this + ".doUpdate_participant: IdUnusedException " + rId + ". ", e);
if (("admins".equals(showOrphanedMembers) && SecurityService.isSuperUser()) || ("maintainers".equals(showOrphanedMembers))) {
Member userMember = realmEdit.getMember(rId);
if (userMember != null) {
Role role = userMember.getRole();
if (role != null) {
roles.add(role.getId());
}
realmEdit.removeMember(rId);
}
}
}
}
}
// if user doesn't have update, don't let them add or remove any role with site.upd in it.
if (!AuthzGroupService.allowUpdate(realmId)) {
// see if any changed have site.upd
for (String rolename: roles) {
Role role = realmEdit.getRole(rolename);
if (role != null && role.isAllowed("site.upd")) {
addAlert(state, rb.getFormattedMessage("java.roleperm", new Object[]{rolename}));
return;
}
}
}
AuthzGroupService.save(realmEdit);
// do the audit logging - Doing this in one bulk call to the database will cause the actual audit stamp to be off by maybe 1 second at the most
// but seems to be a better solution than call this multiple time for every update
if (!userAuditList.isEmpty())
{
userAuditRegistration.addToUserAuditing(userAuditList);
}
// then update all related group realms for the role
doUpdate_related_group_participants(s, realmId);
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(
SiteService.SECURE_UPDATE_SITE_MEMBERSHIP,
realmEdit.getId(), false));
// check the configuration setting, whether logging membership
// change at individual level is allowed
if (ServerConfigurationService.getBoolean(
SiteHelper.WSETUP_TRACK_USER_MEMBERSHIP_CHANGE, false)) {
// event for each individual update
for (String userChangedRole : userUpdated) {
EventTrackingService
.post(EventTrackingService
.newEvent(
org.sakaiproject.site.api.SiteService.EVENT_USER_SITE_MEMBERSHIP_UPDATE,
userChangedRole, true));
}
// event for each individual remove
for (String userDeleted : usersDeleted) {
EventTrackingService
.post(EventTrackingService
.newEvent(
org.sakaiproject.site.api.SiteService.EVENT_USER_SITE_MEMBERSHIP_REMOVE,
userDeleted, true));
}
}
} catch (GroupNotDefinedException e) {
addAlert(state, rb.getString("java.problem2"));
M_log.warn(this + ".doUpdate_participant: IdUnusedException " + s.getTitle() + "(" + realmId + "). ", e);
} catch (AuthzPermissionException e) {
addAlert(state, rb.getString("java.changeroles"));
M_log.warn(this + ".doUpdate_participant: PermissionException " + s.getTitle() + "(" + realmId + "). ", e);
}
}
} // doUpdate_participant
/**
* update realted group realm setting according to parent site realm changes
* @param s
* @param realmId
*/
private void doUpdate_related_group_participants(Site s, String realmId) {
Collection groups = s.getGroups();
boolean trackIndividualChange = ServerConfigurationService.getBoolean(SiteHelper.WSETUP_TRACK_USER_MEMBERSHIP_CHANGE, false);
if (groups != null)
{
try
{
for (Iterator iGroups = groups.iterator(); iGroups.hasNext();)
{
Group g = (Group) iGroups.next();
if (g != null)
{
try
{
Set gMembers = g.getMembers();
for (Iterator iGMembers = gMembers.iterator(); iGMembers.hasNext();)
{
Member gMember = (Member) iGMembers.next();
String gMemberId = gMember.getUserId();
Member siteMember = s.getMember(gMemberId);
if ( siteMember == null)
{
// user has been removed from the site
g.removeMember(gMemberId);
}
else
{
// check for Site Info-managed groups: don't change roles for other groups (e.g. section-managed groups)
String gProp = g.getProperties().getProperty(g.GROUP_PROP_WSETUP_CREATED);
// if there is a difference between the role setting, remove the entry from group and add it back with correct role, all are marked "not provided"
Role groupRole = g.getUserRole(gMemberId);
Role siteRole = siteMember.getRole();
if (gProp != null && gProp.equals(Boolean.TRUE.toString()) &&
groupRole != null && siteRole != null && !groupRole.equals(siteRole))
{
if (g.getRole(siteRole.getId()) == null)
{
// in case there is no matching role as that in the site, create such role and add it to the user
g.addRole(siteRole.getId(), siteRole);
}
g.removeMember(gMemberId);
g.addMember(gMemberId, siteRole.getId(), siteMember.isActive(), false);
// track the group membership change at individual level
if (trackIndividualChange)
{
// an event for each individual member role change
EventTrackingService.post(EventTrackingService.newEvent(org.sakaiproject.site.api.SiteService.EVENT_USER_GROUP_MEMBERSHIP_UPDATE, "uid=" + gMemberId + ";groupId=" + g.getId() + ";oldRole=" + groupRole + ";newRole=" + siteRole + ";active=" + siteMember.isActive() + ";provided=false", true/*update event*/));
}
}
}
}
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_GROUP_MEMBERSHIP, g.getId(),true));
}
catch (Exception ee)
{
M_log.warn(this + ".doUpdate_related_group_participants: " + ee.getMessage() + g.getId(), ee);
}
}
}
// commit, save the site
SiteService.save(s);
}
catch (Exception e)
{
M_log.warn(this + ".doUpdate_related_group_participants: " + e.getMessage() + s.getId(), e);
}
}
}
/**
* doUpdate_site_access
*
*/
public void doUpdate_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site sEdit = getStateSite(state);
ParameterParser params = data.getParameters();
// get all form inputs
readInputAndUpdateStateVariable(state, params, "publishunpublish", STATE_SITE_ACCESS_PUBLISH, true);
readInputAndUpdateStateVariable(state, params, "include", STATE_SITE_ACCESS_INCLUDE, true);
readInputAndUpdateStateVariable(state, params, "joinable", STATE_JOINABLE, true);
readInputAndUpdateStateVariable(state, params, "joinerRole", STATE_JOINERROLE, false);
// bjones86 - SAK-24423 - get all joinable site settings from the form input
JoinableSiteSettings.getAllFormInputs( state, params );
boolean publishUnpublish = state.getAttribute(STATE_SITE_ACCESS_PUBLISH) != null ? ((Boolean) state.getAttribute(STATE_SITE_ACCESS_PUBLISH)).booleanValue() : false;
boolean include = state.getAttribute(STATE_SITE_ACCESS_INCLUDE) != null ? ((Boolean) state.getAttribute(STATE_SITE_ACCESS_INCLUDE)).booleanValue() : false;
if (sEdit != null) {
// editing existing site
// publish site or not
sEdit.setPublished(publishUnpublish);
// site public choice
List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
if (publicChangeableSiteTypes != null && sEdit.getType() != null && !publicChangeableSiteTypes.contains(sEdit.getType()))
{
// set pubview to true for those site types which pubview change is not allowed
sEdit.setPubView(true);
}
else
{
// set pubview according to UI selection
sEdit.setPubView(include);
}
doUpdate_site_access_joinable(data, state, params, sEdit);
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(sEdit);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// TODO: hard coding this frame id is fragile, portal dependent,
// and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
// bjones86 - SAK-24423 - remove joinable site settings from the state
JoinableSiteSettings.removeJoinableSiteSettingsFromState( state );
}
} else {
// adding new site
if (state.getAttribute(STATE_SITE_INFO) != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
siteInfo.published = publishUnpublish;
// site public choice
siteInfo.include = include;
// joinable site or not
boolean joinable = state.getAttribute(STATE_JOINABLE) != null ? ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue() : null;
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromStateOnSiteUpdate( state, siteInfo, joinable );
if (joinable) {
siteInfo.joinable = true;
String joinerRole = state.getAttribute(STATE_JOINERROLE) != null ? (String) state.getAttribute(STATE_JOINERROLE) : null;
if (joinerRole != null) {
siteInfo.joinerRole = joinerRole;
} else {
siteInfo.joinerRole = null;
addAlert(state, rb.getString("java.joinsite") + " ");
}
} else {
siteInfo.joinable = false;
siteInfo.joinerRole = null;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
//if creating a site from an archive, go to that template
//otherwise go to confirm page
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_CREATE_FROM_ARCHIVE) == Boolean.TRUE) {
state.setAttribute(STATE_TEMPLATE_INDEX, "62");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
}
}
}
} // doUpdate_site_access
private void readInputAndUpdateStateVariable(SessionState state, ParameterParser params, String paramName, String stateAttributeName, boolean isBoolean)
{
String paramValue = StringUtils.trimToNull(params.getString(paramName));
if (paramValue != null) {
if (isBoolean)
{
state.setAttribute(stateAttributeName, Boolean.valueOf(paramValue));
}
else
{
state.setAttribute(stateAttributeName, paramValue);
}
} else {
state.removeAttribute(stateAttributeName);
}
}
/**
* Apply requested changes to a site's joinability. Only relevant for
* site edits, not new site creation.
*
* <p>Not intended for direct execution from a Velocity-rendered form
* submit.</p>
*
* <p>Originally extracted from {@link #doUpdate_site_access(RunData)} to
* increase testability when adding special handling for an unspecified
* joinability parameter. The <code>sEdit</code> param is passed in
* to avoid repeated hits to the <code>SiteService</code> from
* {@link #getStateSite(SessionState)}. (It's called <code>sEdit</code> to
* reduce the scope of the refactoring diff just slightly.) <code>state</code>
* is passed in to avoid more proliferation of <code>RunData</code>
* downcasts.</p>
*
* @see #CONVERT_NULL_JOINABLE_TO_UNJOINABLE
* @param data request context -- must not be <code>null</code>
* @param state session state -- must not be <code>null</code>
* @param params request parameter facade -- must not be <code>null</code>
* @param sEdit site to be edited -- must not be <code>null</code>
*/
void doUpdate_site_access_joinable(RunData data,
SessionState state, ParameterParser params, Site sEdit) {
boolean joinable = state.getAttribute(STATE_JOINABLE) != null ? ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue() : null;
if (!sEdit.isPublished())
{
// reset joinable role if the site is not published
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
} else if (joinable) {
sEdit.setJoinable(true);
String joinerRole = state.getAttribute(STATE_JOINERROLE) != null ? (String) state.getAttribute(STATE_JOINERROLE) : null;
if (joinerRole != null) {
sEdit.setJoinerRole(joinerRole);
} else {
addAlert(state, rb.getString("java.joinsite") + " ");
}
// bjones86 - SAK-24423 - update site properties for joinable site settings
JoinableSiteSettings.updateSitePropertiesFromStateOnSiteUpdate( sEdit.getPropertiesEdit(), state );
} else if ( !joinable ||
(!joinable && ServerConfigurationService.getBoolean(CONVERT_NULL_JOINABLE_TO_UNJOINABLE, true))) {
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
} // else just leave joinability alone
}
/**
* /* Actions for vm templates under the "chef_site" root. This method is
* called by doContinue. Each template has a hidden field with the value of
* template-index that becomes the value of index for the switch statement
* here. Some cases not implemented.
*/
private void actionForTemplate(String direction, int index,
ParameterParser params, final SessionState state, RunData data) {
// Continue - make any permanent changes, Back - keep any data entered
// on the form
boolean forward = "continue".equals(direction) ? true : false;
SiteInfo siteInfo = new SiteInfo();
// SAK-16600 change to new template for tool editing
if (index==3) { index= 4;}
switch (index) {
case 0:
/*
* actionForTemplate chef_site-list.vm
*
*/
break;
case 1:
/*
* actionForTemplate chef_site-type.vm
*
*/
break;
case 4:
/*
* actionForTemplate chef_site-editFeatures.vm
* actionForTemplate chef_site-editToolGroupFeatures.vm
*
*/
if (forward) {
// editing existing site or creating a new one?
Site site = getStateSite(state);
getFeatures(params, state, site==null?"18":"15");
}
break;
case 8:
/*
* actionForTemplate chef_site-siteDeleteConfirm.vm
*
*/
break;
case 10:
/*
* actionForTemplate chef_site-newSiteConfirm.vm
*
*/
if (!forward) {
}
break;
case 12:
/*
* actionForTemplate chef_site_siteInfo-list.vm
*
*/
break;
case 13:
/*
* actionForTemplate chef_site_siteInfo-editInfo.vm
*
*/
if (forward) {
if (getStateSite(state) == null)
{
// alerts after clicking Continue but not Back
if (!forward) {
// removing previously selected template site
state.removeAttribute(STATE_TEMPLATE_SITE);
}
updateSiteAttributes(state);
}
updateSiteInfo(params, state);
}
break;
case 14:
/*
* actionForTemplate chef_site_siteInfo-editInfoConfirm.vm
*
*/
break;
case 15:
/*
* actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm
*
*/
break;
case 18:
/*
* actionForTemplate chef_siteInfo-editAccess.vm
*
*/
if (!forward) {
}
break;
case 24:
/*
* actionForTemplate
* chef_site-siteInfo-editAccess-globalAccess-confirm.vm
*
*/
break;
case 26:
/*
* actionForTemplate chef_site-modifyENW.vm
*
*/
updateSelectedToolList(state, params, true);
break;
case 27:
/*
* actionForTemplate chef_site-importSites.vm
*
*/
if (forward) {
Site existingSite = getStateSite(state);
if (existingSite != null) {
// revising a existing site's tool
if (select_import_tools(params, state)) {
String threadName = "SiteImportThread" + existingSite.getId();
boolean found = false;
//check all running threads for our named thread
//this isn't cluster safe, but this check it more targeted towards
//a single user re-importing multiple times during a slow import (which would be on the same server)
for(Thread t : Thread.getAllStackTraces().keySet()){
if(threadName.equals(t.getName())){
found = true;
break;
}
}
if(found){
//an existing thread is running for this site import, throw warning
addAlert(state, rb.getString("java.import.existing"));
}else{
final Hashtable importTools = (Hashtable) state
.getAttribute(STATE_IMPORT_SITE_TOOL);
final List selectedTools = originalToolIds((List<String>) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST), state);
final String userEmail = UserDirectoryService.getCurrentUser().getEmail();
final Session session = SessionManager.getCurrentSession();
final ToolSession toolSession = SessionManager.getCurrentToolSession();
Thread siteImportThread = new Thread(){
public void run() {
Site existingSite = getStateSite(state);
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_START, existingSite.getReference(), false));
SessionManager.setCurrentSession(session);
SessionManager.setCurrentToolSession(toolSession);
importToolIntoSite(selectedTools, importTools,
existingSite);
existingSite = getStateSite(state); // refresh site for
// WC and News
commitSite(existingSite);
userNotificationProvider.notifySiteImportCompleted(userEmail, existingSite.getId(), existingSite.getTitle());
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_END, existingSite.getReference(), false));
}
};
siteImportThread.setName(threadName);
siteImportThread.start();
state.setAttribute(IMPORT_QUEUED, rb.get("importQueued"));
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
} else {
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
} else {
// new site
select_import_tools(params, state);
}
} else {
// read form input about import tools
select_import_tools(params, state);
}
break;
case 60:
/*
* actionForTemplate chef_site-importSitesMigrate.vm
*
*/
if (forward) {
Site existingSite = getStateSite(state);
if (existingSite != null) {
// revising a existing site's tool
if (select_import_tools(params, state)) {
String threadName = "SiteImportThread" + existingSite.getId();
boolean found = false;
//check all running threads for our named thread
//this isn't cluster safe, but this check it more targeted towards
//a single user re-importing multiple times during a slow import (which would be on the same server)
for(Thread t : Thread.getAllStackTraces().keySet()){
if(threadName.equals(t.getName())){
found = true;
break;
}
}
if(found){
//an existing thread is running for this site import, throw warning
addAlert(state, rb.getString("java.import.existing"));
}else{
final Hashtable importTools = (Hashtable) state
.getAttribute(STATE_IMPORT_SITE_TOOL);
final List selectedTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
final String userEmail = UserDirectoryService.getCurrentUser().getEmail();
final Session session = SessionManager.getCurrentSession();
final ToolSession toolSession = SessionManager.getCurrentToolSession();
Thread siteImportThread = new Thread(){
public void run() {
Site existingSite = getStateSite(state);
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_START, existingSite.getReference(), false));
SessionManager.setCurrentSession(session);
SessionManager.setCurrentToolSession(toolSession);
// Remove all old contents before importing contents from new site
importToolIntoSiteMigrate(selectedTools, importTools,
existingSite);
userNotificationProvider.notifySiteImportCompleted(userEmail, existingSite.getId(), existingSite.getTitle());
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_END, existingSite.getReference(), false));
}
};
siteImportThread.setName(threadName);
siteImportThread.start();
state.setAttribute(IMPORT_QUEUED, rb.get("importQueued"));
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
} else {
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
} else {
// new site
select_import_tools(params, state);
}
} else {
// read form input about import tools
select_import_tools(params, state);
}
break;
case 28:
/*
* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
state.removeAttribute(STATE_IMPORT_SITES);
} else {
List importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
sites.put(s, new Vector());
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 58:
/*
* actionForTemplate chef_siteinfo-importSelection.vm
*
*/
break;
case 59:
/*
* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
state.removeAttribute(STATE_IMPORT_SITES);
} else {
List importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
sites.put(s, new Vector());
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 29:
/*
* actionForTemplate chef_siteinfo-duplicate.vm
*
*/
if (forward) {
if (state.getAttribute(SITE_DUPLICATED) == null) {
if (StringUtils.trimToNull(params.getString("title")) == null) {
addAlert(state, rb.getString("java.dupli") + " ");
} else {
String title = params.getString("title");
state.setAttribute(SITE_DUPLICATED_NAME, title);
String newSiteId = IdManager.createUuid();
try {
String oldSiteId = (String) state
.getAttribute(STATE_SITE_INSTANCE_ID);
// Retrieve the source site reference to be used in the EventTrackingService
// notification of the start/end of a site duplication.
String sourceSiteRef = null;
try {
Site sourceSite = SiteService.getSite(oldSiteId);
sourceSiteRef = sourceSite.getReference();
} catch (IdUnusedException e) {
M_log.warn(this + ".actionForTemplate; case29: invalid source siteId: "+oldSiteId);
return;
}
// SAK-20797
long oldSiteQuota = this.getSiteSpecificQuota(oldSiteId);
Site site = SiteService.addSite(newSiteId,
getStateSite(state));
// An event for starting the "duplicate site" action
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_DUPLICATE_START, sourceSiteRef, site.getId(), false, NotificationService.NOTI_OPTIONAL));
// get the new site icon url
if (site.getIconUrl() != null)
{
site.setIconUrl(transferSiteResource(oldSiteId, newSiteId, site.getIconUrl()));
}
// set title
site.setTitle(title);
// SAK-20797 alter quota if required
boolean duplicateQuota = params.getString("dupequota") != null ? params.getBoolean("dupequota") : false;
if (duplicateQuota==true) {
if (oldSiteQuota > 0) {
M_log.info("Saving quota");
try {
String collId = m_contentHostingService
.getSiteCollection(site.getId());
ContentCollectionEdit col = m_contentHostingService.editCollection(collId);
ResourcePropertiesEdit resourceProperties = col.getPropertiesEdit();
resourceProperties.addProperty(
ResourceProperties.PROP_COLLECTION_BODY_QUOTA,
new Long(oldSiteQuota)
.toString());
m_contentHostingService.commitCollection(col);
} catch (Exception ignore) {
M_log.warn("saveQuota: unable to duplicate site-specific quota for site : "
+ site.getId() + " : " + ignore);
}
}
}
try {
SiteService.save(site);
// import tool content
importToolContent(oldSiteId, site, false);
String siteType = site.getType();
if (SiteTypeUtil.isCourseSite(siteType)) {
// for course site, need to
// read in the input for
// term information
String termId = StringUtils.trimToNull(params
.getString("selectTerm"));
if (termId != null) {
AcademicSession term = cms.getAcademicSession(termId);
if (term != null) {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(Site.PROP_SITE_TERM, term.getTitle());
rp.addProperty(Site.PROP_SITE_TERM_EID, term.getEid());
} else {
M_log.warn("termId=" + termId + " not found");
}
}
}
// save again
SiteService.save(site);
String realm = SiteService.siteReference(site.getId());
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm);
if (SiteTypeUtil.isCourseSite(siteType))
{
// also remove the provider id attribute if any
realmEdit.setProviderGroupId(null);
}
// add current user as the maintainer
realmEdit.addMember(UserDirectoryService.getCurrentUser().getId(), site.getMaintainRole(), true, false);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: IdUnusedException, not found, or not an AuthzGroup object "+ realm, e);
addAlert(state, rb.getString("java.realm"));
} catch (AuthzPermissionException e) {
addAlert(state, this + rb.getString("java.notaccess"));
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.notaccess"), e);
}
} catch (IdUnusedException e) {
M_log.warn(this + " actionForTemplate chef_siteinfo-duplicate:: IdUnusedException when saving " + newSiteId);
} catch (PermissionException e) {
M_log.warn(this + " actionForTemplate chef_siteinfo-duplicate:: PermissionException when saving " + newSiteId);
}
// TODO: hard coding this frame id
// is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
// send site notification
sendSiteNotification(state, site, null);
state.setAttribute(SITE_DUPLICATED, Boolean.TRUE);
// An event for ending the "duplicate site" action
EventTrackingService.post(EventTrackingService.newEvent(SiteService.EVENT_SITE_DUPLICATE_END, sourceSiteRef, site.getId(), false, NotificationService.NOTI_OPTIONAL));
} catch (IdInvalidException e) {
addAlert(state, rb.getString("java.siteinval"));
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.siteinval") + " site id = " + newSiteId, e);
} catch (IdUsedException e) {
addAlert(state, rb.getString("java.sitebeenused"));
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.sitebeenused") + " site id = " + newSiteId, e);
} catch (PermissionException e) {
addAlert(state, rb.getString("java.allowcreate"));
M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.allowcreate") + " site id = " + newSiteId, e);
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// site duplication confirmed
state.removeAttribute(SITE_DUPLICATED);
state.removeAttribute(SITE_DUPLICATED_NAME);
// return to the list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
break;
case 33:
break;
case 36:
/*
* actionForTemplate chef_site-newSiteCourse.vm
*/
if (forward) {
List providerChosenList = new Vector();
List providerDescriptionChosenList = new Vector();
if (params.getStrings("providerCourseAdd") == null) {
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
if (params.getString("manualAdds") == null) {
addAlert(state, rb.getString("java.manual") + " ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// The list of courses selected from provider listing
if (params.getStrings("providerCourseAdd") != null) {
providerChosenList = new ArrayList(Arrays.asList(params
.getStrings("providerCourseAdd"))); // list of
// description choices
if (params.getStrings("providerCourseAddDescription") != null) {
providerDescriptionChosenList = new ArrayList(Arrays.asList(params
.getStrings("providerCourseAddDescription"))); // list of
state.setAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN,
providerDescriptionChosenList);
}
// course
// ids
String userId = (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED);
String currentUserId = (String) state
.getAttribute(STATE_CM_CURRENT_USERID);
if (userId == null
|| (userId != null && userId
.equals(currentUserId))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
} else {
// STATE_CM_AUTHORIZER_SECTIONS are SectionObject,
// so need to prepare it
// also in this page, u can pick either section from
// current user OR
// sections from another users but not both. -
// daisy's note 1 for now
// till we are ready to add more complexity
List sectionObjectList = prepareSectionObject(
providerChosenList, userId);
state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS,
sectionObjectList);
state
.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
// set special instruction & we will keep
// STATE_CM_AUTHORIZER_LIST
String additional = StringUtils.trimToEmpty(params
.getString("additional"));
state.setAttribute(FORM_ADDITIONAL, additional);
}
}
collectNewSiteInfo(state, params, providerChosenList);
String find_course = params.getString("find_course");
if (state.getAttribute(STATE_TEMPLATE_SITE) != null && (find_course == null || !"true".equals(find_course)))
{
// creating based on template
doFinish(data);
}
}
}
break;
case 38:
break;
case 39:
break;
case 42:
/*
* actionForTemplate chef_site-type-confirm.vm
*
*/
break;
case 43:
/*
* actionForTemplate chef_site-editClass.vm
*
*/
if (forward) {
if (params.getStrings("providerClassDeletes") == null
&& params.getStrings("manualClassDeletes") == null
&& params.getStrings("cmRequestedClassDeletes") == null
&& !"back".equals(direction)) {
addAlert(state, rb.getString("java.classes"));
}
if (params.getStrings("providerClassDeletes") != null) {
// build the deletions list
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
List providerCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("providerClassDeletes")));
for (ListIterator i = providerCourseDeleteList
.listIterator(); i.hasNext();) {
providerCourseList.remove((String) i.next());
}
//Track provider deletes, seems like the only place to do it. If a confirmation is ever added somewhere, don't do this.
trackRosterChanges(org.sakaiproject.site.api.SiteService.EVENT_SITE_ROSTER_REMOVE,providerCourseDeleteList);
state.setAttribute(SITE_PROVIDER_COURSE_LIST,
providerCourseList);
}
if (params.getStrings("manualClassDeletes") != null) {
// build the deletions list
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
List manualCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("manualClassDeletes")));
for (ListIterator i = manualCourseDeleteList.listIterator(); i
.hasNext();) {
manualCourseList.remove((String) i.next());
}
state.setAttribute(SITE_MANUAL_COURSE_LIST,
manualCourseList);
}
if (params.getStrings("cmRequestedClassDeletes") != null) {
// build the deletions list
List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<String> cmRequestedCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("cmRequestedClassDeletes")));
for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i
.hasNext();) {
String sectionId = (String) i.next();
try
{
SectionObject so = new SectionObject(cms.getSection(sectionId));
SectionObject soFound = null;
for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();)
{
SectionObject k = (SectionObject) j.next();
if (k.eid.equals(sectionId))
{
soFound = k;
}
}
if (soFound != null) cmRequestedCourseList.remove(soFound);
}
catch (IdNotFoundException e)
{
M_log.warn("actionForTemplate 43 editClass: Cannot find section " + sectionId);
}
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList);
}
updateCourseClasses(state, new Vector(), new Vector());
}
break;
case 44:
if (forward) {
AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
Site site = getStateSite(state);
ResourcePropertiesEdit pEdit = site.getPropertiesEdit();
// update the course site property and realm based on the selection
updateCourseSiteSections(state, site.getId(), pEdit, a);
try
{
SiteService.save(site);
}
catch (Exception e)
{
M_log.warn(this + ".actionForTemplate chef_siteinfo-addCourseConfirm: " + e.getMessage() + site.getId(), e);
}
removeAddClassContext(state);
}
break;
case 54:
if (forward) {
// store answers to site setup questions
if (getAnswersToSetupQuestions(params, state))
{
state.setAttribute(STATE_TEMPLATE_INDEX, state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE));
}
}
break;
case 61:
// import users
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
} else {
importSitesUsers(params, state);
}
}
break;
}
}// actionFor Template
/**
*
* @param action
* @param providers
*/
private void trackRosterChanges(String event, List <String> rosters) {
if (ServerConfigurationService.getBoolean(
SiteHelper.WSETUP_TRACK_ROSTER_CHANGE, false)) {
// event for each individual update
if (rosters != null) {
for (String roster : rosters) {
EventTrackingService.post(EventTrackingService.newEvent(event, "roster="+roster, true));
}
}
}
}
/**
* import not-provided users from selected sites
* @param params
*/
private void importSitesUsers(ParameterParser params, SessionState state) {
// the target site
Site site = getStateSite(state);
try {
// the target realm
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(site.getId()));
List importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
for (int i = 0; i < importSites.size(); i++) {
String fromSiteId = (String) importSites.get(i);
try {
Site fromSite = SiteService.getSite(fromSiteId);
// get realm information
String fromRealmId = SiteService.siteReference(fromSite.getId());
AuthzGroup fromRealm = AuthzGroupService.getAuthzGroup(fromRealmId);
// get all users in the from site
Set fromUsers = fromRealm.getUsers();
for (Iterator iFromUsers = fromUsers.iterator(); iFromUsers.hasNext();)
{
String fromUserId = (String) iFromUsers.next();
Member fromMember = fromRealm.getMember(fromUserId);
if (!fromMember.isProvided())
{
// add user
realm.addMember(fromUserId, fromMember.getRole().getId(), fromMember.isActive(), false);
}
}
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".importSitesUsers: GroupNotDefinedException, " + fromSiteId + " not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.cannotedit"));
} catch (IdUnusedException e) {
M_log.warn(this + ".importSitesUsers: IdUnusedException, " + fromSiteId + " not found, or not an AuthzGroup object", e);
}
}
// post event about the realm participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realm.getId(), false));
// save realm
AuthzGroupService.save(realm);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".importSitesUsers: IdUnusedException, " + site.getTitle() + "(" + site.getId() + ") not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.cannotedit"));
} catch (AuthzPermissionException e) {
M_log.warn(this + ".importSitesUsers: PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + site.getId() + "). ", e);
addAlert(state, rb.getString("java.notaccess"));
}
}
/**
* This is used to update exsiting site attributes with encoded site id in it. A new resource item is added to new site when needed
*
* @param oSiteId
* @param nSiteId
* @param siteAttribute
* @return the new migrated resource url
*/
private String transferSiteResource(String oSiteId, String nSiteId, String siteAttribute) {
String rv = "";
String accessUrl = ServerConfigurationService.getAccessUrl();
if (siteAttribute!= null && siteAttribute.indexOf(oSiteId) != -1 && accessUrl != null)
{
// stripe out the access url, get the relative form of "url"
Reference ref = EntityManager.newReference(siteAttribute.replaceAll(accessUrl, ""));
try
{
ContentResource resource = m_contentHostingService.getResource(ref.getId());
// the new resource
ContentResource nResource = null;
String nResourceId = resource.getId().replaceAll(oSiteId, nSiteId);
try
{
nResource = m_contentHostingService.getResource(nResourceId);
}
catch (Exception n2Exception)
{
// copy the resource then
try
{
nResourceId = m_contentHostingService.copy(resource.getId(), nResourceId);
nResource = m_contentHostingService.getResource(nResourceId);
}
catch (Exception n3Exception)
{
}
}
// get the new resource url
rv = nResource != null?nResource.getUrl(false):"";
}
catch (Exception refException)
{
M_log.warn(this + ":transferSiteResource: cannot find resource with ref=" + ref.getReference() + " " + refException.getMessage());
}
}
return rv;
}
/**
* copy tool content from old site
* @param oSiteId source (old) site id
* @param site destination site
* @param bypassSecurity use SecurityAdvisor if true
*/
private void importToolContent(String oSiteId, Site site, boolean bypassSecurity) {
String nSiteId = site.getId();
// import tool content
if (bypassSecurity)
{
// importing from template, bypass the permission checking:
// temporarily allow the user to read and write from assignments (asn.revise permission)
SecurityService.pushAdvisor(new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
});
}
List pageList = site.getPages();
Set<String> toolsCopied = new HashSet<String>();
Map transversalMap = new HashMap();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList
.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
if (!(pageToolList == null || pageToolList.size() == 0))
{
Tool tool = ((ToolConfiguration) pageToolList.get(0)).getTool();
String toolId = tool != null?tool.getId():"";
if (toolId.equalsIgnoreCase("sakai.resources")) {
// handle
// resource
// tool
// specially
Map<String,String> entityMap = transferCopyEntities(
toolId,
m_contentHostingService
.getSiteCollection(oSiteId),
m_contentHostingService
.getSiteCollection(nSiteId));
if(entityMap != null){
transversalMap.putAll(entityMap);
}
} else if (toolId.equalsIgnoreCase(SITE_INFORMATION_TOOL)) {
// handle Home tool specially, need to update the site infomration display url if needed
String newSiteInfoUrl = transferSiteResource(oSiteId, nSiteId, site.getInfoUrl());
site.setInfoUrl(newSiteInfoUrl);
}
else {
// other
// tools
// SAK-19686 - added if statement and toolsCopied.add
if (!toolsCopied.contains(toolId)) {
Map<String,String> entityMap = transferCopyEntities(toolId,
oSiteId, nSiteId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
toolsCopied.add(toolId);
}
}
}
}
//update entity references
toolsCopied = new HashSet<String>();
for (ListIterator i = pageList
.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
if (!(pageToolList == null || pageToolList.size() == 0))
{
Tool tool = ((ToolConfiguration) pageToolList.get(0)).getTool();
String toolId = tool != null?tool.getId():"";
updateEntityReferences(toolId, nSiteId, transversalMap, site);
}
}
}
if (bypassSecurity)
{
SecurityService.popAdvisor();
}
}
/**
* get user answers to setup questions
* @param params
* @param state
* @return
*/
protected boolean getAnswersToSetupQuestions(ParameterParser params, SessionState state)
{
boolean rv = true;
String answerString = null;
String answerId = null;
Set userAnswers = new HashSet();
SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE));
if (siteTypeQuestions != null)
{
List<SiteSetupQuestion> questions = siteTypeQuestions.getQuestions();
for (Iterator i = questions.iterator(); i.hasNext();)
{
SiteSetupQuestion question = (SiteSetupQuestion) i.next();
// get the selected answerId
answerId = params.get(question.getId());
if (question.isRequired() && answerId == null)
{
rv = false;
addAlert(state, rb.getString("sitesetupquestion.alert"));
}
else if (answerId != null)
{
SiteSetupQuestionAnswer answer = questionService.getSiteSetupQuestionAnswer(answerId);
if (answer != null)
{
if (answer.getIsFillInBlank())
{
// need to read the text input instead
answerString = params.get("fillInBlank_" + answerId);
}
SiteSetupUserAnswer uAnswer = questionService.newSiteSetupUserAnswer();
uAnswer.setAnswerId(answerId);
uAnswer.setAnswerString(answerString);
uAnswer.setQuestionId(question.getId());
uAnswer.setUserId(SessionManager.getCurrentSessionUserId());
//update the state variable
userAnswers.add(uAnswer);
}
}
}
state.setAttribute(STATE_SITE_SETUP_QUESTION_ANSWER, userAnswers);
}
return rv;
}
/**
* remove related state variable for adding class
*
* @param state
* SessionState object
*/
private void removeAddClassContext(SessionState state) {
// remove related state variables
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTIONS);
state.removeAttribute(FORM_SITEINFO_ALIASES);
state.removeAttribute(FORM_SITEINFO_URL_BASE);
sitePropertiesIntoState(state);
} // removeAddClassContext
private void updateCourseClasses(SessionState state, List notifyClasses,
List requestClasses) {
List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
Site site = getStateSite(state);
String id = site.getId();
String realmId = SiteService.siteReference(id);
if ((providerCourseSectionList == null)
|| (providerCourseSectionList.size() == 0)) {
// no section access so remove Provider Id
try {
AuthzGroup realmEdit1 = AuthzGroupService
.getAuthzGroup(realmId);
boolean hasNonProvidedMainroleUser = false;
String maintainRoleString = realmEdit1.getMaintainRole();
Set<String> maintainRoleUsers = realmEdit1.getUsersHasRole(maintainRoleString);
if (!maintainRoleUsers.isEmpty())
{
for(Iterator<String> users = maintainRoleUsers.iterator(); !hasNonProvidedMainroleUser && users.hasNext();)
{
String userId = users.next();
if (!realmEdit1.getMember(userId).isProvided())
hasNonProvidedMainroleUser = true;
}
}
if (!hasNonProvidedMainroleUser)
{
// if after the removal, there is no provider id, and there is no maintain role user anymore, show alert message and don't save the update
addAlert(state, rb.getString("sitegen.siteinfolist.nomaintainuser")
+ maintainRoleString + ".");
}
else
{
realmEdit1.setProviderGroupId(NULL_STRING);
AuthzGroupService.save(realmEdit1);
}
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.cannotedit"));
return;
} catch (AuthzPermissionException e) {
M_log.warn(this + ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ", e);
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((providerCourseSectionList != null)
&& (providerCourseSectionList.size() != 0)) {
// section access so rewrite Provider Id, don't need the current realm provider String
String externalRealm = buildExternalRealm(id, state,
providerCourseSectionList, null);
try {
AuthzGroup realmEdit2 = AuthzGroupService
.getAuthzGroup(realmId);
realmEdit2.setProviderGroupId(externalRealm);
AuthzGroupService.save(realmEdit2);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object", e);
addAlert(state, rb.getString("java.cannotclasses"));
return;
} catch (AuthzPermissionException e) {
M_log.warn(this
+ ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ", e);
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
//reload the site object after changes group realms have been removed from the site.
site = getStateSite(state);
// the manual request course into properties
setSiteSectionProperty(manualCourseSectionList, site, PROP_SITE_REQUEST_COURSE);
// the cm request course into properties
setSiteSectionProperty(cmRequestedCourseList, site, STATE_CM_REQUESTED_SECTIONS);
// clean the related site groups
// if the group realm provider id is not listed for the site, remove the related group
for (Iterator iGroups = site.getGroups().iterator(); iGroups.hasNext();)
{
Group group = (Group) iGroups.next();
try
{
AuthzGroup gRealm = AuthzGroupService.getAuthzGroup(group.getReference());
String gProviderId = StringUtils.trimToNull(gRealm.getProviderGroupId());
if (gProviderId != null)
{
if (!listContainsString(manualCourseSectionList, gProviderId)
&& !listContainsString(cmRequestedCourseList, gProviderId)
&& !listContainsString(providerCourseSectionList, gProviderId))
{
// if none of those three lists contains the provider id, remove the group and realm
AuthzGroupService.removeAuthzGroup(group.getReference());
}
}
}
catch (Exception e)
{
M_log.warn(this + ".updateCourseClasses: cannot remove authzgroup : " + group.getReference(), e);
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(site);
} else {
}
if (requestClasses != null && requestClasses.size() > 0
&& state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
try {
// send out class request notifications
sendSiteRequest(state, "change",
((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(),
(List<SectionObject>) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS),
"manual");
} catch (Exception e) {
M_log.warn(this +".updateCourseClasses:" + e.toString(), e);
}
}
if (notifyClasses != null && notifyClasses.size() > 0) {
try {
// send out class access confirmation notifications
sendSiteNotification(state, getStateSite(state), notifyClasses);
} catch (Exception e) {
M_log.warn(this + ".updateCourseClasses:" + e.toString(), e);
}
}
} // updateCourseClasses
/**
* test whether
* @param list
* @param providerId
* @return
*/
boolean listContainsString(List list, String s)
{
boolean rv = false;
if (list != null && !list.isEmpty() && s != null && s.length() != 0)
{
for (Object o : list)
{
// deals with different object type
if (o instanceof SectionObject)
{
rv = ((SectionObject) o).getEid().equals(s);
}
else if (o instanceof String)
{
rv = ((String) o).equals(s);
}
// exit when find match
if (rv)
break;
}
}
return rv;
}
private void setSiteSectionProperty(List courseSectionList, Site site, String propertyName) {
if ((courseSectionList != null) && (courseSectionList.size() != 0)) {
// store the requested sections in one site property
StringBuffer sections = new StringBuffer();
for (int j = 0; j < courseSectionList.size();) {
sections = sections.append(courseSectionList.get(j));
if (courseSectionList.get(j) instanceof SectionObject)
{
SectionObject so = (SectionObject) courseSectionList.get(j);
sections = sections.append(so.getEid());
}
else if (courseSectionList.get(j) instanceof String)
{
sections = sections.append((String) courseSectionList.get(j));
}
j++;
if (j < courseSectionList.size()) {
sections = sections.append("+");
}
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(propertyName, sections.toString());
} else {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.removeProperty(propertyName);
}
}
/**
* Sets selected roles for multiple users
*
* @param params
* The ParameterParser object
* @param listName
* The state variable
*/
private void getSelectedRoles(SessionState state, ParameterParser params,
String listName) {
Hashtable pSelectedRoles = (Hashtable) state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
if (pSelectedRoles == null) {
pSelectedRoles = new Hashtable();
}
List userList = (List) state.getAttribute(listName);
for (int i = 0; i < userList.size(); i++) {
String userId = null;
if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) {
userId = ((Participant) userList.get(i)).getUniqname();
} else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) {
userId = (String) userList.get(i);
}
if (userId != null) {
String rId = StringUtils.trimToNull(params.getString("role"
+ userId));
if (rId == null) {
addAlert(state, rb.getString("java.rolefor") + " " + userId
+ ". ");
pSelectedRoles.remove(userId);
} else {
pSelectedRoles.put(userId, rId);
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles);
} // getSelectedRoles
/**
* dispatch function for changing participants roles
*/
public void doSiteinfo_edit_role(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("same_role_true")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params
.getString("role_to_all"));
} else if (option.equalsIgnoreCase("same_role_false")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) {
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
new Hashtable());
}
} else if (option.equalsIgnoreCase("continue")) {
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
doCancel(data);
}
} // doSiteinfo_edit_role
/**
* save changes to site global access
*/
public void doSiteinfo_save_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site s = getStateSite(state);
boolean joinable = ((Boolean) state.getAttribute("form_joinable"))
.booleanValue();
s.setJoinable(joinable);
if (joinable) {
// set the joiner role
String joinerRole = (String) state.getAttribute("form_joinerRole");
s.setJoinerRole(joinerRole);
// bjones86 - SAK-24423 - update site properties for joinable site settings
JoinableSiteSettings.updateSitePropertiesFromStateOnSiteInfoSaveGlobalAccess( s.getPropertiesEdit(), state );
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// release site edit
commitSite(s);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doSiteinfo_save_globalAccess
/**
* updateSiteAttributes
*
*/
private void updateSiteAttributes(SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
M_log
.warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null");
return;
}
Site site = getStateSite(state);
if (site != null) {
if (StringUtils.trimToNull(siteInfo.title) != null) {
site.setTitle(siteInfo.title);
}
if (siteInfo.description != null) {
site.setDescription(siteInfo.description);
}
site.setPublished(siteInfo.published);
setAppearance(state, site, siteInfo.iconUrl);
site.setJoinable(siteInfo.joinable);
if (StringUtils.trimToNull(siteInfo.joinerRole) != null) {
site.setJoinerRole(siteInfo.joinerRole);
}
// Make changes and then put changed site back in state
String id = site.getId();
// bjones86 - SAK-24423 - update site properties for joinable site settings
JoinableSiteSettings.updateSitePropertiesFromStateOnUpdateSiteAttributes( site, state );
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
if (SiteService.allowUpdateSite(id)) {
try {
SiteService.getSite(id);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
} catch (IdUnusedException e) {
M_log.warn(this + ".updateSiteAttributes: IdUnusedException "
+ siteInfo.getTitle() + "(" + id + ") not found", e);
}
}
// no permission
else {
addAlert(state, rb.getString("java.makechanges"));
M_log.warn(this + ".updateSiteAttributes: PermissionException "
+ siteInfo.getTitle() + "(" + id + ")");
}
}
} // updateSiteAttributes
/**
* %%% legacy properties, to be removed
*/
private void updateSiteInfo(ParameterParser params, SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE);
// title
boolean hasRosterAttached = params.getString("hasRosterAttached") != null ? Boolean.getBoolean(params.getString("hasRosterAttached")) : false;
if ((siteTitleEditable(state, siteInfo.site_type) || !hasRosterAttached) && params.getString("title") != null)
{
// site titel is editable and could not be null
String title = StringUtils.trimToNull(params.getString("title"));
siteInfo.title = title;
if (title == null) {
addAlert(state, rb.getString("java.specify") + " ");
}
// check for site title length
else if (title.length() > SiteConstants.SITE_GROUP_TITLE_LIMIT)
{
addAlert(state, rb.getFormattedMessage("site_group_title_length_limit", new Object[]{SiteConstants.SITE_GROUP_TITLE_LIMIT}));
}
}
if (params.getString("description") != null) {
StringBuilder alertMsg = new StringBuilder();
String description = params.getString("description");
siteInfo.description = FormattedText.processFormattedText(description, alertMsg);
}
if (params.getString("short_description") != null) {
siteInfo.short_description = params.getString("short_description");
}
String skin = params.getString("skin");
if (skin != null) {
// if there is a skin input for course site
skin = StringUtils.trimToNull(skin);
siteInfo.iconUrl = skin;
} else {
// if ther is a icon input for non-course site
String icon = StringUtils.trimToNull(params.getString("icon"));
if (icon != null) {
if (icon.endsWith(PROTOCOL_STRING)) {
addAlert(state, rb.getString("alert.protocol"));
}
siteInfo.iconUrl = icon;
} else {
siteInfo.iconUrl = "";
}
}
if (params.getString("additional") != null) {
siteInfo.additional = params.getString("additional");
}
if (params.getString("iconUrl") != null) {
siteInfo.iconUrl = params.getString("iconUrl");
} else if (params.getString("skin") != null) {
siteInfo.iconUrl = params.getString("skin");
}
if (params.getString("joinerRole") != null) {
siteInfo.joinerRole = params.getString("joinerRole");
}
if (params.getString("joinable") != null) {
boolean joinable = params.getBoolean("joinable");
siteInfo.joinable = joinable;
if (!joinable)
siteInfo.joinerRole = NULL_STRING;
}
if (params.getString("itemStatus") != null) {
siteInfo.published = Boolean
.valueOf(params.getString("itemStatus")).booleanValue();
}
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromParams( params, siteInfo );
// site contact information
String name = StringUtils.trimToEmpty(params.getString("siteContactName"));
if (name.length() == 0)
{
addAlert(state, rb.getString("alert.sitediinf.sitconnam"));
}
siteInfo.site_contact_name = name;
String email = StringUtils.trimToEmpty(params
.getString("siteContactEmail"));
if (email != null) {
if (!email.isEmpty() && !EmailValidator.getInstance().isValid(email)) {
// invalid email
addAlert(state, rb.getFormattedMessage("java.invalid.email", new Object[]{FormattedText.escapeHtml(email,false)}));
}
siteInfo.site_contact_email = email;
}
int aliasCount = params.getInt("alias_count", 0);
siteInfo.siteRefAliases.clear();
for ( int j = 0; j < aliasCount ; j++ ) {
String alias = StringUtils.trimToNull(params.getString("alias_" + j));
if ( alias == null ) {
continue;
}
// Kernel will force these to lower case anyway. Forcing
// to lower case whenever reading out of the form simplifies
// comparisons at save time, though, and provides consistent
// on-screen display.
alias = alias.toLowerCase();
// An invalid alias will set an alert, which theoretically
// disallows further progress in the workflow, but we
// still need to re-render the invalid form contents.
// Thus siteInfo.aliases contains all input aliases, even if
// invalid. (Same thing happens above for email.)
validateSiteAlias(alias, state);
siteInfo.siteRefAliases.add(alias);
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // updateSiteInfo
private boolean validateSiteAlias(String aliasId, SessionState state) {
if ( (aliasId = StringUtils.trimToNull(aliasId)) == null ) {
addAlert(state, rb.getFormattedMessage("java.alias.isinval", new Object[]{aliasId}));
return false;
}
boolean isSimpleResourceName = aliasId.equals(Validator.escapeResourceName(aliasId));
boolean isSimpleUrl = aliasId.equals(Validator.escapeUrl(aliasId));
if ( !(isSimpleResourceName) || !(isSimpleUrl) ) {
// The point of these site aliases is to have easy-to-recall,
// easy-to-guess URLs. So we take a very conservative approach
// here and disallow any aliases which would require special
// encoding or would simply be ignored when building a valid
// resource reference or outputting that reference as a URL.
addAlert(state, rb.getFormattedMessage("java.alias.isinval", new Object[]{aliasId}));
return false;
} else {
String currentSiteId = StringUtils.trimToNull((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
boolean editingSite = currentSiteId != null;
try {
String targetRef = AliasService.getTarget(aliasId);
if ( editingSite ) {
String siteRef = SiteService.siteReference(currentSiteId);
boolean targetsCurrentSite = siteRef.equals(targetRef);
if ( !(targetsCurrentSite) ) {
addAlert(state, rb.getFormattedMessage("java.alias.exists", new Object[]{aliasId}));
return false;
}
} else {
addAlert(state, rb.getFormattedMessage("java.alias.exists", new Object[]{aliasId}));
return false;
}
} catch (IdUnusedException e) {
// No conflicting aliases
}
return true;
}
}
/**
* getParticipantList
*
*/
private Collection getParticipantList(SessionState state) {
List members = new Vector();
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List providerCourseList = null;
providerCourseList = SiteParticipantHelper.getProviderCourseList(siteId);
if (providerCourseList != null && providerCourseList.size() > 0) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
Collection participants = SiteParticipantHelper.prepareParticipants(siteId, providerCourseList);
state.setAttribute(STATE_PARTICIPANT_LIST, participants);
return participants;
} // getParticipantList
/**
* getRoles
*
*/
private List getRoles(SessionState state) {
List roles = new Vector();
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
roles.addAll(realm.getRoles());
Collections.sort(roles);
} catch (GroupNotDefinedException e) {
M_log.warn( this + ".getRoles: IdUnusedException " + realmId, e);
}
return roles;
} // getRoles
/**
* getRoles
*
* bjones86 - SAK-23257 - added state and siteType parameters so list
* of joiner roles can respect the restricted role lists in sakai.properties.
*
*/
private List<Role> getJoinerRoles(String realmId, SessionState state, String siteType) {
List roles = new ArrayList();
/** related to SAK-18462, this is a list of permissions that the joinable roles shouldn't have ***/
String[] prohibitPermissionForJoinerRole = ServerConfigurationService.getStrings("siteinfo.prohibited_permission_for_joiner_role");
if (prohibitPermissionForJoinerRole == null) {
prohibitPermissionForJoinerRole = new String[]{"site.upd"};
}
if (realmId != null)
{
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
// get all roles that allows at least one permission in the list
Set<String> permissionAllowedRoleIds = new HashSet<String>();
for(String permission:prohibitPermissionForJoinerRole)
{
permissionAllowedRoleIds.addAll(realm.getRolesIsAllowed(permission));
}
// bjones86 - SAK-23257
List<Role> allowedRoles = null;
Set<String> restrictedRoles = null;
if (null == state.getAttribute(STATE_SITE_INSTANCE_ID)) {
restrictedRoles = SiteParticipantHelper.getRestrictedRoles(state.getAttribute(STATE_SITE_TYPE ).toString());
}
else {
allowedRoles = SiteParticipantHelper.getAllowedRoles(siteType, getRoles(state));
}
for(Role role:realm.getRoles())
{
if (permissionAllowedRoleIds == null
|| permissionAllowedRoleIds!= null && !permissionAllowedRoleIds.contains(role.getId()))
{
// bjones86 - SAK-23257
if (allowedRoles != null && allowedRoles.contains(role)) {
roles.add(role);
}
else if (restrictedRoles != null &&
(!restrictedRoles.contains(role.getId()) || !restrictedRoles.contains(role.getId().toLowerCase()))) {
roles.add(role);
}
}
}
Collections.sort(roles);
} catch (GroupNotDefinedException e) {
M_log.warn( this + ".getRoles: IdUnusedException " + realmId, e);
}
}
return roles;
} // getRolesWithoutPermission
private void addSynopticTool(SitePage page, String toolId,
String toolTitle, String layoutHint, int position) {
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
// Add synoptic announcements tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool(toolId);
tool.setTool(toolId, reg);
tool.setTitle(toolTitle);
tool.setLayoutHints(layoutHint);
// count how many synoptic tools in the second/right column
int totalSynopticTools = 0;
for (ToolConfiguration t : page.getTools())
{
if (t.getToolId() != null && SYNOPTIC_TOOL_ID_MAP.containsKey(t.getToolId()))
{
totalSynopticTools++;
}
}
// now move the newly added synoptic tool to proper position
for (int i=0; i< (totalSynopticTools-position-1);i++)
{
tool.moveUp();
}
}
private void saveFeatures(ParameterParser params, SessionState state, Site site) {
String siteType = checkNullSiteType(state, site.getType(), site.getId());
// get the list of Worksite Setup configured pages
List wSetupPageList = state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST)!=null?(List) state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST):new Vector();
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
WorksiteSetupPage wSetupHome = new WorksiteSetupPage();
List pageList = new Vector();
// declare some flags used in making decisions about Home, whether to
// add, remove, or do nothing
boolean hasHome = false;
String homePageId = null;
boolean homeInWSetupPageList = false;
List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
boolean hasEmail = false;
boolean hasSiteInfo = false;
// tools to be imported from other sites?
Hashtable importTools = null;
if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) {
importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);
}
// Home tool chosen?
if (chosenList.contains(TOOL_ID_HOME)) {
// add home tool later
hasHome = true;
}
// order the id list
chosenList = orderToolIds(state, siteType, chosenList, false);
// Special case - Worksite Setup Home comes from a hardcoded checkbox on
// the vm template rather than toolRegistrationList
// see if Home was chosen
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String choice = (String) j.next();
if ("sakai.mailbox".equals(choice)) {
hasEmail = true;
String alias = StringUtils.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
String channelReference = mailArchiveChannelReference(site.getId());
if (alias != null) {
if (!Validator.checkEmailLocal(alias)) {
addAlert(state, rb.getString("java.theemail"));
} else if (!AliasService.allowSetAlias(alias, channelReference )) {
addAlert(state, rb.getString("java.addalias"));
} else {
try {
// first, clear any alias set to this channel
AliasService.removeTargetAliases(channelReference); // check
// to
// see
// whether
// the
// alias
// has
// been
// used
try {
String target = AliasService.getTarget(alias);
boolean targetsThisSite = site.getReference().equals(target);
if (!(targetsThisSite)) {
addAlert(state, rb.getString("java.emailinuse") + " ");
}
} catch (IdUnusedException ee) {
try {
AliasService.setAlias(alias,
channelReference);
} catch (IdUsedException exception) {
} catch (IdInvalidException exception) {
} catch (PermissionException exception) {
}
}
} catch (PermissionException exception) {
}
}
}
}else if (choice.equals(TOOL_ID_SITEINFO)) {
hasSiteInfo = true;
}
}
// see if Home and/or Help in the wSetupPageList (can just check title
// here, because we checked patterns before adding to the list)
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
wSetupPage = (WorksiteSetupPage) i.next();
if (isHomePage(site.getPage(wSetupPage.getPageId()))) {
homeInWSetupPageList = true;
homePageId = wSetupPage.getPageId();
break;
}
}
if (hasHome) {
SitePage page = site.getPage(homePageId);
if (!homeInWSetupPageList) {
// if Home is chosen and Home is not in wSetupPageList, add Home
// to site and wSetupPageList
page = site.addPage();
page.setTitle(rb.getString("java.home"));
wSetupHome.pageId = page.getId();
wSetupHome.pageTitle = page.getTitle();
wSetupHome.toolId = TOOL_ID_HOME;
wSetupPageList.add(wSetupHome);
}
// the list tools on the home page
List<ToolConfiguration> toolList = page.getTools();
// get tool id set for Home page from configuration
List<String> homeToolIds = getHomeToolIds(state, !homeInWSetupPageList, page);
// count
int nonSynopticToolIndex=0, synopticToolIndex = 0;
for (String homeToolId: homeToolIds)
{
if (!SYNOPTIC_TOOL_ID_MAP.containsKey(homeToolId))
{
if (!pageHasToolId(toolList, homeToolId))
{
// not a synoptic tool and is not in Home page yet, just add it
Tool reg = ToolManager.getTool(homeToolId);
if (reg != null)
{
ToolConfiguration tool = page.addTool();
tool.setTool(homeToolId, reg);
tool.setTitle(reg.getTitle() != null?reg.getTitle():"");
tool.setLayoutHints("0," + nonSynopticToolIndex++);
}
}
}
else
{
// synoptic tool
List<String> parentToolList = (List<String>) SYNOPTIC_TOOL_ID_MAP.get(homeToolId);
List chosenListClone = new Vector();
// chosenlist may have things like bcf89cd4-fa3a-4dda-80bd-ed0b89981ce7sakai.chat
// get list of the actual tool names
List<String>chosenOrigToolList = new ArrayList<String>();
for (String chosenTool: (List<String>)chosenList)
chosenOrigToolList.add(findOriginalToolId(state, chosenTool));
chosenListClone.addAll(chosenOrigToolList);
boolean hasAnyParentToolId = chosenListClone.removeAll(parentToolList);
//first check whether the parent tool is available in site but its parent tool is no longer selected
if (pageHasToolId(toolList, homeToolId))
{
if (!hasAnyParentToolId && !SiteService.isUserSite(site.getId()))
{
for (ListIterator iToolList = toolList.listIterator(); iToolList.hasNext();)
{
ToolConfiguration tConf= (ToolConfiguration) iToolList.next();
// avoid NPE when the tool definition is missing
if (tConf.getTool() != null && homeToolId.equals(tConf.getTool().getId()))
{
page.removeTool((ToolConfiguration) tConf);
break;
}
}
}
else
{
synopticToolIndex++;
}
}
// then add those synoptic tools which wasn't there before
if (!pageHasToolId(toolList, homeToolId) && hasAnyParentToolId)
{
try
{
// use value from map to find an internationalized tool title
String toolTitleText = rb.getString(SYNOPTIC_TOOL_TITLE_MAP.get(homeToolId));
addSynopticTool(page, homeToolId, toolTitleText, synopticToolIndex + ",1", synopticToolIndex++);
} catch (Exception e) {
M_log.warn(this + ".saveFeatures addSynotpicTool: " + e.getMessage() + " site id = " + site.getId() + " tool = " + homeToolId, e);
}
}
}
}
if (page.getTools().size() == 1)
{
// only use one column layout
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
// mark this page as Home page inside its property
if (page.getProperties().getProperty(SitePage.IS_HOME_PAGE) == null)
{
page.getPropertiesEdit().addProperty(SitePage.IS_HOME_PAGE, Boolean.TRUE.toString());
}
} // add Home
// if Home is in wSetupPageList and not chosen, remove Home feature from
// wSetupPageList and site
if (!hasHome && homeInWSetupPageList) {
// remove Home from wSetupPageList
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
SitePage sitePage = site.getPage(comparePage.getPageId());
if (sitePage != null && isHomePage(sitePage)) {
// remove the Home page
site.removePage(sitePage);
wSetupPageList.remove(comparePage);
break;
}
}
}
// declare flags used in making decisions about whether to add, remove,
// or do nothing
boolean inChosenList;
boolean inWSetupPageList;
Set categories = new HashSet();
// UMICH 1035
categories.add(siteType);
categories.add(SiteTypeUtil.getTargetSiteType(siteType));
Set toolRegistrationSet = ToolManager.findTools(categories, null);
// first looking for any tool for removal
Vector removePageIds = new Vector();
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page id + tool id for multiple tool instances
if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
inChosenList = false;
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
if (pageToolId.equals(toolId)) {
inChosenList = true;
}
}
// exclude the Home page if there is any
if (!inChosenList && !(homePageId != null && wSetupPage.getPageId().equals(homePageId))) {
removePageIds.add(wSetupPage.getPageId());
}
}
for (int i = 0; i < removePageIds.size(); i++) {
// if the tool exists in the wSetupPageList, remove it from the site
String removeId = (String) removePageIds.get(i);
SitePage sitePage = site.getPage(removeId);
site.removePage(sitePage);
// and remove it from wSetupPageList
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
if (!wSetupPage.getPageId().equals(removeId)) {
wSetupPage = null;
}
}
if (wSetupPage != null) {
wSetupPageList.remove(wSetupPage);
}
}
// then looking for any tool to add
for (ListIterator j = orderToolIds(state, siteType, chosenList, false)
.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
boolean multiAllowed = isMultipleInstancesAllowed(findOriginalToolId(state, toolId));
// exclude Home tool
if (!toolId.equals(TOOL_ID_HOME))
{
// Is the tool in the wSetupPageList?
inWSetupPageList = false;
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page Id + toolId for multiple tool instances
if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
if (pageToolId.equals(toolId)) {
inWSetupPageList = true;
// but for tool of multiple instances, need to change the title
if (multiAllowed) {
SitePage pEdit = (SitePage) site
.getPage(wSetupPage.pageId);
pEdit.setTitle((String) multipleToolIdTitleMap.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) jTool
.next();
String tId = tool.getTool().getId();
if (isMultipleInstancesAllowed(findOriginalToolId(state, tId))) {
// set tool title
tool.setTitle((String) multipleToolIdTitleMap.get(toolId));
// save tool configuration
saveMultipleToolConfiguration(state, tool, toolId);
}
}
}
}
}
if (inWSetupPageList) {
// if the tool already in the list, do nothing so to save the
// option settings
} else {
// if in chosen list but not in wSetupPageList, add it to the
// site (one tool on a page)
Tool toolRegFound = null;
for (Iterator i = toolRegistrationSet.iterator(); i.hasNext();) {
Tool toolReg = (Tool) i.next();
String toolRegId = toolReg.getId();
if (toolId.equals(toolRegId)) {
toolRegFound = toolReg;
break;
}
else if (multiAllowed && toolId.startsWith(toolRegId))
{
try
{
// in case of adding multiple tools, tool id is of format ORIGINAL_TOOL_ID + INDEX_NUMBER
Integer.parseInt(toolId.replace(toolRegId, ""));
toolRegFound = toolReg;
break;
}
catch (Exception parseException)
{
// ignore parse exception
}
}
}
if (toolRegFound != null) {
// we know such a tool, so add it
WorksiteSetupPage addPage = new WorksiteSetupPage();
SitePage page = site.addPage();
addPage.pageId = page.getId();
if (multiAllowed) {
// set tool title
page.setTitle((String) multipleToolIdTitleMap.get(toolId));
page.setTitleCustom(true);
} else {
// other tools with default title
page.setTitle(toolRegFound.getTitle());
}
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
// if so specified in the tool's registration file,
// configure the tool's page to open in a new window.
if ("true".equals(toolRegFound.getRegisteredConfig().getProperty("popup"))) {
page.setPopup(true);
}
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
addPage.toolId = toolId;
wSetupPageList.add(addPage);
// set tool title
if (multiAllowed) {
// set tool title
tool.setTitle((String) multipleToolIdTitleMap.get(toolId));
// save tool configuration
saveMultipleToolConfiguration(state, tool, toolId);
} else {
tool.setTitle(toolRegFound.getTitle());
}
}
}
}
} // for
// commit
commitSite(site);
site = refreshSiteObject(site);
// check the status of external lti tools
// 1. any lti tool to remove?
HashMap<String, Map<String, Object>> ltiTools = state.getAttribute(STATE_LTITOOL_SELECTED_LIST) != null?(HashMap<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_SELECTED_LIST):null;
Map<String, Map<String, Object>> oldLtiTools = state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) != null? (Map<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) : null;;
if (oldLtiTools != null)
{
// get all the old enalbed lti tools
for(String oldLtiToolsId : oldLtiTools.keySet())
{
if (ltiTools == null || !ltiTools.containsKey(oldLtiToolsId))
{
// the tool is not selectd now. Remove it from site
Map<String, Object> oldLtiToolValues = oldLtiTools.get(oldLtiToolsId);
Long contentKey = Long.valueOf(oldLtiToolValues.get("contentKey").toString());
m_ltiService.deleteContent(contentKey);
// refresh the site object
site = refreshSiteObject(site);
}
}
}
// 2. any lti tool to add?
if (ltiTools != null)
{
// then looking for any lti tool to add
for (Map.Entry<String, Map<String, Object>> ltiTool : ltiTools.entrySet()) {
String ltiToolId = ltiTool.getKey();
if (!oldLtiTools.containsKey(ltiToolId))
{
Map<String, Object> toolValues = ltiTool.getValue();
Properties reqProperties = (Properties) toolValues.get("reqProperties");
if (reqProperties==null) {
reqProperties = new Properties();
}
Object retval = m_ltiService.insertToolContent(null, ltiToolId, reqProperties, site.getId());
if (retval instanceof String)
{
// error inserting tool content
addAlert(state, (String) retval);
break;
}
else
{
// success inserting tool content
String pageTitle = reqProperties.getProperty("pagetitle");
retval = m_ltiService.insertToolSiteLink(((Long) retval).toString(), pageTitle, site.getId());
if (retval instanceof String)
{
addAlert(state, ((String) retval).substring(2));
break;
}
}
}
// refresh the site object
site = refreshSiteObject(site);
}
} // if
// reorder Home and Site Info only if the site has not been customized order before
if (!site.isCustomPageOrdered())
{
// the steps for moving page within the list
int moves = 0;
if (hasHome) {
SitePage homePage = null;
// Order tools - move Home to the top - first find it
pageList = site.getPages();
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
if (isHomePage(page))
{
homePage = page;
break;
}
}
}
if (homePage != null)
{
moves = pageList.indexOf(homePage);
for (int n = 0; n < moves; n++) {
homePage.moveUp();
}
}
}
// if Site Info is newly added, more it to the last
if (hasSiteInfo) {
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = { TOOL_ID_SITEINFO };
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); siteInfoPage == null
&& i.hasNext();) {
SitePage page = (SitePage) i.next();
int s = page.getTools(toolIds).size();
if (s > 0) {
siteInfoPage = page;
break;
}
}
if (siteInfoPage != null)
{
// move home from it's index to the first position
moves = pageList.indexOf(siteInfoPage);
for (int n = moves; n < pageList.size(); n++) {
siteInfoPage.moveDown();
}
}
}
}
}
// if there is no email tool chosen
if (!hasEmail) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
// commit
commitSite(site);
site = refreshSiteObject(site);
// import
importToolIntoSite(chosenList, importTools, site);
} // saveFeatures
/**
* refresh site object
* @param site
* @return
*/
private Site refreshSiteObject(Site site) {
// refresh the site object
try
{
site = SiteService.getSite(site.getId());
}
catch (Exception e)
{
// error getting site after tool modification
M_log.warn(this + " - cannot get site " + site.getId() + " after inserting lti tools");
}
return site;
}
/**
* Save configuration values for multiple tool instances
*/
private void saveMultipleToolConfiguration(SessionState state, ToolConfiguration tool, String toolId) {
// get the configuration of multiple tool instance
HashMap<String, HashMap<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(HashMap<String, HashMap<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap<String, HashMap<String, String>>();
// set tool attributes
HashMap<String, String> attributes = multipleToolConfiguration.get(toolId);
if (attributes != null)
{
for(Map.Entry<String, String> attributeEntry : attributes.entrySet())
{
String attribute = attributeEntry.getKey();
String attributeValue = attributeEntry.getValue();
// if we have a value
if (attributeValue != null)
{
// if this value is not the same as the tool's registered, set it in the placement
if (!attributeValue.equals(tool.getTool().getRegisteredConfig().getProperty(attribute)))
{
tool.getPlacementConfig().setProperty(attribute, attributeValue);
}
// otherwise clear it
else
{
tool.getPlacementConfig().remove(attribute);
}
}
// if no value
else
{
tool.getPlacementConfig().remove(attribute);
}
}
}
}
/**
* Is the tool stealthed or hidden
* @param toolId
* @return
*/
private boolean notStealthOrHiddenTool(String toolId) {
Tool tool = ToolManager.getTool(toolId);
Set<Tool> tools = ToolManager.findTools(Collections.emptySet(), null);
boolean result = tool != null && tools.contains(tool);
return result;
}
/**
* Is the siteType listed in the tool properties list of categories?
* @param siteType
* @param tool
* @return
* SAK 23808
*/
private boolean isSiteTypeInToolCategory(String siteType, Tool tool) {
Set<Tool> tools = ToolManager.findTools(Collections.emptySet(), null);
Set<String> categories = tool.getCategories();
Iterator<String> iterator = categories.iterator();
while(iterator.hasNext()) {
String nextCat = iterator.next();
if(nextCat.equals(siteType)) {
return true;
}
}
return false;
}
/**
* getFeatures gets features for a new site
*
*/
private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) {
List idsSelected = new Vector();
List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
// to reset the state variable of the multiple tool instances
Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet();
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// related to LTI Tool selection
Map<String, Map<String, Object>> existingLtiIds = state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) != null? (Map<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST):null;
HashMap<String, Map<String, Object>> ltiTools = (HashMap<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_LIST);
HashMap<String, Map<String, Object>> ltiSelectedTools = new HashMap<String, Map<String, Object>> ();
boolean goToToolConfigPage = false;
boolean homeSelected = false;
// lti tool selection
boolean ltiToolSelected = false;
// Add new pages and tools, if any
if (params.getStrings("selectedTools") == null && params.getStrings("selectedLtiTools") == null) {
addAlert(state, rb.getString("atleastonetool"));
} else {
List l = new ArrayList(Arrays.asList(params
.getStrings("selectedTools"))); // toolId's of chosen tools
for (int i = 0; i < l.size(); i++) {
String toolId = (String) l.get(i);
if (toolId.equals(TOOL_ID_HOME)) {
homeSelected = true;
if (!idsSelected.contains(toolId))
idsSelected.add(toolId);
}
else if (toolId.startsWith(LTITOOL_ID_PREFIX))
{
String ltiToolId = toolId.substring(LTITOOL_ID_PREFIX.length());
// whether there is any lti tool been selected
if (existingLtiIds == null)
{
ltiToolSelected = true;
}
else
{
if (!existingLtiIds.keySet().contains(ltiToolId))
{
// there are some new lti tool(s) selected
ltiToolSelected = true;
}
}
// add tool entry to list
ltiSelectedTools.put(ltiToolId, ltiTools.get(ltiToolId));
}
else
{
String originId = findOriginalToolId(state, toolId);
if (isMultipleInstancesAllowed(originId))
{
// if user is adding either EmailArchive tool, News tool
// or Web Content tool, go to the Customize page for the
// tool
if (!existTools.contains(toolId)) {
goToToolConfigPage = true;
if (!multipleToolIdSet.contains(toolId))
multipleToolIdSet.add(toolId);
if (!multipleToolIdTitleMap.containsKey(toolId))
{
// reset tool title if there is a different title config setting
String titleConfig = ServerConfigurationService.getString(CONFIG_TOOL_TITLE + originId);
if (titleConfig != null && titleConfig.length() > 0 )
{
multipleToolIdTitleMap.put(toolId, titleConfig);
}
else
{
multipleToolIdTitleMap.put(toolId, ToolManager.getTool(originId).getTitle());
}
}
}
}
else if ("sakai.mailbox".equals(toolId)) {
// get the email alias when an Email Archive tool
// has been selected
String alias = getSiteAlias(mailArchiveChannelReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID)));
if (alias != null) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, alias);
}
// go to the config page
if (!existTools.contains(toolId))
{
goToToolConfigPage = true;
}
}
if (!idsSelected.contains(toolId))
idsSelected.add(toolId);
}
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.valueOf(
homeSelected));
if (!ltiSelectedTools.isEmpty())
{
state.setAttribute(STATE_LTITOOL_SELECTED_LIST, ltiSelectedTools);
}
else
{
state.removeAttribute(STATE_LTITOOL_SELECTED_LIST);
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's
// in case of import
String importString = params.getString("import");
if (importString != null
&& importString.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
List importSites = new Vector();
if (params.getStrings("importSites") != null) {
importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
}
if (importSites.size() == 0) {
addAlert(state, rb.getString("java.toimport") + " ");
} else {
Hashtable sites = new Hashtable();
for (int index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
if (!sites.containsKey(s)) {
sites.put(s, new Vector());
}
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
// of
// ToolRegistration
// toolId's
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_IMPORT) != null) {
// go to import tool page
state.setAttribute(STATE_TEMPLATE_INDEX, "27");
} else if (goToToolConfigPage || ltiToolSelected) {
state.setAttribute(STATE_MULTIPLE_TOOL_INSTANCE_SELECTED, Boolean.valueOf(goToToolConfigPage));
// go to the configuration page for multiple instances of tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else {
// go to next page
state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex);
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
}
} // getFeatures
// import tool content into site
private void importToolIntoSite(List toolIds, Hashtable importTools,
Site site) {
if (importTools != null) {
Map transversalMap = new HashMap();
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++) {
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = m_contentHostingService
.getSiteCollection(fromSiteId);
String toSiteCollectionId = m_contentHostingService
.getSiteCollection(toSiteId);
Map<String,String> entityMap = transferCopyEntities(toolId, fromSiteCollectionId,
toSiteCollectionId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
resourcesImported = true;
}
}
}
// import other tools then
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
if(SITE_INFO_TOOL_ID.equals(toolId)){
copySiteInformation(fromSiteId, site);
}else{
Map<String,String> entityMap = transferCopyEntities(toolId, fromSiteId, toSiteId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
resourcesImported = true;
}
}
}
}
//update entity references
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if(importTools.containsKey(toolId)){
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String toSiteId = site.getId();
updateEntityReferences(toolId, toSiteId, transversalMap, site);
}
}
}
}
} // importToolIntoSite
private void importToolIntoSiteMigrate(List toolIds, Hashtable importTools,
Site site) {
if (importTools != null) {
Map transversalMap = new HashMap();
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++) {
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = m_contentHostingService
.getSiteCollection(fromSiteId);
String toSiteCollectionId = m_contentHostingService
.getSiteCollection(toSiteId);
Map<String,String> entityMap = transferCopyEntitiesMigrate(toolId, fromSiteCollectionId,
toSiteCollectionId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
resourcesImported = true;
}
}
}
// import other tools then
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
if(SITE_INFO_TOOL_ID.equals(toolId)){
copySiteInformation(fromSiteId, site);
}else{
Map<String,String> entityMap = transferCopyEntitiesMigrate(toolId, fromSiteId, toSiteId);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
}
}
}
}
//update entity references
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if(importTools.containsKey(toolId)){
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String toSiteId = site.getId();
updateEntityReferences(toolId, toSiteId, transversalMap, site);
}
}
}
}
} // importToolIntoSiteMigrate
private void copySiteInformation(String fromSiteId, Site toSite){
try {
Site fromSite = SiteService.getSite(fromSiteId);
//we must get the new site again b/c some tools (lesson builder) can make changes to the site structure (i.e. add pages).
Site editToSite = SiteService.getSite(toSite.getId());
editToSite.setDescription(fromSite.getDescription());
editToSite.setInfoUrl(fromSite.getInfoUrl());
commitSite(editToSite);
toSite = editToSite;
} catch (IdUnusedException e) {
}
}
public void saveSiteStatus(SessionState state, boolean published) {
Site site = getStateSite(state);
site.setPublished(published);
} // saveSiteStatus
public void commitSite(Site site, boolean published) {
site.setPublished(published);
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
} // commitSite
public void commitSite(Site site) {
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
}// commitSite
private String getSetupRequestEmailAddress() {
String from = ServerConfigurationService.getString("setup.request",
null);
if (from == null) {
from = "postmaster@".concat(ServerConfigurationService
.getServerName());
M_log.warn(this + " - no 'setup.request' in configuration, using: "+ from);
}
return from;
}
/**
* get the setup.request.replyTo setting. If missing, use setup.request setting.
* @return
*/
private String getSetupRequestReplyToEmailAddress() {
String rv = ServerConfigurationService.getString("setup.request.replyTo", null);
if (rv == null) {
rv = getSetupRequestEmailAddress();
}
return rv;
}
/**
* addNewSite is called when the site has enough information to create a new
* site
*
*/
private void addNewSite(ParameterParser params, SessionState state) {
if (getStateSite(state) != null) {
// There is a Site in state already, so use it rather than creating
// a new Site
return;
}
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
String id = StringUtils.trimToNull(siteInfo.getSiteId());
if (id == null) {
// get id
id = IdManager.createUuid();
siteInfo.site_id = id;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
Site site = null;
// if create based on template,
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
if (templateSite != null) {
site = SiteService.addSite(id, templateSite);
// set site type
site.setType(SiteTypeUtil.getTargetSiteType(templateSite.getType()));
} else {
site = SiteService.addSite(id, siteInfo.site_type);
}
// add current user as the maintainer
site.addMember(UserDirectoryService.getCurrentUser().getId(), site.getMaintainRole(), true, false);
String title = StringUtils.trimToNull(siteInfo.title);
String description = siteInfo.description;
setAppearance(state, site, siteInfo.iconUrl);
site.setDescription(description);
if (title != null) {
site.setTitle(title);
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
/// site language information
String locale_string = (String) state.getAttribute("locale_string");
rp.addProperty(PROP_SITE_LANGUAGE, locale_string);
site.setShortDescription(siteInfo.short_description);
site.setPubView(siteInfo.include);
site.setJoinable(siteInfo.joinable);
site.setJoinerRole(siteInfo.joinerRole);
site.setPublished(siteInfo.published);
// site contact information
rp.addProperty(Site.PROP_SITE_CONTACT_NAME,
siteInfo.site_contact_name);
rp.addProperty(Site.PROP_SITE_CONTACT_EMAIL,
siteInfo.site_contact_email);
// SAK-22790 add props from SiteInfo object
rp.addAll(siteInfo.getProperties());
// SAK-23491 add template_used property
if (templateSite != null) {
// if the site was created from template
rp.addProperty(TEMPLATE_USED, templateSite.getId());
}
// bjones86 - SAK-24423 - update site properties for joinable site settings
JoinableSiteSettings.updateSitePropertiesFromSiteInfoOnAddNewSite( siteInfo, rp );
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
// commit newly added site in order to enable related realm
commitSite(site);
} catch (IdUsedException e) {
addAlert(state, rb.getFormattedMessage("java.sitewithid.exists", new Object[]{id}));
M_log.warn(this + ".addNewSite: " + rb.getFormattedMessage("java.sitewithid.exists", new Object[]{id}), e);
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex"));
return;
} catch (IdInvalidException e) {
addAlert(state, rb.getFormattedMessage("java.sitewithid.notvalid", new Object[]{id}));
M_log.warn(this + ".addNewSite: " + rb.getFormattedMessage("java.sitewithid.notvalid", new Object[]{id}), e);
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex"));
return;
} catch (PermissionException e) {
addAlert(state, rb.getFormattedMessage("java.permission", new Object[]{id}));
M_log.warn(this + ".addNewSite: " + rb.getFormattedMessage("java.permission", new Object[]{id}), e);
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex"));
return;
}
}
} // addNewSite
/**
* created based on setTermListForContext - Denny
* @param context
* @param state
*/
private void setTemplateListForContext(Context context, SessionState state)
{
List<Site> templateSites = new ArrayList<Site>();
boolean allowedForTemplateSites = true;
// system wide setting for disable site creation based on template sites
if (ServerConfigurationService.getString("wsetup.enableSiteTemplate", "true").equalsIgnoreCase(Boolean.FALSE.toString()))
{
allowedForTemplateSites = false;
}
else
{
if (ServerConfigurationService.getStrings("wsetup.enableSiteTemplate.userType") != null) {
List<String> userTypes = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("wsetup.enableSiteTemplate.userType")));
if (userTypes != null && userTypes.size() > 0)
{
User u = UserDirectoryService.getCurrentUser();
if (!(u != null && (SecurityService.isSuperUser() || userTypes.contains(u.getType()))))
{
// be an admin type user or any type of users defined in the configuration
allowedForTemplateSites = false;
}
}
}
}
if (allowedForTemplateSites)
{
// We're searching for template sites and these are marked by a property
// called 'template' with a value of true
Map templateCriteria = new HashMap(1);
templateCriteria.put("template", "true");
templateSites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ANY, null, null, templateCriteria, SortType.TITLE_ASC, null);
}
// If no templates could be found, stick an empty list in the context
if(templateSites == null || templateSites.size() <= 0)
templateSites = new ArrayList();
//SAK25400 sort templates by type
context.put("templateSites",sortTemplateSitesByType(templateSites));
context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX));
} // setTemplateListForContext
/**
* %%% legacy properties, to be cleaned up
*
*/
private void sitePropertiesIntoState(SessionState state) {
try {
Site site = getStateSite(state);
SiteInfo siteInfo = new SiteInfo();
if (site != null)
{
ResourceProperties siteProperties = site.getProperties();
// set from site attributes
siteInfo.title = site.getTitle();
siteInfo.description = site.getDescription();
siteInfo.iconUrl = site.getIconUrl();
siteInfo.infoUrl = site.getInfoUrl();
siteInfo.joinable = site.isJoinable();
siteInfo.joinerRole = site.getJoinerRole();
siteInfo.published = site.isPublished();
siteInfo.include = site.isPubView();
siteInfo.short_description = site.getShortDescription();
siteInfo.site_type = site.getType();
// term information
String term = siteProperties.getProperty(Site.PROP_SITE_TERM);
if (term != null) {
siteInfo.term = term;
}
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromSiteProperties( siteProperties, siteInfo );
// site contact information
String contactName = siteProperties.getProperty(Site.PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(Site.PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
if (u != null)
{
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
}
if (contactName != null) {
siteInfo.site_contact_name = contactName;
}
if (contactEmail != null) {
siteInfo.site_contact_email = contactEmail;
}
state.setAttribute(FORM_SITEINFO_ALIASES, getSiteReferenceAliasIds(site));
}
siteInfo.additional = "";
state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type);
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute(FORM_SITEINFO_URL_BASE, getSiteBaseUrl());
} catch (Exception e) {
M_log.warn(this + ".sitePropertiesIntoState: " + e.getMessage(), e);
}
} // sitePropertiesIntoState
/**
* pageMatchesPattern returns tool id if a SitePage matches a WorkSite Setuppattern
* otherwise return null
* @param state
* @param page
* @return
*/
private List<String> pageMatchesPattern(SessionState state, SitePage page) {
List<String> rv = new Vector<String>();
List pageToolList = page.getTools();
// if no tools on the page, return false
if (pageToolList == null) {
return null;
}
// don't compare tool properties, which may be changed using Options
List toolList = new Vector();
int count = pageToolList.size();
// check Home tool first
if (isHomePage(page))
{
rv.add(TOOL_ID_HOME);
rv.add(TOOL_ID_HOME);
return rv;
}
// check whether the page has Site Info tool
boolean foundSiteInfoTool = false;
for (int i = 0; i < count; i++)
{
ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList.get(i);
if (toolConfiguration.getToolId().equals(TOOL_ID_SITEINFO))
{
foundSiteInfoTool = true;
break;
}
}
if (foundSiteInfoTool)
{
rv.add(TOOL_ID_SITEINFO);
rv.add(TOOL_ID_SITEINFO);
return rv;
}
// Other than Home, Site Info page, no other page is allowed to have more than one tool within. Otherwise, WSetup/Site Info tool won't handle it
if (count != 1)
{
return null;
}
// if the page layout doesn't match, return false
else if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return null;
}
else
{
// for the case where the page has one tool
ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList.get(0);
toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
if (pageToolList != null && pageToolList.size() != 0) {
// if tool attributes don't match, return false
String match = null;
for (ListIterator i = toolList.listIterator(); i.hasNext();) {
MyTool tool = (MyTool) i.next();
if (toolConfiguration.getTitle() != null) {
if (toolConfiguration.getTool() != null
&& originalToolId(toolConfiguration.getTool().getId(), tool.getId()) != null) {
match = tool.getId();
rv.add(match);
rv.add(toolConfiguration.getId());
}
}
}
// no tool registeration is found (tool is not editable within Site Info tool), set return value to be null
if (match == null)
{
rv = null;
}
}
}
return rv;
} // pageMatchesPattern
/**
* check whether the page tool list contains certain toolId
* @param pageToolList
* @param toolId
* @return
*/
private boolean pageHasToolId(List pageToolList, String toolId) {
for (Iterator iPageToolList = pageToolList.iterator(); iPageToolList.hasNext();)
{
ToolConfiguration toolConfiguration = (ToolConfiguration) iPageToolList.next();
Tool t = toolConfiguration.getTool();
if (t != null && toolId.equals(toolConfiguration.getTool().getId()))
{
return true;
}
}
return false;
}
/**
* siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list
* of pages and tools that match WorkSite Setup configurations into state
*/
private void siteToolsIntoState(SessionState state) {
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
Map<String, Map<String, String>> multipleToolIdAttributeMap = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null? (Map<String, Map<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap();
String wSetupTool = NULL_STRING;
String wSetupToolId = NULL_STRING;
List wSetupPageList = new Vector();
Site site = getStateSite(state, true);
List pageList = site.getPages();
// Put up tool lists filtered by category
String type = checkNullSiteType(state, site.getType(), site.getId());
if (type == null) {
M_log.warn(this + ": - unknown STATE_SITE_TYPE");
} else {
state.setAttribute(STATE_SITE_TYPE, type);
}
// set tool registration list
setToolRegistrationList(state, type);
multipleToolIdAttributeMap = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null? (Map<String, Map<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap();
// for the selected tools
boolean check_home = false;
Vector idSelected = new Vector();
HashMap<String, String> toolTitles = new HashMap<String, String>();
List toolRegList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// populate the tool title list
if (toolRegList != null)
{
for (Object t: toolRegList) {
toolTitles.put(((MyTool) t).getId(),((MyTool) t).getTitle());
}
}
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
// reset
wSetupTool = null;
wSetupToolId = null;
SitePage page = (SitePage) i.next();
// collect the pages consistent with Worksite Setup patterns
List<String> pmList = pageMatchesPattern(state, page);
if (pmList != null)
{
wSetupTool = pmList.get(0);
wSetupToolId = pmList.get(1);
}
if (wSetupTool != null) {
if (isHomePage(page))
{
check_home = true;
toolTitles.put("home", page.getTitle());
}
else
{
if (isMultipleInstancesAllowed(findOriginalToolId(state, wSetupTool)))
{
String mId = page.getId() + wSetupTool;
idSelected.add(mId);
toolTitles.put(mId, page.getTitle());
multipleToolIdTitleMap.put(mId, page.getTitle());
// get the configuration for multiple instance
HashMap<String, String> toolConfigurations = getMultiToolConfiguration(wSetupTool, page.getTool(wSetupToolId));
multipleToolIdAttributeMap.put(mId, toolConfigurations);
MyTool newTool = new MyTool();
String titleConfig = ServerConfigurationService.getString(CONFIG_TOOL_TITLE + mId);
if (titleConfig != null && titleConfig.length() > 0)
{
// check whether there is a different title setting
newTool.title = titleConfig;
}
else
{
// use the default
newTool.title = ToolManager.getTool(wSetupTool).getTitle();
}
newTool.id = mId;
newTool.selected = false;
boolean hasThisMultipleTool = false;
int j = 0;
for (; j < toolRegList.size() && !hasThisMultipleTool; j++) {
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals(wSetupTool)) {
hasThisMultipleTool = true;
newTool.description = t.getDescription();
}
}
if (hasThisMultipleTool) {
toolRegList.add(j - 1, newTool);
} else {
toolRegList.add(newTool);
}
}
else
{
idSelected.add(wSetupTool);
toolTitles.put(wSetupTool, page.getTitle());
}
}
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
wSetupPage.pageId = page.getId();
wSetupPage.pageTitle = page.getTitle();
wSetupPage.toolId = wSetupTool;
wSetupPageList.add(wSetupPage);
}
}
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolIdAttributeMap);
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.valueOf(check_home));
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
state.setAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST, toolTitles);
// of
// ToolRegistration
// toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST,idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home));
state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList);
} // siteToolsIntoState
/**
* adjust site type
* @param state
* @param site
* @return
*/
private String checkNullSiteType(SessionState state, String type, String siteId) {
if (type == null) {
if (siteId != null && SiteService.isUserSite(siteId)) {
type = "myworkspace";
} else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
// for those sites without type, use the tool set for default
// site type
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
return type;
}
/**
* reset the state variables used in edit tools mode
*
* @state The SessionState object
*/
private void removeEditToolState(SessionState state) {
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
state.removeAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION);
state.removeAttribute(STATE_TOOL_REGISTRATION_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
MathJaxEnabler.removeMathJaxToolsAttributeFromState(state); // SAK-22384
}
private List orderToolIds(SessionState state, String type, List<String> toolIdList, boolean synoptic) {
List rv = new Vector();
// look for null site type
if (type == null && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
if (type != null && toolIdList != null) {
List<String> orderedToolIds = ServerConfigurationService.getToolOrder(SiteTypeUtil.getTargetSiteType(type)); // UMICH-1035
for (String tool_id : orderedToolIds) {
for (String toolId : toolIdList) {
String rToolId = originalToolId(toolId, tool_id);
if (rToolId != null)
{
rv.add(toolId);
break;
}
else
{
List<String> parentToolList = (List<String>) SYNOPTIC_TOOL_ID_MAP.get(toolId);
if (parentToolList != null && parentToolList.contains(tool_id))
{
rv.add(toolId);
break;
}
}
}
}
}
// add those toolids without specified order
if (toolIdList != null)
{
for (String toolId : toolIdList) {
if (!rv.contains(toolId)) {
rv.add(toolId);
}
}
}
return rv;
} // orderToolIds
private void setupFormNamesAndConstants(SessionState state) {
TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear()
+ ", " + UserDirectoryService.getCurrentUser().getDisplayName()
+ ". All Rights Reserved. ";
state.setAttribute(STATE_MY_COPYRIGHT, mycopyright);
state.setAttribute(STATE_SITE_INSTANCE_ID, null);
state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString());
SiteInfo siteInfo = new SiteInfo();
Participant participant = new Participant();
participant.name = NULL_STRING;
participant.uniqname = NULL_STRING;
participant.active = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute("form_participantToAdd", participant);
state.setAttribute(FORM_ADDITIONAL, NULL_STRING);
// legacy
state.setAttribute(FORM_HONORIFIC, "0");
state.setAttribute(FORM_REUSE, "0");
state.setAttribute(FORM_RELATED_CLASS, "0");
state.setAttribute(FORM_RELATED_PROJECT, "0");
state.setAttribute(FORM_INSTITUTION, "0");
// sundry form variables
state.setAttribute(FORM_PHONE, "");
state.setAttribute(FORM_EMAIL, "");
state.setAttribute(FORM_SUBJECT, "");
state.setAttribute(FORM_DESCRIPTION, "");
state.setAttribute(FORM_TITLE, "");
state.setAttribute(FORM_NAME, "");
state.setAttribute(FORM_SHORT_DESCRIPTION, "");
} // setupFormNamesAndConstants
/**
* setupSkins
*
*/
private void setupIcons(SessionState state) {
List icons = new Vector();
String[] iconNames = {"*default*"};
String[] iconUrls = {""};
String[] iconSkins = {""};
// get icon information
if (ServerConfigurationService.getStrings("iconNames") != null) {
iconNames = ServerConfigurationService.getStrings("iconNames");
}
if (ServerConfigurationService.getStrings("iconUrls") != null) {
iconUrls = ServerConfigurationService.getStrings("iconUrls");
}
if (ServerConfigurationService.getStrings("iconSkins") != null) {
iconSkins = ServerConfigurationService.getStrings("iconSkins");
}
if ((iconNames != null) && (iconUrls != null) && (iconSkins != null)
&& (iconNames.length == iconUrls.length)
&& (iconNames.length == iconSkins.length)) {
for (int i = 0; i < iconNames.length; i++) {
MyIcon s = new MyIcon(StringUtils.trimToNull((String) iconNames[i]),
StringUtils.trimToNull((String) iconUrls[i]), StringUtils.trimToNull((String) iconSkins[i]));
icons.add(s);
}
}
state.setAttribute(STATE_ICONS, icons);
}
private void setAppearance(SessionState state, Site edit, String iconUrl) {
// set the icon
iconUrl = StringUtils.trimToNull(iconUrl);
//SAK-18721 convert spaces in URL to %20
iconUrl = StringUtils.replace(iconUrl, " ", "%20");
edit.setIconUrl(iconUrl);
// if this icon is in the config appearance list, find a skin to set
List icons = (List) state.getAttribute(STATE_ICONS);
for (Iterator i = icons.iterator(); i.hasNext();) {
Object icon = (Object) i.next();
if (icon instanceof MyIcon && StringUtils.equals(((MyIcon) icon).getUrl(), iconUrl)) {
edit.setSkin(((MyIcon) icon).getSkin());
return;
}
}
}
/**
* A dispatch funtion when selecting course features
*/
public void doAdd_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// to reset the state variable of the multiple tool instances
Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet();
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// editing existing site or creating a new one?
Site site = getStateSite(state);
// dispatch
if (option.startsWith("add_")) {
// this could be format of originalToolId plus number of multiplication
String addToolId = option.substring("add_".length(), option.length());
// find the original tool id
String originToolId = findOriginalToolId(state, addToolId);
if (originToolId != null)
{
Tool tool = ToolManager.getTool(originToolId);
if (tool != null)
{
insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId)));
updateSelectedToolList(state, params, false);
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
}
}else if (option.startsWith("remove_")) {
// this could be format of originalToolId plus number of multiplication
String removeToolId = option.substring("remove_".length(), option.length());
// find the original tool id
String originToolId = findOriginalToolId(state, removeToolId);
if (originToolId != null)
{
Tool tool = ToolManager.getTool(originToolId);
if (tool != null)
{
updateSelectedToolList(state, params, false);
removeTool(state, removeToolId, originToolId);
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
}
} else if (option.equalsIgnoreCase("import")) {
// import or not
updateSelectedToolList(state, params, false);
String importSites = params.getString("import");
if (importSites != null
&& importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
} else if (option.equalsIgnoreCase("continueENW")) {
// continue in multiple tools page
updateSelectedToolList(state, params, false);
doContinue(data);
} else if (option.equalsIgnoreCase("continue")) {
// continue
MathJaxEnabler.applyToolSettingsToState(state, site, params); // SAK-22384
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
// back
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
if (site == null)
{
// cancel
doCancel_create(data);
}
else
{
// cancel editing
doCancel(data);
}
}
} // doAdd_features
/**
* update the selected tool list
*
* @param params
* The ParameterParser object
* @param updateConfigVariables
* Need to update configuration variables
*/
private void updateSelectedToolList(SessionState state, ParameterParser params, boolean updateConfigVariables) {
if (params.getStrings("selectedTools") != null)
{
// read entries for multiple tool customization
List selectedTools = new ArrayList(Arrays.asList(params.getStrings("selectedTools")));
HashMap<String, String> toolTitles = state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST) != null ? (HashMap<String, String>) state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST) : new HashMap<String, String>();
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
HashMap<String, HashMap<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(HashMap<String, HashMap<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap<String, HashMap<String, String>>();
Vector<String> idSelected = (Vector<String>) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
boolean has_home = false;
String emailId = state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null?(String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS):null;
for (int i = 0; i < selectedTools.size(); i++)
{
String id = (String) selectedTools.get(i);
if (id.equalsIgnoreCase(TOOL_ID_HOME)) {
has_home = true;
} else if (id.equalsIgnoreCase("sakai.mailbox")) {
// read email id
emailId = StringUtils.trimToNull(params.getString("emailId"));
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId);
if ( updateConfigVariables ) {
// if Email archive tool is selected, check the email alias
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
String channelReference = mailArchiveChannelReference(siteId);
if (emailId == null) {
addAlert(state, rb.getString("java.emailarchive") + " ");
} else {
if (!Validator.checkEmailLocal(emailId)) {
addAlert(state, rb.getString("java.theemail"));
} else if (!AliasService.allowSetAlias(emailId, channelReference )) {
addAlert(state, rb.getString("java.addalias"));
} else {
// check to see whether the alias has been used by
// other sites
try {
String target = AliasService.getTarget(emailId);
if (target != null) {
if (siteId != null) {
if (!target.equals(channelReference)) {
// the email alias is not used by
// current site
addAlert(state, rb.getString("java.emailinuse") + " ");
}
} else {
addAlert(state, rb.getString("java.emailinuse") + " ");
}
}
} catch (IdUnusedException ee) {
}
}
}
}
}
else if (isMultipleInstancesAllowed(findOriginalToolId(state, id)) && (idSelected != null && !idSelected.contains(id) || idSelected == null))
{
// newly added mutliple instances
String title = StringUtils.trimToNull(params.getString("title_" + id));
if (title != null)
{
// truncate the title to maxlength as defined
if (title.length() > MAX_TOOL_TITLE_LENGTH)
{
title = title.substring(0, MAX_TOOL_TITLE_LENGTH);
}
// save the titles entered
multipleToolIdTitleMap.put(id, title);
}
toolTitles.put(id, title);
// get the attribute input
HashMap<String, String> attributes = multipleToolConfiguration.get(id);
if (attributes == null)
{
// if missing, get the default setting for original id
attributes = multipleToolConfiguration.get(findOriginalToolId(state, id));
}
if (attributes != null)
{
for(Iterator<String> e = attributes.keySet().iterator(); e.hasNext();)
{
String attribute = e.next();
String attributeInput = StringUtils.trimToNull(params.getString(attribute + "_" + id));
if (attributeInput != null)
{
// save the attribute input if valid, otherwise generate alert
if ( FormattedText.validateURL(attributeInput) )
attributes.put(attribute, attributeInput);
else
addAlert(state, rb.getString("java.invurl"));
}
}
multipleToolConfiguration.put(id, attributes);
}
}
}
// update the state objects
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration);
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.valueOf(has_home));
state.setAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST, toolTitles);
}
// read in the input for external tool list
updateSelectedExternalToolList(state, params);
} // updateSelectedToolList
/**
* read in the input for external tool list
* @param state
* @param params
*/
private void updateSelectedExternalToolList(SessionState state,
ParameterParser params) {
// update the lti tool list
if (state.getAttribute(STATE_LTITOOL_SELECTED_LIST) != null)
{
Properties reqProps = params.getProperties();
// remember the reqProps may contain multiple lti inputs, so we need to differentiate those inputs and store one tool specific input into the map
HashMap<String, Map<String, Object>> ltiTools = (HashMap<String, Map<String, Object>>) state.getAttribute(STATE_LTITOOL_SELECTED_LIST);
for ( Map.Entry<String,Map<String, Object>> ltiToolEntry : ltiTools.entrySet())
{
String ltiToolId = ltiToolEntry.getKey();
Map<String, Object> ltiToolAttributes = ltiToolEntry.getValue();
String[] contentToolModel=m_ltiService.getContentModel(Long.valueOf(ltiToolId));
Properties reqForCurrentTool = new Properties();
// the input page contains attributes prefixed with lti tool id, need to look for those attribute inut values
for (int k=0; k< contentToolModel.length;k++)
{
// sample format of contentToolModel[k]:
// title:text:label=bl_content_title:required=true:maxlength=255
String contentToolModelAttribute = contentToolModel[k].substring(0, contentToolModel[k].indexOf(":"));
String k_contentToolModelAttribute = ltiToolId + "_" + contentToolModelAttribute;
if (reqProps.containsKey(k_contentToolModelAttribute))
{
reqForCurrentTool.put(contentToolModelAttribute, reqProps.get(k_contentToolModelAttribute));
}
}
// add the tool id field
reqForCurrentTool.put(LTIService.LTI_TOOL_ID, ltiToolId);
ltiToolAttributes.put("reqProperties", reqForCurrentTool);
// update the lti tool list
ltiTools.put(ltiToolId, ltiToolAttributes);
}
state.setAttribute(STATE_LTITOOL_SELECTED_LIST, ltiTools);
}
}
/**
* find the tool in the tool list and insert another tool instance to the list
* @param state
* @param toolId
* @param defaultTitle
* @param defaultDescription
* @param insertTimes
*/
private void insertTool(SessionState state, String toolId, String defaultTitle, String defaultDescription, int insertTimes) {
// the list of available tools
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
HashMap<String, String> toolTitles = state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST) != null ? (HashMap<String, String>) state.getAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST) : new HashMap<String, String>();
List oTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// get the attributes of multiple tool instances
HashMap<String, HashMap<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(HashMap<String, HashMap<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap<String, HashMap<String, String>>();
int toolListedTimes = 0;
// get the proper insert index for the whole tool list
int index = 0;
int insertIndex = 0;
while (index < toolList.size()) {
MyTool tListed = (MyTool) toolList.get(index);
if (tListed.getId().indexOf(toolId) != -1 && !oTools.contains(tListed.getId())) {
toolListedTimes++;
// update the insert index
insertIndex = index+1;
}
index++;
}
// get the proper insert index for the selected tool list
List toolSelected = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
index = 0;
int insertSelectedToolIndex = 0;
while (index < toolSelected.size()) {
String selectedId = (String) toolSelected.get(index);
if (selectedId.indexOf(toolId) != -1 ) {
// update the insert index
insertSelectedToolIndex = index+1;
}
index++;
}
// insert multiple tools
for (int i = 0; i < insertTimes; i++) {
toolSelected.add(insertSelectedToolIndex, toolId + toolListedTimes);
// We need to insert a specific tool entry only if all the specific
// tool entries have been selected
String newToolId = toolId + toolListedTimes;
MyTool newTool = new MyTool();
String titleConfig = ServerConfigurationService.getString(CONFIG_TOOL_TITLE + toolId);
if (titleConfig != null && titleConfig.length() > 0)
{
// check whether there is a different title setting
defaultTitle = titleConfig;
}
newTool.title = defaultTitle;
newTool.id = newToolId;
newTool.description = defaultDescription;
toolList.add(insertIndex, newTool);
toolListedTimes++;
// add title
multipleToolIdTitleMap.put(newToolId, defaultTitle);
toolTitles.put(newToolId, defaultTitle);
// get the attribute input
HashMap<String, String> attributes = multipleToolConfiguration.get(newToolId);
if (attributes == null)
{
// if missing, get the default setting for original id
attributes = getMultiToolConfiguration(toolId, null);
multipleToolConfiguration.put(newToolId, attributes);
}
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_TITLE_LIST, toolTitles);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
} // insertTool
/**
* find the tool in the tool list and remove the tool instance
* @param state
* @param toolId
* @param originalToolId
*/
private void removeTool(SessionState state, String toolId, String originalToolId) {
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// get the attributes of multiple tool instances
HashMap<String, HashMap<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(HashMap<String, HashMap<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new HashMap<String, HashMap<String, String>>();
// the selected tool list
List toolSelected = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// remove the tool from related state variables
toolSelected.remove(toolId);
// remove the tool from the title map
multipleToolIdTitleMap.remove(toolId);
// remove the tool from the configuration map
boolean found = false;
for (ListIterator i = toolList.listIterator(); i.hasNext() && !found;)
{
MyTool tool = (MyTool) i.next();
if (tool.getId().equals(toolId))
{
toolList.remove(tool);
found = true;
}
}
multipleToolConfiguration.remove(toolId);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
} // removeTool
/**
*
* set selected participant role Hashtable
*/
private void setSelectedParticipantRoles(SessionState state) {
List selectedUserIds = (List) state
.getAttribute(STATE_SELECTED_USER_LIST);
List participantList = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST));
List selectedParticipantList = new Vector();
Hashtable selectedParticipantRoles = new Hashtable();
if (!selectedUserIds.isEmpty() && participantList != null) {
for (int i = 0; i < participantList.size(); i++) {
String id = "";
Object o = (Object) participantList.get(i);
if (o.getClass().equals(Participant.class)) {
// get participant roles
id = ((Participant) o).getUniqname();
selectedParticipantRoles.put(id, ((Participant) o)
.getRole());
}
if (selectedUserIds.contains(id)) {
selectedParticipantList.add(participantList.get(i));
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
selectedParticipantRoles);
state.setAttribute(STATE_SELECTED_PARTICIPANTS, selectedParticipantList);
} // setSelectedParticipantRol3es
public class MyIcon {
protected String m_name = null;
protected String m_url = null;
protected String m_skin = null;
public MyIcon(String name, String url, String skin) {
m_name = name;
m_url = url;
m_skin = skin;
}
public String getName() {
return m_name;
}
public String getUrl() {
return m_url;
}
public String getSkin() {
return m_skin;
}
}
// a utility class for working with ToolConfigurations and ToolRegistrations
// %%% convert featureList from IdAndText to Tool so getFeatures item.id =
// chosen-feature.id is a direct mapping of data
public class MyTool {
public String id = NULL_STRING;
public String title = NULL_STRING;
public String description = NULL_STRING;
public boolean selected = false;
public boolean multiple = false;
public String group = NULL_STRING;
public String moreInfo = NULL_STRING;
public HashMap<String,MyTool> multiples = new HashMap<String,MyTool>();
public boolean required = false;
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public boolean getSelected() {
return selected;
}
public boolean isRequired() {
return required;
}
public boolean hasMultiples() {
return multiple;
}
public String getGroup() {
return group;
}
public String getMoreInfo() {
return moreInfo;
}
// SAK-16600
public HashMap<String,MyTool> getMultiples(String toolId) {
if (multiples == null) {
return new HashMap<String,MyTool>();
} else {
return multiples;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyTool other = (MyTool) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
private SiteAction getOuterType() {
return SiteAction.this;
}
}
/*
* WorksiteSetupPage is a utility class for working with site pages
* configured by Worksite Setup
*
*/
public class WorksiteSetupPage {
public String pageId = NULL_STRING;
public String pageTitle = NULL_STRING;
public String toolId = NULL_STRING;
public String getPageId() {
return pageId;
}
public String getPageTitle() {
return pageTitle;
}
public String getToolId() {
return toolId;
}
} // WorksiteSetupPage
public class SiteInfo {
public String site_id = NULL_STRING; // getId of Resource
public String external_id = NULL_STRING; // if matches site_id
// connects site with U-M
// course information
public String site_type = "";
public String iconUrl = NULL_STRING;
public String infoUrl = NULL_STRING;
public boolean joinable = false;
public String joinerRole = NULL_STRING;
public String title = NULL_STRING; // the short name of the site
public Set<String> siteRefAliases = new HashSet<String>(); // the aliases for the site itself
public String short_description = NULL_STRING; // the short (20 char)
// description of the
// site
public String description = NULL_STRING; // the longer description of
// the site
public String additional = NULL_STRING; // additional information on
// crosslists, etc.
public boolean published = false;
public boolean include = true; // include the site in the Sites index;
// default is true.
public String site_contact_name = NULL_STRING; // site contact name
public String site_contact_email = NULL_STRING; // site contact email
public String term = NULL_STRING; // academic term
public ResourceProperties properties = new BaseResourcePropertiesEdit();
// bjones86 - SAK-24423 - joinable site settings
public String joinerGroup = NULL_STRING;
public String getJoinerGroup()
{
return joinerGroup;
}
public boolean joinExcludePublic = false;
public boolean getJoinExcludePublic()
{
return joinExcludePublic;
}
public boolean joinLimitByAccountType = false;
public boolean getJoinLimitByAccountType()
{
return joinLimitByAccountType;
}
public String joinLimitedAccountTypes = NULL_STRING;
public String getJoinLimitedAccountTypes()
{
return joinLimitedAccountTypes;
} // end joinable site settings
public String getSiteId() {
return site_id;
}
public String getSiteType() {
return site_type;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getIconUrl() {
return iconUrl;
}
public String getInfoUrll() {
return infoUrl;
}
public boolean getJoinable() {
return joinable;
}
public String getJoinerRole() {
return joinerRole;
}
public String getAdditional() {
return additional;
}
public boolean getPublished() {
return published;
}
public boolean getInclude() {
return include;
}
public String getSiteContactName() {
return site_contact_name;
}
public String getSiteContactEmail() {
return site_contact_email;
}
public String getFirstAlias() {
return siteRefAliases.isEmpty() ? NULL_STRING : siteRefAliases.iterator().next();
}
public void addProperty(String key, String value) {
properties.addProperty(key, value);
}
public ResourceProperties getProperties() {
return properties;
}
public Set<String> getSiteRefAliases() {
return siteRefAliases;
}
public void setSiteRefAliases(Set<String> siteRefAliases) {
this.siteRefAliases = siteRefAliases;
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
} // SiteInfo
// customized type tool related
/**
* doFinish_site_type_tools is called when creation of a customized type site is
* confirmed
*/
public void doFinish_site_type_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// set up for the coming template
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue"));
int index = Integer.valueOf(params.getString("templateIndex"))
.intValue();
actionForTemplate("continue", index, params, state, data);
// add the pre-configured site type tools to a new site
addSiteTypeFeatures(state);
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
}// doFinish_site-type_tools
/**
* addSiteTypeToolsFeatures adds features to a new customized type site
*
*/
private void addSiteTypeFeatures(SessionState state) {
Site edit = null;
Site template = null;
String type = (String) state.getAttribute(STATE_SITE_TYPE);
HashMap<String, String> templates = siteTypeProvider.getTemplateForSiteTypes();
// get the template site id for this site type
if (templates != null && templates.containsKey(type))
{
String templateId = templates.get(type);
// get a unique id
String id = IdManager.createUuid();
// get the site template
try {
template = SiteService.getSite(templateId);
} catch (Exception e) {
M_log.warn(this + ".addSiteTypeFeatures:" + e.getMessage() + templateId, e);
}
if (template != null) {
// create a new site based on the template
try {
edit = SiteService.addSite(id, template);
// set site type
edit.setType(SiteTypeUtil.getTargetSiteType(template.getType()));
} catch (Exception e) {
M_log.warn(this + ".addSiteTypeFeatures:" + " add/edit site id=" + id, e);
}
// set the tab, etc.
if (edit != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
edit.setShortDescription(siteInfo.short_description);
edit.setTitle(siteInfo.title);
edit.setPublished(true);
edit.setPubView(false);
// SAK-23491 add template_used property
edit.getPropertiesEdit().addProperty(TEMPLATE_USED, templateId);
try {
SiteService.save(edit);
} catch (Exception e) {
M_log.warn(this + ".addSiteTypeFeatures:" + " commitEdit site id=" + id, e);
}
// now that the site and realm exist, we can set the email alias
// set the site alias as:
User currentUser = UserDirectoryService.getCurrentUser();
List<String> pList = new ArrayList<String>();
pList.add(currentUser != null ? currentUser.getEid():"");
String alias = siteTypeProvider.getSiteAlias(type, pList);
String channelReference = mailArchiveChannelReference(id);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
addAlert(state, rb.getFormattedMessage("java.alias.exists", new Object[]{alias}));
M_log.warn(this + ".addSiteTypeFeatures:" + rb.getFormattedMessage("java.alias.exists", new Object[]{alias}), ee);
} catch (IdInvalidException ee) {
addAlert(state, rb.getFormattedMessage("java.alias.isinval", new Object[]{alias}));
M_log.warn(this + ".addSiteTypeFeatures:" + rb.getFormattedMessage("java.alias.isinval", new Object[]{alias}), ee);
} catch (PermissionException ee) {
addAlert(state, rb.getString("java.addalias"));
M_log.warn(this + ".addSiteTypeFeatures:" + SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. ", ee);
}
}
}
}
} // addSiteTypeFeatures
/**
* handle with add site options
*
*/
public void doAdd_site_option(RunData data) {
String option = data.getParameters().getString("option");
if ("finish".equals(option)) {
doFinish(data);
} else if ("cancel".equals(option)) {
doCancel_create(data);
} else if ("back".equals(option)) {
doBack(data);
}
} // doAdd_site_option
/**
* handle with duplicate site options
*
*/
public void doDuplicate_site_option(RunData data) {
String option = data.getParameters().getString("option");
if ("duplicate".equals(option)) {
doContinue(data);
} else if ("cancel".equals(option)) {
doCancel(data);
} else if ("finish".equals(option)) {
doContinue(data);
}
} // doDuplicate_site_option
/**
* Get the mail archive channel reference for the main container placement
* for this site.
*
* @param siteId
* The site id.
* @return The mail archive channel reference for this site.
*/
protected String mailArchiveChannelReference(String siteId) {
Object m = ComponentManager
.get("org.sakaiproject.mailarchive.api.MailArchiveService");
if (m != null) {
return "/mailarchive"+Entity.SEPARATOR+"channel"+Entity.SEPARATOR+siteId+Entity.SEPARATOR+SiteService.MAIN_CONTAINER;
} else {
return "";
}
}
/**
* Transfer a copy of all entites from another context for any entity
* producer that claims this tool id.
*
* @param toolId
* The tool id.
* @param fromContext
* The context to import from.
* @param toContext
* The context to import into.
*/
protected Map transferCopyEntities(String toolId, String fromContext,
String toContext) {
// TODO: used to offer to resources first - why? still needed? -ggolden
Map transversalMap = new HashMap();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
if(ep instanceof EntityTransferrerRefMigrator){
EntityTransferrerRefMigrator etMp = (EntityTransferrerRefMigrator) ep;
Map<String,String> entityMap = etMp.transferCopyEntitiesRefMigrator(fromContext, toContext,
new Vector());
if(entityMap != null){
transversalMap.putAll(entityMap);
}
}else{
et.transferCopyEntities(fromContext, toContext, new Vector());
}
}
} catch (Throwable t) {
M_log.warn(this + ".transferCopyEntities: Error encountered while asking EntityTransfer to transferCopyEntities from: "
+ fromContext + " to: " + toContext, t);
}
}
}
return transversalMap;
}
private void updateSiteInfoToolEntityReferences(Map transversalMap, Site newSite){
if(transversalMap != null && transversalMap.size() > 0 && newSite != null){
Set<Entry<String, String>> entrySet = (Set<Entry<String, String>>) transversalMap.entrySet();
String msgBody = newSite.getDescription();
if(msgBody != null && !"".equals(msgBody)){
boolean updated = false;
Iterator<Entry<String, String>> entryItr = entrySet.iterator();
while(entryItr.hasNext()) {
Entry<String, String> entry = (Entry<String, String>) entryItr.next();
String fromContextRef = entry.getKey();
if(msgBody.contains(fromContextRef)){
msgBody = msgBody.replace(fromContextRef, entry.getValue());
updated = true;
}
}
if(updated){
//update the site b/c some tools (Lessonbuilder) updates the site structure (add/remove pages) and we don't want to
//over write this
try {
newSite = SiteService.getSite(newSite.getId());
newSite.setDescription(msgBody);
SiteService.save(newSite);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
}
}
}
}
protected void updateEntityReferences(String toolId, String toContext, Map transversalMap, Site newSite) {
if (toolId.equalsIgnoreCase(SITE_INFORMATION_TOOL)) {
updateSiteInfoToolEntityReferences(transversalMap, newSite);
}else{
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrerRefMigrator && ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
EntityTransferrerRefMigrator etRM = (EntityTransferrerRefMigrator) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
etRM.updateEntityReferences(toContext, transversalMap);
}
} catch (Throwable t) {
M_log.warn(
"Error encountered while asking EntityTransfer to updateEntityReferences at site: "
+ toContext, t);
}
}
}
}
}
protected Map transferCopyEntitiesMigrate(String toolId, String fromContext,
String toContext) {
Map transversalMap = new HashMap();
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
if(ep instanceof EntityTransferrerRefMigrator){
EntityTransferrerRefMigrator etRM = (EntityTransferrerRefMigrator) ep;
Map<String,String> entityMap = etRM.transferCopyEntitiesRefMigrator(fromContext, toContext,
new Vector(), true);
if(entityMap != null){
transversalMap.putAll(entityMap);
}
}else{
et.transferCopyEntities(fromContext, toContext,
new Vector(), true);
}
}
} catch (Throwable t) {
M_log.warn(
"Error encountered while asking EntityTransfer to transferCopyEntities from: "
+ fromContext + " to: " + toContext, t);
}
}
}
return transversalMap;
}
/**
* @return Get a list of all tools that support the import (transfer copy)
* option
*/
protected Set importTools() {
HashSet rv = new HashSet();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
EntityTransferrer et = (EntityTransferrer) ep;
String[] tools = et.myToolIds();
if (tools != null) {
for (int t = 0; t < tools.length; t++) {
rv.add(tools[t]);
}
}
}
}
if (ServerConfigurationService.getBoolean("site-manage.importoption.siteinfo", false)){
rv.add(SITE_INFO_TOOL_ID);
}
return rv;
}
/**
* @param state
* @return Get a list of all tools that should be included as options for
* import
*/
protected List getToolsAvailableForImport(SessionState state, List<String> toolIdList) {
// The Web Content and News tools do not follow the standard rules for
// import
// Even if the current site does not contain the tool, News and WC will
// be
// an option if the imported site contains it
boolean displayWebContent = false;
boolean displayNews = false;
Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES))
.keySet();
Iterator sitesIter = importSites.iterator();
while (sitesIter.hasNext()) {
Site site = (Site) sitesIter.next();
// web content is a little tricky because worksite setup has the same tool id. you
// can differentiate b/c worksite setup has a property with the key "special"
Collection iframeTools = new ArrayList<Tool>();
iframeTools = site.getTools(new String[] {WEB_CONTENT_TOOL_ID});
if (iframeTools != null && iframeTools.size() > 0) {
for (Iterator i = iframeTools.iterator(); i.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) i.next();
if (!tool.getPlacementConfig().containsKey("special")) {
displayWebContent = true;
}
}
}
if (site.getToolForCommonId(NEWS_TOOL_ID) != null)
displayNews = true;
}
if (displayWebContent && !toolIdList.contains(WEB_CONTENT_TOOL_ID))
toolIdList.add(WEB_CONTENT_TOOL_ID);
if (displayNews && !toolIdList.contains(NEWS_TOOL_ID))
toolIdList.add(NEWS_TOOL_ID);
if (ServerConfigurationService.getBoolean("site-manage.importoption.siteinfo", false)){
toolIdList.add(SITE_INFO_TOOL_ID);
}
return toolIdList;
} // getToolsAvailableForImport
// bjones86 - SAK-23256 - added userFilteringIfEnabled parameter
private List<AcademicSession> setTermListForContext(Context context, SessionState state,
boolean upcomingOnly, boolean useFilteringIfEnabled) {
List<AcademicSession> terms;
if (upcomingOnly) {
terms = cms != null?cms.getCurrentAcademicSessions():null;
} else { // get all
terms = cms != null?cms.getAcademicSessions():null;
}
if (terms != null && terms.size() > 0) {
// bjones86 - SAK-23256
if( useFilteringIfEnabled )
{
if( !SecurityService.isSuperUser() )
{
if( ServerConfigurationService.getBoolean( SAK_PROP_FILTER_TERMS, false ) )
{
terms = filterTermDropDowns();
}
}
}
context.put("termList", sortAcademicSessions(terms));
}
return terms;
} // setTermListForContext
private void setSelectedTermForContext(Context context, SessionState state,
String stateAttribute) {
if (state.getAttribute(stateAttribute) != null) {
context.put("selectedTerm", state.getAttribute(stateAttribute));
}
} // setSelectedTermForContext
/**
* Removes any academic sessions that the user is not currently enrolled in
*
* @author bjones86 - SAK-23256
*
* @return the filtered list of academic sessions
*/
public List<AcademicSession> filterTermDropDowns()
{
List<AcademicSession> academicSessions = new ArrayList<AcademicSession>();
User user = UserDirectoryService.getCurrentUser();
if( cms != null && user != null)
{
Map<String, String> sectionRoles = cms.findSectionRoles( user.getEid() );
if( sectionRoles != null )
{
// Iterate through all the sections and add their corresponding academic sessions to our return value
Set<String> sectionEids = sectionRoles.keySet();
Iterator<String> itr = sectionEids.iterator();
while( itr.hasNext() )
{
String sectionEid = itr.next();
Section section = cms.getSection( sectionEid );
if( section != null )
{
CourseOffering courseOffering = cms.getCourseOffering( section.getCourseOfferingEid() );
if( courseOffering != null )
{
academicSessions.add( courseOffering.getAcademicSession() );
}
}
}
}
}
// Remove duplicates
for( int i = 0; i < academicSessions.size(); i++ )
{
for( int j = i + 1; j < academicSessions.size(); j++ )
{
if( academicSessions.get( i ).getEid().equals( academicSessions.get( j ).getEid() ) )
{
academicSessions.remove( academicSessions.get( j ) );
j--; //stay on this index (ie. j will get incremented back)
}
}
}
return academicSessions;
}
/**
* rewrote for 2.4
*
* @param userId
* @param academicSessionEid
* @param courseOfferingHash
* @param sectionHash
*/
private void prepareCourseAndSectionMap(String userId,
String academicSessionEid, HashMap courseOfferingHash,
HashMap sectionHash) {
// looking for list of courseOffering and sections that should be
// included in
// the selection list. The course offering must be offered
// 1. in the specific academic Session
// 2. that the specified user has right to attach its section to a
// course site
// map = (section.eid, sakai rolename)
if (groupProvider == null)
{
M_log.warn("Group provider not found");
return;
}
Map map = groupProvider.getGroupRolesForUser(userId);
if (map == null)
return;
Set keys = map.keySet();
Set roleSet = getRolesAllowedToAttachSection();
for (Iterator i = keys.iterator(); i.hasNext();) {
String sectionEid = (String) i.next();
String role = (String) map.get(sectionEid);
if (includeRole(role, roleSet)) {
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
// now consider those user with affiliated sections
List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid);
if (affiliatedSectionEids != null)
{
for (int k = 0; k < affiliatedSectionEids.size(); k++) {
String sectionEid = (String) affiliatedSectionEids.get(k);
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
} // prepareCourseAndSectionMap
private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) {
try {
section = cms.getSection(sectionEid);
} catch (IdNotFoundException e) {
M_log.warn("getCourseOfferingAndSectionMap: cannot find section " + sectionEid);
}
if (section != null) {
String courseOfferingEid = section.getCourseOfferingEid();
CourseOffering courseOffering = cms
.getCourseOffering(courseOfferingEid);
String sessionEid = courseOffering.getAcademicSession()
.getEid();
if (academicSessionEid.equals(sessionEid)) {
// a long way to the conclusion that yes, this course
// offering
// should be included in the selected list. Sigh...
// -daisyf
ArrayList sectionList = (ArrayList) sectionHash
.get(courseOffering.getEid());
if (sectionList == null) {
sectionList = new ArrayList();
}
sectionList.add(new SectionObject(section));
sectionHash.put(courseOffering.getEid(), sectionList);
courseOfferingHash.put(courseOffering.getEid(),
courseOffering);
}
}
}
/**
* for 2.4
*
* @param role
* @return
*/
private boolean includeRole(String role, Set roleSet) {
boolean includeRole = false;
for (Iterator i = roleSet.iterator(); i.hasNext();) {
String r = (String) i.next();
if (r.equals(role)) {
includeRole = true;
break;
}
}
return includeRole;
} // includeRole
protected Set getRolesAllowedToAttachSection() {
// Use !site.template.[site_type]
String azgId = "!site.template.course";
AuthzGroup azgTemplate;
try {
azgTemplate = AuthzGroupService.getAuthzGroup(azgId);
} catch (GroupNotDefinedException e) {
M_log.warn(this + ".getRolesAllowedToAttachSection: Could not find authz group " + azgId, e);
return new HashSet();
}
Set roles = azgTemplate.getRolesIsAllowed("site.upd");
roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd"));
return roles;
} // getRolesAllowedToAttachSection
/**
* Here, we will preapre two HashMap: 1. courseOfferingHash stores
* courseOfferingId and CourseOffering 2. sectionHash stores
* courseOfferingId and a list of its Section We sorted the CourseOffering
* by its eid & title and went through them one at a time to construct the
* CourseObject that is used for the displayed in velocity. Each
* CourseObject will contains a list of CourseOfferingObject(again used for
* vm display). Usually, a CourseObject would only contain one
* CourseOfferingObject. A CourseObject containing multiple
* CourseOfferingObject implies that this is a cross-listing situation.
*
* @param userId
* @param academicSessionEid
* @return
*/
private List prepareCourseAndSectionListing(String userId,
String academicSessionEid, SessionState state) {
// courseOfferingHash = (courseOfferingEid, vourseOffering)
// sectionHash = (courseOfferingEid, list of sections)
HashMap courseOfferingHash = new HashMap();
HashMap sectionHash = new HashMap();
prepareCourseAndSectionMap(userId, academicSessionEid,
courseOfferingHash, sectionHash);
// courseOfferingHash & sectionHash should now be filled with stuffs
// put section list in state for later use
state.setAttribute(STATE_PROVIDER_SECTION_LIST,
getSectionList(sectionHash));
ArrayList offeringList = new ArrayList();
Set keys = courseOfferingHash.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
CourseOffering o = (CourseOffering) courseOfferingHash
.get((String) i.next());
offeringList.add(o);
}
Collection offeringListSorted = sortCourseOfferings(offeringList);
ArrayList resultedList = new ArrayList();
// use this to keep track of courseOffering that we have dealt with
// already
// this is important 'cos cross-listed offering is dealt with together
// with its
// equivalents
ArrayList dealtWith = new ArrayList();
for (Iterator j = offeringListSorted.iterator(); j.hasNext();) {
CourseOffering o = (CourseOffering) j.next();
if (!dealtWith.contains(o.getEid())) {
// 1. construct list of CourseOfferingObject for CourseObject
ArrayList l = new ArrayList();
CourseOfferingObject coo = new CourseOfferingObject(o,
(ArrayList) sectionHash.get(o.getEid()));
l.add(coo);
// 2. check if course offering is cross-listed
Set set = cms.getEquivalentCourseOfferings(o.getEid());
if (set != null)
{
for (Iterator k = set.iterator(); k.hasNext();) {
CourseOffering eo = (CourseOffering) k.next();
if (courseOfferingHash.containsKey(eo.getEid())) {
// => cross-listed, then list them together
CourseOfferingObject coo_equivalent = new CourseOfferingObject(
eo, (ArrayList) sectionHash.get(eo.getEid()));
l.add(coo_equivalent);
dealtWith.add(eo.getEid());
}
}
}
CourseObject co = new CourseObject(o, l);
dealtWith.add(o.getEid());
resultedList.add(co);
}
}
return resultedList;
} // prepareCourseAndSectionListing
/* SAK-25400 template site types duplicated in list
* Sort template sites by type
**/
private Collection sortTemplateSitesByType(Collection<Site> templates) {
String[] sortKey = {"type"};
String[] sortOrder = {"asc"};
return sortCmObject(templates, sortKey, sortOrder);
}
/**
* Helper method for sortCmObject
* by order from sakai properties if specified or
* by default of eid, title
* using velocity SortTool
*
* @param offerings
* @return
*/
private Collection sortCourseOfferings(Collection<CourseOffering> offerings) {
// Get the keys from sakai.properties
String[] keys = ServerConfigurationService.getStrings(SORT_KEY_COURSE_OFFERING);
String[] orders = ServerConfigurationService.getStrings(SORT_ORDER_COURSE_OFFERING);
return sortCmObject(offerings, keys, orders);
} // sortCourseOffering
/**
* Helper method for sortCmObject
* by order from sakai properties if specified or
* by default of eid, title
* using velocity SortTool
*
* @param courses
* @return
*/
private Collection sortCourseSets(Collection<CourseSet> courses) {
// Get the keys from sakai.properties
String[] keys = ServerConfigurationService.getStrings(SORT_KEY_COURSE_SET);
String[] orders = ServerConfigurationService.getStrings(SORT_ORDER_COURSE_SET);
return sortCmObject(courses, keys, orders);
} // sortCourseOffering
/**
* Helper method for sortCmObject
* by order from sakai properties if specified or
* by default of eid, title
* using velocity SortTool
*
* @param sections
* @return
*/
private Collection sortSections(Collection<Section> sections) {
// Get the keys from sakai.properties
String[] keys = ServerConfigurationService.getStrings(SORT_KEY_SECTION);
String[] orders = ServerConfigurationService.getStrings(SORT_ORDER_SECTION);
return sortCmObject(sections, keys, orders);
} // sortCourseOffering
/**
* Helper method for sortCmObject
* by order from sakai properties if specified or
* by default of eid, title
* using velocity SortTool
*
* @param sessions
* @return
*/
private Collection sortAcademicSessions(Collection<AcademicSession> sessions) {
// Get the keys from sakai.properties
String[] keys = ServerConfigurationService.getStrings(SORT_KEY_SESSION);
String[] orders = ServerConfigurationService.getStrings(SORT_ORDER_SESSION);
return sortCmObject(sessions, keys, orders);
} // sortCourseOffering
/**
* Custom sort CM collections using properties provided object has getter & setter for
* properties in keys and orders
* defaults to eid & title if none specified
*
* @param collection a collection to be sorted
* @param keys properties to sort on
* @param orders properties on how to sort (asc, dsc)
* @return Collection the sorted collection
*/
private Collection sortCmObject(Collection collection, String[] keys, String[] orders) {
if (collection != null && !collection.isEmpty()) {
// Add them to a list for the SortTool (they must have the form
// "<key:order>" in this implementation)
List propsList = new ArrayList();
if (keys == null || orders == null || keys.length == 0 || orders.length == 0) {
// No keys are specified, so use the default sort order
propsList.add("eid");
propsList.add("title");
} else {
// Populate propsList
for (int i = 0; i < Math.min(keys.length, orders.length); i++) {
String key = keys[i];
String order = orders[i];
propsList.add(key + ":" + order);
}
}
// Sort the collection and return
SortTool sort = new SortTool();
return sort.sort(collection, propsList);
}
return Collections.emptyList();
} // sortCmObject
/**
* Custom sort CM collections provided object has getter & setter for
* eid & title
*
* @param collection a collection to be sorted
* @return Collection the sorted collection
*/
private Collection sortCmObject(Collection collection) {
return sortCmObject(collection, null, null);
}
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class SectionObject {
public Section section;
public String eid;
public String title;
public String category;
public String categoryDescription;
public boolean isLecture;
public boolean attached;
public List<String> authorizer;
public String description;
public SectionObject(Section section) {
this.section = section;
this.eid = section.getEid();
this.title = section.getTitle();
this.category = section.getCategory();
List<String> authorizers = new ArrayList<String>();
if (section.getEnrollmentSet() != null){
Set<String> instructorset = section.getEnrollmentSet().getOfficialInstructors();
if (instructorset != null) {
for (String instructor:instructorset) {
authorizers.add(instructor);
}
}
}
this.authorizer = authorizers;
this.categoryDescription = cms
.getSectionCategoryDescription(section.getCategory());
if ("01.lct".equals(section.getCategory())) {
this.isLecture = true;
} else {
this.isLecture = false;
}
Set set = authzGroupService.getAuthzGroupIds(section.getEid());
if (set != null && !set.isEmpty()) {
this.attached = true;
} else {
this.attached = false;
}
this.description = section.getDescription();
}
public Section getSection() {
return section;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public String getCategory() {
return category;
}
public String getCategoryDescription() {
return categoryDescription;
}
public boolean getIsLecture() {
return isLecture;
}
public boolean getAttached() {
return attached;
}
public String getDescription() {
return description;
}
public List<String> getAuthorizer() {
return authorizer;
}
public String getAuthorizerString() {
StringBuffer rv = new StringBuffer();
if (authorizer != null && !authorizer.isEmpty())
{
for (int count = 0; count < authorizer.size(); count++)
{
// concatenate all authorizers into a String
if (count > 0)
{
rv.append(", ");
}
rv.append(authorizer.get(count));
}
}
return rv.toString();
}
public void setAuthorizer(List<String> authorizer) {
this.authorizer = authorizer;
}
} // SectionObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseObject {
public String eid;
public String title;
public List courseOfferingObjects;
public CourseObject(CourseOffering offering, List courseOfferingObjects) {
this.eid = offering.getEid();
this.title = offering.getTitle();
this.courseOfferingObjects = courseOfferingObjects;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getCourseOfferingObjects() {
return courseOfferingObjects;
}
} // CourseObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseOfferingObject {
public String eid;
public String title;
public List sections;
public CourseOfferingObject(CourseOffering offering,
List unsortedSections) {
List propsList = new ArrayList();
propsList.add("category");
propsList.add("eid");
SortTool sort = new SortTool();
this.sections = new ArrayList();
if (unsortedSections != null) {
this.sections = (List) sort.sort(unsortedSections, propsList);
}
this.eid = offering.getEid();
this.title = offering.getTitle();
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getSections() {
return sections;
}
} // CourseOfferingObject constructor
/**
* get campus user directory for dispaly in chef_newSiteCourse.vm
*
* @return
*/
private String getCampusDirectory() {
return ServerConfigurationService.getString(
"site-manage.campusUserDirectory", null);
} // getCampusDirectory
private void removeAnyFlagedSection(SessionState state,
ParameterParser params) {
List all = new ArrayList();
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerCourseList != null && providerCourseList.size() > 0) {
all.addAll(providerCourseList);
}
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
if (manualCourseList != null && manualCourseList.size() > 0) {
all.addAll(manualCourseList);
}
for (int i = 0; i < all.size(); i++) {
String eid = (String) all.get(i);
String field = "removeSection" + eid;
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
// eid is in either providerCourseList or manualCourseList
// either way, just remove it
if (providerCourseList != null)
providerCourseList.remove(eid);
if (manualCourseList != null)
manualCourseList.remove(eid);
}
}
// if list is empty, set to null. This is important 'cos null is
// the indication that the list is empty in the code. See case 2 on line
// 1081
if (manualCourseList != null && manualCourseList.size() == 0)
manualCourseList = null;
if (providerCourseList != null && providerCourseList.size() == 0)
providerCourseList = null;
removeAnyFlaggedSectionFromState(state, params, STATE_CM_REQUESTED_SECTIONS);
removeAnyFlaggedSectionFromState(state, params, STATE_CM_SELECTED_SECTIONS);
removeAnyFlaggedSectionFromState(state, params, STATE_CM_AUTHORIZER_SECTIONS);
// remove manually requested sections
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector();
List removeRequiredFieldList = null;
for (int i = 0; i < requiredFields.size(); i++) {
String sectionTitle = "";
List requiredFieldList = (List) requiredFields.get(i);
for (int j = 0; j < requiredFieldList.size(); j++) {
SectionField requiredField = (SectionField) requiredFieldList.get(j);
sectionTitle = sectionTitle.concat(requiredField.getValue() + " ");
}
String field = "removeSection" + sectionTitle.trim();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
removeRequiredFieldList = requiredFieldList;
break;
}
}
if (removeRequiredFieldList != null)
{
requiredFields.remove(removeRequiredFieldList);
if (number > 1)
{
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, requiredFields);
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf(number -1));
}
else
{
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
}
}
}
}
private void removeAnyFlaggedSectionFromState(SessionState state, ParameterParser params, String state_variable)
{
List<SectionObject> rv = (List<SectionObject>) state.getAttribute(state_variable);
if (rv != null) {
for (int i = 0; i < rv.size(); i++) {
SectionObject so = (SectionObject) rv.get(i);
String field = "removeSection" + so.getEid();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
rv.remove(so);
}
}
if (rv.size() == 0)
state.removeAttribute(state_variable);
else
state.setAttribute(state_variable, rv);
}
}
private void collectNewSiteInfo(SessionState state,
ParameterParser params, List providerChosenList) {
if (state.getAttribute(STATE_MESSAGE) == null) {
SiteInfo siteInfo = state.getAttribute(STATE_SITE_INFO) != null? (SiteInfo) state.getAttribute(STATE_SITE_INFO): new SiteInfo();
// site title is the title of the 1st section selected -
// daisyf's note
if (providerChosenList != null && providerChosenList.size() >= 1) {
String title = prepareTitle((List) state
.getAttribute(STATE_PROVIDER_SECTION_LIST),
providerChosenList);
siteInfo.title = title;
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN) != null)
{
List<String> providerDescriptionChosenList = (List<String>) state.getAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
if (providerDescriptionChosenList != null)
{
for (String providerSectionId : providerDescriptionChosenList)
{
try
{
Section s = cms.getSection(providerSectionId);
if (s != null)
{
String sDescription = StringUtils.trimToNull(s.getDescription());
if (sDescription != null && !siteInfo.description.contains(sDescription))
{
siteInfo.description = siteInfo.description.concat(sDescription);
}
}
}
catch (IdNotFoundException e)
{
M_log.warn("collectNewSiteInfo: cannot find section " + providerSectionId);
}
}
}
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (params.getString("manualAdds") != null
&& ("true").equals(params.getString("manualAdds"))) {
// if creating a new site
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf(
1));
} else if (params.getString("find_course") != null
&& ("true").equals(params.getString("find_course"))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
prepFindPage(state);
} else {
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
if (getStateSite(state) != null) {
// if revising a site, go to the confirmation
// page of adding classes
//state.setAttribute(STATE_TEMPLATE_INDEX, "37");
} else {
// if creating a site, go the the site
// information entry page
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
}
}
}
/**
* By default, courseManagement is implemented
*
* @return
*/
private boolean courseManagementIsImplemented() {
boolean returnValue = true;
String isImplemented = ServerConfigurationService.getString(
"site-manage.courseManagementSystemImplemented", "true");
if (("false").equals(isImplemented))
returnValue = false;
return returnValue;
}
private List getCMSections(String offeringEid) {
if (offeringEid == null || offeringEid.trim().length() == 0)
return null;
if (cms != null) {
try
{
Set sections = cms.getSections(offeringEid);
if (sections != null)
{
Collection c = sortSections(new ArrayList(sections));
return (List) c;
}
}
catch (IdNotFoundException e)
{
M_log.warn("getCMSections: Cannot find sections for " + offeringEid);
}
}
return new ArrayList(0);
}
private List getCMCourseOfferings(String subjectEid, String termID) {
if (subjectEid == null || subjectEid.trim().length() == 0
|| termID == null || termID.trim().length() == 0)
return null;
if (cms != null) {
Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// ,
// termID);
ArrayList returnList = new ArrayList();
if (offerings != null)
{
Iterator coIt = offerings.iterator();
while (coIt.hasNext()) {
CourseOffering co = (CourseOffering) coIt.next();
AcademicSession as = co.getAcademicSession();
if (as != null && as.getEid().equals(termID))
returnList.add(co);
}
}
Collection c = sortCourseOfferings(returnList);
return (List) c;
}
return new ArrayList(0);
}
private List<String> getCMLevelLabels(SessionState state) {
List<String> rv = new Vector<String>();
// get CourseSet
Set courseSets = getCourseSet(state);
String currentLevel = "";
if (courseSets != null)
{
// Hieriarchy of CourseSet, CourseOffering and Section are multiple levels in CourseManagementService
List<SectionField> sectionFields = sectionFieldProvider.getRequiredFields();
for (SectionField field : sectionFields)
{
rv.add(field.getLabelKey());
}
}
return rv;
}
/**
* a recursive function to add courseset categories
* @param rv
* @param courseSets
*/
private List<String> addCategories(List<String> rv, Set courseSets) {
if (courseSets != null)
{
for (Iterator i = courseSets.iterator(); i.hasNext();)
{
// get the CourseSet object level
CourseSet cs = (CourseSet) i.next();
String level = cs.getCategory();
if (!rv.contains(level))
{
rv.add(level);
}
try
{
// recursively add child categories
rv = addCategories(rv, cms.getChildCourseSets(cs.getEid()));
}
catch (IdNotFoundException e)
{
// current CourseSet not found
}
}
}
return rv;
}
private void prepFindPage(SessionState state) {
// check the configuration setting for choosing next screen
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean(SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue())
{
// go to the course/section selection page
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
// get cm levels
final List cmLevels = getCMLevelLabels(state), selections = (List) state.getAttribute(STATE_CM_LEVEL_SELECTIONS);
int lvlSz = 0;
if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) {
// TODO: no cm levels configured, redirect to manual add
return;
}
if (selections != null && selections.size() >= lvlSz) {
// multiple selections for the section level
List<SectionObject> soList = new Vector<SectionObject>();
for (int k = cmLevels.size() -1; k < selections.size(); k++)
{
String string = (String) selections.get(k);
if (string != null && string.length() > 0)
{
try
{
Section sect = cms.getSection(string);
if (sect != null)
{
SectionObject so = new SectionObject(sect);
soList.add(so);
}
}
catch (IdNotFoundException e)
{
M_log.warn("prepFindPage: Cannot find section " + string);
}
}
}
state.setAttribute(STATE_CM_SELECTED_SECTION, soList);
} else
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.setAttribute(STATE_CM_LEVELS, cmLevels);
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
}
else
{
// skip the course/section selection page, go directly into the manually create course page
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
private void addRequestedSection(SessionState state) {
List<SectionObject> soList = (List<SectionObject>) state
.getAttribute(STATE_CM_SELECTED_SECTION);
String uniqueName = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (soList == null || soList.isEmpty())
return;
String s = ServerConfigurationService.getString("officialAccountName");
if (uniqueName == null)
{
addAlert(state, rb.getFormattedMessage("java.author", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
return;
}
if (getStateSite(state) == null)
{
// creating new site
List<SectionObject> requestedSections = (List<SectionObject>) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
for (SectionObject so : soList)
{
so.setAuthorizer(new ArrayList(Arrays.asList(uniqueName.split(","))));
if (requestedSections == null) {
requestedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!requestedSections.contains(so))
requestedSections.add(so);
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
// if the title has not yet been set and there is just
// one section, set the title to that section's EID
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo == null) {
siteInfo = new SiteInfo();
}
if (siteInfo.title == null || siteInfo.title.trim().length() == 0) {
if (requestedSections.size() >= 1) {
siteInfo.title = requestedSections.get(0).getTitle();
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
}
}
else
{
// editing site
for (SectionObject so : soList)
{
so.setAuthorizer(new ArrayList(Arrays.asList(uniqueName.split(","))));
List<SectionObject> cmSelectedSections = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmSelectedSections == null) {
cmSelectedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!cmSelectedSections.contains(so))
cmSelectedSections.add(so);
state.setAttribute(STATE_CM_SELECTED_SECTIONS, cmSelectedSections);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
}
}
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
}
public void doFind_course(RunData data) {
final SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
final ParameterParser params = data.getParameters();
final String option = params.get("option");
if (option != null && option.length() > 0)
{
if ("continue".equals(option))
{
String uniqname = StringUtils.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue())
{
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null)
{
addAlert(state, rb.getFormattedMessage("java.author", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
}
else
{
// check instructors
List instructors = new ArrayList(Arrays.asList(uniqname.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
String instructorId = (String) iInstructors.next();
try
{
UserDirectoryService.getUserByEid(instructorId);
}
catch (UserNotDefinedException e)
{
addAlert(state, rb.getFormattedMessage("java.validAuthor", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
M_log.warn(this + ".doFind_course:" + rb.getFormattedMessage("java.validAuthor", new Object[]{ServerConfigurationService.getString("officialAccountName")}));
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
addRequestedSection(state);
}
}
}
else
{
addRequestedSection(state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
if (getStateSite(state) == null) {
if (state.getAttribute(STATE_TEMPLATE_SITE) != null)
{
// if creating site using template, stop here and generate the new site
// create site based on template
doFinish(data);
}
else
{
// else follow the normal flow
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
doContinue(data);
return;
} else if ("back".equals(option)) {
doBack(data);
return;
} else if ("cancel".equals(option)) {
if (getStateSite(state) == null)
{
doCancel_create(data);// cancel from new site creation
}
else
{
doCancel(data);// cancel from site info editing
}
return;
} else if ("add".equals(option)) {
// get the uniqname input
String uniqname = StringUtils.trimToNull(params.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
addRequestedSection(state);
return;
} else if ("manual".equals(option)) {
// TODO: send to case 37
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, Integer.valueOf(
1));
return;
} else if ("remove".equals(option))
removeAnyFlagedSection(state, params);
}
final List selections = new ArrayList(3);
int cmLevel = getCMLevelLabels(state).size();
String cmLevelChanged = params.get("cmLevelChanged");
if ("true".equals(cmLevelChanged)) {
// when cm level changes, set the focus to the new level
String cmChangedLevel = params.get("cmChangedLevel");
cmLevel = cmChangedLevel != null ? Integer.valueOf(cmChangedLevel).intValue() + 1:cmLevel;
}
for (int i = 0; i < cmLevel; i++) {
String[] val = params.getStrings("idField_" + i);
if (val == null || val.length == 0) {
break;
}
if (val.length == 1)
{
selections.add(val[0]);
}
else
{
for (int k=0; k<val.length;k++)
{
selections.add(val[k]);
}
}
}
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
prepFindPage(state);
}
/**
* return the title of the 1st section in the chosen list that has an
* enrollment set. No discrimination on section category
*
* @param sectionList
* @param chosenList
* @return
*/
private String prepareTitle(List sectionList, List chosenList) {
String title = null;
HashMap map = new HashMap();
for (Iterator i = sectionList.iterator(); i.hasNext();) {
SectionObject o = (SectionObject) i.next();
map.put(o.getEid(), o.getSection());
}
for (int j = 0; j < chosenList.size(); j++) {
String eid = (String) chosenList.get(j);
Section s = (Section) map.get(eid);
// we will always has a title regardless but we prefer it to be the
// 1st section on the chosen list that has an enrollment set
if (j == 0) {
title = s.getTitle();
}
if (s.getEnrollmentSet() != null) {
title = s.getTitle();
break;
}
}
return title;
} // prepareTitle
/**
* return an ArrayList of SectionObject
*
* @param sectionHash
* contains an ArrayList collection of SectionObject
* @return
*/
private ArrayList getSectionList(HashMap sectionHash) {
ArrayList list = new ArrayList();
// values is an ArrayList of section
Collection c = sectionHash.values();
for (Iterator i = c.iterator(); i.hasNext();) {
ArrayList l = (ArrayList) i.next();
list.addAll(l);
}
return list;
}
private String getAuthorizers(SessionState state, String attributeName) {
String authorizers = "";
ArrayList list = (ArrayList) state
.getAttribute(attributeName);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
if (i == 0) {
authorizers = (String) list.get(i);
} else {
authorizers = authorizers + ", " + list.get(i);
}
}
}
return authorizers;
}
private List prepareSectionObject(List sectionList, String userId) {
ArrayList list = new ArrayList();
if (sectionList != null) {
for (int i = 0; i < sectionList.size(); i++) {
String sectionEid = (String) sectionList.get(i);
try
{
Section s = cms.getSection(sectionEid);
if (s != null)
{
SectionObject so = new SectionObject(s);
so.setAuthorizer(new ArrayList(Arrays.asList(userId.split(","))));
list.add(so);
}
}
catch (IdNotFoundException e)
{
M_log.warn("prepareSectionObject: Cannot find section " + sectionEid);
}
}
}
return list;
}
/**
* change collection object to list object
* @param c
* @return
*/
private List collectionToList(Collection c)
{
List rv = new Vector();
if (c!=null)
{
for (Iterator i = c.iterator(); i.hasNext();)
{
rv.add(i.next());
}
}
return rv;
}
protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
throws ToolException
{
ToolSession toolSession = SessionManager.getCurrentToolSession();
SessionState state = getState(req);
if (SITE_MODE_HELPER_DONE.equals(state.getAttribute(STATE_SITE_MODE)))
{
String url = (String) SessionManager.getCurrentToolSession().getAttribute(Tool.HELPER_DONE_URL);
SessionManager.getCurrentToolSession().removeAttribute(Tool.HELPER_DONE_URL);
// TODO: Implement cleanup.
cleanState(state);
// Helper cleanup.
cleanStateHelper(state);
if (M_log.isDebugEnabled())
{
M_log.debug("Sending redirect to: "+ url);
}
try
{
res.sendRedirect(url);
}
catch (IOException e)
{
M_log.warn("Problem sending redirect to: "+ url, e);
}
return;
}
else
{
super.toolModeDispatch(methodBase, methodExt, req, res);
}
}
private void cleanStateHelper(SessionState state) {
state.removeAttribute(STATE_SITE_MODE);
state.removeAttribute(STATE_TEMPLATE_INDEX);
state.removeAttribute(STATE_INITIALIZED);
}
private String getSiteBaseUrl() {
return ServerConfigurationService.getPortalUrl() + "/" +
ServerConfigurationService.getString("portal.handler.default", "site") +
"/";
}
private String getDefaultSiteUrl(String siteId) {
return prefixString(getSiteBaseUrl(), siteId);
}
private Collection<String> getSiteReferenceAliasIds(Site forSite) {
return prefixSiteAliasIds(null, forSite);
}
private Collection<String> getSiteUrlsForSite(Site site) {
return prefixSiteAliasIds(getSiteBaseUrl(), site);
}
private Collection<String> getSiteUrlsForAliasIds(Collection<String> aliasIds) {
return prefixSiteAliasIds(getSiteBaseUrl(), aliasIds);
}
private String getSiteUrlForAliasId(String aliasId) {
return prefixString(getSiteBaseUrl(), aliasId);
}
private Collection<String> prefixSiteAliasIds(String prefix, Site site) {
return prefixSiteAliasIds(prefix, AliasService.getAliases(site.getReference()));
}
private Collection<String> prefixSiteAliasIds(String prefix, Collection<? extends Object> aliases) {
List<String> siteAliases = new ArrayList<String>();
for (Object alias : aliases) {
String aliasId = null;
if ( alias instanceof Alias ) {
aliasId = ((Alias)alias).getId();
} else {
aliasId = alias.toString();
}
siteAliases.add(prefixString(prefix,aliasId));
}
return siteAliases;
}
private String prefixString(String prefix, String aliasId) {
return (prefix == null ? "" : prefix) + aliasId;
}
private List<String> toIdList(List<? extends Entity> entities) {
List<String> ids = new ArrayList<String>(entities.size());
for ( Entity entity : entities ) {
ids.add(entity.getId());
}
return ids;
}
/**
* whether this tool title is of Home tool title
* @param toolTitle
* @return
*/
private boolean isHomePage(SitePage page)
{
if (page.getProperties().getProperty(SitePage.IS_HOME_PAGE) != null)
{
// check based on the page property first
return true;
}
else
{
// if above fails, check based on the page title
String pageTitle = page.getTitle();
return TOOL_ID_HOME.equalsIgnoreCase(pageTitle) || rb.getString("java.home").equalsIgnoreCase(pageTitle);
}
}
public boolean displaySiteAlias() {
if (ServerConfigurationService.getBoolean("wsetup.disable.siteAlias", false)) {
return false;
}
return true;
}
private void putPrintParticipantLinkIntoContext(Context context, RunData data, Site site) {
// the status servlet reqest url
String url = Web.serverUrl(data.getRequest()) + "/sakai-site-manage-tool/tool/printparticipant/" + site.getId();
context.put("printParticipantUrl", url);
}
/**
* dispatch function for site type vm
* @param data
*/
public void doSite_type_option(RunData data)
{
ParameterParser params = data.getParameters();
String option = StringUtils.trimToNull(params.getString("option"));
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (option != null)
{
if ("cancel".equals(option))
{
doCancel_create(data);
}
else if ("siteType".equals(option))
{
doSite_type(data);
}
else if ("createOnTemplate".equals(option))
{
doSite_copyFromTemplate(data);
}
else if ("createCourseOnTemplate".equals(option))
{
doSite_copyFromCourseTemplate(data);
}
else if ("createCourseOnTemplate".equals(option))
{
doSite_copyFromCourseTemplate(data);
}
else if ("createFromArchive".equals(option))
{
state.setAttribute(STATE_CREATE_FROM_ARCHIVE, Boolean.TRUE);
//continue with normal workflow
doSite_type(data);
}
}
}
/**
* create site from template
* @param params
* @param state
*/
private void doSite_copyFromTemplate(RunData data)
{
ParameterParser params = data.getParameters();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read template information
readCreateSiteTemplateInformation(params, state);
// create site
doFinish(data);
}
/**
* create course site from template, next step would be select roster
* @param params
* @param state
*/
private void doSite_copyFromCourseTemplate(RunData data)
{
ParameterParser params = data.getParameters();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read template information
readCreateSiteTemplateInformation(params, state);
// redirect for site roster selection
redirectCourseCreation(params, state, "selectTermTemplate");
}
/**
* read the user input for creating site based on template
* @param params
* @param state
*/
private void readCreateSiteTemplateInformation(ParameterParser params, SessionState state)
{
// get the template site id
String templateSiteId = params.getString("templateSiteId");
try {
Site templateSite = SiteService.getSite(templateSiteId);
state.setAttribute(STATE_TEMPLATE_SITE, templateSite);
state.setAttribute(STATE_SITE_TYPE, templateSite.getType());
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = templateSite.getType();
siteInfo.title = StringUtils.trimToNull(params.getString("siteTitleField"));
siteInfo.term = StringUtils.trimToNull(params.getString("selectTermTemplate"));
siteInfo.iconUrl = templateSite.getIconUrl();
// description is site-specific. Shouldn't come from template
// siteInfo.description = templateSite.getDescription();
siteInfo.short_description = templateSite.getShortDescription();
siteInfo.joinable = templateSite.isJoinable();
siteInfo.joinerRole = templateSite.getJoinerRole();
state.setAttribute(STATE_SITE_INFO, siteInfo);
// bjones86 - SAK-24423 - update site info for joinable site settings
JoinableSiteSettings.updateSiteInfoFromParams( params, siteInfo );
// whether to copy users or site content over?
if (params.getBoolean("copyUsers")) state.setAttribute(STATE_TEMPLATE_SITE_COPY_USERS, Boolean.TRUE); else state.removeAttribute(STATE_TEMPLATE_SITE_COPY_USERS);
if (params.getBoolean("copyContent")) state.setAttribute(STATE_TEMPLATE_SITE_COPY_CONTENT, Boolean.TRUE); else state.removeAttribute(STATE_TEMPLATE_SITE_COPY_CONTENT);
if (params.getBoolean("publishSite")) state.setAttribute(STATE_TEMPLATE_PUBLISH, Boolean.TRUE); else state.removeAttribute(STATE_TEMPLATE_PUBLISH);
}
catch(Exception e){
M_log.warn(this + "readCreateSiteTemplateInformation: problem of getting template site: " + templateSiteId);
}
}
/**
* redirect course creation process after the term selection step
* @param params
* @param state
* @param termFieldName
*/
private void redirectCourseCreation(ParameterParser params, SessionState state, String termFieldName) {
User user = UserDirectoryService.getCurrentUser();
String currentUserId = user.getEid();
String userId = params.getString("userId");
if (userId == null || "".equals(userId)) {
userId = currentUserId;
} else {
// implies we are trying to pick sections owned by other
// users. Currently "select section by user" page only
// take one user per sitte request - daisy's note 1
ArrayList<String> list = new ArrayList();
list.add(userId);
state.setAttribute(STATE_CM_AUTHORIZER_LIST, list);
}
state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId);
String academicSessionEid = params.getString(termFieldName);
// check whether the academicsession might be null
if (academicSessionEid != null)
{
AcademicSession t = cms.getAcademicSession(academicSessionEid);
state.setAttribute(STATE_TERM_SELECTED, t);
if (t != null) {
List sections = prepareCourseAndSectionListing(userId, t
.getEid(), state);
isFutureTermSelected(state);
if (sections != null && sections.size() > 0) {
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean(SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue() && courseManagementIsImplemented())
{
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
} else { // not course type
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
}
public void doEdit_site_info(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String locale_string = params.getString("locales");
state.setAttribute("locale_string",locale_string);
String option = params.getString("option");
if ("removeSection".equals(option))
{
// remove section
removeAnyFlagedSection(state, params);
}
else if ("continue".equals(option))
{
// continue with site information edit
MathJaxEnabler.applyAllowedSettingsToState(state, params); // SAK-22384
doContinue(data);
}
else if ("back".equals(option))
{
// go back to previous pages
doBack(data);
}
else if ("cancel".equals(option))
{
// cancel
doCancel(data);
}
}
/**
* *
*
* @return Locale based on its string representation (language_region)
*/
private Locale getLocaleFromString(String localeString)
{
org.sakaiproject.component.api.ServerConfigurationService scs = (org.sakaiproject.component.api.ServerConfigurationService) ComponentManager.get(org.sakaiproject.component.api.ServerConfigurationService.class);
return scs.getLocaleFromString(localeString);
}
/**
* @return Returns the prefLocales
*/
public List<Locale> getPrefLocales()
{
// Initialize list of supported locales, if necessary
if (prefLocales.size() == 0) {
org.sakaiproject.component.api.ServerConfigurationService scs = (org.sakaiproject.component.api.ServerConfigurationService) ComponentManager.get(org.sakaiproject.component.api.ServerConfigurationService.class);
Locale[] localeArray = scs.getSakaiLocales();
// Add to prefLocales list
for (int i = 0; i < localeArray.length; i++) {
prefLocales.add(localeArray[i]);
}
}
return prefLocales;
}
// SAK-20797
/**
* return quota on site specified by siteId
* @param siteId
* @return value of site-specific quota or 0 if not found
*/
private long getSiteSpecificQuota(String siteId) {
long quota = 0;
try {
Site site = SiteService.getSite(siteId);
if (site != null) {
quota = getSiteSpecificQuota(site);
}
} catch (IdUnusedException e) {
M_log.warn("Quota calculation could not find the site " + siteId
+ "for site specific quota calculation",
M_log.isDebugEnabled() ? e : null);
}
return quota;
}
// SAK-20797
/**
* return quota set on this specific site
* @param collection
* @return value of site-specific quota or 0 if not found
*/
private long getSiteSpecificQuota(Site site) {
long quota = 0;
try
{
String collId = m_contentHostingService
.getSiteCollection(site.getId());
ContentCollection site_collection = m_contentHostingService.getCollection(collId);
long siteSpecific = site_collection.getProperties().getLongProperty(
ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
quota = siteSpecific;
}
catch (Exception ignore)
{
M_log.warn("getQuota: reading quota property for site : " + site.getId() + " : " + ignore);
quota = 0;
}
return quota;
}
// SAK-20797
/**
* return file size in bytes as formatted string
* @param quota
* @return formatted string (i.e. 2048 as 2 KB)
*/
private String formatSize(long quota) {
String size = "";
NumberFormat formatter = NumberFormat.getInstance(rb.getLocale());
formatter.setMaximumFractionDigits(1);
if (quota > 700000000L) {
String[] args = { formatter.format(1.0 * quota
/ (1024L * 1024L * 1024L)) };
size = rb.getFormattedMessage("size.gb", args);
} else if (quota > 700000L) {
String[] args = { formatter.format(1.0 * quota / (1024L * 1024L)) };
size = rb.getFormattedMessage("size.mb", args);
} else if (quota > 700L) {
String[] args = { formatter.format(1.0 * quota / 1024L) };
size = rb.getFormattedMessage("size.kb", args);
} else {
String[] args = { formatter.format(quota) };
size = rb.getFormattedMessage("size.bytes", args);
}
return size;
}
public class JoinableGroup{
private String reference;
private String title;
private String joinableSet;
private int size;
private int max;
private String members;
private boolean preview;
public JoinableGroup(String reference, String title, String joinableSet, int size, int max, String members, boolean preview){
this.reference = reference;
this.title = title;
this.joinableSet = joinableSet;
this.size = size;
this.max = max;
this.members = members;
this.preview = preview;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getJoinableSet() {
return joinableSet;
}
public void setJoinableSet(String joinableSet) {
this.joinableSet = joinableSet;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public String getMembers() {
return members;
}
public void setMembers(String members) {
this.members = members;
}
public boolean isPreview() {
return preview;
}
public void setPreview(boolean preview) {
this.preview = preview;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
}
/**
* Handles uploading an archive file as part of the site creation workflow
* @param data
*/
public void doUploadArchive(RunData data)
{
ParameterParser params = data.getParameters();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
//get params
FileItem fi = data.getParameters().getFileItem ("importFile");
//get uploaded file into a location we can process
String archiveUnzipBase = ServerConfigurationService.getString("archive.storage.path", FileUtils.getTempDirectoryPath());
//convert inputstream into actual file so we can unzip it
String zipFilePath = archiveUnzipBase + File.separator + fi.getFileName();
//rudimentary check that the file is a zip file
if(!StringUtils.endsWith(fi.getFileName(), ".zip")){
addAlert(state, rb.getString("archive.createsite.failedupload"));
return;
}
File tempZipFile = new File(zipFilePath);
if(tempZipFile.exists()) {
tempZipFile.delete();
}
try {
//copy contents into this file
IOUtils.copyLarge(fi.getInputStream(), new FileOutputStream(tempZipFile));
//set path into state so we can process it later
state.setAttribute(STATE_UPLOADED_ARCHIVE_PATH, tempZipFile.getAbsolutePath());
state.setAttribute(STATE_UPLOADED_ARCHIVE_NAME, tempZipFile.getName());
} catch (Exception e) {
M_log.error(e.getMessage(), e); //general catch all for the various exceptions that occur above. all are failures.
addAlert(state, rb.getString("archive.createsite.failedupload"));
}
//go to confirm screen
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
}
/**
* Handles merging an uploaded archive into the newly created site
* This is done after the site has been created in the site creation workflow
*
* @param siteId
* @param state
*/
private void doMergeArchiveIntoNewSite(String siteId, SessionState state) {
String currentUserId = userDirectoryService.getCurrentUser().getId();
try {
String archivePath = (String)state.getAttribute(STATE_UPLOADED_ARCHIVE_PATH);
//merge the zip into our new site
//we ignore the return because its not very useful. See ArchiveService for more details
archiveService.mergeFromZip(archivePath, siteId, currentUserId);
} catch (Exception e) {
M_log.error(e.getMessage(), e); //general catch all for the various exceptions that occur above. all are failures.
addAlert(state, rb.getString("archive.createsite.failedmerge"));
}
}
}
| SAK-26302 check for post
git-svn-id: 19a9fd284f7506c72ea2840aac2b5d740703d7e8@310378 66ffb92e-73f9-0310-93c1-f5514f145a0a
| site-manage/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java | SAK-26302 check for post |
|
Java | apache-2.0 | 0226d74f1e732ab98135370338430916eeaaf19c | 0 | gongpu/killbill,kares/killbill,joansmith/killbill,liqianggao/killbill,Massiv-IO/killbill,kares/killbill,dconcha/killbill,chengjunjian/killbill,sbrossie/killbill,aglne/killbill,aeq/killbill,Massiv-IO/killbill,gsanblas/Prueba,andrenpaes/killbill,chengjunjian/killbill,maguero/killbill,aglne/killbill,gsanblas/Prueba,maguero/killbill,Massiv-IO/killbill,joansmith/killbill,24671335/killbill,aeq/killbill,sbrossie/killbill,gongpu/killbill,kares/killbill,marksimu/killbill,andrenpaes/killbill,marksimu/killbill,gongpu/killbill,kares/killbill,chengjunjian/killbill,gsanblas/Prueba,killbill/killbill,24671335/killbill,joansmith/killbill,andrenpaes/killbill,aeq/killbill,marksimu/killbill,gongpu/killbill,24671335/killbill,andrenpaes/killbill,maguero/killbill,marksimu/killbill,sbrossie/killbill,aglne/killbill,24671335/killbill,dut3062796s/killbill,dconcha/killbill,dconcha/killbill,chengjunjian/killbill,marksimu/killbill,Massiv-IO/killbill,gongpu/killbill,dut3062796s/killbill,24671335/killbill,liqianggao/killbill,sbrossie/killbill,dconcha/killbill,aeq/killbill,sbrossie/killbill,killbill/killbill,gsanblas/Prueba,killbill/killbill,maguero/killbill,dut3062796s/killbill,maguero/killbill,aeq/killbill,killbill/killbill,dut3062796s/killbill,Massiv-IO/killbill,dconcha/killbill,joansmith/killbill,aglne/killbill,killbill/killbill,andrenpaes/killbill,liqianggao/killbill,joansmith/killbill,dut3062796s/killbill,aglne/killbill,liqianggao/killbill,chengjunjian/killbill,liqianggao/killbill | /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning 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.ning.billing.entitlement.api;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.inject.Inject;
import org.joda.time.DateTimeZone;
import com.ning.billing.ErrorCode;
import com.ning.billing.ObjectType;
import com.ning.billing.callcontext.InternalCallContext;
import com.ning.billing.callcontext.InternalTenantContext;
import com.ning.billing.entitlement.AccountEntitlements;
import com.ning.billing.entitlement.EntitlementInternalApi;
import com.ning.billing.entitlement.EventsStream;
import com.ning.billing.entitlement.api.svcs.DefaultEntitlementInternalApi;
import com.ning.billing.entitlement.engine.core.EntitlementUtils;
import com.ning.billing.subscription.api.SubscriptionBase;
import com.ning.billing.subscription.api.SubscriptionBaseInternalApi;
import com.ning.billing.subscription.api.user.SubscriptionBaseApiException;
import com.ning.billing.subscription.api.user.SubscriptionBaseBundle;
import com.ning.billing.util.cache.Cachable.CacheType;
import com.ning.billing.util.cache.CacheControllerDispatcher;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.InternalCallContextFactory;
import com.ning.billing.util.callcontext.TenantContext;
import com.ning.billing.util.customfield.ShouldntHappenException;
import com.ning.billing.util.dao.NonEntityDao;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
public class DefaultSubscriptionApi implements SubscriptionApi {
private static final Comparator<SubscriptionBundle> SUBSCRIPTION_BUNDLE_COMPARATOR = new Comparator<SubscriptionBundle>() {
@Override
public int compare(final SubscriptionBundle o1, final SubscriptionBundle o2) {
final int compared = o1.getOriginalCreatedDate().compareTo(o2.getOriginalCreatedDate());
if (compared != 0) {
return compared;
} else {
final int compared2 = o1.getUpdatedDate().compareTo(o2.getUpdatedDate());
if (compared2 != 0) {
return compared2;
} else {
// Default, stable, ordering
return o1.getId().compareTo(o2.getId());
}
}
}
};
private final EntitlementInternalApi entitlementInternalApi;
private final SubscriptionBaseInternalApi subscriptionBaseInternalApi;
private final InternalCallContextFactory internalCallContextFactory;
private final NonEntityDao nonEntityDao;
private final CacheControllerDispatcher cacheControllerDispatcher;
private final EntitlementUtils entitlementUtils;
@Inject
public DefaultSubscriptionApi(final EntitlementInternalApi entitlementInternalApi, final SubscriptionBaseInternalApi subscriptionInternalApi,
final InternalCallContextFactory internalCallContextFactory, final EntitlementUtils entitlementUtils, final NonEntityDao nonEntityDao, final CacheControllerDispatcher cacheControllerDispatcher) {
this.entitlementInternalApi = entitlementInternalApi;
this.subscriptionBaseInternalApi = subscriptionInternalApi;
this.internalCallContextFactory = internalCallContextFactory;
this.nonEntityDao = nonEntityDao;
this.entitlementUtils = entitlementUtils;
this.cacheControllerDispatcher = cacheControllerDispatcher;
}
@Override
public Subscription getSubscriptionForEntitlementId(final UUID entitlementId, final TenantContext context) throws SubscriptionApiException {
final Long accountRecordId = nonEntityDao.retrieveAccountRecordIdFromObject(entitlementId, ObjectType.SUBSCRIPTION, cacheControllerDispatcher.getCacheController(CacheType.ACCOUNT_RECORD_ID));
final UUID accountId = nonEntityDao.retrieveIdFromObject(accountRecordId, ObjectType.ACCOUNT);
// Retrieve entitlements
final AccountEntitlements accountEntitlements;
try {
accountEntitlements = entitlementInternalApi.getAllEntitlementsForAccountId(accountId, context);
} catch (EntitlementApiException e) {
throw new SubscriptionApiException(e);
}
// Build subscriptions
final Iterable<Subscription> accountSubscriptions = Iterables.<Subscription>concat(buildSubscriptionsFromEntitlements(accountEntitlements).values());
return Iterables.<Subscription>find(accountSubscriptions,
new Predicate<Subscription>() {
@Override
public boolean apply(final Subscription subscription) {
return subscription.getId().equals(entitlementId);
}
});
}
@Override
public SubscriptionBundle getSubscriptionBundle(final UUID bundleId, final TenantContext context) throws SubscriptionApiException {
final Long accountRecordId = nonEntityDao.retrieveAccountRecordIdFromObject(bundleId, ObjectType.BUNDLE, cacheControllerDispatcher.getCacheController(CacheType.ACCOUNT_RECORD_ID));
final UUID accountId = nonEntityDao.retrieveIdFromObject(accountRecordId, ObjectType.ACCOUNT);
final Optional<SubscriptionBundle> bundleOptional = Iterables.<SubscriptionBundle>tryFind(getSubscriptionBundlesForAccount(accountId, context),
new Predicate<SubscriptionBundle>() {
@Override
public boolean apply(final SubscriptionBundle bundle) {
return bundle.getId().equals(bundleId);
}
});
if (!bundleOptional.isPresent()) {
throw new SubscriptionApiException(ErrorCode.SUB_GET_INVALID_BUNDLE_ID, bundleId);
} else {
return bundleOptional.get();
}
}
@Override
public void updateExternalKey(final UUID uuid, final String newExternalKey, final CallContext callContext) {
final InternalCallContext internalContext = internalCallContextFactory.createInternalCallContext(callContext);
subscriptionBaseInternalApi.updateExternalKey(uuid, newExternalKey, internalContext);
}
@Override
public List<SubscriptionBundle> getSubscriptionBundlesForAccountIdAndExternalKey(final UUID accountId, final String externalKey, final TenantContext context) throws SubscriptionApiException {
return ImmutableList.<SubscriptionBundle>copyOf(Iterables.<SubscriptionBundle>filter(getSubscriptionBundlesForAccount(accountId, context),
new Predicate<SubscriptionBundle>() {
@Override
public boolean apply(final SubscriptionBundle bundle) {
return bundle.getExternalKey().equals(externalKey);
}
}));
}
@Override
public SubscriptionBundle getActiveSubscriptionBundleForExternalKey(final String externalKey, final TenantContext context) throws SubscriptionApiException {
final InternalTenantContext internalContext = internalCallContextFactory.createInternalTenantContext(context);
try {
final UUID activeSubscriptionIdForKey = entitlementUtils.getFirstActiveSubscriptionIdForKeyOrNull(externalKey, internalContext);
if (activeSubscriptionIdForKey == null) {
throw new SubscriptionApiException(new SubscriptionBaseApiException(ErrorCode.SUB_GET_INVALID_BUNDLE_KEY, externalKey));
}
final SubscriptionBase subscriptionBase = subscriptionBaseInternalApi.getSubscriptionFromId(activeSubscriptionIdForKey, internalContext);
return getSubscriptionBundle(subscriptionBase.getBundleId(), context);
} catch (SubscriptionBaseApiException e) {
throw new SubscriptionApiException(e);
}
}
@Override
public List<SubscriptionBundle> getSubscriptionBundlesForExternalKey(final String externalKey, final TenantContext context) throws SubscriptionApiException {
final InternalTenantContext internalContext = internalCallContextFactory.createInternalTenantContext(context);
final List<SubscriptionBaseBundle> baseBundles = subscriptionBaseInternalApi.getBundlesForKey(externalKey, internalContext);
final List<SubscriptionBundle> result = new ArrayList<SubscriptionBundle>(baseBundles.size());
for (final SubscriptionBaseBundle cur : baseBundles) {
final SubscriptionBundle bundle = getSubscriptionBundle(cur.getId(), context);
result.add(bundle);
}
return result;
}
@Override
public List<SubscriptionBundle> getSubscriptionBundlesForAccountId(final UUID accountId, final TenantContext context) throws SubscriptionApiException {
return getSubscriptionBundlesForAccount(accountId, context);
}
private List<SubscriptionBundle> getSubscriptionBundlesForAccount(final UUID accountId, final TenantContext tenantContext) throws SubscriptionApiException {
// Retrieve entitlements
final AccountEntitlements accountEntitlements;
try {
accountEntitlements = entitlementInternalApi.getAllEntitlementsForAccountId(accountId, tenantContext);
} catch (EntitlementApiException e) {
throw new SubscriptionApiException(e);
}
// Build subscriptions
final Map<UUID, List<Subscription>> subscriptionsPerBundle = buildSubscriptionsFromEntitlements(accountEntitlements);
final DateTimeZone accountTimeZone = accountEntitlements.getAccount().getTimeZone();
// Build subscription bundles
final List<SubscriptionBundle> bundles = new LinkedList<SubscriptionBundle>();
for (final UUID bundleId : subscriptionsPerBundle.keySet()) {
final List<Subscription> subscriptionsForBundle = subscriptionsPerBundle.get(bundleId);
final String externalKey = subscriptionsForBundle.get(0).getExternalKey();
final SubscriptionBundleTimeline timeline = new DefaultSubscriptionBundleTimeline(accountTimeZone,
accountId,
bundleId,
externalKey,
accountEntitlements.getEntitlements().get(bundleId));
final SubscriptionBaseBundle baseBundle = accountEntitlements.getBundles().get(bundleId);
final SubscriptionBundle subscriptionBundle = new DefaultSubscriptionBundle(bundleId,
accountId,
externalKey,
subscriptionsForBundle,
timeline,
baseBundle.getOriginalCreatedDate(),
baseBundle.getCreatedDate(),
baseBundle.getUpdatedDate());
bundles.add(subscriptionBundle);
}
// Sort the results for predictability
return Ordering.<SubscriptionBundle>from(SUBSCRIPTION_BUNDLE_COMPARATOR).sortedCopy(bundles);
}
private Map<UUID, List<Subscription>> buildSubscriptionsFromEntitlements(final AccountEntitlements accountEntitlements) {
final Map<UUID, List<Subscription>> subscriptionsPerBundle = new HashMap<UUID, List<Subscription>>();
for (final UUID bundleId : accountEntitlements.getEntitlements().keySet()) {
if (subscriptionsPerBundle.get(bundleId) == null) {
subscriptionsPerBundle.put(bundleId, new LinkedList<Subscription>());
}
for (final Entitlement entitlement : accountEntitlements.getEntitlements().get(bundleId)) {
if (entitlement instanceof DefaultEntitlement) {
subscriptionsPerBundle.get(bundleId).add(new DefaultSubscription((DefaultEntitlement) entitlement));
} else {
throw new ShouldntHappenException("Entitlement should be a DefaultEntitlement instance");
}
}
}
return subscriptionsPerBundle;
}
}
| entitlement/src/main/java/com/ning/billing/entitlement/api/DefaultSubscriptionApi.java | /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning 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.ning.billing.entitlement.api;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.inject.Inject;
import org.joda.time.DateTimeZone;
import com.ning.billing.ErrorCode;
import com.ning.billing.ObjectType;
import com.ning.billing.callcontext.InternalCallContext;
import com.ning.billing.callcontext.InternalTenantContext;
import com.ning.billing.entitlement.AccountEntitlements;
import com.ning.billing.entitlement.EntitlementInternalApi;
import com.ning.billing.entitlement.EventsStream;
import com.ning.billing.entitlement.api.svcs.DefaultEntitlementInternalApi;
import com.ning.billing.entitlement.engine.core.EntitlementUtils;
import com.ning.billing.subscription.api.SubscriptionBase;
import com.ning.billing.subscription.api.SubscriptionBaseInternalApi;
import com.ning.billing.subscription.api.user.SubscriptionBaseApiException;
import com.ning.billing.subscription.api.user.SubscriptionBaseBundle;
import com.ning.billing.util.cache.Cachable.CacheType;
import com.ning.billing.util.cache.CacheControllerDispatcher;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.InternalCallContextFactory;
import com.ning.billing.util.callcontext.TenantContext;
import com.ning.billing.util.customfield.ShouldntHappenException;
import com.ning.billing.util.dao.NonEntityDao;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
public class DefaultSubscriptionApi implements SubscriptionApi {
private static final Comparator<SubscriptionBundle> SUBSCRIPTION_BUNDLE_COMPARATOR = new Comparator<SubscriptionBundle>() {
@Override
public int compare(final SubscriptionBundle o1, final SubscriptionBundle o2) {
final int compared = o1.getOriginalCreatedDate().compareTo(o2.getOriginalCreatedDate());
if (compared != 0) {
return compared;
} else {
final int compared2 = o1.getUpdatedDate().compareTo(o2.getUpdatedDate());
if (compared2 != 0) {
return compared2;
} else {
// Default, stable, ordering
return o1.getId().compareTo(o2.getId());
}
}
}
};
private final EntitlementInternalApi entitlementInternalApi;
private final SubscriptionBaseInternalApi subscriptionBaseInternalApi;
private final InternalCallContextFactory internalCallContextFactory;
private final NonEntityDao nonEntityDao;
private final CacheControllerDispatcher cacheControllerDispatcher;
private final EntitlementUtils entitlementUtils;
@Inject
public DefaultSubscriptionApi(final EntitlementInternalApi entitlementInternalApi, final SubscriptionBaseInternalApi subscriptionInternalApi,
final InternalCallContextFactory internalCallContextFactory, final EntitlementUtils entitlementUtils, final NonEntityDao nonEntityDao, final CacheControllerDispatcher cacheControllerDispatcher) {
this.entitlementInternalApi = entitlementInternalApi;
this.subscriptionBaseInternalApi = subscriptionInternalApi;
this.internalCallContextFactory = internalCallContextFactory;
this.nonEntityDao = nonEntityDao;
this.entitlementUtils = entitlementUtils;
this.cacheControllerDispatcher = cacheControllerDispatcher;
}
@Override
public Subscription getSubscriptionForEntitlementId(final UUID entitlementId, final TenantContext context) throws SubscriptionApiException {
final Long accountRecordId = nonEntityDao.retrieveAccountRecordIdFromObject(entitlementId, ObjectType.SUBSCRIPTION, cacheControllerDispatcher.getCacheController(CacheType.ACCOUNT_RECORD_ID));
final UUID accountId = nonEntityDao.retrieveIdFromObject(accountRecordId, ObjectType.ACCOUNT);
// Retrieve entitlements
final AccountEntitlements accountEntitlements;
try {
accountEntitlements = entitlementInternalApi.getAllEntitlementsForAccountId(accountId, context);
} catch (EntitlementApiException e) {
throw new SubscriptionApiException(e);
}
// Build subscriptions
final Iterable<Subscription> accountSubscriptions = Iterables.<Subscription>concat(buildSubscriptionsFromEntitlements(accountEntitlements).values());
return Iterables.<Subscription>find(accountSubscriptions,
new Predicate<Subscription>() {
@Override
public boolean apply(final Subscription subscription) {
return subscription.getId().equals(entitlementId);
}
});
}
@Override
public SubscriptionBundle getSubscriptionBundle(final UUID bundleId, final TenantContext context) throws SubscriptionApiException {
final Long accountRecordId = nonEntityDao.retrieveAccountRecordIdFromObject(bundleId, ObjectType.BUNDLE, cacheControllerDispatcher.getCacheController(CacheType.ACCOUNT_RECORD_ID));
final UUID accountId = nonEntityDao.retrieveIdFromObject(accountRecordId, ObjectType.ACCOUNT);
final Optional<SubscriptionBundle> bundleOptional = Iterables.<SubscriptionBundle>tryFind(getSubscriptionBundlesForAccount(accountId, context),
new Predicate<SubscriptionBundle>() {
@Override
public boolean apply(final SubscriptionBundle bundle) {
return bundle.getId().equals(bundleId);
}
});
if (!bundleOptional.isPresent()) {
throw new SubscriptionApiException(ErrorCode.SUB_GET_INVALID_BUNDLE_ID, bundleId);
} else {
return bundleOptional.get();
}
}
@Override
public void updateExternalKey(final UUID uuid, final String newExternalKey, final CallContext callContext) {
final InternalCallContext internalContext = internalCallContextFactory.createInternalCallContext(callContext);
subscriptionBaseInternalApi.updateExternalKey(uuid, newExternalKey, internalContext);
}
@Override
public List<SubscriptionBundle> getSubscriptionBundlesForAccountIdAndExternalKey(final UUID accountId, final String externalKey, final TenantContext context) throws SubscriptionApiException {
return ImmutableList.<SubscriptionBundle>copyOf(Iterables.<SubscriptionBundle>filter(getSubscriptionBundlesForAccount(accountId, context),
new Predicate<SubscriptionBundle>() {
@Override
public boolean apply(final SubscriptionBundle bundle) {
return bundle.getExternalKey().equals(externalKey);
}
}));
}
@Override
public SubscriptionBundle getActiveSubscriptionBundleForExternalKey(final String externalKey, final TenantContext context) throws SubscriptionApiException {
final InternalTenantContext internalContext = internalCallContextFactory.createInternalTenantContext(context);
try {
final UUID activeSubscriptionIdForKey = entitlementUtils.getFirstActiveSubscriptionIdForKeyOrNull(externalKey, internalContext);
if (activeSubscriptionIdForKey == null) {
throw new SubscriptionApiException(new SubscriptionBaseApiException(ErrorCode.SUB_CREATE_ACTIVE_BUNDLE_KEY_EXISTS, externalKey));
}
final SubscriptionBase subscriptionBase = subscriptionBaseInternalApi.getSubscriptionFromId(activeSubscriptionIdForKey, internalContext);
return getSubscriptionBundle(subscriptionBase.getBundleId(), context);
} catch (SubscriptionBaseApiException e) {
throw new SubscriptionApiException(e);
}
}
@Override
public List<SubscriptionBundle> getSubscriptionBundlesForExternalKey(final String externalKey, final TenantContext context) throws SubscriptionApiException {
final InternalTenantContext internalContext = internalCallContextFactory.createInternalTenantContext(context);
final List<SubscriptionBaseBundle> baseBundles = subscriptionBaseInternalApi.getBundlesForKey(externalKey, internalContext);
final List<SubscriptionBundle> result = new ArrayList<SubscriptionBundle>(baseBundles.size());
for (final SubscriptionBaseBundle cur : baseBundles) {
final SubscriptionBundle bundle = getSubscriptionBundle(cur.getId(), context);
result.add(bundle);
}
return result;
}
@Override
public List<SubscriptionBundle> getSubscriptionBundlesForAccountId(final UUID accountId, final TenantContext context) throws SubscriptionApiException {
return getSubscriptionBundlesForAccount(accountId, context);
}
private List<SubscriptionBundle> getSubscriptionBundlesForAccount(final UUID accountId, final TenantContext tenantContext) throws SubscriptionApiException {
// Retrieve entitlements
final AccountEntitlements accountEntitlements;
try {
accountEntitlements = entitlementInternalApi.getAllEntitlementsForAccountId(accountId, tenantContext);
} catch (EntitlementApiException e) {
throw new SubscriptionApiException(e);
}
// Build subscriptions
final Map<UUID, List<Subscription>> subscriptionsPerBundle = buildSubscriptionsFromEntitlements(accountEntitlements);
final DateTimeZone accountTimeZone = accountEntitlements.getAccount().getTimeZone();
// Build subscription bundles
final List<SubscriptionBundle> bundles = new LinkedList<SubscriptionBundle>();
for (final UUID bundleId : subscriptionsPerBundle.keySet()) {
final List<Subscription> subscriptionsForBundle = subscriptionsPerBundle.get(bundleId);
final String externalKey = subscriptionsForBundle.get(0).getExternalKey();
final SubscriptionBundleTimeline timeline = new DefaultSubscriptionBundleTimeline(accountTimeZone,
accountId,
bundleId,
externalKey,
accountEntitlements.getEntitlements().get(bundleId));
final SubscriptionBaseBundle baseBundle = accountEntitlements.getBundles().get(bundleId);
final SubscriptionBundle subscriptionBundle = new DefaultSubscriptionBundle(bundleId,
accountId,
externalKey,
subscriptionsForBundle,
timeline,
baseBundle.getOriginalCreatedDate(),
baseBundle.getCreatedDate(),
baseBundle.getUpdatedDate());
bundles.add(subscriptionBundle);
}
// Sort the results for predictability
return Ordering.<SubscriptionBundle>from(SUBSCRIPTION_BUNDLE_COMPARATOR).sortedCopy(bundles);
}
private Map<UUID, List<Subscription>> buildSubscriptionsFromEntitlements(final AccountEntitlements accountEntitlements) {
final Map<UUID, List<Subscription>> subscriptionsPerBundle = new HashMap<UUID, List<Subscription>>();
for (final UUID bundleId : accountEntitlements.getEntitlements().keySet()) {
if (subscriptionsPerBundle.get(bundleId) == null) {
subscriptionsPerBundle.put(bundleId, new LinkedList<Subscription>());
}
for (final Entitlement entitlement : accountEntitlements.getEntitlements().get(bundleId)) {
if (entitlement instanceof DefaultEntitlement) {
subscriptionsPerBundle.get(bundleId).add(new DefaultSubscription((DefaultEntitlement) entitlement));
} else {
throw new ShouldntHappenException("Entitlement should be a DefaultEntitlement instance");
}
}
}
return subscriptionsPerBundle;
}
}
| Fix wrong error code in entitlement
| entitlement/src/main/java/com/ning/billing/entitlement/api/DefaultSubscriptionApi.java | Fix wrong error code in entitlement |
|
Java | apache-2.0 | db77e0d73266388c0dbd5a95da167d944ec4f871 | 0 | clescot/webappender | package com.clescot.webappender.formatter;
import com.clescot.webappender.Row;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.Maps;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class ChromeLoggerFormatter extends AbstractFormatter<ChromeRow> {
public final static String RESPONSE_CHROME_LOGGER_HEADER = "X-ChromeLogger-Data";
public static final String HTTP_USER_AGENT = "user-agent";
private static Pattern chromeUserAgentPattern = Pattern.compile("like Gecko\\) (.)*Chrome/");
protected String getJSON(List<Row> rows) throws JsonProcessingException {
Map<String, Object> globalStructure = Maps.newHashMap();
globalStructure.put("version", "1.0");
globalStructure.put("columns", Arrays.asList("log", "backtrace", "type"));
globalStructure.put("rows", getFormatterRows(rows));
return objectMapper.writeValueAsString(globalStructure);
}
@Override
protected ChromeRow newFormatterRow(Row row) {
return new ChromeRow(row);
}
@Override
public boolean isActive(Map<String, List<String>> headers) {
//active on chrome browsers and derivated one
List<String> userAgentHeaders = headers.get(HTTP_USER_AGENT);
if(userAgentHeaders!=null&&!userAgentHeaders.isEmpty()){
String userAgent = userAgentHeaders.get(0);
return chromeUserAgentPattern.matcher(userAgent).find();
}
return false;
}
@Override
public Map<String, String> serializeRows(List<com.clescot.webappender.Row> rows) throws JsonProcessingException {
Map<String,String> rowsSerialized = Maps.newHashMap();
rowsSerialized.put(RESPONSE_CHROME_LOGGER_HEADER, format(rows));
return rowsSerialized;
}
}
| webappender/src/main/java/com/clescot/webappender/formatter/ChromeLoggerFormatter.java | package com.clescot.webappender.formatter;
import com.clescot.webappender.Row;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.Maps;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class ChromeLoggerFormatter extends AbstractFormatter<ChromeRow> {
public final static String RESPONSE_CHROME_LOGGER_HEADER = "X-ChromeLogger-Data";
public static final String HTTP_USER_AGENT = "user-agent";
private static Pattern chromeUserAgentPattern = Pattern.compile("like Gecko\\) (.)*Chrome/");
protected String getJSON(List<Row> rows) throws JsonProcessingException {
Map<String, Object> globalStructure = Maps.newHashMap();
globalStructure.put("version", "1.0");
globalStructure.put("columns", Arrays.asList("log", "backtrace", "type"));
globalStructure.put("rows", getFormatterRows(rows));
return objectMapper.writeValueAsString(globalStructure);
}
@Override
protected ChromeRow newFormatterRow(Row row) {
return new ChromeRow(row);
}
@Override
public boolean isActive(Map<String, List<String>> headers) {
//active on chrome browsers and derivated one
List<String> userAgentHeaders = headers.get(HTTP_USER_AGENT);
if(userAgentHeaders!=null&&!userAgentHeaders.isEmpty()){
String userAgent = userAgentHeaders.get(0);
return chromeUserAgentPattern.matcher(userAgent).find();
}
return false;
}
@Override
public Map<String, String> serializeRows(List<com.clescot.webappender.Row> rows) throws JsonProcessingException {
Map<String,String> rowsSerialized = Maps.newHashMap();
rowsSerialized.put(RESPONSE_CHROME_LOGGER_HEADER, getJSON(rows));
return rowsSerialized;
}
}
| add base64 encoding step
| webappender/src/main/java/com/clescot/webappender/formatter/ChromeLoggerFormatter.java | add base64 encoding step |
|
Java | apache-2.0 | bb05d9bb05835f4ea3599494d060139b6b5a0d3c | 0 | estatio/estatio,estatio/estatio,estatio/estatio,estatio/estatio | package org.estatio.module.capex.integtests.task.overview;
import java.util.List;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.apache.isis.applib.fixtures.TickingFixtureClock;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.services.clock.ClockService;
import org.apache.isis.applib.services.sudo.SudoService;
import org.apache.isis.applib.services.wrapper.DisabledException;
import org.incode.module.communications.dom.impl.commchannel.CommunicationChannelRepository;
import org.incode.module.communications.dom.impl.commchannel.CommunicationChannelType;
import org.estatio.module.asset.fixtures.person.enums.Person_enum;
import org.estatio.module.capex.app.taskreminder.TaskOverview;
import org.estatio.module.capex.app.taskreminder.TaskReminderService;
import org.estatio.module.capex.dom.task.Task;
import org.estatio.module.capex.dom.task.TaskRepository;
import org.estatio.module.capex.fixtures.incominginvoice.enums.IncomingInvoice_enum;
import org.estatio.module.capex.integtests.CapexModuleIntegTestAbstract;
import org.estatio.module.capex.seed.DocumentTypesAndTemplatesForCapexFixture;
import org.estatio.module.charge.fixtures.incoming.builders.IncomingChargesFraXlsxFixture;
import org.estatio.module.party.dom.Person;
import static org.assertj.core.api.Assertions.assertThat;
public class TaskOverview_IntegTest extends CapexModuleIntegTestAbstract {
public static class OverdueTasks extends TaskOverview_IntegTest {
@Before
public void setupData() {
runFixtureScript(new FixtureScript() {
@Override
protected void execute(final ExecutionContext executionContext) {
executionContext.executeChild(this, new IncomingChargesFraXlsxFixture());
executionContext.executeChild(this, new DocumentTypesAndTemplatesForCapexFixture());
executionContext.executeChild(this, IncomingInvoice_enum.fakeInvoice2Pdf.builder());
executionContext.executeChild(this, Person_enum.DanielOfficeAdministratorFr.builder());
executionContext.executeChild(this, Person_enum.FleuretteRenaudFr.builder());
}
});
}
@Test
public void noOverdueTasks() {
// given
final Person person = Person_enum.DanielOfficeAdministratorFr.findUsing(serviceRegistry);
final TaskOverview overview = serviceRegistry.injectServicesInto(new TaskOverview(person));
// then
assertThat(overview.getListOfTasksOverdue()).isEmpty();
}
@Test
public void overdueTasks() {
// given
final Person person = Person_enum.FleuretteRenaudFr.findUsing(serviceRegistry);
final List<Task> unassigned = taskRepository.findIncompleteByUnassigned();
assertThat(unassigned).hasSize(2);
// when
unassigned.forEach(task -> task.setPersonAssignedTo(person));
TickingFixtureClock.replaceExisting().addDate(0, 0, 20);
final TaskOverview overview = serviceRegistry.injectServicesInto(new TaskOverview(person));
// then
sudoService.sudo(person.getUsername(), () -> {
assertThat(overview.getListOfTasksOverdue()).hasSize(1); // order excluded
});
}
@Inject
SudoService sudoService;
}
public static class SendReminder extends TaskOverview_IntegTest {
@Before
public void setupData() {
runFixtureScript(new FixtureScript() {
@Override
protected void execute(final ExecutionContext executionContext) {
executionContext.executeChild(this, new IncomingChargesFraXlsxFixture());
executionContext.executeChild(this, new DocumentTypesAndTemplatesForCapexFixture());
executionContext.executeChild(this, IncomingInvoice_enum.fakeInvoice2Pdf.builder());
executionContext.executeChild(this, Person_enum.DanielOfficeAdministratorFr.builder());
executionContext.executeChild(this, Person_enum.FleuretteRenaudFr.builder());
}
});
}
@Test
public void sadCase_noEmailAddress() {
// given
final Person person = Person_enum.FleuretteRenaudFr.findUsing(serviceRegistry);
final List<Task> unassigned = taskRepository.findIncompleteByUnassigned();
assertThat(unassigned).hasSize(2);
unassigned.forEach(task -> task.setPersonAssignedTo(person));
TickingFixtureClock.replaceExisting().addDate(0, 0, 20);
final TaskOverview overview = serviceRegistry.injectServicesInto(new TaskOverview(person));
assertThat(overview.getListOfTasksOverdue()).hasSize(2);
// then
expectedExceptions.expect(DisabledException.class);
expectedExceptions.expectMessage("No email address is known for Renaud, Fleurette");
// when
wrap(overview).sendReminder();
}
@Test
public void sadCase_noOverdueTasks() {
// given
final Person person = Person_enum.FleuretteRenaudFr.findUsing(serviceRegistry);
communicationChannelRepository.newEmail(person, CommunicationChannelType.EMAIL_ADDRESS, "[email protected]");
final TaskOverview overview = serviceRegistry.injectServicesInto(new TaskOverview(person));
// then
expectedExceptions.expect(DisabledException.class);
expectedExceptions.expectMessage("Renaud, Fleurette does not have any overdue tasks");
// when
wrap(overview).sendReminder();
}
@Inject
CommunicationChannelRepository communicationChannelRepository;
}
@Inject
TaskRepository taskRepository;
@Inject
ClockService clockService;
@Inject
TaskReminderService taskReminderService;
}
| estatioapp/app/src/test/java/org/estatio/module/capex/integtests/task/overview/TaskOverview_IntegTest.java | package org.estatio.module.capex.integtests.task.overview;
import java.util.List;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.apache.isis.applib.fixtures.TickingFixtureClock;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.services.clock.ClockService;
import org.apache.isis.applib.services.wrapper.DisabledException;
import org.incode.module.communications.dom.impl.commchannel.CommunicationChannelRepository;
import org.incode.module.communications.dom.impl.commchannel.CommunicationChannelType;
import org.estatio.module.asset.fixtures.person.enums.Person_enum;
import org.estatio.module.capex.app.taskreminder.TaskOverview;
import org.estatio.module.capex.app.taskreminder.TaskReminderService;
import org.estatio.module.capex.dom.task.Task;
import org.estatio.module.capex.dom.task.TaskRepository;
import org.estatio.module.capex.fixtures.incominginvoice.enums.IncomingInvoice_enum;
import org.estatio.module.capex.integtests.CapexModuleIntegTestAbstract;
import org.estatio.module.capex.seed.DocumentTypesAndTemplatesForCapexFixture;
import org.estatio.module.charge.fixtures.incoming.builders.IncomingChargesFraXlsxFixture;
import org.estatio.module.party.dom.Person;
import static org.assertj.core.api.Assertions.assertThat;
public class TaskOverview_IntegTest extends CapexModuleIntegTestAbstract {
public static class OverdueTasks extends TaskOverview_IntegTest {
@Before
public void setupData() {
runFixtureScript(new FixtureScript() {
@Override
protected void execute(final ExecutionContext executionContext) {
executionContext.executeChild(this, new IncomingChargesFraXlsxFixture());
executionContext.executeChild(this, new DocumentTypesAndTemplatesForCapexFixture());
executionContext.executeChild(this, IncomingInvoice_enum.fakeInvoice2Pdf.builder());
executionContext.executeChild(this, Person_enum.DanielOfficeAdministratorFr.builder());
executionContext.executeChild(this, Person_enum.FleuretteRenaudFr.builder());
}
});
}
@Test
public void noOverdueTasks() {
// given
final Person person = Person_enum.DanielOfficeAdministratorFr.findUsing(serviceRegistry);
final TaskOverview overview = serviceRegistry.injectServicesInto(new TaskOverview(person));
// then
assertThat(overview.getListOfTasksOverdue()).isEmpty();
}
@Test
public void overdueTasks() {
// given
final Person person = Person_enum.FleuretteRenaudFr.findUsing(serviceRegistry);
final List<Task> unassigned = taskRepository.findIncompleteByUnassigned();
assertThat(unassigned).hasSize(2);
// when
unassigned.forEach(task -> task.setPersonAssignedTo(person));
TickingFixtureClock.replaceExisting().addDate(0, 0, 20);
final TaskOverview overview = serviceRegistry.injectServicesInto(new TaskOverview(person));
// then
assertThat(overview.getListOfTasksOverdue()).hasSize(1); // order excluded
}
}
public static class SendReminder extends TaskOverview_IntegTest {
@Before
public void setupData() {
runFixtureScript(new FixtureScript() {
@Override
protected void execute(final ExecutionContext executionContext) {
executionContext.executeChild(this, new IncomingChargesFraXlsxFixture());
executionContext.executeChild(this, new DocumentTypesAndTemplatesForCapexFixture());
executionContext.executeChild(this, IncomingInvoice_enum.fakeInvoice2Pdf.builder());
executionContext.executeChild(this, Person_enum.DanielOfficeAdministratorFr.builder());
executionContext.executeChild(this, Person_enum.FleuretteRenaudFr.builder());
}
});
}
@Test
public void sadCase_noEmailAddress() {
// given
final Person person = Person_enum.FleuretteRenaudFr.findUsing(serviceRegistry);
final List<Task> unassigned = taskRepository.findIncompleteByUnassigned();
assertThat(unassigned).hasSize(2);
unassigned.forEach(task -> task.setPersonAssignedTo(person));
TickingFixtureClock.replaceExisting().addDate(0, 0, 20);
final TaskOverview overview = serviceRegistry.injectServicesInto(new TaskOverview(person));
assertThat(overview.getListOfTasksOverdue()).hasSize(2);
// then
expectedExceptions.expect(DisabledException.class);
expectedExceptions.expectMessage("No email address is known for Renaud, Fleurette");
// when
wrap(overview).sendReminder();
}
@Test
public void sadCase_noOverdueTasks() {
// given
final Person person = Person_enum.FleuretteRenaudFr.findUsing(serviceRegistry);
communicationChannelRepository.newEmail(person, CommunicationChannelType.EMAIL_ADDRESS, "[email protected]");
final TaskOverview overview = serviceRegistry.injectServicesInto(new TaskOverview(person));
// then
expectedExceptions.expect(DisabledException.class);
expectedExceptions.expectMessage("Renaud, Fleurette does not have any overdue tasks");
// when
wrap(overview).sendReminder();
}
@Inject
CommunicationChannelRepository communicationChannelRepository;
}
@Inject
TaskRepository taskRepository;
@Inject
ClockService clockService;
@Inject
TaskReminderService taskReminderService;
}
| EST-1923: fixes testing
| estatioapp/app/src/test/java/org/estatio/module/capex/integtests/task/overview/TaskOverview_IntegTest.java | EST-1923: fixes testing |
|
Java | apache-2.0 | 8c3fabdf7b73e5613b9fd5064770f1003db85c22 | 0 | serge-rider/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,dbeaver/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2016 Serge Rieder ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2)
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jkiss.dbeaver.model.impl.jdbc.struct;
import org.jkiss.dbeaver.Log;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.messages.ModelMessages;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPSaveableObject;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.data.*;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement;
import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer;
import org.jkiss.dbeaver.model.impl.data.ExecuteBatchImpl;
import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCStructCache;
import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCColumnMetaData;
import org.jkiss.dbeaver.model.impl.struct.AbstractTable;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLDataSource;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.*;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.util.List;
/**
* JDBC abstract table implementation
*/
public abstract class JDBCTable<DATASOURCE extends DBPDataSource, CONTAINER extends DBSObjectContainer>
extends AbstractTable<DATASOURCE, CONTAINER>
implements DBSDataManipulator, DBPSaveableObject
{
static final Log log = Log.getLog(JDBCTable.class);
public static final String DEFAULT_TABLE_ALIAS = "x";
public static final int DEFAULT_READ_FETCH_SIZE = 10000;
private boolean persisted;
protected JDBCTable(CONTAINER container, boolean persisted)
{
super(container);
this.persisted = persisted;
}
protected JDBCTable(CONTAINER container, @Nullable String tableName, boolean persisted)
{
super(container, tableName);
this.persisted = persisted;
}
public abstract JDBCStructCache<CONTAINER, ? extends DBSEntity, ? extends DBSEntityAttribute> getCache();
@NotNull
@Property(viewable = true, editable = true, valueTransformer = DBObjectNameCaseTransformer.class, order = 1)
@Override
public String getName()
{
return super.getName();
}
@Override
public boolean isPersisted()
{
return persisted;
}
@Override
public void setPersisted(boolean persisted)
{
this.persisted = persisted;
}
@Override
public int getSupportedFeatures()
{
return DATA_COUNT | DATA_FILTER | DATA_SEARCH | DATA_INSERT | DATA_UPDATE | DATA_DELETE;
}
@NotNull
@Override
public DBCStatistics readData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @NotNull DBDDataReceiver dataReceiver, DBDDataFilter dataFilter, long firstRow, long maxRows, long flags)
throws DBCException
{
DBCStatistics statistics = new DBCStatistics();
boolean hasLimits = firstRow >= 0 && maxRows > 0;
DBPDataSource dataSource = session.getDataSource();
DBRProgressMonitor monitor = session.getProgressMonitor();
try {
readRequiredMeta(monitor);
} catch (DBException e) {
log.warn(e);
}
// Always use alias. Some criteria doesn't work without alias
// (e.g. structured attributes in Oracle requires table alias)
String tableAlias = null;
if (dataSource instanceof SQLDataSource) {
if (((SQLDataSource )dataSource).getSQLDialect().supportsAliasInSelect()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
}
DBDPseudoAttribute rowIdAttribute = null;
if ((flags & FLAG_READ_PSEUDO) != 0 && this instanceof DBDPseudoAttributeContainer) {
try {
rowIdAttribute = DBDPseudoAttribute.getAttribute(
((DBDPseudoAttributeContainer) this).getPseudoAttributes(),
DBDPseudoAttributeType.ROWID);
} catch (DBException e) {
log.warn("Can't get pseudo attributes for '" + getName() + "'", e);
}
}
if (rowIdAttribute != null && tableAlias == null) {
log.warn("Can't query ROWID - table alias not supported");
rowIdAttribute = null;
}
StringBuilder query = new StringBuilder(100);
query.append("SELECT ");
appendSelectSource(session.getProgressMonitor(), query, tableAlias, rowIdAttribute);
query.append(" FROM ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(" ").append(tableAlias); //$NON-NLS-1$
}
appendQueryConditions(query, tableAlias, dataFilter);
appendQueryOrder(query, tableAlias, dataFilter);
String sqlQuery = query.toString();
statistics.setQueryText(sqlQuery);
monitor.subTask(ModelMessages.model_jdbc_fetch_table_data);
try (DBCStatement dbStat = DBUtils.prepareStatement(
source,
session,
DBCStatementType.SCRIPT,
sqlQuery,
firstRow,
maxRows))
{
if (dbStat instanceof JDBCStatement && maxRows > 0) {
try {
((JDBCStatement) dbStat).setFetchSize(
maxRows <= 0 ? DEFAULT_READ_FETCH_SIZE : (int) maxRows);
} catch (Exception e) {
log.warn(e);
}
}
long startTime = System.currentTimeMillis();
boolean executeResult = dbStat.executeStatement();
statistics.setExecuteTime(System.currentTimeMillis() - startTime);
if (executeResult) {
DBCResultSet dbResult = dbStat.openResultSet();
if (dbResult != null) {
try {
if (rowIdAttribute != null) {
String attrId = rowIdAttribute.getAlias();
if (CommonUtils.isEmpty(attrId)) {
attrId = rowIdAttribute.getName();
}
// Annotate last attribute with row id
List<DBCAttributeMetaData> metaAttributes = dbResult.getMeta().getAttributes();
for (int i = metaAttributes.size(); i > 0; i--) {
DBCAttributeMetaData attr = metaAttributes.get(i - 1);
if (attrId.equalsIgnoreCase(attr.getName()) && attr instanceof JDBCColumnMetaData) {
((JDBCColumnMetaData) attr).setPseudoAttribute(rowIdAttribute);
break;
}
}
}
dataReceiver.fetchStart(session, dbResult, firstRow, maxRows);
startTime = System.currentTimeMillis();
long rowCount = 0;
while (dbResult.nextRow()) {
if (monitor.isCanceled() || (hasLimits && rowCount >= maxRows)) {
// Fetch not more than max rows
break;
}
dataReceiver.fetchRow(session, dbResult);
rowCount++;
if (rowCount % 100 == 0) {
monitor.subTask(rowCount + ModelMessages.model_jdbc__rows_fetched);
monitor.worked(100);
}
}
statistics.setFetchTime(System.currentTimeMillis() - startTime);
statistics.setRowsFetched(rowCount);
} finally {
// First - close cursor
try {
dbResult.close();
} catch (Throwable e) {
log.error("Error closing result set", e); //$NON-NLS-1$
}
// Then - signal that fetch was ended
try {
dataReceiver.fetchEnd(session, dbResult);
} catch (Throwable e) {
log.error("Error while finishing result set fetch", e); //$NON-NLS-1$
}
}
}
}
return statistics;
} finally {
dataReceiver.close();
}
}
protected void appendSelectSource(DBRProgressMonitor monitor, StringBuilder query, String tableAlias, DBDPseudoAttribute rowIdAttribute) {
if (rowIdAttribute != null) {
// If we have pseudo attributes then query gonna be more complex
query.append(tableAlias).append(".*"); //$NON-NLS-1$
query.append(",").append(rowIdAttribute.translateExpression(tableAlias));
if (rowIdAttribute.getAlias() != null) {
query.append(" as ").append(rowIdAttribute.getAlias());
}
} else {
if (tableAlias != null) {
query.append(tableAlias).append(".");
}
query.append("*"); //$NON-NLS-1$
}
}
@Override
public long countData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @Nullable DBDDataFilter dataFilter) throws DBCException
{
DBRProgressMonitor monitor = session.getProgressMonitor();
StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM "); //$NON-NLS-1$
query.append(getFullQualifiedName());
appendQueryConditions(query, null, dataFilter);
monitor.subTask(ModelMessages.model_jdbc_fetch_table_row_count);
try (DBCStatement dbStat = session.prepareStatement(
DBCStatementType.QUERY,
query.toString(),
false, false, false))
{
dbStat.setStatementSource(source);
if (!dbStat.executeStatement()) {
return 0;
}
DBCResultSet dbResult = dbStat.openResultSet();
if (dbResult == null) {
return 0;
}
try {
if (dbResult.nextRow()) {
Object result = dbResult.getAttributeValue(0);
if (result == null) {
return 0;
} else if (result instanceof Number) {
return ((Number) result).longValue();
} else {
return Long.parseLong(result.toString());
}
} else {
return 0;
}
} finally {
dbResult.close();
}
}
}
@NotNull
@Override
public ExecuteBatch insertData(@NotNull DBCSession session, @NotNull final DBSAttributeBase[] attributes, @Nullable DBDDataReceiver keysReceiver, @NotNull final DBCExecutionSource source)
throws DBCException
{
readRequiredMeta(session.getProgressMonitor());
return new ExecuteBatchImpl(attributes, keysReceiver, true) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
// Make query
StringBuilder query = new StringBuilder(200);
query.append("INSERT INTO ").append(getFullQualifiedName()).append(" ("); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (int i = 0; i < attributes.length; i++) {
DBSAttributeBase attribute = attributes[i];
if (attribute.isPseudoAttribute() || DBUtils.isNullValue(attributeValues[i])) {
continue;
}
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
query.append(getAttributeName(attribute));
}
query.append(")\nVALUES ("); //$NON-NLS-1$
hasKey = false;
for (int i = 0; i < attributes.length; i++) {
DBSAttributeBase attribute = attributes[i];
if (attribute.isPseudoAttribute() || DBUtils.isNullValue(attributeValues[i])) {
continue;
}
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
query.append("?"); //$NON-NLS-1$
}
query.append(")"); //$NON-NLS-1$
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, keysReceiver != null);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (attribute.isPseudoAttribute() || DBUtils.isNullValue(attributeValues[k])) {
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
@NotNull
@Override
public ExecuteBatch updateData(
@NotNull DBCSession session,
@NotNull final DBSAttributeBase[] updateAttributes,
@NotNull final DBSAttributeBase[] keyAttributes,
@Nullable DBDDataReceiver keysReceiver, @NotNull final DBCExecutionSource source)
throws DBCException
{
readRequiredMeta(session.getProgressMonitor());
DBSAttributeBase[] attributes = ArrayUtils.concatArrays(updateAttributes, keyAttributes);
return new ExecuteBatchImpl(attributes, keysReceiver, false) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
String tableAlias = null;
SQLDialect dialect = ((SQLDataSource) session.getDataSource()).getSQLDialect();
if (dialect.supportsAliasInUpdate()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
// Make query
StringBuilder query = new StringBuilder();
query.append("UPDATE ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(' ').append(tableAlias);
}
query.append("\nSET "); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (DBSAttributeBase attribute : updateAttributes) {
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
if (tableAlias != null) {
query.append(tableAlias).append(dialect.getStructSeparator());
}
query.append(getAttributeName(attribute)).append("=?"); //$NON-NLS-1$
}
query.append("\nWHERE "); //$NON-NLS-1$
hasKey = false;
for (int i = 0; i < keyAttributes.length; i++) {
DBSAttributeBase attribute = keyAttributes[i];
if (hasKey) query.append(" AND "); //$NON-NLS-1$
hasKey = true;
appendAttributeCriteria(tableAlias, dialect, query, attribute, attributeValues[updateAttributes.length + i]);
}
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, keysReceiver != null);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (k >= updateAttributes.length && DBUtils.isNullValue(attributeValues[k])) {
// Skip NULL criteria binding
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
@NotNull
@Override
public ExecuteBatch deleteData(@NotNull DBCSession session, @NotNull final DBSAttributeBase[] keyAttributes, @NotNull final DBCExecutionSource source)
throws DBCException
{
readRequiredMeta(session.getProgressMonitor());
return new ExecuteBatchImpl(keyAttributes, null, false) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
String tableAlias = null;
SQLDialect dialect = ((SQLDataSource) session.getDataSource()).getSQLDialect();
if (dialect.supportsAliasInUpdate()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
// Make query
StringBuilder query = new StringBuilder();
query.append("DELETE FROM ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(' ').append(tableAlias);
}
query.append("\nWHERE "); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (int i = 0; i < keyAttributes.length; i++) {
if (hasKey) query.append(" AND "); //$NON-NLS-1$
hasKey = true;
appendAttributeCriteria(tableAlias, dialect, query, keyAttributes[i], attributeValues[i]);
}
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, false);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (DBUtils.isNullValue(attributeValues[k])) {
// Skip NULL criteria binding
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
private String getAttributeName(@NotNull DBSAttributeBase attribute) {
// Entity attribute obtain commented because it broke complex attributes full name construction
// We can't use entity attr because only particular query metadata contains real structure
// if (attribute instanceof DBDAttributeBinding) {
// DBSEntityAttribute entityAttribute = ((DBDAttributeBinding) attribute).getEntityAttribute();
// if (entityAttribute != null) {
// attribute = entityAttribute;
// }
// }
// Do not quote pseudo attribute name
return attribute.isPseudoAttribute() ? attribute.getName() : DBUtils.getObjectFullName(getDataSource(), attribute);
}
private void appendQueryConditions(@NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter)
{
if (dataFilter != null && dataFilter.hasConditions()) {
query.append("\nWHERE "); //$NON-NLS-1$
SQLUtils.appendConditionString(dataFilter, getDataSource(), tableAlias, query, true);
}
}
private void appendQueryOrder(@NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter)
{
if (dataFilter != null) {
// Construct ORDER BY
if (dataFilter.hasOrdering()) {
query.append("\nORDER BY "); //$NON-NLS-1$
SQLUtils.appendOrderString(dataFilter, getDataSource(), tableAlias, query);
}
}
}
private void appendAttributeCriteria(@Nullable String tableAlias, SQLDialect dialect, StringBuilder query, DBSAttributeBase attribute, Object value) {
DBDPseudoAttribute pseudoAttribute = null;
if (attribute.isPseudoAttribute()) {
if (attribute instanceof DBDAttributeBinding) {
pseudoAttribute = ((DBDAttributeBinding) attribute).getMetaAttribute().getPseudoAttribute();
} else if (attribute instanceof DBCAttributeMetaData) {
pseudoAttribute = ((DBCAttributeMetaData)attribute).getPseudoAttribute();
} else {
log.error("Unsupported attribute argument: " + attribute);
}
}
if (pseudoAttribute != null) {
if (tableAlias == null) {
tableAlias = this.getFullQualifiedName();
}
String criteria = pseudoAttribute.translateExpression(tableAlias);
query.append(criteria);
} else {
if (tableAlias != null) {
query.append(tableAlias).append(dialect.getStructSeparator());
}
query.append(getAttributeName(attribute));
}
if (DBUtils.isNullValue(value)) {
query.append(" IS NULL"); //$NON-NLS-1$
} else {
query.append("=?"); //$NON-NLS-1$
}
}
/**
* Reads and caches metadata which is required for data requests
* @param monitor progress monitor
* @throws DBCException on error
*/
private void readRequiredMeta(DBRProgressMonitor monitor)
throws DBCException
{
try {
getAttributes(monitor);
}
catch (DBException e) {
throw new DBCException("Can't cache table columns", e);
}
}
}
| plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/struct/JDBCTable.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2016 Serge Rieder ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2)
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jkiss.dbeaver.model.impl.jdbc.struct;
import org.jkiss.dbeaver.Log;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.messages.ModelMessages;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPSaveableObject;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.data.*;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement;
import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer;
import org.jkiss.dbeaver.model.impl.data.ExecuteBatchImpl;
import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCStructCache;
import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCColumnMetaData;
import org.jkiss.dbeaver.model.impl.struct.AbstractTable;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLDataSource;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.*;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.util.List;
/**
* JDBC abstract table implementation
*/
public abstract class JDBCTable<DATASOURCE extends DBPDataSource, CONTAINER extends DBSObjectContainer>
extends AbstractTable<DATASOURCE, CONTAINER>
implements DBSDataManipulator, DBPSaveableObject
{
static final Log log = Log.getLog(JDBCTable.class);
public static final String DEFAULT_TABLE_ALIAS = "x";
public static final int DEFAULT_READ_FETCH_SIZE = 10000;
private boolean persisted;
protected JDBCTable(CONTAINER container, boolean persisted)
{
super(container);
this.persisted = persisted;
}
protected JDBCTable(CONTAINER container, @Nullable String tableName, boolean persisted)
{
super(container, tableName);
this.persisted = persisted;
}
public abstract JDBCStructCache<CONTAINER, ? extends DBSEntity, ? extends DBSEntityAttribute> getCache();
@NotNull
@Property(viewable = true, editable = true, valueTransformer = DBObjectNameCaseTransformer.class, order = 1)
@Override
public String getName()
{
return super.getName();
}
@Override
public boolean isPersisted()
{
return persisted;
}
@Override
public void setPersisted(boolean persisted)
{
this.persisted = persisted;
}
@Override
public int getSupportedFeatures()
{
return DATA_COUNT | DATA_FILTER | DATA_SEARCH | DATA_INSERT | DATA_UPDATE | DATA_DELETE;
}
@NotNull
@Override
public DBCStatistics readData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @NotNull DBDDataReceiver dataReceiver, DBDDataFilter dataFilter, long firstRow, long maxRows, long flags)
throws DBCException
{
DBCStatistics statistics = new DBCStatistics();
boolean hasLimits = firstRow >= 0 && maxRows > 0;
DBPDataSource dataSource = session.getDataSource();
DBRProgressMonitor monitor = session.getProgressMonitor();
try {
readRequiredMeta(monitor);
} catch (DBException e) {
log.warn(e);
}
// Always use alias. Some criteria doesn't work without alias
// (e.g. structured attributes in Oracle requires table alias)
String tableAlias = null;
if (dataSource instanceof SQLDataSource) {
if (((SQLDataSource )dataSource).getSQLDialect().supportsAliasInSelect()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
}
DBDPseudoAttribute rowIdAttribute = null;
if ((flags & FLAG_READ_PSEUDO) != 0 && this instanceof DBDPseudoAttributeContainer) {
try {
rowIdAttribute = DBDPseudoAttribute.getAttribute(
((DBDPseudoAttributeContainer) this).getPseudoAttributes(),
DBDPseudoAttributeType.ROWID);
} catch (DBException e) {
log.warn("Can't get pseudo attributes for '" + getName() + "'", e);
}
}
if (rowIdAttribute != null && tableAlias == null) {
log.warn("Can't query ROWID - table alias not supported");
rowIdAttribute = null;
}
StringBuilder query = new StringBuilder(100);
query.append("SELECT ");
appendSelectSource(session.getProgressMonitor(), query, tableAlias, rowIdAttribute);
query.append(" FROM ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(" ").append(tableAlias); //$NON-NLS-1$
}
appendQueryConditions(query, tableAlias, dataFilter);
appendQueryOrder(query, tableAlias, dataFilter);
String sqlQuery = query.toString();
statistics.setQueryText(sqlQuery);
monitor.subTask(ModelMessages.model_jdbc_fetch_table_data);
try (DBCStatement dbStat = DBUtils.prepareStatement(
source,
session,
DBCStatementType.SCRIPT,
sqlQuery,
firstRow,
maxRows))
{
if (dbStat instanceof JDBCStatement && maxRows > 0) {
try {
((JDBCStatement) dbStat).setFetchSize(
maxRows <= 0 ? DEFAULT_READ_FETCH_SIZE : (int) maxRows);
} catch (Exception e) {
log.warn(e);
}
}
long startTime = System.currentTimeMillis();
boolean executeResult = dbStat.executeStatement();
statistics.setExecuteTime(System.currentTimeMillis() - startTime);
if (executeResult) {
DBCResultSet dbResult = dbStat.openResultSet();
if (dbResult != null) {
try {
if (rowIdAttribute != null) {
String attrId = rowIdAttribute.getAlias();
if (CommonUtils.isEmpty(attrId)) {
attrId = rowIdAttribute.getName();
}
// Annotate last attribute with row id
List<DBCAttributeMetaData> metaAttributes = dbResult.getMeta().getAttributes();
for (int i = metaAttributes.size(); i > 0; i--) {
DBCAttributeMetaData attr = metaAttributes.get(i - 1);
if (attrId.equalsIgnoreCase(attr.getName()) && attr instanceof JDBCColumnMetaData) {
((JDBCColumnMetaData) attr).setPseudoAttribute(rowIdAttribute);
break;
}
}
}
dataReceiver.fetchStart(session, dbResult, firstRow, maxRows);
startTime = System.currentTimeMillis();
long rowCount = 0;
while (dbResult.nextRow()) {
if (monitor.isCanceled() || (hasLimits && rowCount >= maxRows)) {
// Fetch not more than max rows
break;
}
dataReceiver.fetchRow(session, dbResult);
rowCount++;
if (rowCount % 100 == 0) {
monitor.subTask(rowCount + ModelMessages.model_jdbc__rows_fetched);
monitor.worked(100);
}
}
statistics.setFetchTime(System.currentTimeMillis() - startTime);
statistics.setRowsFetched(rowCount);
} finally {
// First - close cursor
try {
dbResult.close();
} catch (Throwable e) {
log.error("Error closing result set", e); //$NON-NLS-1$
}
// Then - signal that fetch was ended
try {
dataReceiver.fetchEnd(session, dbResult);
} catch (Throwable e) {
log.error("Error while finishing result set fetch", e); //$NON-NLS-1$
}
}
}
}
return statistics;
} finally {
dataReceiver.close();
}
}
protected void appendSelectSource(DBRProgressMonitor monitor, StringBuilder query, String tableAlias, DBDPseudoAttribute rowIdAttribute) {
if (rowIdAttribute != null) {
// If we have pseudo attributes then query gonna be more complex
query.append(tableAlias).append(".*"); //$NON-NLS-1$
query.append(",").append(rowIdAttribute.translateExpression(tableAlias));
if (rowIdAttribute.getAlias() != null) {
query.append(" as ").append(rowIdAttribute.getAlias());
}
} else {
if (tableAlias != null) {
query.append(tableAlias).append(".");
}
query.append("*"); //$NON-NLS-1$
}
}
@Override
public long countData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @Nullable DBDDataFilter dataFilter) throws DBCException
{
DBRProgressMonitor monitor = session.getProgressMonitor();
StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM "); //$NON-NLS-1$
query.append(getFullQualifiedName());
appendQueryConditions(query, null, dataFilter);
monitor.subTask(ModelMessages.model_jdbc_fetch_table_row_count);
try (DBCStatement dbStat = session.prepareStatement(
DBCStatementType.QUERY,
query.toString(),
false, false, false))
{
dbStat.setStatementSource(source);
if (!dbStat.executeStatement()) {
return 0;
}
DBCResultSet dbResult = dbStat.openResultSet();
if (dbResult == null) {
return 0;
}
try {
if (dbResult.nextRow()) {
Object result = dbResult.getAttributeValue(0);
if (result == null) {
return 0;
} else if (result instanceof Number) {
return ((Number) result).longValue();
} else {
return Long.parseLong(result.toString());
}
} else {
return 0;
}
} finally {
dbResult.close();
}
}
}
@NotNull
@Override
public ExecuteBatch insertData(@NotNull DBCSession session, @NotNull final DBSAttributeBase[] attributes, @Nullable DBDDataReceiver keysReceiver, @NotNull final DBCExecutionSource source)
throws DBCException
{
readRequiredMeta(session.getProgressMonitor());
return new ExecuteBatchImpl(attributes, keysReceiver, true) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
// Make query
StringBuilder query = new StringBuilder(200);
query.append("INSERT INTO ").append(getFullQualifiedName()).append(" ("); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (int i = 0; i < attributes.length; i++) {
DBSAttributeBase attribute = attributes[i];
if (attribute.isPseudoAttribute() || attribute.isAutoGenerated() || DBUtils.isNullValue(attributeValues[i])) {
continue;
}
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
query.append(getAttributeName(attribute));
}
query.append(")\nVALUES ("); //$NON-NLS-1$
hasKey = false;
for (int i = 0; i < attributes.length; i++) {
DBSAttributeBase attribute = attributes[i];
if (attribute.isPseudoAttribute() || attribute.isAutoGenerated() || DBUtils.isNullValue(attributeValues[i])) {
continue;
}
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
query.append("?"); //$NON-NLS-1$
}
query.append(")"); //$NON-NLS-1$
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, keysReceiver != null);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (attribute.isPseudoAttribute() || attribute.isAutoGenerated() || DBUtils.isNullValue(attributeValues[k])) {
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
@NotNull
@Override
public ExecuteBatch updateData(
@NotNull DBCSession session,
@NotNull final DBSAttributeBase[] updateAttributes,
@NotNull final DBSAttributeBase[] keyAttributes,
@Nullable DBDDataReceiver keysReceiver, @NotNull final DBCExecutionSource source)
throws DBCException
{
readRequiredMeta(session.getProgressMonitor());
DBSAttributeBase[] attributes = ArrayUtils.concatArrays(updateAttributes, keyAttributes);
return new ExecuteBatchImpl(attributes, keysReceiver, false) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
String tableAlias = null;
SQLDialect dialect = ((SQLDataSource) session.getDataSource()).getSQLDialect();
if (dialect.supportsAliasInUpdate()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
// Make query
StringBuilder query = new StringBuilder();
query.append("UPDATE ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(' ').append(tableAlias);
}
query.append("\nSET "); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (DBSAttributeBase attribute : updateAttributes) {
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
if (tableAlias != null) {
query.append(tableAlias).append(dialect.getStructSeparator());
}
query.append(getAttributeName(attribute)).append("=?"); //$NON-NLS-1$
}
query.append("\nWHERE "); //$NON-NLS-1$
hasKey = false;
for (int i = 0; i < keyAttributes.length; i++) {
DBSAttributeBase attribute = keyAttributes[i];
if (hasKey) query.append(" AND "); //$NON-NLS-1$
hasKey = true;
appendAttributeCriteria(tableAlias, dialect, query, attribute, attributeValues[updateAttributes.length + i]);
}
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, keysReceiver != null);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (k >= updateAttributes.length && DBUtils.isNullValue(attributeValues[k])) {
// Skip NULL criteria binding
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
@NotNull
@Override
public ExecuteBatch deleteData(@NotNull DBCSession session, @NotNull final DBSAttributeBase[] keyAttributes, @NotNull final DBCExecutionSource source)
throws DBCException
{
readRequiredMeta(session.getProgressMonitor());
return new ExecuteBatchImpl(keyAttributes, null, false) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
String tableAlias = null;
SQLDialect dialect = ((SQLDataSource) session.getDataSource()).getSQLDialect();
if (dialect.supportsAliasInUpdate()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
// Make query
StringBuilder query = new StringBuilder();
query.append("DELETE FROM ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(' ').append(tableAlias);
}
query.append("\nWHERE "); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (int i = 0; i < keyAttributes.length; i++) {
if (hasKey) query.append(" AND "); //$NON-NLS-1$
hasKey = true;
appendAttributeCriteria(tableAlias, dialect, query, keyAttributes[i], attributeValues[i]);
}
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, false);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (DBUtils.isNullValue(attributeValues[k])) {
// Skip NULL criteria binding
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
private String getAttributeName(@NotNull DBSAttributeBase attribute) {
// Entity attribute obtain commented because it broke complex attributes full name construction
// We can't use entity attr because only particular query metadata contains real structure
// if (attribute instanceof DBDAttributeBinding) {
// DBSEntityAttribute entityAttribute = ((DBDAttributeBinding) attribute).getEntityAttribute();
// if (entityAttribute != null) {
// attribute = entityAttribute;
// }
// }
// Do not quote pseudo attribute name
return attribute.isPseudoAttribute() ? attribute.getName() : DBUtils.getObjectFullName(getDataSource(), attribute);
}
private void appendQueryConditions(@NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter)
{
if (dataFilter != null && dataFilter.hasConditions()) {
query.append("\nWHERE "); //$NON-NLS-1$
SQLUtils.appendConditionString(dataFilter, getDataSource(), tableAlias, query, true);
}
}
private void appendQueryOrder(@NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter)
{
if (dataFilter != null) {
// Construct ORDER BY
if (dataFilter.hasOrdering()) {
query.append("\nORDER BY "); //$NON-NLS-1$
SQLUtils.appendOrderString(dataFilter, getDataSource(), tableAlias, query);
}
}
}
private void appendAttributeCriteria(@Nullable String tableAlias, SQLDialect dialect, StringBuilder query, DBSAttributeBase attribute, Object value) {
DBDPseudoAttribute pseudoAttribute = null;
if (attribute.isPseudoAttribute()) {
if (attribute instanceof DBDAttributeBinding) {
pseudoAttribute = ((DBDAttributeBinding) attribute).getMetaAttribute().getPseudoAttribute();
} else if (attribute instanceof DBCAttributeMetaData) {
pseudoAttribute = ((DBCAttributeMetaData)attribute).getPseudoAttribute();
} else {
log.error("Unsupported attribute argument: " + attribute);
}
}
if (pseudoAttribute != null) {
if (tableAlias == null) {
tableAlias = this.getFullQualifiedName();
}
String criteria = pseudoAttribute.translateExpression(tableAlias);
query.append(criteria);
} else {
if (tableAlias != null) {
query.append(tableAlias).append(dialect.getStructSeparator());
}
query.append(getAttributeName(attribute));
}
if (DBUtils.isNullValue(value)) {
query.append(" IS NULL"); //$NON-NLS-1$
} else {
query.append("=?"); //$NON-NLS-1$
}
}
/**
* Reads and caches metadata which is required for data requests
* @param monitor progress monitor
* @throws DBCException on error
*/
private void readRequiredMeta(DBRProgressMonitor monitor)
throws DBCException
{
try {
getAttributes(monitor);
}
catch (DBException e) {
throw new DBCException("Can't cache table columns", e);
}
}
}
| #294 Insert explicit auto-increment values (if specified)
Former-commit-id: 7182148ca964b8d7943eb200d7a2e10b133252af | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/struct/JDBCTable.java | #294 Insert explicit auto-increment values (if specified) |
|
Java | apache-2.0 | a5ef1437e6501dc596911aeea5057a0a55191fc9 | 0 | sunjincheng121/flink,hequn8128/flink,hequn8128/flink,wwjiang007/flink,apache/flink,tillrohrmann/flink,kl0u/flink,greghogan/flink,twalthr/flink,kl0u/flink,gyfora/flink,greghogan/flink,greghogan/flink,apache/flink,twalthr/flink,zentol/flink,rmetzger/flink,clarkyzl/flink,twalthr/flink,godfreyhe/flink,rmetzger/flink,wwjiang007/flink,wwjiang007/flink,bowenli86/flink,kaibozhou/flink,kl0u/flink,gyfora/flink,sunjincheng121/flink,darionyaphet/flink,hequn8128/flink,zentol/flink,tony810430/flink,wwjiang007/flink,apache/flink,zjureel/flink,hequn8128/flink,zentol/flink,gyfora/flink,zentol/flink,tony810430/flink,bowenli86/flink,apache/flink,darionyaphet/flink,xccui/flink,bowenli86/flink,jinglining/flink,jinglining/flink,bowenli86/flink,godfreyhe/flink,StephanEwen/incubator-flink,hequn8128/flink,apache/flink,zentol/flink,GJL/flink,lincoln-lil/flink,aljoscha/flink,tony810430/flink,lincoln-lil/flink,wwjiang007/flink,rmetzger/flink,godfreyhe/flink,lincoln-lil/flink,kaibozhou/flink,darionyaphet/flink,darionyaphet/flink,GJL/flink,GJL/flink,tillrohrmann/flink,greghogan/flink,twalthr/flink,lincoln-lil/flink,xccui/flink,jinglining/flink,rmetzger/flink,StephanEwen/incubator-flink,tzulitai/flink,lincoln-lil/flink,jinglining/flink,lincoln-lil/flink,wwjiang007/flink,GJL/flink,kl0u/flink,tillrohrmann/flink,kl0u/flink,zentol/flink,kaibozhou/flink,twalthr/flink,kaibozhou/flink,zjureel/flink,tzulitai/flink,aljoscha/flink,tzulitai/flink,wwjiang007/flink,xccui/flink,GJL/flink,clarkyzl/flink,zjureel/flink,tzulitai/flink,xccui/flink,rmetzger/flink,tillrohrmann/flink,zentol/flink,GJL/flink,sunjincheng121/flink,gyfora/flink,kl0u/flink,kaibozhou/flink,zjureel/flink,twalthr/flink,zjureel/flink,xccui/flink,kaibozhou/flink,tillrohrmann/flink,StephanEwen/incubator-flink,clarkyzl/flink,tony810430/flink,godfreyhe/flink,StephanEwen/incubator-flink,gyfora/flink,tzulitai/flink,aljoscha/flink,bowenli86/flink,jinglining/flink,gyfora/flink,rmetzger/flink,StephanEwen/incubator-flink,zjureel/flink,xccui/flink,twalthr/flink,clarkyzl/flink,sunjincheng121/flink,aljoscha/flink,rmetzger/flink,jinglining/flink,tony810430/flink,xccui/flink,apache/flink,StephanEwen/incubator-flink,greghogan/flink,aljoscha/flink,tony810430/flink,lincoln-lil/flink,hequn8128/flink,tzulitai/flink,sunjincheng121/flink,tony810430/flink,aljoscha/flink,godfreyhe/flink,tillrohrmann/flink,apache/flink,bowenli86/flink,tillrohrmann/flink,darionyaphet/flink,sunjincheng121/flink,godfreyhe/flink,greghogan/flink,clarkyzl/flink,godfreyhe/flink,zjureel/flink,gyfora/flink | /*
* 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.flink.runtime.executiongraph;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.ArchivedExecutionConfig;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.api.common.accumulators.Accumulator;
import org.apache.flink.api.common.accumulators.AccumulatorHelper;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.SimpleCounter;
import org.apache.flink.runtime.JobException;
import org.apache.flink.runtime.accumulators.AccumulatorSnapshot;
import org.apache.flink.runtime.accumulators.StringifiedAccumulatorResult;
import org.apache.flink.runtime.blob.BlobWriter;
import org.apache.flink.runtime.blob.PermanentBlobKey;
import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
import org.apache.flink.runtime.checkpoint.CheckpointFailureManager;
import org.apache.flink.runtime.checkpoint.CheckpointIDCounter;
import org.apache.flink.runtime.checkpoint.CheckpointStatsSnapshot;
import org.apache.flink.runtime.checkpoint.CheckpointStatsTracker;
import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore;
import org.apache.flink.runtime.checkpoint.MasterTriggerRestoreHook;
import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.concurrent.FutureUtils.ConjunctFuture;
import org.apache.flink.runtime.concurrent.ScheduledExecutorServiceAdapter;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.execution.SuppressRestartsException;
import org.apache.flink.runtime.executiongraph.failover.FailoverStrategy;
import org.apache.flink.runtime.executiongraph.failover.flip1.FailoverTopology;
import org.apache.flink.runtime.executiongraph.failover.flip1.ResultPartitionAvailabilityChecker;
import org.apache.flink.runtime.executiongraph.failover.flip1.partitionrelease.PartitionReleaseStrategy;
import org.apache.flink.runtime.executiongraph.restart.ExecutionGraphRestartCallback;
import org.apache.flink.runtime.executiongraph.restart.RestartCallback;
import org.apache.flink.runtime.executiongraph.restart.RestartStrategy;
import org.apache.flink.runtime.io.network.partition.JobMasterPartitionTracker;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.ScheduleMode;
import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration;
import org.apache.flink.runtime.jobmanager.scheduler.CoLocationGroup;
import org.apache.flink.runtime.jobmaster.slotpool.SlotProvider;
import org.apache.flink.runtime.query.KvStateLocationRegistry;
import org.apache.flink.runtime.scheduler.InternalFailuresListener;
import org.apache.flink.runtime.scheduler.adapter.DefaultExecutionTopology;
import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
import org.apache.flink.runtime.scheduler.strategy.SchedulingExecutionVertex;
import org.apache.flink.runtime.scheduler.strategy.SchedulingResultPartition;
import org.apache.flink.runtime.scheduler.strategy.SchedulingTopology;
import org.apache.flink.runtime.shuffle.ShuffleMaster;
import org.apache.flink.runtime.state.SharedStateRegistry;
import org.apache.flink.runtime.state.StateBackend;
import org.apache.flink.runtime.taskmanager.DispatcherThreadFactory;
import org.apache.flink.runtime.taskmanager.TaskExecutionState;
import org.apache.flink.types.Either;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.OptionalFailure;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.SerializedThrowable;
import org.apache.flink.util.SerializedValue;
import org.apache.flink.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* The execution graph is the central data structure that coordinates the distributed
* execution of a data flow. It keeps representations of each parallel task, each
* intermediate stream, and the communication between them.
*
* <p>The execution graph consists of the following constructs:
* <ul>
* <li>The {@link ExecutionJobVertex} represents one vertex from the JobGraph (usually one operation like
* "map" or "join") during execution. It holds the aggregated state of all parallel subtasks.
* The ExecutionJobVertex is identified inside the graph by the {@link JobVertexID}, which it takes
* from the JobGraph's corresponding JobVertex.</li>
* <li>The {@link ExecutionVertex} represents one parallel subtask. For each ExecutionJobVertex, there are
* as many ExecutionVertices as the parallelism. The ExecutionVertex is identified by
* the ExecutionJobVertex and the index of the parallel subtask</li>
* <li>The {@link Execution} is one attempt to execute a ExecutionVertex. There may be multiple Executions
* for the ExecutionVertex, in case of a failure, or in the case where some data needs to be recomputed
* because it is no longer available when requested by later operations. An Execution is always
* identified by an {@link ExecutionAttemptID}. All messages between the JobManager and the TaskManager
* about deployment of tasks and updates in the task status always use the ExecutionAttemptID to
* address the message receiver.</li>
* </ul>
*
* <h2>Global and local failover</h2>
*
* <p>The Execution Graph has two failover modes: <i>global failover</i> and <i>local failover</i>.
*
* <p>A <b>global failover</b> aborts the task executions for all vertices and restarts whole
* data flow graph from the last completed checkpoint. Global failover is considered the
* "fallback strategy" that is used when a local failover is unsuccessful, or when a issue is
* found in the state of the ExecutionGraph that could mark it as inconsistent (caused by a bug).
*
* <p>A <b>local failover</b> is triggered when an individual vertex execution (a task) fails.
* The local failover is coordinated by the {@link FailoverStrategy}. A local failover typically
* attempts to restart as little as possible, but as much as necessary.
*
* <p>Between local- and global failover, the global failover always takes precedence, because it
* is the core mechanism that the ExecutionGraph relies on to bring back consistency. The
* guard that, the ExecutionGraph maintains a <i>global modification version</i>, which is incremented
* with every global failover (and other global actions, like job cancellation, or terminal
* failure). Local failover is always scoped by the modification version that the execution graph
* had when the failover was triggered. If a new global modification version is reached during
* local failover (meaning there is a concurrent global failover), the failover strategy has to
* yield before the global failover.
*/
public class ExecutionGraph implements AccessExecutionGraph {
/** The log object used for debugging. */
static final Logger LOG = LoggerFactory.getLogger(ExecutionGraph.class);
// --------------------------------------------------------------------------------------------
/** Job specific information like the job id, job name, job configuration, etc. */
private final JobInformation jobInformation;
/** Serialized job information or a blob key pointing to the offloaded job information. */
private final Either<SerializedValue<JobInformation>, PermanentBlobKey> jobInformationOrBlobKey;
/** The executor which is used to execute futures. */
private final ScheduledExecutorService futureExecutor;
/** The executor which is used to execute blocking io operations. */
private final Executor ioExecutor;
/** Executor that runs tasks in the job manager's main thread. */
@Nonnull
private ComponentMainThreadExecutor jobMasterMainThreadExecutor;
/** {@code true} if all source tasks are stoppable. */
private boolean isStoppable = true;
/** All job vertices that are part of this graph. */
private final Map<JobVertexID, ExecutionJobVertex> tasks;
/** All vertices, in the order in which they were created. **/
private final List<ExecutionJobVertex> verticesInCreationOrder;
/** All intermediate results that are part of this graph. */
private final Map<IntermediateDataSetID, IntermediateResult> intermediateResults;
/** The currently executed tasks, for callbacks. */
private final Map<ExecutionAttemptID, Execution> currentExecutions;
/** Listeners that receive messages when the entire job switches it status
* (such as from RUNNING to FINISHED). */
private final List<JobStatusListener> jobStatusListeners;
/** The implementation that decides how to recover the failures of tasks. */
private final FailoverStrategy failoverStrategy;
/** Timestamps (in milliseconds as returned by {@code System.currentTimeMillis()} when
* the execution graph transitioned into a certain state. The index into this array is the
* ordinal of the enum value, i.e. the timestamp when the graph went into state "RUNNING" is
* at {@code stateTimestamps[RUNNING.ordinal()]}. */
private final long[] stateTimestamps;
/** The timeout for all messages that require a response/acknowledgement. */
private final Time rpcTimeout;
/** The timeout for slot allocations. */
private final Time allocationTimeout;
/** Strategy to use for restarts. */
private final RestartStrategy restartStrategy;
/** The slot provider strategy to use for allocating slots for tasks as they are needed. */
private final SlotProviderStrategy slotProviderStrategy;
/** The classloader for the user code. Needed for calls into user code classes. */
private final ClassLoader userClassLoader;
/** Registered KvState instances reported by the TaskManagers. */
private final KvStateLocationRegistry kvStateLocationRegistry;
/** Blob writer used to offload RPC messages. */
private final BlobWriter blobWriter;
private boolean legacyScheduling = true;
/** The total number of vertices currently in the execution graph. */
private int numVerticesTotal;
private final PartitionReleaseStrategy.Factory partitionReleaseStrategyFactory;
private PartitionReleaseStrategy partitionReleaseStrategy;
private DefaultExecutionTopology executionTopology;
@Nullable
private InternalFailuresListener internalTaskFailuresListener;
/** Counts all restarts. Used by other Gauges/Meters and does not register to metric group. */
private final Counter numberOfRestartsCounter = new SimpleCounter();
// ------ Configuration of the Execution -------
/** The mode of scheduling. Decides how to select the initial set of tasks to be deployed.
* May indicate to deploy all sources, or to deploy everything, or to deploy via backtracking
* from results than need to be materialized. */
private final ScheduleMode scheduleMode;
/** The maximum number of prior execution attempts kept in history. */
private final int maxPriorAttemptsHistoryLength;
// ------ Execution status and progress. These values are volatile, and accessed under the lock -------
private int verticesFinished;
/** Current status of the job execution. */
private volatile JobStatus state = JobStatus.CREATED;
/** A future that completes once the job has reached a terminal state. */
private final CompletableFuture<JobStatus> terminationFuture = new CompletableFuture<>();
/** On each global recovery, this version is incremented. The version breaks conflicts
* between concurrent restart attempts by local failover strategies. */
private long globalModVersion;
/** The exception that caused the job to fail. This is set to the first root exception
* that was not recoverable and triggered job failure. */
private Throwable failureCause;
/** The extended failure cause information for the job. This exists in addition to 'failureCause',
* to let 'failureCause' be a strong reference to the exception, while this info holds no
* strong reference to any user-defined classes.*/
private ErrorInfo failureInfo;
private final JobMasterPartitionTracker partitionTracker;
private final ResultPartitionAvailabilityChecker resultPartitionAvailabilityChecker;
/**
* Future for an ongoing or completed scheduling action.
*/
@Nullable
private CompletableFuture<Void> schedulingFuture;
// ------ Fields that are relevant to the execution and need to be cleared before archiving -------
/** The coordinator for checkpoints, if snapshot checkpoints are enabled. */
@Nullable
private CheckpointCoordinator checkpointCoordinator;
/** TODO, replace it with main thread executor. */
@Nullable
private ScheduledExecutorService checkpointCoordinatorTimer;
/** Checkpoint stats tracker separate from the coordinator in order to be
* available after archiving. */
private CheckpointStatsTracker checkpointStatsTracker;
// ------ Fields that are only relevant for archived execution graphs ------------
@Nullable
private String stateBackendName;
private String jsonPlan;
/** Shuffle master to register partitions for task deployment. */
private final ShuffleMaster<?> shuffleMaster;
// --------------------------------------------------------------------------------------------
// Constructors
// --------------------------------------------------------------------------------------------
public ExecutionGraph(
JobInformation jobInformation,
ScheduledExecutorService futureExecutor,
Executor ioExecutor,
Time rpcTimeout,
RestartStrategy restartStrategy,
int maxPriorAttemptsHistoryLength,
FailoverStrategy.Factory failoverStrategyFactory,
SlotProvider slotProvider,
ClassLoader userClassLoader,
BlobWriter blobWriter,
Time allocationTimeout,
PartitionReleaseStrategy.Factory partitionReleaseStrategyFactory,
ShuffleMaster<?> shuffleMaster,
JobMasterPartitionTracker partitionTracker,
ScheduleMode scheduleMode) throws IOException {
this.jobInformation = Preconditions.checkNotNull(jobInformation);
this.blobWriter = Preconditions.checkNotNull(blobWriter);
this.scheduleMode = checkNotNull(scheduleMode);
this.jobInformationOrBlobKey = BlobWriter.serializeAndTryOffload(jobInformation, jobInformation.getJobId(), blobWriter);
this.futureExecutor = Preconditions.checkNotNull(futureExecutor);
this.ioExecutor = Preconditions.checkNotNull(ioExecutor);
this.slotProviderStrategy = SlotProviderStrategy.from(
scheduleMode,
slotProvider,
allocationTimeout);
this.userClassLoader = Preconditions.checkNotNull(userClassLoader, "userClassLoader");
this.tasks = new HashMap<>(16);
this.intermediateResults = new HashMap<>(16);
this.verticesInCreationOrder = new ArrayList<>(16);
this.currentExecutions = new HashMap<>(16);
this.jobStatusListeners = new ArrayList<>();
this.stateTimestamps = new long[JobStatus.values().length];
this.stateTimestamps[JobStatus.CREATED.ordinal()] = System.currentTimeMillis();
this.rpcTimeout = checkNotNull(rpcTimeout);
this.allocationTimeout = checkNotNull(allocationTimeout);
this.partitionReleaseStrategyFactory = checkNotNull(partitionReleaseStrategyFactory);
this.restartStrategy = restartStrategy;
this.kvStateLocationRegistry = new KvStateLocationRegistry(jobInformation.getJobId(), getAllVertices());
this.globalModVersion = 1L;
// the failover strategy must be instantiated last, so that the execution graph
// is ready by the time the failover strategy sees it
this.failoverStrategy = checkNotNull(failoverStrategyFactory.create(this), "null failover strategy");
this.maxPriorAttemptsHistoryLength = maxPriorAttemptsHistoryLength;
this.schedulingFuture = null;
this.jobMasterMainThreadExecutor =
new ComponentMainThreadExecutor.DummyComponentMainThreadExecutor(
"ExecutionGraph is not initialized with proper main thread executor. " +
"Call to ExecutionGraph.start(...) required.");
this.shuffleMaster = checkNotNull(shuffleMaster);
this.partitionTracker = checkNotNull(partitionTracker);
this.resultPartitionAvailabilityChecker = new ExecutionGraphResultPartitionAvailabilityChecker(
this::createResultPartitionId,
partitionTracker);
}
public void start(@Nonnull ComponentMainThreadExecutor jobMasterMainThreadExecutor) {
this.jobMasterMainThreadExecutor = jobMasterMainThreadExecutor;
}
// --------------------------------------------------------------------------------------------
// Configuration of Data-flow wide execution settings
// --------------------------------------------------------------------------------------------
/**
* Gets the number of job vertices currently held by this execution graph.
* @return The current number of job vertices.
*/
public int getNumberOfExecutionJobVertices() {
return this.verticesInCreationOrder.size();
}
public SchedulingTopology<?, ?> getSchedulingTopology() {
return executionTopology;
}
public FailoverTopology<?, ?> getFailoverTopology() {
return executionTopology;
}
public ScheduleMode getScheduleMode() {
return scheduleMode;
}
public Time getAllocationTimeout() {
return allocationTimeout;
}
@Nonnull
public ComponentMainThreadExecutor getJobMasterMainThreadExecutor() {
return jobMasterMainThreadExecutor;
}
@Override
public boolean isArchived() {
return false;
}
@Override
public Optional<String> getStateBackendName() {
return Optional.ofNullable(stateBackendName);
}
public void enableCheckpointing(
CheckpointCoordinatorConfiguration chkConfig,
List<ExecutionJobVertex> verticesToTrigger,
List<ExecutionJobVertex> verticesToWaitFor,
List<ExecutionJobVertex> verticesToCommitTo,
List<MasterTriggerRestoreHook<?>> masterHooks,
CheckpointIDCounter checkpointIDCounter,
CompletedCheckpointStore checkpointStore,
StateBackend checkpointStateBackend,
CheckpointStatsTracker statsTracker) {
checkState(state == JobStatus.CREATED, "Job must be in CREATED state");
checkState(checkpointCoordinator == null, "checkpointing already enabled");
ExecutionVertex[] tasksToTrigger = collectExecutionVertices(verticesToTrigger);
ExecutionVertex[] tasksToWaitFor = collectExecutionVertices(verticesToWaitFor);
ExecutionVertex[] tasksToCommitTo = collectExecutionVertices(verticesToCommitTo);
checkpointStatsTracker = checkNotNull(statsTracker, "CheckpointStatsTracker");
CheckpointFailureManager failureManager = new CheckpointFailureManager(
chkConfig.getTolerableCheckpointFailureNumber(),
new CheckpointFailureManager.FailJobCallback() {
@Override
public void failJob(Throwable cause) {
getJobMasterMainThreadExecutor().execute(() -> failGlobal(cause));
}
@Override
public void failJobDueToTaskFailure(Throwable cause, ExecutionAttemptID failingTask) {
getJobMasterMainThreadExecutor().execute(() -> failGlobalIfExecutionIsStillRunning(cause, failingTask));
}
}
);
checkState(checkpointCoordinatorTimer == null);
checkpointCoordinatorTimer = Executors.newSingleThreadScheduledExecutor(
new DispatcherThreadFactory(
Thread.currentThread().getThreadGroup(), "Checkpoint Timer"));
// create the coordinator that triggers and commits checkpoints and holds the state
checkpointCoordinator = new CheckpointCoordinator(
jobInformation.getJobId(),
chkConfig,
tasksToTrigger,
tasksToWaitFor,
tasksToCommitTo,
checkpointIDCounter,
checkpointStore,
checkpointStateBackend,
ioExecutor,
new ScheduledExecutorServiceAdapter(checkpointCoordinatorTimer),
SharedStateRegistry.DEFAULT_FACTORY,
failureManager);
// register the master hooks on the checkpoint coordinator
for (MasterTriggerRestoreHook<?> hook : masterHooks) {
if (!checkpointCoordinator.addMasterHook(hook)) {
LOG.warn("Trying to register multiple checkpoint hooks with the name: {}", hook.getIdentifier());
}
}
checkpointCoordinator.setCheckpointStatsTracker(checkpointStatsTracker);
// interval of max long value indicates disable periodic checkpoint,
// the CheckpointActivatorDeactivator should be created only if the interval is not max value
if (chkConfig.getCheckpointInterval() != Long.MAX_VALUE) {
// the periodic checkpoint scheduler is activated and deactivated as a result of
// job status changes (running -> on, all other states -> off)
registerJobStatusListener(checkpointCoordinator.createActivatorDeactivator());
}
this.stateBackendName = checkpointStateBackend.getClass().getSimpleName();
}
@Nullable
public CheckpointCoordinator getCheckpointCoordinator() {
return checkpointCoordinator;
}
public KvStateLocationRegistry getKvStateLocationRegistry() {
return kvStateLocationRegistry;
}
public RestartStrategy getRestartStrategy() {
return restartStrategy;
}
@Override
public CheckpointCoordinatorConfiguration getCheckpointCoordinatorConfiguration() {
if (checkpointStatsTracker != null) {
return checkpointStatsTracker.getJobCheckpointingConfiguration();
} else {
return null;
}
}
@Override
public CheckpointStatsSnapshot getCheckpointStatsSnapshot() {
if (checkpointStatsTracker != null) {
return checkpointStatsTracker.createSnapshot();
} else {
return null;
}
}
private ExecutionVertex[] collectExecutionVertices(List<ExecutionJobVertex> jobVertices) {
if (jobVertices.size() == 1) {
ExecutionJobVertex jv = jobVertices.get(0);
if (jv.getGraph() != this) {
throw new IllegalArgumentException("Can only use ExecutionJobVertices of this ExecutionGraph");
}
return jv.getTaskVertices();
}
else {
ArrayList<ExecutionVertex> all = new ArrayList<>();
for (ExecutionJobVertex jv : jobVertices) {
if (jv.getGraph() != this) {
throw new IllegalArgumentException("Can only use ExecutionJobVertices of this ExecutionGraph");
}
all.addAll(Arrays.asList(jv.getTaskVertices()));
}
return all.toArray(new ExecutionVertex[all.size()]);
}
}
// --------------------------------------------------------------------------------------------
// Properties and Status of the Execution Graph
// --------------------------------------------------------------------------------------------
public void setJsonPlan(String jsonPlan) {
this.jsonPlan = jsonPlan;
}
@Override
public String getJsonPlan() {
return jsonPlan;
}
public SlotProviderStrategy getSlotProviderStrategy() {
return slotProviderStrategy;
}
public Either<SerializedValue<JobInformation>, PermanentBlobKey> getJobInformationOrBlobKey() {
return jobInformationOrBlobKey;
}
@Override
public JobID getJobID() {
return jobInformation.getJobId();
}
@Override
public String getJobName() {
return jobInformation.getJobName();
}
@Override
public boolean isStoppable() {
return this.isStoppable;
}
public Configuration getJobConfiguration() {
return jobInformation.getJobConfiguration();
}
public ClassLoader getUserClassLoader() {
return this.userClassLoader;
}
@Override
public JobStatus getState() {
return state;
}
public Throwable getFailureCause() {
return failureCause;
}
public ErrorInfo getFailureInfo() {
return failureInfo;
}
/**
* Gets the number of restarts, including full restarts and fine grained restarts.
* If a recovery is currently pending, this recovery is included in the count.
*
* @return The number of restarts so far
*/
public long getNumberOfRestarts() {
return numberOfRestartsCounter.getCount();
}
@Override
public ExecutionJobVertex getJobVertex(JobVertexID id) {
return this.tasks.get(id);
}
@Override
public Map<JobVertexID, ExecutionJobVertex> getAllVertices() {
return Collections.unmodifiableMap(this.tasks);
}
@Override
public Iterable<ExecutionJobVertex> getVerticesTopologically() {
// we return a specific iterator that does not fail with concurrent modifications
// the list is append only, so it is safe for that
final int numElements = this.verticesInCreationOrder.size();
return new Iterable<ExecutionJobVertex>() {
@Override
public Iterator<ExecutionJobVertex> iterator() {
return new Iterator<ExecutionJobVertex>() {
private int pos = 0;
@Override
public boolean hasNext() {
return pos < numElements;
}
@Override
public ExecutionJobVertex next() {
if (hasNext()) {
return verticesInCreationOrder.get(pos++);
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
public int getTotalNumberOfVertices() {
return numVerticesTotal;
}
public Map<IntermediateDataSetID, IntermediateResult> getAllIntermediateResults() {
return Collections.unmodifiableMap(this.intermediateResults);
}
@Override
public Iterable<ExecutionVertex> getAllExecutionVertices() {
return new Iterable<ExecutionVertex>() {
@Override
public Iterator<ExecutionVertex> iterator() {
return new AllVerticesIterator(getVerticesTopologically().iterator());
}
};
}
@Override
public long getStatusTimestamp(JobStatus status) {
return this.stateTimestamps[status.ordinal()];
}
public final BlobWriter getBlobWriter() {
return blobWriter;
}
/**
* Returns the ExecutionContext associated with this ExecutionGraph.
*
* @return ExecutionContext associated with this ExecutionGraph
*/
public Executor getFutureExecutor() {
return futureExecutor;
}
/**
* Merges all accumulator results from the tasks previously executed in the Executions.
* @return The accumulator map
*/
public Map<String, OptionalFailure<Accumulator<?, ?>>> aggregateUserAccumulators() {
Map<String, OptionalFailure<Accumulator<?, ?>>> userAccumulators = new HashMap<>();
for (ExecutionVertex vertex : getAllExecutionVertices()) {
Map<String, Accumulator<?, ?>> next = vertex.getCurrentExecutionAttempt().getUserAccumulators();
if (next != null) {
AccumulatorHelper.mergeInto(userAccumulators, next);
}
}
return userAccumulators;
}
/**
* Gets a serialized accumulator map.
* @return The accumulator map with serialized accumulator values.
*/
@Override
public Map<String, SerializedValue<OptionalFailure<Object>>> getAccumulatorsSerialized() {
return aggregateUserAccumulators()
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> serializeAccumulator(entry.getKey(), entry.getValue())));
}
private static SerializedValue<OptionalFailure<Object>> serializeAccumulator(String name, OptionalFailure<Accumulator<?, ?>> accumulator) {
try {
if (accumulator.isFailure()) {
return new SerializedValue<>(OptionalFailure.ofFailure(accumulator.getFailureCause()));
}
return new SerializedValue<>(OptionalFailure.of(accumulator.getUnchecked().getLocalValue()));
} catch (IOException ioe) {
LOG.error("Could not serialize accumulator " + name + '.', ioe);
try {
return new SerializedValue<>(OptionalFailure.ofFailure(ioe));
} catch (IOException e) {
throw new RuntimeException("It should never happen that we cannot serialize the accumulator serialization exception.", e);
}
}
}
/**
* Returns the a stringified version of the user-defined accumulators.
* @return an Array containing the StringifiedAccumulatorResult objects
*/
@Override
public StringifiedAccumulatorResult[] getAccumulatorResultsStringified() {
Map<String, OptionalFailure<Accumulator<?, ?>>> accumulatorMap = aggregateUserAccumulators();
return StringifiedAccumulatorResult.stringifyAccumulatorResults(accumulatorMap);
}
public void enableNgScheduling(final InternalFailuresListener internalTaskFailuresListener) {
checkNotNull(internalTaskFailuresListener);
checkState(this.internalTaskFailuresListener == null, "enableNgScheduling can be only called once");
this.internalTaskFailuresListener = internalTaskFailuresListener;
this.legacyScheduling = false;
}
// --------------------------------------------------------------------------------------------
// Actions
// --------------------------------------------------------------------------------------------
public void attachJobGraph(List<JobVertex> topologiallySorted) throws JobException {
assertRunningInJobMasterMainThread();
LOG.debug("Attaching {} topologically sorted vertices to existing job graph with {} " +
"vertices and {} intermediate results.",
topologiallySorted.size(),
tasks.size(),
intermediateResults.size());
final ArrayList<ExecutionJobVertex> newExecJobVertices = new ArrayList<>(topologiallySorted.size());
final long createTimestamp = System.currentTimeMillis();
for (JobVertex jobVertex : topologiallySorted) {
if (jobVertex.isInputVertex() && !jobVertex.isStoppable()) {
this.isStoppable = false;
}
// create the execution job vertex and attach it to the graph
ExecutionJobVertex ejv = new ExecutionJobVertex(
this,
jobVertex,
1,
maxPriorAttemptsHistoryLength,
rpcTimeout,
globalModVersion,
createTimestamp);
ejv.connectToPredecessors(this.intermediateResults);
ExecutionJobVertex previousTask = this.tasks.putIfAbsent(jobVertex.getID(), ejv);
if (previousTask != null) {
throw new JobException(String.format("Encountered two job vertices with ID %s : previous=[%s] / new=[%s]",
jobVertex.getID(), ejv, previousTask));
}
for (IntermediateResult res : ejv.getProducedDataSets()) {
IntermediateResult previousDataSet = this.intermediateResults.putIfAbsent(res.getId(), res);
if (previousDataSet != null) {
throw new JobException(String.format("Encountered two intermediate data set with ID %s : previous=[%s] / new=[%s]",
res.getId(), res, previousDataSet));
}
}
this.verticesInCreationOrder.add(ejv);
this.numVerticesTotal += ejv.getParallelism();
newExecJobVertices.add(ejv);
}
// the topology assigning should happen before notifying new vertices to failoverStrategy
executionTopology = new DefaultExecutionTopology(this);
failoverStrategy.notifyNewVertices(newExecJobVertices);
partitionReleaseStrategy = partitionReleaseStrategyFactory.createInstance(getSchedulingTopology());
}
public boolean isLegacyScheduling() {
return legacyScheduling;
}
public void transitionToRunning() {
if (!transitionState(JobStatus.CREATED, JobStatus.RUNNING)) {
throw new IllegalStateException("Job may only be scheduled from state " + JobStatus.CREATED);
}
}
public void scheduleForExecution() throws JobException {
assertRunningInJobMasterMainThread();
if (isLegacyScheduling()) {
LOG.info("Job recovers via failover strategy: {}", failoverStrategy.getStrategyName());
}
final long currentGlobalModVersion = globalModVersion;
if (transitionState(JobStatus.CREATED, JobStatus.RUNNING)) {
final CompletableFuture<Void> newSchedulingFuture = SchedulingUtils.schedule(
scheduleMode,
getAllExecutionVertices(),
this);
if (state == JobStatus.RUNNING && currentGlobalModVersion == globalModVersion) {
schedulingFuture = newSchedulingFuture;
newSchedulingFuture.whenComplete(
(Void ignored, Throwable throwable) -> {
if (throwable != null) {
final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable);
if (!(strippedThrowable instanceof CancellationException)) {
// only fail if the scheduling future was not canceled
failGlobal(strippedThrowable);
}
}
});
} else {
newSchedulingFuture.cancel(false);
}
}
else {
throw new IllegalStateException("Job may only be scheduled from state " + JobStatus.CREATED);
}
}
public void cancel() {
assertRunningInJobMasterMainThread();
while (true) {
JobStatus current = state;
if (current == JobStatus.RUNNING || current == JobStatus.CREATED) {
if (transitionState(current, JobStatus.CANCELLING)) {
// make sure no concurrent local actions interfere with the cancellation
final long globalVersionForRestart = incrementGlobalModVersion();
final CompletableFuture<Void> ongoingSchedulingFuture = schedulingFuture;
// cancel ongoing scheduling action
if (ongoingSchedulingFuture != null) {
ongoingSchedulingFuture.cancel(false);
}
final ConjunctFuture<Void> allTerminal = cancelVerticesAsync();
allTerminal.whenComplete(
(Void value, Throwable throwable) -> {
if (throwable != null) {
transitionState(
JobStatus.CANCELLING,
JobStatus.FAILED,
new FlinkException(
"Could not cancel job " + getJobName() + " because not all execution job vertices could be cancelled.",
throwable));
} else {
// cancellations may currently be overridden by failures which trigger
// restarts, so we need to pass a proper restart global version here
allVerticesInTerminalState(globalVersionForRestart);
}
});
return;
}
}
// Executions are being canceled. Go into cancelling and wait for
// all vertices to be in their final state.
else if (current == JobStatus.FAILING) {
if (transitionState(current, JobStatus.CANCELLING)) {
return;
}
}
// All vertices have been cancelled and it's safe to directly go
// into the canceled state.
else if (current == JobStatus.RESTARTING) {
if (transitionState(current, JobStatus.CANCELED)) {
onTerminalState(JobStatus.CANCELED);
LOG.info("Canceled during restart.");
return;
}
}
else {
// no need to treat other states
return;
}
}
}
private ConjunctFuture<Void> cancelVerticesAsync() {
final ArrayList<CompletableFuture<?>> futures = new ArrayList<>(verticesInCreationOrder.size());
// cancel all tasks (that still need cancelling)
for (ExecutionJobVertex ejv : verticesInCreationOrder) {
futures.add(ejv.cancelWithFuture());
}
// we build a future that is complete once all vertices have reached a terminal state
return FutureUtils.waitForAll(futures);
}
/**
* Suspends the current ExecutionGraph.
*
* <p>The JobStatus will be directly set to {@link JobStatus#SUSPENDED} iff the current state is not a terminal
* state. All ExecutionJobVertices will be canceled and the onTerminalState() is executed.
*
* <p>The {@link JobStatus#SUSPENDED} state is a local terminal state which stops the execution of the job but does
* not remove the job from the HA job store so that it can be recovered by another JobManager.
*
* @param suspensionCause Cause of the suspension
*/
public void suspend(Throwable suspensionCause) {
assertRunningInJobMasterMainThread();
if (state.isTerminalState()) {
// stay in a terminal state
return;
} else if (transitionState(state, JobStatus.SUSPENDED, suspensionCause)) {
initFailureCause(suspensionCause);
// make sure no concurrent local actions interfere with the cancellation
incrementGlobalModVersion();
// cancel ongoing scheduling action
if (schedulingFuture != null) {
schedulingFuture.cancel(false);
}
final ArrayList<CompletableFuture<Void>> executionJobVertexTerminationFutures = new ArrayList<>(verticesInCreationOrder.size());
for (ExecutionJobVertex ejv: verticesInCreationOrder) {
executionJobVertexTerminationFutures.add(ejv.suspend());
}
final ConjunctFuture<Void> jobVerticesTerminationFuture = FutureUtils.waitForAll(executionJobVertexTerminationFutures);
checkState(jobVerticesTerminationFuture.isDone(), "Suspend needs to happen atomically");
jobVerticesTerminationFuture.whenComplete(
(Void ignored, Throwable throwable) -> {
if (throwable != null) {
LOG.debug("Could not properly suspend the execution graph.", throwable);
}
onTerminalState(state);
LOG.info("Job {} has been suspended.", getJobID());
});
} else {
throw new IllegalStateException(String.format("Could not suspend because transition from %s to %s failed.", state, JobStatus.SUSPENDED));
}
}
void failGlobalIfExecutionIsStillRunning(Throwable cause, ExecutionAttemptID failingAttempt) {
final Execution failedExecution = currentExecutions.get(failingAttempt);
if (failedExecution != null && failedExecution.getState() == ExecutionState.RUNNING) {
failGlobal(cause);
} else {
LOG.debug("The failing attempt {} belongs to an already not" +
" running task thus won't fail the job", failingAttempt);
}
}
/**
* Fails the execution graph globally. This failure will not be recovered by a specific
* failover strategy, but results in a full restart of all tasks.
*
* <p>This global failure is meant to be triggered in cases where the consistency of the
* execution graph' state cannot be guaranteed any more (for example when catching unexpected
* exceptions that indicate a bug or an unexpected call race), and where a full restart is the
* safe way to get consistency back.
*
* @param t The exception that caused the failure.
*/
public void failGlobal(Throwable t) {
if (!isLegacyScheduling()) {
internalTaskFailuresListener.notifyGlobalFailure(t);
return;
}
assertRunningInJobMasterMainThread();
while (true) {
JobStatus current = state;
// stay in these states
if (current == JobStatus.FAILING ||
current == JobStatus.SUSPENDED ||
current.isGloballyTerminalState()) {
return;
} else if (transitionState(current, JobStatus.FAILING, t)) {
initFailureCause(t);
// make sure no concurrent local or global actions interfere with the failover
final long globalVersionForRestart = incrementGlobalModVersion();
final CompletableFuture<Void> ongoingSchedulingFuture = schedulingFuture;
// cancel ongoing scheduling action
if (ongoingSchedulingFuture != null) {
ongoingSchedulingFuture.cancel(false);
}
// we build a future that is complete once all vertices have reached a terminal state
final ConjunctFuture<Void> allTerminal = cancelVerticesAsync();
FutureUtils.assertNoException(allTerminal.handle(
(Void ignored, Throwable throwable) -> {
if (throwable != null) {
transitionState(
JobStatus.FAILING,
JobStatus.FAILED,
new FlinkException("Could not cancel all execution job vertices properly.", throwable));
} else {
allVerticesInTerminalState(globalVersionForRestart);
}
return null;
}));
return;
}
// else: concurrent change to execution state, retry
}
}
public void restart(long expectedGlobalVersion) {
assertRunningInJobMasterMainThread();
try {
// check the global version to see whether this recovery attempt is still valid
if (globalModVersion != expectedGlobalVersion) {
LOG.info("Concurrent full restart subsumed this restart.");
return;
}
final JobStatus current = state;
if (current == JobStatus.CANCELED) {
LOG.info("Canceled job during restart. Aborting restart.");
return;
} else if (current == JobStatus.FAILED) {
LOG.info("Failed job during restart. Aborting restart.");
return;
} else if (current == JobStatus.SUSPENDED) {
LOG.info("Suspended job during restart. Aborting restart.");
return;
} else if (current != JobStatus.RESTARTING) {
throw new IllegalStateException("Can only restart job from state restarting.");
}
this.currentExecutions.clear();
final Collection<CoLocationGroup> colGroups = new HashSet<>();
final long resetTimestamp = System.currentTimeMillis();
for (ExecutionJobVertex jv : this.verticesInCreationOrder) {
CoLocationGroup cgroup = jv.getCoLocationGroup();
if (cgroup != null && !colGroups.contains(cgroup)){
cgroup.resetConstraints();
colGroups.add(cgroup);
}
jv.resetForNewExecution(resetTimestamp, expectedGlobalVersion);
}
for (int i = 0; i < stateTimestamps.length; i++) {
if (i != JobStatus.RESTARTING.ordinal()) {
// Only clear the non restarting state in order to preserve when the job was
// restarted. This is needed for the restarting time gauge
stateTimestamps[i] = 0;
}
}
transitionState(JobStatus.RESTARTING, JobStatus.CREATED);
// if we have checkpointed state, reload it into the executions
if (checkpointCoordinator != null) {
checkpointCoordinator.restoreLatestCheckpointedState(getAllVertices(), false, false);
}
scheduleForExecution();
}
// TODO remove the catch block if we align the schematics to not fail global within the restarter.
catch (Throwable t) {
LOG.warn("Failed to restart the job.", t);
failGlobal(t);
}
}
/**
* Returns the serializable {@link ArchivedExecutionConfig}.
*
* @return ArchivedExecutionConfig which may be null in case of errors
*/
@Override
public ArchivedExecutionConfig getArchivedExecutionConfig() {
// create a summary of all relevant data accessed in the web interface's JobConfigHandler
try {
ExecutionConfig executionConfig = jobInformation.getSerializedExecutionConfig().deserializeValue(userClassLoader);
if (executionConfig != null) {
return executionConfig.archive();
}
} catch (IOException | ClassNotFoundException e) {
LOG.error("Couldn't create ArchivedExecutionConfig for job {} ", getJobID(), e);
}
return null;
}
/**
* Returns the termination future of this {@link ExecutionGraph}. The termination future
* is completed with the terminal {@link JobStatus} once the ExecutionGraph reaches this
* terminal state and all {@link Execution} have been terminated.
*
* @return Termination future of this {@link ExecutionGraph}.
*/
public CompletableFuture<JobStatus> getTerminationFuture() {
return terminationFuture;
}
@VisibleForTesting
public JobStatus waitUntilTerminal() throws InterruptedException {
try {
return terminationFuture.get();
}
catch (ExecutionException e) {
// this should never happen
// it would be a bug, so we don't expect this to be handled and throw
// an unchecked exception here
throw new RuntimeException(e);
}
}
/**
* Gets the failover strategy used by the execution graph to recover from failures of tasks.
*/
public FailoverStrategy getFailoverStrategy() {
return this.failoverStrategy;
}
/**
* Gets the current global modification version of the ExecutionGraph.
* The global modification version is incremented with each global action (cancel/fail/restart)
* and is used to disambiguate concurrent modifications between local and global
* failover actions.
*/
public long getGlobalModVersion() {
return globalModVersion;
}
// ------------------------------------------------------------------------
// State Transitions
// ------------------------------------------------------------------------
private boolean transitionState(JobStatus current, JobStatus newState) {
return transitionState(current, newState, null);
}
private void transitionState(JobStatus newState, Throwable error) {
transitionState(state, newState, error);
}
private boolean transitionState(JobStatus current, JobStatus newState, Throwable error) {
assertRunningInJobMasterMainThread();
// consistency check
if (current.isTerminalState()) {
String message = "Job is trying to leave terminal state " + current;
LOG.error(message);
throw new IllegalStateException(message);
}
// now do the actual state transition
if (state == current) {
state = newState;
LOG.info("Job {} ({}) switched from state {} to {}.", getJobName(), getJobID(), current, newState, error);
stateTimestamps[newState.ordinal()] = System.currentTimeMillis();
notifyJobStatusChange(newState, error);
return true;
}
else {
return false;
}
}
private long incrementGlobalModVersion() {
incrementRestarts();
return ++globalModVersion;
}
public void incrementRestarts() {
numberOfRestartsCounter.inc();
}
public void initFailureCause(Throwable t) {
this.failureCause = t;
this.failureInfo = new ErrorInfo(t, System.currentTimeMillis());
}
// ------------------------------------------------------------------------
// Job Status Progress
// ------------------------------------------------------------------------
/**
* Called whenever a vertex reaches state FINISHED (completed successfully).
* Once all vertices are in the FINISHED state, the program is successfully done.
*/
void vertexFinished() {
assertRunningInJobMasterMainThread();
final int numFinished = ++verticesFinished;
if (numFinished == numVerticesTotal) {
// done :-)
// check whether we are still in "RUNNING" and trigger the final cleanup
if (state == JobStatus.RUNNING) {
// we do the final cleanup in the I/O executor, because it may involve
// some heavier work
try {
for (ExecutionJobVertex ejv : verticesInCreationOrder) {
ejv.getJobVertex().finalizeOnMaster(getUserClassLoader());
}
}
catch (Throwable t) {
ExceptionUtils.rethrowIfFatalError(t);
failGlobal(new Exception("Failed to finalize execution on master", t));
return;
}
// if we do not make this state transition, then a concurrent
// cancellation or failure happened
if (transitionState(JobStatus.RUNNING, JobStatus.FINISHED)) {
onTerminalState(JobStatus.FINISHED);
}
}
}
}
void vertexUnFinished() {
assertRunningInJobMasterMainThread();
verticesFinished--;
}
/**
* This method is a callback during cancellation/failover and called when all tasks
* have reached a terminal state (cancelled/failed/finished).
*/
private void allVerticesInTerminalState(long expectedGlobalVersionForRestart) {
assertRunningInJobMasterMainThread();
// we are done, transition to the final state
JobStatus current;
while (true) {
current = this.state;
if (current == JobStatus.RUNNING) {
failGlobal(new Exception("ExecutionGraph went into allVerticesInTerminalState() from RUNNING"));
}
else if (current == JobStatus.CANCELLING) {
if (transitionState(current, JobStatus.CANCELED)) {
onTerminalState(JobStatus.CANCELED);
break;
}
}
else if (current == JobStatus.FAILING) {
if (tryRestartOrFail(expectedGlobalVersionForRestart)) {
break;
}
// concurrent job status change, let's check again
}
else if (current.isGloballyTerminalState()) {
LOG.warn("Job has entered globally terminal state without waiting for all " +
"job vertices to reach final state.");
break;
}
else {
failGlobal(new Exception("ExecutionGraph went into final state from state " + current));
break;
}
}
// done transitioning the state
}
/**
* Try to restart the job. If we cannot restart the job (e.g. no more restarts allowed), then
* try to fail the job. This operation is only permitted if the current state is FAILING or
* RESTARTING.
*
* @return true if the operation could be executed; false if a concurrent job status change occurred
*/
@Deprecated
private boolean tryRestartOrFail(long globalModVersionForRestart) {
if (!isLegacyScheduling()) {
return true;
}
JobStatus currentState = state;
if (currentState == JobStatus.FAILING || currentState == JobStatus.RESTARTING) {
final Throwable failureCause = this.failureCause;
if (LOG.isDebugEnabled()) {
LOG.debug("Try to restart or fail the job {} ({}) if no longer possible.", getJobName(), getJobID(), failureCause);
} else {
LOG.info("Try to restart or fail the job {} ({}) if no longer possible.", getJobName(), getJobID());
}
final boolean isFailureCauseAllowingRestart = !(failureCause instanceof SuppressRestartsException);
final boolean isRestartStrategyAllowingRestart = restartStrategy.canRestart();
boolean isRestartable = isFailureCauseAllowingRestart && isRestartStrategyAllowingRestart;
if (isRestartable && transitionState(currentState, JobStatus.RESTARTING)) {
LOG.info("Restarting the job {} ({}).", getJobName(), getJobID());
RestartCallback restarter = new ExecutionGraphRestartCallback(this, globalModVersionForRestart);
FutureUtils.assertNoException(
restartStrategy
.restart(restarter, getJobMasterMainThreadExecutor())
.exceptionally((throwable) -> {
failGlobal(throwable);
return null;
}));
return true;
}
else if (!isRestartable && transitionState(currentState, JobStatus.FAILED, failureCause)) {
final String cause1 = isFailureCauseAllowingRestart ? null :
"a type of SuppressRestartsException was thrown";
final String cause2 = isRestartStrategyAllowingRestart ? null :
"the restart strategy prevented it";
LOG.info("Could not restart the job {} ({}) because {}.", getJobName(), getJobID(),
StringUtils.concatenateWithAnd(cause1, cause2), failureCause);
onTerminalState(JobStatus.FAILED);
return true;
} else {
// we must have changed the state concurrently, thus we cannot complete this operation
return false;
}
} else {
// this operation is only allowed in the state FAILING or RESTARTING
return false;
}
}
public void failJob(Throwable cause) {
if (state == JobStatus.FAILING || state.isGloballyTerminalState()) {
return;
}
transitionState(JobStatus.FAILING, cause);
initFailureCause(cause);
FutureUtils.assertNoException(
cancelVerticesAsync().whenComplete((aVoid, throwable) -> {
transitionState(JobStatus.FAILED, cause);
onTerminalState(JobStatus.FAILED);
}));
}
private void onTerminalState(JobStatus status) {
try {
CheckpointCoordinator coord = this.checkpointCoordinator;
this.checkpointCoordinator = null;
if (coord != null) {
coord.shutdown(status);
}
if (checkpointCoordinatorTimer != null) {
checkpointCoordinatorTimer.shutdownNow();
checkpointCoordinatorTimer = null;
}
}
catch (Exception e) {
LOG.error("Error while cleaning up after execution", e);
}
finally {
terminationFuture.complete(status);
}
}
// --------------------------------------------------------------------------------------------
// Callbacks and Callback Utilities
// --------------------------------------------------------------------------------------------
/**
* Updates the state of one of the ExecutionVertex's Execution attempts.
* If the new status if "FINISHED", this also updates the accumulators.
*
* @param state The state update.
* @return True, if the task update was properly applied, false, if the execution attempt was not found.
*/
public boolean updateState(TaskExecutionState state) {
assertRunningInJobMasterMainThread();
final Execution attempt = currentExecutions.get(state.getID());
if (attempt != null) {
try {
final boolean stateUpdated = updateStateInternal(state, attempt);
maybeReleasePartitions(attempt);
return stateUpdated;
}
catch (Throwable t) {
ExceptionUtils.rethrowIfFatalErrorOrOOM(t);
// failures during updates leave the ExecutionGraph inconsistent
failGlobal(t);
return false;
}
}
else {
return false;
}
}
private boolean updateStateInternal(final TaskExecutionState state, final Execution attempt) {
Map<String, Accumulator<?, ?>> accumulators;
switch (state.getExecutionState()) {
case RUNNING:
return attempt.switchToRunning();
case FINISHED:
// this deserialization is exception-free
accumulators = deserializeAccumulators(state);
attempt.markFinished(accumulators, state.getIOMetrics());
return true;
case CANCELED:
// this deserialization is exception-free
accumulators = deserializeAccumulators(state);
attempt.completeCancelling(accumulators, state.getIOMetrics(), false);
return true;
case FAILED:
// this deserialization is exception-free
accumulators = deserializeAccumulators(state);
attempt.markFailed(state.getError(userClassLoader), accumulators, state.getIOMetrics(), !isLegacyScheduling());
return true;
default:
// we mark as failed and return false, which triggers the TaskManager
// to remove the task
attempt.fail(new Exception("TaskManager sent illegal state update: " + state.getExecutionState()));
return false;
}
}
private void maybeReleasePartitions(final Execution attempt) {
final ExecutionVertexID finishedExecutionVertex = attempt.getVertex().getID();
if (attempt.getState() == ExecutionState.FINISHED) {
final List<IntermediateResultPartitionID> releasablePartitions = partitionReleaseStrategy.vertexFinished(finishedExecutionVertex);
releasePartitions(releasablePartitions);
} else {
partitionReleaseStrategy.vertexUnfinished(finishedExecutionVertex);
}
}
private void releasePartitions(final List<IntermediateResultPartitionID> releasablePartitions) {
if (releasablePartitions.size() > 0) {
final List<ResultPartitionID> partitionIds = releasablePartitions.stream()
.map(this::createResultPartitionId)
.collect(Collectors.toList());
partitionTracker.stopTrackingAndReleasePartitions(partitionIds);
}
}
ResultPartitionID createResultPartitionId(final IntermediateResultPartitionID resultPartitionId) {
final SchedulingResultPartition<?, ?> schedulingResultPartition =
getSchedulingTopology().getResultPartitionOrThrow(resultPartitionId);
final SchedulingExecutionVertex<?, ?> producer = schedulingResultPartition.getProducer();
final ExecutionVertexID producerId = producer.getId();
final JobVertexID jobVertexId = producerId.getJobVertexId();
final ExecutionJobVertex jobVertex = getJobVertex(jobVertexId);
checkNotNull(jobVertex, "Unknown job vertex %s", jobVertexId);
final ExecutionVertex[] taskVertices = jobVertex.getTaskVertices();
final int subtaskIndex = producerId.getSubtaskIndex();
checkState(subtaskIndex < taskVertices.length, "Invalid subtask index %d for job vertex %s", subtaskIndex, jobVertexId);
final ExecutionVertex taskVertex = taskVertices[subtaskIndex];
final Execution execution = taskVertex.getCurrentExecutionAttempt();
return new ResultPartitionID(resultPartitionId, execution.getAttemptId());
}
/**
* Deserializes accumulators from a task state update.
*
* <p>This method never throws an exception!
*
* @param state The task execution state from which to deserialize the accumulators.
* @return The deserialized accumulators, of null, if there are no accumulators or an error occurred.
*/
private Map<String, Accumulator<?, ?>> deserializeAccumulators(TaskExecutionState state) {
AccumulatorSnapshot serializedAccumulators = state.getAccumulators();
if (serializedAccumulators != null) {
try {
return serializedAccumulators.deserializeUserAccumulators(userClassLoader);
}
catch (Throwable t) {
// we catch Throwable here to include all form of linking errors that may
// occur if user classes are missing in the classpath
LOG.error("Failed to deserialize final accumulator results.", t);
}
}
return null;
}
/**
* Schedule or updates consumers of the given result partition.
*
* @param partitionId specifying the result partition whose consumer shall be scheduled or updated
* @throws ExecutionGraphException if the schedule or update consumers operation could not be executed
*/
public void scheduleOrUpdateConsumers(ResultPartitionID partitionId) throws ExecutionGraphException {
assertRunningInJobMasterMainThread();
final Execution execution = currentExecutions.get(partitionId.getProducerId());
if (execution == null) {
throw new ExecutionGraphException("Cannot find execution for execution Id " +
partitionId.getPartitionId() + '.');
}
else if (execution.getVertex() == null){
throw new ExecutionGraphException("Execution with execution Id " +
partitionId.getPartitionId() + " has no vertex assigned.");
} else {
execution.getVertex().scheduleOrUpdateConsumers(partitionId);
}
}
public Map<ExecutionAttemptID, Execution> getRegisteredExecutions() {
return Collections.unmodifiableMap(currentExecutions);
}
void registerExecution(Execution exec) {
assertRunningInJobMasterMainThread();
Execution previous = currentExecutions.putIfAbsent(exec.getAttemptId(), exec);
if (previous != null) {
failGlobal(new Exception("Trying to register execution " + exec + " for already used ID " + exec.getAttemptId()));
}
}
void deregisterExecution(Execution exec) {
assertRunningInJobMasterMainThread();
Execution contained = currentExecutions.remove(exec.getAttemptId());
if (contained != null && contained != exec) {
failGlobal(new Exception("De-registering execution " + exec + " failed. Found for same ID execution " + contained));
}
}
/**
* Updates the accumulators during the runtime of a job. Final accumulator results are transferred
* through the UpdateTaskExecutionState message.
* @param accumulatorSnapshot The serialized flink and user-defined accumulators
*/
public void updateAccumulators(AccumulatorSnapshot accumulatorSnapshot) {
Map<String, Accumulator<?, ?>> userAccumulators;
try {
userAccumulators = accumulatorSnapshot.deserializeUserAccumulators(userClassLoader);
ExecutionAttemptID execID = accumulatorSnapshot.getExecutionAttemptID();
Execution execution = currentExecutions.get(execID);
if (execution != null) {
execution.setAccumulators(userAccumulators);
} else {
LOG.debug("Received accumulator result for unknown execution {}.", execID);
}
} catch (Exception e) {
LOG.error("Cannot update accumulators for job {}.", getJobID(), e);
}
}
// --------------------------------------------------------------------------------------------
// Listeners & Observers
// --------------------------------------------------------------------------------------------
public void registerJobStatusListener(JobStatusListener listener) {
if (listener != null) {
jobStatusListeners.add(listener);
}
}
private void notifyJobStatusChange(JobStatus newState, Throwable error) {
if (jobStatusListeners.size() > 0) {
final long timestamp = System.currentTimeMillis();
final Throwable serializedError = error == null ? null : new SerializedThrowable(error);
for (JobStatusListener listener : jobStatusListeners) {
try {
listener.jobStatusChanges(getJobID(), newState, timestamp, serializedError);
} catch (Throwable t) {
LOG.warn("Error while notifying JobStatusListener", t);
}
}
}
}
void notifyExecutionChange(
final Execution execution,
final ExecutionState newExecutionState,
final Throwable error) {
if (!isLegacyScheduling()) {
return;
}
// see what this means for us. currently, the first FAILED state means -> FAILED
if (newExecutionState == ExecutionState.FAILED) {
final Throwable ex = error != null ? error : new FlinkException("Unknown Error (missing cause)");
// by filtering out late failure calls, we can save some work in
// avoiding redundant local failover
if (execution.getGlobalModVersion() == globalModVersion) {
try {
// fail all checkpoints which the failed task has not yet acknowledged
if (checkpointCoordinator != null) {
checkpointCoordinator.failUnacknowledgedPendingCheckpointsFor(execution.getAttemptId(), ex);
}
failoverStrategy.onTaskFailure(execution, ex);
}
catch (Throwable t) {
// bug in the failover strategy - fall back to global failover
LOG.warn("Error in failover strategy - falling back to global restart", t);
failGlobal(ex);
}
}
}
}
void assertRunningInJobMasterMainThread() {
if (!(jobMasterMainThreadExecutor instanceof ComponentMainThreadExecutor.DummyComponentMainThreadExecutor)) {
jobMasterMainThreadExecutor.assertRunningInMainThread();
}
}
void notifySchedulerNgAboutInternalTaskFailure(final ExecutionAttemptID attemptId, final Throwable t) {
if (internalTaskFailuresListener != null) {
internalTaskFailuresListener.notifyTaskFailure(attemptId, t);
}
}
ShuffleMaster<?> getShuffleMaster() {
return shuffleMaster;
}
public JobMasterPartitionTracker getPartitionTracker() {
return partitionTracker;
}
public ResultPartitionAvailabilityChecker getResultPartitionAvailabilityChecker() {
return resultPartitionAvailabilityChecker;
}
PartitionReleaseStrategy getPartitionReleaseStrategy() {
return partitionReleaseStrategy;
}
}
| flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/ExecutionGraph.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.flink.runtime.executiongraph;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.ArchivedExecutionConfig;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.api.common.accumulators.Accumulator;
import org.apache.flink.api.common.accumulators.AccumulatorHelper;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.SimpleCounter;
import org.apache.flink.runtime.JobException;
import org.apache.flink.runtime.accumulators.AccumulatorSnapshot;
import org.apache.flink.runtime.accumulators.StringifiedAccumulatorResult;
import org.apache.flink.runtime.blob.BlobWriter;
import org.apache.flink.runtime.blob.PermanentBlobKey;
import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
import org.apache.flink.runtime.checkpoint.CheckpointFailureManager;
import org.apache.flink.runtime.checkpoint.CheckpointIDCounter;
import org.apache.flink.runtime.checkpoint.CheckpointStatsSnapshot;
import org.apache.flink.runtime.checkpoint.CheckpointStatsTracker;
import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore;
import org.apache.flink.runtime.checkpoint.MasterTriggerRestoreHook;
import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.concurrent.FutureUtils.ConjunctFuture;
import org.apache.flink.runtime.concurrent.ScheduledExecutorServiceAdapter;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.execution.SuppressRestartsException;
import org.apache.flink.runtime.executiongraph.failover.FailoverStrategy;
import org.apache.flink.runtime.executiongraph.failover.flip1.FailoverTopology;
import org.apache.flink.runtime.executiongraph.failover.flip1.ResultPartitionAvailabilityChecker;
import org.apache.flink.runtime.executiongraph.failover.flip1.partitionrelease.PartitionReleaseStrategy;
import org.apache.flink.runtime.executiongraph.restart.ExecutionGraphRestartCallback;
import org.apache.flink.runtime.executiongraph.restart.RestartCallback;
import org.apache.flink.runtime.executiongraph.restart.RestartStrategy;
import org.apache.flink.runtime.io.network.partition.JobMasterPartitionTracker;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.ScheduleMode;
import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration;
import org.apache.flink.runtime.jobmanager.scheduler.CoLocationGroup;
import org.apache.flink.runtime.jobmaster.slotpool.SlotProvider;
import org.apache.flink.runtime.query.KvStateLocationRegistry;
import org.apache.flink.runtime.scheduler.InternalFailuresListener;
import org.apache.flink.runtime.scheduler.adapter.DefaultExecutionTopology;
import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
import org.apache.flink.runtime.scheduler.strategy.SchedulingExecutionVertex;
import org.apache.flink.runtime.scheduler.strategy.SchedulingResultPartition;
import org.apache.flink.runtime.scheduler.strategy.SchedulingTopology;
import org.apache.flink.runtime.shuffle.ShuffleMaster;
import org.apache.flink.runtime.state.SharedStateRegistry;
import org.apache.flink.runtime.state.StateBackend;
import org.apache.flink.runtime.taskmanager.DispatcherThreadFactory;
import org.apache.flink.runtime.taskmanager.TaskExecutionState;
import org.apache.flink.types.Either;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.OptionalFailure;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.SerializedThrowable;
import org.apache.flink.util.SerializedValue;
import org.apache.flink.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* The execution graph is the central data structure that coordinates the distributed
* execution of a data flow. It keeps representations of each parallel task, each
* intermediate stream, and the communication between them.
*
* <p>The execution graph consists of the following constructs:
* <ul>
* <li>The {@link ExecutionJobVertex} represents one vertex from the JobGraph (usually one operation like
* "map" or "join") during execution. It holds the aggregated state of all parallel subtasks.
* The ExecutionJobVertex is identified inside the graph by the {@link JobVertexID}, which it takes
* from the JobGraph's corresponding JobVertex.</li>
* <li>The {@link ExecutionVertex} represents one parallel subtask. For each ExecutionJobVertex, there are
* as many ExecutionVertices as the parallelism. The ExecutionVertex is identified by
* the ExecutionJobVertex and the index of the parallel subtask</li>
* <li>The {@link Execution} is one attempt to execute a ExecutionVertex. There may be multiple Executions
* for the ExecutionVertex, in case of a failure, or in the case where some data needs to be recomputed
* because it is no longer available when requested by later operations. An Execution is always
* identified by an {@link ExecutionAttemptID}. All messages between the JobManager and the TaskManager
* about deployment of tasks and updates in the task status always use the ExecutionAttemptID to
* address the message receiver.</li>
* </ul>
*
* <h2>Global and local failover</h2>
*
* <p>The Execution Graph has two failover modes: <i>global failover</i> and <i>local failover</i>.
*
* <p>A <b>global failover</b> aborts the task executions for all vertices and restarts whole
* data flow graph from the last completed checkpoint. Global failover is considered the
* "fallback strategy" that is used when a local failover is unsuccessful, or when a issue is
* found in the state of the ExecutionGraph that could mark it as inconsistent (caused by a bug).
*
* <p>A <b>local failover</b> is triggered when an individual vertex execution (a task) fails.
* The local failover is coordinated by the {@link FailoverStrategy}. A local failover typically
* attempts to restart as little as possible, but as much as necessary.
*
* <p>Between local- and global failover, the global failover always takes precedence, because it
* is the core mechanism that the ExecutionGraph relies on to bring back consistency. The
* guard that, the ExecutionGraph maintains a <i>global modification version</i>, which is incremented
* with every global failover (and other global actions, like job cancellation, or terminal
* failure). Local failover is always scoped by the modification version that the execution graph
* had when the failover was triggered. If a new global modification version is reached during
* local failover (meaning there is a concurrent global failover), the failover strategy has to
* yield before the global failover.
*/
public class ExecutionGraph implements AccessExecutionGraph {
/** The log object used for debugging. */
static final Logger LOG = LoggerFactory.getLogger(ExecutionGraph.class);
// --------------------------------------------------------------------------------------------
/** Job specific information like the job id, job name, job configuration, etc. */
private final JobInformation jobInformation;
/** Serialized job information or a blob key pointing to the offloaded job information. */
private final Either<SerializedValue<JobInformation>, PermanentBlobKey> jobInformationOrBlobKey;
/** The executor which is used to execute futures. */
private final ScheduledExecutorService futureExecutor;
/** The executor which is used to execute blocking io operations. */
private final Executor ioExecutor;
/** Executor that runs tasks in the job manager's main thread. */
@Nonnull
private ComponentMainThreadExecutor jobMasterMainThreadExecutor;
/** {@code true} if all source tasks are stoppable. */
private boolean isStoppable = true;
/** All job vertices that are part of this graph. */
private final Map<JobVertexID, ExecutionJobVertex> tasks;
/** All vertices, in the order in which they were created. **/
private final List<ExecutionJobVertex> verticesInCreationOrder;
/** All intermediate results that are part of this graph. */
private final Map<IntermediateDataSetID, IntermediateResult> intermediateResults;
/** The currently executed tasks, for callbacks. */
private final Map<ExecutionAttemptID, Execution> currentExecutions;
/** Listeners that receive messages when the entire job switches it status
* (such as from RUNNING to FINISHED). */
private final List<JobStatusListener> jobStatusListeners;
/** The implementation that decides how to recover the failures of tasks. */
private final FailoverStrategy failoverStrategy;
/** Timestamps (in milliseconds as returned by {@code System.currentTimeMillis()} when
* the execution graph transitioned into a certain state. The index into this array is the
* ordinal of the enum value, i.e. the timestamp when the graph went into state "RUNNING" is
* at {@code stateTimestamps[RUNNING.ordinal()]}. */
private final long[] stateTimestamps;
/** The timeout for all messages that require a response/acknowledgement. */
private final Time rpcTimeout;
/** The timeout for slot allocations. */
private final Time allocationTimeout;
/** Strategy to use for restarts. */
private final RestartStrategy restartStrategy;
/** The slot provider strategy to use for allocating slots for tasks as they are needed. */
private final SlotProviderStrategy slotProviderStrategy;
/** The classloader for the user code. Needed for calls into user code classes. */
private final ClassLoader userClassLoader;
/** Registered KvState instances reported by the TaskManagers. */
private final KvStateLocationRegistry kvStateLocationRegistry;
/** Blob writer used to offload RPC messages. */
private final BlobWriter blobWriter;
private boolean legacyScheduling = true;
/** The total number of vertices currently in the execution graph. */
private int numVerticesTotal;
private final PartitionReleaseStrategy.Factory partitionReleaseStrategyFactory;
private PartitionReleaseStrategy partitionReleaseStrategy;
private DefaultExecutionTopology executionTopology;
@Nullable
private InternalFailuresListener internalTaskFailuresListener;
/** Counts all restarts. Used by other Gauges/Meters and does not register to metric group. */
private final Counter numberOfRestartsCounter = new SimpleCounter();
// ------ Configuration of the Execution -------
/** The mode of scheduling. Decides how to select the initial set of tasks to be deployed.
* May indicate to deploy all sources, or to deploy everything, or to deploy via backtracking
* from results than need to be materialized. */
private final ScheduleMode scheduleMode;
/** The maximum number of prior execution attempts kept in history. */
private final int maxPriorAttemptsHistoryLength;
// ------ Execution status and progress. These values are volatile, and accessed under the lock -------
private int verticesFinished;
/** Current status of the job execution. */
private volatile JobStatus state = JobStatus.CREATED;
/** A future that completes once the job has reached a terminal state. */
private final CompletableFuture<JobStatus> terminationFuture = new CompletableFuture<>();
/** On each global recovery, this version is incremented. The version breaks conflicts
* between concurrent restart attempts by local failover strategies. */
private long globalModVersion;
/** The exception that caused the job to fail. This is set to the first root exception
* that was not recoverable and triggered job failure. */
private Throwable failureCause;
/** The extended failure cause information for the job. This exists in addition to 'failureCause',
* to let 'failureCause' be a strong reference to the exception, while this info holds no
* strong reference to any user-defined classes.*/
private ErrorInfo failureInfo;
private final JobMasterPartitionTracker partitionTracker;
private final ResultPartitionAvailabilityChecker resultPartitionAvailabilityChecker;
/**
* Future for an ongoing or completed scheduling action.
*/
@Nullable
private CompletableFuture<Void> schedulingFuture;
// ------ Fields that are relevant to the execution and need to be cleared before archiving -------
/** The coordinator for checkpoints, if snapshot checkpoints are enabled. */
@Nullable
private CheckpointCoordinator checkpointCoordinator;
/** TODO, replace it with main thread executor. */
@Nullable
private ScheduledExecutorService checkpointCoordinatorTimer;
/** Checkpoint stats tracker separate from the coordinator in order to be
* available after archiving. */
private CheckpointStatsTracker checkpointStatsTracker;
// ------ Fields that are only relevant for archived execution graphs ------------
@Nullable
private String stateBackendName;
private String jsonPlan;
/** Shuffle master to register partitions for task deployment. */
private final ShuffleMaster<?> shuffleMaster;
// --------------------------------------------------------------------------------------------
// Constructors
// --------------------------------------------------------------------------------------------
public ExecutionGraph(
JobInformation jobInformation,
ScheduledExecutorService futureExecutor,
Executor ioExecutor,
Time rpcTimeout,
RestartStrategy restartStrategy,
int maxPriorAttemptsHistoryLength,
FailoverStrategy.Factory failoverStrategyFactory,
SlotProvider slotProvider,
ClassLoader userClassLoader,
BlobWriter blobWriter,
Time allocationTimeout,
PartitionReleaseStrategy.Factory partitionReleaseStrategyFactory,
ShuffleMaster<?> shuffleMaster,
JobMasterPartitionTracker partitionTracker,
ScheduleMode scheduleMode) throws IOException {
this.jobInformation = Preconditions.checkNotNull(jobInformation);
this.blobWriter = Preconditions.checkNotNull(blobWriter);
this.scheduleMode = checkNotNull(scheduleMode);
this.jobInformationOrBlobKey = BlobWriter.serializeAndTryOffload(jobInformation, jobInformation.getJobId(), blobWriter);
this.futureExecutor = Preconditions.checkNotNull(futureExecutor);
this.ioExecutor = Preconditions.checkNotNull(ioExecutor);
this.slotProviderStrategy = SlotProviderStrategy.from(
scheduleMode,
slotProvider,
allocationTimeout);
this.userClassLoader = Preconditions.checkNotNull(userClassLoader, "userClassLoader");
this.tasks = new HashMap<>(16);
this.intermediateResults = new HashMap<>(16);
this.verticesInCreationOrder = new ArrayList<>(16);
this.currentExecutions = new HashMap<>(16);
this.jobStatusListeners = new CopyOnWriteArrayList<>();
this.stateTimestamps = new long[JobStatus.values().length];
this.stateTimestamps[JobStatus.CREATED.ordinal()] = System.currentTimeMillis();
this.rpcTimeout = checkNotNull(rpcTimeout);
this.allocationTimeout = checkNotNull(allocationTimeout);
this.partitionReleaseStrategyFactory = checkNotNull(partitionReleaseStrategyFactory);
this.restartStrategy = restartStrategy;
this.kvStateLocationRegistry = new KvStateLocationRegistry(jobInformation.getJobId(), getAllVertices());
this.globalModVersion = 1L;
// the failover strategy must be instantiated last, so that the execution graph
// is ready by the time the failover strategy sees it
this.failoverStrategy = checkNotNull(failoverStrategyFactory.create(this), "null failover strategy");
this.maxPriorAttemptsHistoryLength = maxPriorAttemptsHistoryLength;
this.schedulingFuture = null;
this.jobMasterMainThreadExecutor =
new ComponentMainThreadExecutor.DummyComponentMainThreadExecutor(
"ExecutionGraph is not initialized with proper main thread executor. " +
"Call to ExecutionGraph.start(...) required.");
this.shuffleMaster = checkNotNull(shuffleMaster);
this.partitionTracker = checkNotNull(partitionTracker);
this.resultPartitionAvailabilityChecker = new ExecutionGraphResultPartitionAvailabilityChecker(
this::createResultPartitionId,
partitionTracker);
}
public void start(@Nonnull ComponentMainThreadExecutor jobMasterMainThreadExecutor) {
this.jobMasterMainThreadExecutor = jobMasterMainThreadExecutor;
}
// --------------------------------------------------------------------------------------------
// Configuration of Data-flow wide execution settings
// --------------------------------------------------------------------------------------------
/**
* Gets the number of job vertices currently held by this execution graph.
* @return The current number of job vertices.
*/
public int getNumberOfExecutionJobVertices() {
return this.verticesInCreationOrder.size();
}
public SchedulingTopology<?, ?> getSchedulingTopology() {
return executionTopology;
}
public FailoverTopology<?, ?> getFailoverTopology() {
return executionTopology;
}
public ScheduleMode getScheduleMode() {
return scheduleMode;
}
public Time getAllocationTimeout() {
return allocationTimeout;
}
@Nonnull
public ComponentMainThreadExecutor getJobMasterMainThreadExecutor() {
return jobMasterMainThreadExecutor;
}
@Override
public boolean isArchived() {
return false;
}
@Override
public Optional<String> getStateBackendName() {
return Optional.ofNullable(stateBackendName);
}
public void enableCheckpointing(
CheckpointCoordinatorConfiguration chkConfig,
List<ExecutionJobVertex> verticesToTrigger,
List<ExecutionJobVertex> verticesToWaitFor,
List<ExecutionJobVertex> verticesToCommitTo,
List<MasterTriggerRestoreHook<?>> masterHooks,
CheckpointIDCounter checkpointIDCounter,
CompletedCheckpointStore checkpointStore,
StateBackend checkpointStateBackend,
CheckpointStatsTracker statsTracker) {
checkState(state == JobStatus.CREATED, "Job must be in CREATED state");
checkState(checkpointCoordinator == null, "checkpointing already enabled");
ExecutionVertex[] tasksToTrigger = collectExecutionVertices(verticesToTrigger);
ExecutionVertex[] tasksToWaitFor = collectExecutionVertices(verticesToWaitFor);
ExecutionVertex[] tasksToCommitTo = collectExecutionVertices(verticesToCommitTo);
checkpointStatsTracker = checkNotNull(statsTracker, "CheckpointStatsTracker");
CheckpointFailureManager failureManager = new CheckpointFailureManager(
chkConfig.getTolerableCheckpointFailureNumber(),
new CheckpointFailureManager.FailJobCallback() {
@Override
public void failJob(Throwable cause) {
getJobMasterMainThreadExecutor().execute(() -> failGlobal(cause));
}
@Override
public void failJobDueToTaskFailure(Throwable cause, ExecutionAttemptID failingTask) {
getJobMasterMainThreadExecutor().execute(() -> failGlobalIfExecutionIsStillRunning(cause, failingTask));
}
}
);
checkState(checkpointCoordinatorTimer == null);
checkpointCoordinatorTimer = Executors.newSingleThreadScheduledExecutor(
new DispatcherThreadFactory(
Thread.currentThread().getThreadGroup(), "Checkpoint Timer"));
// create the coordinator that triggers and commits checkpoints and holds the state
checkpointCoordinator = new CheckpointCoordinator(
jobInformation.getJobId(),
chkConfig,
tasksToTrigger,
tasksToWaitFor,
tasksToCommitTo,
checkpointIDCounter,
checkpointStore,
checkpointStateBackend,
ioExecutor,
new ScheduledExecutorServiceAdapter(checkpointCoordinatorTimer),
SharedStateRegistry.DEFAULT_FACTORY,
failureManager);
// register the master hooks on the checkpoint coordinator
for (MasterTriggerRestoreHook<?> hook : masterHooks) {
if (!checkpointCoordinator.addMasterHook(hook)) {
LOG.warn("Trying to register multiple checkpoint hooks with the name: {}", hook.getIdentifier());
}
}
checkpointCoordinator.setCheckpointStatsTracker(checkpointStatsTracker);
// interval of max long value indicates disable periodic checkpoint,
// the CheckpointActivatorDeactivator should be created only if the interval is not max value
if (chkConfig.getCheckpointInterval() != Long.MAX_VALUE) {
// the periodic checkpoint scheduler is activated and deactivated as a result of
// job status changes (running -> on, all other states -> off)
registerJobStatusListener(checkpointCoordinator.createActivatorDeactivator());
}
this.stateBackendName = checkpointStateBackend.getClass().getSimpleName();
}
@Nullable
public CheckpointCoordinator getCheckpointCoordinator() {
return checkpointCoordinator;
}
public KvStateLocationRegistry getKvStateLocationRegistry() {
return kvStateLocationRegistry;
}
public RestartStrategy getRestartStrategy() {
return restartStrategy;
}
@Override
public CheckpointCoordinatorConfiguration getCheckpointCoordinatorConfiguration() {
if (checkpointStatsTracker != null) {
return checkpointStatsTracker.getJobCheckpointingConfiguration();
} else {
return null;
}
}
@Override
public CheckpointStatsSnapshot getCheckpointStatsSnapshot() {
if (checkpointStatsTracker != null) {
return checkpointStatsTracker.createSnapshot();
} else {
return null;
}
}
private ExecutionVertex[] collectExecutionVertices(List<ExecutionJobVertex> jobVertices) {
if (jobVertices.size() == 1) {
ExecutionJobVertex jv = jobVertices.get(0);
if (jv.getGraph() != this) {
throw new IllegalArgumentException("Can only use ExecutionJobVertices of this ExecutionGraph");
}
return jv.getTaskVertices();
}
else {
ArrayList<ExecutionVertex> all = new ArrayList<>();
for (ExecutionJobVertex jv : jobVertices) {
if (jv.getGraph() != this) {
throw new IllegalArgumentException("Can only use ExecutionJobVertices of this ExecutionGraph");
}
all.addAll(Arrays.asList(jv.getTaskVertices()));
}
return all.toArray(new ExecutionVertex[all.size()]);
}
}
// --------------------------------------------------------------------------------------------
// Properties and Status of the Execution Graph
// --------------------------------------------------------------------------------------------
public void setJsonPlan(String jsonPlan) {
this.jsonPlan = jsonPlan;
}
@Override
public String getJsonPlan() {
return jsonPlan;
}
public SlotProviderStrategy getSlotProviderStrategy() {
return slotProviderStrategy;
}
public Either<SerializedValue<JobInformation>, PermanentBlobKey> getJobInformationOrBlobKey() {
return jobInformationOrBlobKey;
}
@Override
public JobID getJobID() {
return jobInformation.getJobId();
}
@Override
public String getJobName() {
return jobInformation.getJobName();
}
@Override
public boolean isStoppable() {
return this.isStoppable;
}
public Configuration getJobConfiguration() {
return jobInformation.getJobConfiguration();
}
public ClassLoader getUserClassLoader() {
return this.userClassLoader;
}
@Override
public JobStatus getState() {
return state;
}
public Throwable getFailureCause() {
return failureCause;
}
public ErrorInfo getFailureInfo() {
return failureInfo;
}
/**
* Gets the number of restarts, including full restarts and fine grained restarts.
* If a recovery is currently pending, this recovery is included in the count.
*
* @return The number of restarts so far
*/
public long getNumberOfRestarts() {
return numberOfRestartsCounter.getCount();
}
@Override
public ExecutionJobVertex getJobVertex(JobVertexID id) {
return this.tasks.get(id);
}
@Override
public Map<JobVertexID, ExecutionJobVertex> getAllVertices() {
return Collections.unmodifiableMap(this.tasks);
}
@Override
public Iterable<ExecutionJobVertex> getVerticesTopologically() {
// we return a specific iterator that does not fail with concurrent modifications
// the list is append only, so it is safe for that
final int numElements = this.verticesInCreationOrder.size();
return new Iterable<ExecutionJobVertex>() {
@Override
public Iterator<ExecutionJobVertex> iterator() {
return new Iterator<ExecutionJobVertex>() {
private int pos = 0;
@Override
public boolean hasNext() {
return pos < numElements;
}
@Override
public ExecutionJobVertex next() {
if (hasNext()) {
return verticesInCreationOrder.get(pos++);
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
public int getTotalNumberOfVertices() {
return numVerticesTotal;
}
public Map<IntermediateDataSetID, IntermediateResult> getAllIntermediateResults() {
return Collections.unmodifiableMap(this.intermediateResults);
}
@Override
public Iterable<ExecutionVertex> getAllExecutionVertices() {
return new Iterable<ExecutionVertex>() {
@Override
public Iterator<ExecutionVertex> iterator() {
return new AllVerticesIterator(getVerticesTopologically().iterator());
}
};
}
@Override
public long getStatusTimestamp(JobStatus status) {
return this.stateTimestamps[status.ordinal()];
}
public final BlobWriter getBlobWriter() {
return blobWriter;
}
/**
* Returns the ExecutionContext associated with this ExecutionGraph.
*
* @return ExecutionContext associated with this ExecutionGraph
*/
public Executor getFutureExecutor() {
return futureExecutor;
}
/**
* Merges all accumulator results from the tasks previously executed in the Executions.
* @return The accumulator map
*/
public Map<String, OptionalFailure<Accumulator<?, ?>>> aggregateUserAccumulators() {
Map<String, OptionalFailure<Accumulator<?, ?>>> userAccumulators = new HashMap<>();
for (ExecutionVertex vertex : getAllExecutionVertices()) {
Map<String, Accumulator<?, ?>> next = vertex.getCurrentExecutionAttempt().getUserAccumulators();
if (next != null) {
AccumulatorHelper.mergeInto(userAccumulators, next);
}
}
return userAccumulators;
}
/**
* Gets a serialized accumulator map.
* @return The accumulator map with serialized accumulator values.
*/
@Override
public Map<String, SerializedValue<OptionalFailure<Object>>> getAccumulatorsSerialized() {
return aggregateUserAccumulators()
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> serializeAccumulator(entry.getKey(), entry.getValue())));
}
private static SerializedValue<OptionalFailure<Object>> serializeAccumulator(String name, OptionalFailure<Accumulator<?, ?>> accumulator) {
try {
if (accumulator.isFailure()) {
return new SerializedValue<>(OptionalFailure.ofFailure(accumulator.getFailureCause()));
}
return new SerializedValue<>(OptionalFailure.of(accumulator.getUnchecked().getLocalValue()));
} catch (IOException ioe) {
LOG.error("Could not serialize accumulator " + name + '.', ioe);
try {
return new SerializedValue<>(OptionalFailure.ofFailure(ioe));
} catch (IOException e) {
throw new RuntimeException("It should never happen that we cannot serialize the accumulator serialization exception.", e);
}
}
}
/**
* Returns the a stringified version of the user-defined accumulators.
* @return an Array containing the StringifiedAccumulatorResult objects
*/
@Override
public StringifiedAccumulatorResult[] getAccumulatorResultsStringified() {
Map<String, OptionalFailure<Accumulator<?, ?>>> accumulatorMap = aggregateUserAccumulators();
return StringifiedAccumulatorResult.stringifyAccumulatorResults(accumulatorMap);
}
public void enableNgScheduling(final InternalFailuresListener internalTaskFailuresListener) {
checkNotNull(internalTaskFailuresListener);
checkState(this.internalTaskFailuresListener == null, "enableNgScheduling can be only called once");
this.internalTaskFailuresListener = internalTaskFailuresListener;
this.legacyScheduling = false;
}
// --------------------------------------------------------------------------------------------
// Actions
// --------------------------------------------------------------------------------------------
public void attachJobGraph(List<JobVertex> topologiallySorted) throws JobException {
assertRunningInJobMasterMainThread();
LOG.debug("Attaching {} topologically sorted vertices to existing job graph with {} " +
"vertices and {} intermediate results.",
topologiallySorted.size(),
tasks.size(),
intermediateResults.size());
final ArrayList<ExecutionJobVertex> newExecJobVertices = new ArrayList<>(topologiallySorted.size());
final long createTimestamp = System.currentTimeMillis();
for (JobVertex jobVertex : topologiallySorted) {
if (jobVertex.isInputVertex() && !jobVertex.isStoppable()) {
this.isStoppable = false;
}
// create the execution job vertex and attach it to the graph
ExecutionJobVertex ejv = new ExecutionJobVertex(
this,
jobVertex,
1,
maxPriorAttemptsHistoryLength,
rpcTimeout,
globalModVersion,
createTimestamp);
ejv.connectToPredecessors(this.intermediateResults);
ExecutionJobVertex previousTask = this.tasks.putIfAbsent(jobVertex.getID(), ejv);
if (previousTask != null) {
throw new JobException(String.format("Encountered two job vertices with ID %s : previous=[%s] / new=[%s]",
jobVertex.getID(), ejv, previousTask));
}
for (IntermediateResult res : ejv.getProducedDataSets()) {
IntermediateResult previousDataSet = this.intermediateResults.putIfAbsent(res.getId(), res);
if (previousDataSet != null) {
throw new JobException(String.format("Encountered two intermediate data set with ID %s : previous=[%s] / new=[%s]",
res.getId(), res, previousDataSet));
}
}
this.verticesInCreationOrder.add(ejv);
this.numVerticesTotal += ejv.getParallelism();
newExecJobVertices.add(ejv);
}
// the topology assigning should happen before notifying new vertices to failoverStrategy
executionTopology = new DefaultExecutionTopology(this);
failoverStrategy.notifyNewVertices(newExecJobVertices);
partitionReleaseStrategy = partitionReleaseStrategyFactory.createInstance(getSchedulingTopology());
}
public boolean isLegacyScheduling() {
return legacyScheduling;
}
public void transitionToRunning() {
if (!transitionState(JobStatus.CREATED, JobStatus.RUNNING)) {
throw new IllegalStateException("Job may only be scheduled from state " + JobStatus.CREATED);
}
}
public void scheduleForExecution() throws JobException {
assertRunningInJobMasterMainThread();
if (isLegacyScheduling()) {
LOG.info("Job recovers via failover strategy: {}", failoverStrategy.getStrategyName());
}
final long currentGlobalModVersion = globalModVersion;
if (transitionState(JobStatus.CREATED, JobStatus.RUNNING)) {
final CompletableFuture<Void> newSchedulingFuture = SchedulingUtils.schedule(
scheduleMode,
getAllExecutionVertices(),
this);
if (state == JobStatus.RUNNING && currentGlobalModVersion == globalModVersion) {
schedulingFuture = newSchedulingFuture;
newSchedulingFuture.whenComplete(
(Void ignored, Throwable throwable) -> {
if (throwable != null) {
final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable);
if (!(strippedThrowable instanceof CancellationException)) {
// only fail if the scheduling future was not canceled
failGlobal(strippedThrowable);
}
}
});
} else {
newSchedulingFuture.cancel(false);
}
}
else {
throw new IllegalStateException("Job may only be scheduled from state " + JobStatus.CREATED);
}
}
public void cancel() {
assertRunningInJobMasterMainThread();
while (true) {
JobStatus current = state;
if (current == JobStatus.RUNNING || current == JobStatus.CREATED) {
if (transitionState(current, JobStatus.CANCELLING)) {
// make sure no concurrent local actions interfere with the cancellation
final long globalVersionForRestart = incrementGlobalModVersion();
final CompletableFuture<Void> ongoingSchedulingFuture = schedulingFuture;
// cancel ongoing scheduling action
if (ongoingSchedulingFuture != null) {
ongoingSchedulingFuture.cancel(false);
}
final ConjunctFuture<Void> allTerminal = cancelVerticesAsync();
allTerminal.whenComplete(
(Void value, Throwable throwable) -> {
if (throwable != null) {
transitionState(
JobStatus.CANCELLING,
JobStatus.FAILED,
new FlinkException(
"Could not cancel job " + getJobName() + " because not all execution job vertices could be cancelled.",
throwable));
} else {
// cancellations may currently be overridden by failures which trigger
// restarts, so we need to pass a proper restart global version here
allVerticesInTerminalState(globalVersionForRestart);
}
});
return;
}
}
// Executions are being canceled. Go into cancelling and wait for
// all vertices to be in their final state.
else if (current == JobStatus.FAILING) {
if (transitionState(current, JobStatus.CANCELLING)) {
return;
}
}
// All vertices have been cancelled and it's safe to directly go
// into the canceled state.
else if (current == JobStatus.RESTARTING) {
if (transitionState(current, JobStatus.CANCELED)) {
onTerminalState(JobStatus.CANCELED);
LOG.info("Canceled during restart.");
return;
}
}
else {
// no need to treat other states
return;
}
}
}
private ConjunctFuture<Void> cancelVerticesAsync() {
final ArrayList<CompletableFuture<?>> futures = new ArrayList<>(verticesInCreationOrder.size());
// cancel all tasks (that still need cancelling)
for (ExecutionJobVertex ejv : verticesInCreationOrder) {
futures.add(ejv.cancelWithFuture());
}
// we build a future that is complete once all vertices have reached a terminal state
return FutureUtils.waitForAll(futures);
}
/**
* Suspends the current ExecutionGraph.
*
* <p>The JobStatus will be directly set to {@link JobStatus#SUSPENDED} iff the current state is not a terminal
* state. All ExecutionJobVertices will be canceled and the onTerminalState() is executed.
*
* <p>The {@link JobStatus#SUSPENDED} state is a local terminal state which stops the execution of the job but does
* not remove the job from the HA job store so that it can be recovered by another JobManager.
*
* @param suspensionCause Cause of the suspension
*/
public void suspend(Throwable suspensionCause) {
assertRunningInJobMasterMainThread();
if (state.isTerminalState()) {
// stay in a terminal state
return;
} else if (transitionState(state, JobStatus.SUSPENDED, suspensionCause)) {
initFailureCause(suspensionCause);
// make sure no concurrent local actions interfere with the cancellation
incrementGlobalModVersion();
// cancel ongoing scheduling action
if (schedulingFuture != null) {
schedulingFuture.cancel(false);
}
final ArrayList<CompletableFuture<Void>> executionJobVertexTerminationFutures = new ArrayList<>(verticesInCreationOrder.size());
for (ExecutionJobVertex ejv: verticesInCreationOrder) {
executionJobVertexTerminationFutures.add(ejv.suspend());
}
final ConjunctFuture<Void> jobVerticesTerminationFuture = FutureUtils.waitForAll(executionJobVertexTerminationFutures);
checkState(jobVerticesTerminationFuture.isDone(), "Suspend needs to happen atomically");
jobVerticesTerminationFuture.whenComplete(
(Void ignored, Throwable throwable) -> {
if (throwable != null) {
LOG.debug("Could not properly suspend the execution graph.", throwable);
}
onTerminalState(state);
LOG.info("Job {} has been suspended.", getJobID());
});
} else {
throw new IllegalStateException(String.format("Could not suspend because transition from %s to %s failed.", state, JobStatus.SUSPENDED));
}
}
void failGlobalIfExecutionIsStillRunning(Throwable cause, ExecutionAttemptID failingAttempt) {
final Execution failedExecution = currentExecutions.get(failingAttempt);
if (failedExecution != null && failedExecution.getState() == ExecutionState.RUNNING) {
failGlobal(cause);
} else {
LOG.debug("The failing attempt {} belongs to an already not" +
" running task thus won't fail the job", failingAttempt);
}
}
/**
* Fails the execution graph globally. This failure will not be recovered by a specific
* failover strategy, but results in a full restart of all tasks.
*
* <p>This global failure is meant to be triggered in cases where the consistency of the
* execution graph' state cannot be guaranteed any more (for example when catching unexpected
* exceptions that indicate a bug or an unexpected call race), and where a full restart is the
* safe way to get consistency back.
*
* @param t The exception that caused the failure.
*/
public void failGlobal(Throwable t) {
if (!isLegacyScheduling()) {
internalTaskFailuresListener.notifyGlobalFailure(t);
return;
}
assertRunningInJobMasterMainThread();
while (true) {
JobStatus current = state;
// stay in these states
if (current == JobStatus.FAILING ||
current == JobStatus.SUSPENDED ||
current.isGloballyTerminalState()) {
return;
} else if (transitionState(current, JobStatus.FAILING, t)) {
initFailureCause(t);
// make sure no concurrent local or global actions interfere with the failover
final long globalVersionForRestart = incrementGlobalModVersion();
final CompletableFuture<Void> ongoingSchedulingFuture = schedulingFuture;
// cancel ongoing scheduling action
if (ongoingSchedulingFuture != null) {
ongoingSchedulingFuture.cancel(false);
}
// we build a future that is complete once all vertices have reached a terminal state
final ConjunctFuture<Void> allTerminal = cancelVerticesAsync();
FutureUtils.assertNoException(allTerminal.handle(
(Void ignored, Throwable throwable) -> {
if (throwable != null) {
transitionState(
JobStatus.FAILING,
JobStatus.FAILED,
new FlinkException("Could not cancel all execution job vertices properly.", throwable));
} else {
allVerticesInTerminalState(globalVersionForRestart);
}
return null;
}));
return;
}
// else: concurrent change to execution state, retry
}
}
public void restart(long expectedGlobalVersion) {
assertRunningInJobMasterMainThread();
try {
// check the global version to see whether this recovery attempt is still valid
if (globalModVersion != expectedGlobalVersion) {
LOG.info("Concurrent full restart subsumed this restart.");
return;
}
final JobStatus current = state;
if (current == JobStatus.CANCELED) {
LOG.info("Canceled job during restart. Aborting restart.");
return;
} else if (current == JobStatus.FAILED) {
LOG.info("Failed job during restart. Aborting restart.");
return;
} else if (current == JobStatus.SUSPENDED) {
LOG.info("Suspended job during restart. Aborting restart.");
return;
} else if (current != JobStatus.RESTARTING) {
throw new IllegalStateException("Can only restart job from state restarting.");
}
this.currentExecutions.clear();
final Collection<CoLocationGroup> colGroups = new HashSet<>();
final long resetTimestamp = System.currentTimeMillis();
for (ExecutionJobVertex jv : this.verticesInCreationOrder) {
CoLocationGroup cgroup = jv.getCoLocationGroup();
if (cgroup != null && !colGroups.contains(cgroup)){
cgroup.resetConstraints();
colGroups.add(cgroup);
}
jv.resetForNewExecution(resetTimestamp, expectedGlobalVersion);
}
for (int i = 0; i < stateTimestamps.length; i++) {
if (i != JobStatus.RESTARTING.ordinal()) {
// Only clear the non restarting state in order to preserve when the job was
// restarted. This is needed for the restarting time gauge
stateTimestamps[i] = 0;
}
}
transitionState(JobStatus.RESTARTING, JobStatus.CREATED);
// if we have checkpointed state, reload it into the executions
if (checkpointCoordinator != null) {
checkpointCoordinator.restoreLatestCheckpointedState(getAllVertices(), false, false);
}
scheduleForExecution();
}
// TODO remove the catch block if we align the schematics to not fail global within the restarter.
catch (Throwable t) {
LOG.warn("Failed to restart the job.", t);
failGlobal(t);
}
}
/**
* Returns the serializable {@link ArchivedExecutionConfig}.
*
* @return ArchivedExecutionConfig which may be null in case of errors
*/
@Override
public ArchivedExecutionConfig getArchivedExecutionConfig() {
// create a summary of all relevant data accessed in the web interface's JobConfigHandler
try {
ExecutionConfig executionConfig = jobInformation.getSerializedExecutionConfig().deserializeValue(userClassLoader);
if (executionConfig != null) {
return executionConfig.archive();
}
} catch (IOException | ClassNotFoundException e) {
LOG.error("Couldn't create ArchivedExecutionConfig for job {} ", getJobID(), e);
}
return null;
}
/**
* Returns the termination future of this {@link ExecutionGraph}. The termination future
* is completed with the terminal {@link JobStatus} once the ExecutionGraph reaches this
* terminal state and all {@link Execution} have been terminated.
*
* @return Termination future of this {@link ExecutionGraph}.
*/
public CompletableFuture<JobStatus> getTerminationFuture() {
return terminationFuture;
}
@VisibleForTesting
public JobStatus waitUntilTerminal() throws InterruptedException {
try {
return terminationFuture.get();
}
catch (ExecutionException e) {
// this should never happen
// it would be a bug, so we don't expect this to be handled and throw
// an unchecked exception here
throw new RuntimeException(e);
}
}
/**
* Gets the failover strategy used by the execution graph to recover from failures of tasks.
*/
public FailoverStrategy getFailoverStrategy() {
return this.failoverStrategy;
}
/**
* Gets the current global modification version of the ExecutionGraph.
* The global modification version is incremented with each global action (cancel/fail/restart)
* and is used to disambiguate concurrent modifications between local and global
* failover actions.
*/
public long getGlobalModVersion() {
return globalModVersion;
}
// ------------------------------------------------------------------------
// State Transitions
// ------------------------------------------------------------------------
private boolean transitionState(JobStatus current, JobStatus newState) {
return transitionState(current, newState, null);
}
private void transitionState(JobStatus newState, Throwable error) {
transitionState(state, newState, error);
}
private boolean transitionState(JobStatus current, JobStatus newState, Throwable error) {
assertRunningInJobMasterMainThread();
// consistency check
if (current.isTerminalState()) {
String message = "Job is trying to leave terminal state " + current;
LOG.error(message);
throw new IllegalStateException(message);
}
// now do the actual state transition
if (state == current) {
state = newState;
LOG.info("Job {} ({}) switched from state {} to {}.", getJobName(), getJobID(), current, newState, error);
stateTimestamps[newState.ordinal()] = System.currentTimeMillis();
notifyJobStatusChange(newState, error);
return true;
}
else {
return false;
}
}
private long incrementGlobalModVersion() {
incrementRestarts();
return ++globalModVersion;
}
public void incrementRestarts() {
numberOfRestartsCounter.inc();
}
public void initFailureCause(Throwable t) {
this.failureCause = t;
this.failureInfo = new ErrorInfo(t, System.currentTimeMillis());
}
// ------------------------------------------------------------------------
// Job Status Progress
// ------------------------------------------------------------------------
/**
* Called whenever a vertex reaches state FINISHED (completed successfully).
* Once all vertices are in the FINISHED state, the program is successfully done.
*/
void vertexFinished() {
assertRunningInJobMasterMainThread();
final int numFinished = ++verticesFinished;
if (numFinished == numVerticesTotal) {
// done :-)
// check whether we are still in "RUNNING" and trigger the final cleanup
if (state == JobStatus.RUNNING) {
// we do the final cleanup in the I/O executor, because it may involve
// some heavier work
try {
for (ExecutionJobVertex ejv : verticesInCreationOrder) {
ejv.getJobVertex().finalizeOnMaster(getUserClassLoader());
}
}
catch (Throwable t) {
ExceptionUtils.rethrowIfFatalError(t);
failGlobal(new Exception("Failed to finalize execution on master", t));
return;
}
// if we do not make this state transition, then a concurrent
// cancellation or failure happened
if (transitionState(JobStatus.RUNNING, JobStatus.FINISHED)) {
onTerminalState(JobStatus.FINISHED);
}
}
}
}
void vertexUnFinished() {
assertRunningInJobMasterMainThread();
verticesFinished--;
}
/**
* This method is a callback during cancellation/failover and called when all tasks
* have reached a terminal state (cancelled/failed/finished).
*/
private void allVerticesInTerminalState(long expectedGlobalVersionForRestart) {
assertRunningInJobMasterMainThread();
// we are done, transition to the final state
JobStatus current;
while (true) {
current = this.state;
if (current == JobStatus.RUNNING) {
failGlobal(new Exception("ExecutionGraph went into allVerticesInTerminalState() from RUNNING"));
}
else if (current == JobStatus.CANCELLING) {
if (transitionState(current, JobStatus.CANCELED)) {
onTerminalState(JobStatus.CANCELED);
break;
}
}
else if (current == JobStatus.FAILING) {
if (tryRestartOrFail(expectedGlobalVersionForRestart)) {
break;
}
// concurrent job status change, let's check again
}
else if (current.isGloballyTerminalState()) {
LOG.warn("Job has entered globally terminal state without waiting for all " +
"job vertices to reach final state.");
break;
}
else {
failGlobal(new Exception("ExecutionGraph went into final state from state " + current));
break;
}
}
// done transitioning the state
}
/**
* Try to restart the job. If we cannot restart the job (e.g. no more restarts allowed), then
* try to fail the job. This operation is only permitted if the current state is FAILING or
* RESTARTING.
*
* @return true if the operation could be executed; false if a concurrent job status change occurred
*/
@Deprecated
private boolean tryRestartOrFail(long globalModVersionForRestart) {
if (!isLegacyScheduling()) {
return true;
}
JobStatus currentState = state;
if (currentState == JobStatus.FAILING || currentState == JobStatus.RESTARTING) {
final Throwable failureCause = this.failureCause;
if (LOG.isDebugEnabled()) {
LOG.debug("Try to restart or fail the job {} ({}) if no longer possible.", getJobName(), getJobID(), failureCause);
} else {
LOG.info("Try to restart or fail the job {} ({}) if no longer possible.", getJobName(), getJobID());
}
final boolean isFailureCauseAllowingRestart = !(failureCause instanceof SuppressRestartsException);
final boolean isRestartStrategyAllowingRestart = restartStrategy.canRestart();
boolean isRestartable = isFailureCauseAllowingRestart && isRestartStrategyAllowingRestart;
if (isRestartable && transitionState(currentState, JobStatus.RESTARTING)) {
LOG.info("Restarting the job {} ({}).", getJobName(), getJobID());
RestartCallback restarter = new ExecutionGraphRestartCallback(this, globalModVersionForRestart);
FutureUtils.assertNoException(
restartStrategy
.restart(restarter, getJobMasterMainThreadExecutor())
.exceptionally((throwable) -> {
failGlobal(throwable);
return null;
}));
return true;
}
else if (!isRestartable && transitionState(currentState, JobStatus.FAILED, failureCause)) {
final String cause1 = isFailureCauseAllowingRestart ? null :
"a type of SuppressRestartsException was thrown";
final String cause2 = isRestartStrategyAllowingRestart ? null :
"the restart strategy prevented it";
LOG.info("Could not restart the job {} ({}) because {}.", getJobName(), getJobID(),
StringUtils.concatenateWithAnd(cause1, cause2), failureCause);
onTerminalState(JobStatus.FAILED);
return true;
} else {
// we must have changed the state concurrently, thus we cannot complete this operation
return false;
}
} else {
// this operation is only allowed in the state FAILING or RESTARTING
return false;
}
}
public void failJob(Throwable cause) {
if (state == JobStatus.FAILING || state.isGloballyTerminalState()) {
return;
}
transitionState(JobStatus.FAILING, cause);
initFailureCause(cause);
FutureUtils.assertNoException(
cancelVerticesAsync().whenComplete((aVoid, throwable) -> {
transitionState(JobStatus.FAILED, cause);
onTerminalState(JobStatus.FAILED);
}));
}
private void onTerminalState(JobStatus status) {
try {
CheckpointCoordinator coord = this.checkpointCoordinator;
this.checkpointCoordinator = null;
if (coord != null) {
coord.shutdown(status);
}
if (checkpointCoordinatorTimer != null) {
checkpointCoordinatorTimer.shutdownNow();
checkpointCoordinatorTimer = null;
}
}
catch (Exception e) {
LOG.error("Error while cleaning up after execution", e);
}
finally {
terminationFuture.complete(status);
}
}
// --------------------------------------------------------------------------------------------
// Callbacks and Callback Utilities
// --------------------------------------------------------------------------------------------
/**
* Updates the state of one of the ExecutionVertex's Execution attempts.
* If the new status if "FINISHED", this also updates the accumulators.
*
* @param state The state update.
* @return True, if the task update was properly applied, false, if the execution attempt was not found.
*/
public boolean updateState(TaskExecutionState state) {
assertRunningInJobMasterMainThread();
final Execution attempt = currentExecutions.get(state.getID());
if (attempt != null) {
try {
final boolean stateUpdated = updateStateInternal(state, attempt);
maybeReleasePartitions(attempt);
return stateUpdated;
}
catch (Throwable t) {
ExceptionUtils.rethrowIfFatalErrorOrOOM(t);
// failures during updates leave the ExecutionGraph inconsistent
failGlobal(t);
return false;
}
}
else {
return false;
}
}
private boolean updateStateInternal(final TaskExecutionState state, final Execution attempt) {
Map<String, Accumulator<?, ?>> accumulators;
switch (state.getExecutionState()) {
case RUNNING:
return attempt.switchToRunning();
case FINISHED:
// this deserialization is exception-free
accumulators = deserializeAccumulators(state);
attempt.markFinished(accumulators, state.getIOMetrics());
return true;
case CANCELED:
// this deserialization is exception-free
accumulators = deserializeAccumulators(state);
attempt.completeCancelling(accumulators, state.getIOMetrics(), false);
return true;
case FAILED:
// this deserialization is exception-free
accumulators = deserializeAccumulators(state);
attempt.markFailed(state.getError(userClassLoader), accumulators, state.getIOMetrics(), !isLegacyScheduling());
return true;
default:
// we mark as failed and return false, which triggers the TaskManager
// to remove the task
attempt.fail(new Exception("TaskManager sent illegal state update: " + state.getExecutionState()));
return false;
}
}
private void maybeReleasePartitions(final Execution attempt) {
final ExecutionVertexID finishedExecutionVertex = attempt.getVertex().getID();
if (attempt.getState() == ExecutionState.FINISHED) {
final List<IntermediateResultPartitionID> releasablePartitions = partitionReleaseStrategy.vertexFinished(finishedExecutionVertex);
releasePartitions(releasablePartitions);
} else {
partitionReleaseStrategy.vertexUnfinished(finishedExecutionVertex);
}
}
private void releasePartitions(final List<IntermediateResultPartitionID> releasablePartitions) {
if (releasablePartitions.size() > 0) {
final List<ResultPartitionID> partitionIds = releasablePartitions.stream()
.map(this::createResultPartitionId)
.collect(Collectors.toList());
partitionTracker.stopTrackingAndReleasePartitions(partitionIds);
}
}
ResultPartitionID createResultPartitionId(final IntermediateResultPartitionID resultPartitionId) {
final SchedulingResultPartition<?, ?> schedulingResultPartition =
getSchedulingTopology().getResultPartitionOrThrow(resultPartitionId);
final SchedulingExecutionVertex<?, ?> producer = schedulingResultPartition.getProducer();
final ExecutionVertexID producerId = producer.getId();
final JobVertexID jobVertexId = producerId.getJobVertexId();
final ExecutionJobVertex jobVertex = getJobVertex(jobVertexId);
checkNotNull(jobVertex, "Unknown job vertex %s", jobVertexId);
final ExecutionVertex[] taskVertices = jobVertex.getTaskVertices();
final int subtaskIndex = producerId.getSubtaskIndex();
checkState(subtaskIndex < taskVertices.length, "Invalid subtask index %d for job vertex %s", subtaskIndex, jobVertexId);
final ExecutionVertex taskVertex = taskVertices[subtaskIndex];
final Execution execution = taskVertex.getCurrentExecutionAttempt();
return new ResultPartitionID(resultPartitionId, execution.getAttemptId());
}
/**
* Deserializes accumulators from a task state update.
*
* <p>This method never throws an exception!
*
* @param state The task execution state from which to deserialize the accumulators.
* @return The deserialized accumulators, of null, if there are no accumulators or an error occurred.
*/
private Map<String, Accumulator<?, ?>> deserializeAccumulators(TaskExecutionState state) {
AccumulatorSnapshot serializedAccumulators = state.getAccumulators();
if (serializedAccumulators != null) {
try {
return serializedAccumulators.deserializeUserAccumulators(userClassLoader);
}
catch (Throwable t) {
// we catch Throwable here to include all form of linking errors that may
// occur if user classes are missing in the classpath
LOG.error("Failed to deserialize final accumulator results.", t);
}
}
return null;
}
/**
* Schedule or updates consumers of the given result partition.
*
* @param partitionId specifying the result partition whose consumer shall be scheduled or updated
* @throws ExecutionGraphException if the schedule or update consumers operation could not be executed
*/
public void scheduleOrUpdateConsumers(ResultPartitionID partitionId) throws ExecutionGraphException {
assertRunningInJobMasterMainThread();
final Execution execution = currentExecutions.get(partitionId.getProducerId());
if (execution == null) {
throw new ExecutionGraphException("Cannot find execution for execution Id " +
partitionId.getPartitionId() + '.');
}
else if (execution.getVertex() == null){
throw new ExecutionGraphException("Execution with execution Id " +
partitionId.getPartitionId() + " has no vertex assigned.");
} else {
execution.getVertex().scheduleOrUpdateConsumers(partitionId);
}
}
public Map<ExecutionAttemptID, Execution> getRegisteredExecutions() {
return Collections.unmodifiableMap(currentExecutions);
}
void registerExecution(Execution exec) {
assertRunningInJobMasterMainThread();
Execution previous = currentExecutions.putIfAbsent(exec.getAttemptId(), exec);
if (previous != null) {
failGlobal(new Exception("Trying to register execution " + exec + " for already used ID " + exec.getAttemptId()));
}
}
void deregisterExecution(Execution exec) {
assertRunningInJobMasterMainThread();
Execution contained = currentExecutions.remove(exec.getAttemptId());
if (contained != null && contained != exec) {
failGlobal(new Exception("De-registering execution " + exec + " failed. Found for same ID execution " + contained));
}
}
/**
* Updates the accumulators during the runtime of a job. Final accumulator results are transferred
* through the UpdateTaskExecutionState message.
* @param accumulatorSnapshot The serialized flink and user-defined accumulators
*/
public void updateAccumulators(AccumulatorSnapshot accumulatorSnapshot) {
Map<String, Accumulator<?, ?>> userAccumulators;
try {
userAccumulators = accumulatorSnapshot.deserializeUserAccumulators(userClassLoader);
ExecutionAttemptID execID = accumulatorSnapshot.getExecutionAttemptID();
Execution execution = currentExecutions.get(execID);
if (execution != null) {
execution.setAccumulators(userAccumulators);
} else {
LOG.debug("Received accumulator result for unknown execution {}.", execID);
}
} catch (Exception e) {
LOG.error("Cannot update accumulators for job {}.", getJobID(), e);
}
}
// --------------------------------------------------------------------------------------------
// Listeners & Observers
// --------------------------------------------------------------------------------------------
public void registerJobStatusListener(JobStatusListener listener) {
if (listener != null) {
jobStatusListeners.add(listener);
}
}
private void notifyJobStatusChange(JobStatus newState, Throwable error) {
if (jobStatusListeners.size() > 0) {
final long timestamp = System.currentTimeMillis();
final Throwable serializedError = error == null ? null : new SerializedThrowable(error);
for (JobStatusListener listener : jobStatusListeners) {
try {
listener.jobStatusChanges(getJobID(), newState, timestamp, serializedError);
} catch (Throwable t) {
LOG.warn("Error while notifying JobStatusListener", t);
}
}
}
}
void notifyExecutionChange(
final Execution execution,
final ExecutionState newExecutionState,
final Throwable error) {
if (!isLegacyScheduling()) {
return;
}
// see what this means for us. currently, the first FAILED state means -> FAILED
if (newExecutionState == ExecutionState.FAILED) {
final Throwable ex = error != null ? error : new FlinkException("Unknown Error (missing cause)");
// by filtering out late failure calls, we can save some work in
// avoiding redundant local failover
if (execution.getGlobalModVersion() == globalModVersion) {
try {
// fail all checkpoints which the failed task has not yet acknowledged
if (checkpointCoordinator != null) {
checkpointCoordinator.failUnacknowledgedPendingCheckpointsFor(execution.getAttemptId(), ex);
}
failoverStrategy.onTaskFailure(execution, ex);
}
catch (Throwable t) {
// bug in the failover strategy - fall back to global failover
LOG.warn("Error in failover strategy - falling back to global restart", t);
failGlobal(ex);
}
}
}
}
void assertRunningInJobMasterMainThread() {
if (!(jobMasterMainThreadExecutor instanceof ComponentMainThreadExecutor.DummyComponentMainThreadExecutor)) {
jobMasterMainThreadExecutor.assertRunningInMainThread();
}
}
void notifySchedulerNgAboutInternalTaskFailure(final ExecutionAttemptID attemptId, final Throwable t) {
if (internalTaskFailuresListener != null) {
internalTaskFailuresListener.notifyTaskFailure(attemptId, t);
}
}
ShuffleMaster<?> getShuffleMaster() {
return shuffleMaster;
}
public JobMasterPartitionTracker getPartitionTracker() {
return partitionTracker;
}
public ResultPartitionAvailabilityChecker getResultPartitionAvailabilityChecker() {
return resultPartitionAvailabilityChecker;
}
PartitionReleaseStrategy getPartitionReleaseStrategy() {
return partitionReleaseStrategy;
}
}
| [FLINK-14655][runtime] Change type of field jobStatusListeners from CopyOnWriteArrayList to ArrayList
This closes #10116.
| flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/ExecutionGraph.java | [FLINK-14655][runtime] Change type of field jobStatusListeners from CopyOnWriteArrayList to ArrayList |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.